Udostępnij za pośrednictwem


Creating a SharePoint Visual Web Part using Visual Studio 2010

Last year we built a business application for order management for Northwind Traders on the Office and SharePoint platform using Visual Studio 2008 and Office & SharePoint 2007. Lately I’ve been writing articles that show how to upgrade it to Office & SharePoint 2010 using Visual Studio 2010. If you missed them:

I also released the migrated sample application here: https://code.msdn.microsoft.com/OBANorthwind

If you look at the VS2010 solution in that sample you’ll see a few extra projects in there that add more functionality to our application. One of those new pieces is a Visual Web Part that shows low inventory from the Northwind database. Northwind’s operations department not only wants to see Order status in SharePoint (which we built into our workflow) but also wants to be able to quickly eyeball any low inventory. Visual Studio 2010 includes many new project and item templates for SharePoint 2010, one being a Visual Web part. If you’re familiar with ASP.NET development then you can easily start building a SharePoint web part using Visual Studio 2010. Let’s see how we can do that.

Creating a Visual Web Part Project in Visual Studio

First thing you need to do is open Visual Studio as an Administrator. You need to do this when you are programming against SharePoint because the debugger & tools need Administrator access to SharePoint. Visual Studio will warn you if you forget.

Next create a new project and select SharePoint 2010 -> Visual Web Part. (Make sure you select Visual Web Part and not Web Part). Name the project LowInventoryWebPart. The SharePoint Customization Wizard opens. Select your SharePoint site, in my case I’ve created a team site called Northwind.

Notice that “Deploy as a farm solution” is the only option. This means that when you design a visual web part it is available to all site collections on the farm as opposed to a sandboxed solution which is only available at the site collection level. The key difference between these two is what processes they run in, farm being the IIS worker process, which dictates which access levels they have. For more information on the differences see Differences Between Sandboxed and Farm Solutions in the MSDN library.

image

Click Finish and the the ASP.NET designer opens and displays a web user control that we can design. But first we need to add a service reference to our data service. If you recall we are exposing our line-of-business data (in this case the Northwind SQL database) over WCF-REST using a data service. As long as we can access this service from our SharePoint instance once we deploy, then we’re good to go.

To add a Service Reference to the data service, select Project -> Add Service Reference. If your data service is in the same solution as in the case of this one, just click Discover to browse the types that the data service exposes. Set the Namespace to NorthwindService and click OK.

Designing the Visual Web Part and Loading Data

I don’t have any super-fancy design skillz here so we’re just going to create a data-bound GridView and then write a LINQ query to get the low inventory items to display. The key takeaway is that this would be the same code to write if we were writing any ASP.NET webpage, you can even use the Ajax controls in the toolbox. In the next section below we’ll take advantage of the SharePoint server model in order to interact with SharePoint lists, but to pull data from our LOB database it’s standard data access stuff.

So from the Data tab in the toolbox, I’m going to drag a GridView onto the form. I’m also going to drop a Label at the bottom of the form to display any errors or messages. I can style these controls how I like and these styles will be displayed the same way in the Web Part in SharePoint.

image

Right-click on the designer to open the code-behind. In the Page_Load event handler we’ll write the code to load the low inventory from our data service:

 Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports LowInventoryWebPart.NorthwindService

Partial Public Class LowInventoryWebPartUserControl
    Inherits UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        'Webpart Code to display Low Inventory:
        Try
            Dim ctx As New NorthwindEntities(New Uri("https://myserver/Northwind.svc/"))

            Dim result = From p In ctx.Products _
                         Where p.UnitsInStock <= p.ReorderLevel _
                         Order By p.UnitsInStock


            Me.GridView1.AutoGenerateColumns = True
            Me.GridView1.DataSource = result.ToList()
            Me.GridView1.DataBind()

        Catch ex As Exception
            Me.Label1.Text = ex.ToString
        End Try
    End Sub

End Class

Debugging the Web Part

Let’s test this so far. Set the LowInventoryWebPart project as the startup project of your solution (if it isn’t already) and set a breakpoint on the LINQ query. Hit F5 and Visual Studio will recycle the IIS worker process, package & deploy & activate the feature, and attach the debugger automatically for you. This is shown in the Output window and it’s fun to watch so you may want to pin that window open. :-)

 ------ Deploy started: Project: LowInventoryWebPart, Configuration: Debug Any CPU ------

Active Deployment Configuration: Default

Run Pre-Deployment Command:

  Skipping deployment step because a pre-deployment command is not specified.

Recycle IIS Application Pool:

  Skipping application pool recycle because no matching package on the server was found.

Retract Solution:

  Skipping package retraction because no matching package on the server was found.

Add Solution:

  Adding solution 'LowInventoryWebPart.wsp'...

  Deploying solution 'LowInventoryWebPart.wsp'...

Activate Features:

  Activating feature 'Feature1' ...

Run Post-Deployment Command:

  Skipping deployment step because a post-deployment command is not specified.

========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========

The nice thing is that Visual Studio handles all the deployment as well as all the cleanup. When you close the debugger the feature is deactivated and the package is retracted and deleted. Notice that you can also specify pre and post deployment commands, plus a whole lot more. The Feature and Package designers are very flexible. (For more information watch this Channel 9 Interview: SharePoint Feature and Package Designers in Visual Studio 2010 and read Packaging and Deploying SharePoint Solutions in the MSDN library.)

In order to debug this sucker we first have to add it to a page on our site. When the debugger starts up, it opens a page to the site we specified in the SharePoint Customization Wizard in the beginning. So select Site Actions in the upper left, then Edit Page. Select the Insert tab on the Ribbon and click Web Part. Select the Custom category and you should see your web part. Select it and click Add on the bottom right of the section.

image

At this point you should hit your breakpoint. Hit F11 and the query will return the low inventory so you can see the data as you design the page. The Page_Load will get called a couple times when designing the web part so keep that in mind.

Next drop down the LowInventoryWebPart menu at the top right of the web part and select Edit Web Part to open the properties. Set the Title to “Low Inventory” and click OK. On the Page tab on the Ribbon select Save to save and close the page editor. Now we’ve got a nice looking web part for browsing low inventory. Sweet!

image

Close the browser window and this will close your debugging session, recycle the IIS app pool, deactivate the feature and retract the solution automatically for you. These steps are also displayed in the Output window.

Interacting with SharePoint using the Server Object Model

Well that was pretty easy to incorporate our LOB data into SharePoint with a simple web part and a data service but what if the user sees a critically low item and wants to add an item to the Task list? It would be nice if they could do it right here. The way we interact with SharePoint in a Visual Web Part is via the SharePoint Server Object Model. There are also SharePoint client object models as well; one for Silverlight clients and one for other .NET Framework clients. But because we are on the server when we are running a web part, we have access here to the server object model.

So let’s add a TextBox and a Button to our web part that allow the user to enter tasks directly onto the Task list. Go back to design mode on the Web Part, hit enter under the GridView and and type “Create Task:” under it. From the Standard tab on the toolbox, drag a Textbox onto the form then drag a Button and set its Text property to “Add”.

Double-click on the button and we can write this code in the Button1 click event handler to add a Task:

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    'Webpart code to Add to task list 
    Try
        Dim mySite As SPWeb = SPContext.Current.Web
        Dim listItems As SPListItemCollection = mySite.Lists("Tasks").Items

        Dim item As SPListItem = listItems.Add()

        item("Title") = Me.TextBox1.Text
        item("Assigned To") = mySite.AllUsers(Me.Context.User.Identity.Name)

        item.Update()
        Me.TextBox1.Text = ""
        Me.Label1.Text = "Your task has been added to the task list"

    Catch ex As Exception
        Me.Label1.Text = ex.ToString
    End Try
End Sub

The way we access the current SharePoint site by using the SPContext object and getting the Current.Web. Just like you have an HttpContext in ASP.NET development you have a SPContext in SharePoint development. So let’s test this one out. Put a breakpoint on the Button1_Click handler and hit F5 to deploy and debug. The second time around you don’t need to add the web part to the site page again but it will be refreshed with our new controls and code.

Now create a task by entering a description and click the Add button. The breakpoint will hit and you can debug the code and explore some of the server object model.

image

When you’re done, navigate to the task list to see that your task has been added.

image

This project is included in the Northwind OBA solution for VS2010 located here https://code.msdn.microsoft.com/OBANorthwind  so have a look. If you’re an ASP.NET developer just getting started with SharePoint development there’s still a lot to learn, but fortunately Visual Studio 2010 can help make an unfamiliar platform easier to approach with the right tools in hand.

Download Visual Studio 2010 Beta and read the walkthroughs here: https://msdn.com/vstudio

Enjoy!

Comments

  • Anonymous
    January 28, 2010
    It would be nice to be able to develop web parts for WSS off of the server. Will MS create a developer SDK that developers can install on their developer PC's (not a server) so they can develop and deploy web parts to a SharePoint server?

  • Anonymous
    January 29, 2010
    The comment has been removed

  • Anonymous
    January 29, 2010
    @Beth, what version of Vista will WSS 2010 run on? I'm running Vista with IIS 7 and SP2, also what version of Win 7 will WSS 2010 run on? Though I don't have it, I'm looking to possibly upgrade to it soon.

  • Anonymous
    January 29, 2010
    Hi Mike, You'll need 64-bit Windows 7 Professional or higher or 64-bit Vista SP1 or higher (not home edition). http://msdn.microsoft.com/en-us/library/ee554869(office.14).aspx

  • Anonymous
    March 13, 2010
    Hi Mike, you might want to take a look at the SharePoint SDK available here: http://www.microsoft.com/downloads/details.aspx?FamilyID=f0c9daf3-4c54-45ed-9bde-7b4d83a8f26f&displaylang=en It targets SharePoint 2010 Beta and can be used from Visual Studio 2010.

  • Anonymous
    April 02, 2010
    Hi Beth I am looking for sample of visual webparts for

  • connecting webparts
  • toolparts Thank you Max
  • Anonymous
    July 23, 2010
    Can you create webparts and deploy to a SharePoint 2007 server using Visual Studio 2010?

  • Anonymous
    July 27, 2010
    hi i am creating real estate web portal.i want to create wizard style web form using share point web portal.can any body help me how sharepoint web portal help me creating wizards in my portal

  • Anonymous
    August 25, 2010
    I want to access annoucement items to datalist. how can I access to visaul webpart

  • Anonymous
    September 22, 2010
    Is that possible to migrate the webpart created in vs 2008 to vs 2010

  • Anonymous
    September 25, 2010
    Sundarram, if you used VSeWSS to create your web part in VS2008, then you should take a look at a conversion tool that has been created that will help you migrate these projects into the new VS2010 structure.  You can find that tool here: code.msdn.microsoft.com/VSeWSSImport If you did not use VSeWSS, you will need to create a new, empty VS2010 project targeting SP2010 and then add a web part (or visual web part) to the project.  After that you can copy/paste your markup/code. Hope this helps, Mike Senior Program Manager - Visual Studio

  • Anonymous
    October 21, 2010
    Hi, I converted the webpart for VS 2010 using the VSeWss tool. The project is building with out any error and it also deployed sucessfully but when i try to add the webpart to the sharepoint website it throw the following error mesage "The directory is not a subdirectory of the root directory. (Exception from HRESULT: 0x80070090)" What could be causing this problem. Please advice

  • Anonymous
    October 21, 2010
    @Mike - like she said you can install SharePoint 2010 on your Win7/Vista Workstation by modifying the setup config file to ignore. here a link to it msdn.microsoft.com/.../ee554869.aspx really easy to do!

  • Anonymous
    February 14, 2011
    hi all.can anyone tell me how to upload pictures to picture gallery of sharepoint from asp page.

  • Anonymous
    February 28, 2011
    Beth, Thanks for the post. Do you know if its possible to create a custom Ribbon with a visual web part. It seems like it should be but the only examples I've found have been with the non-visual type. Thanks

  • Anonymous
    March 20, 2011
    Hi Beth This is very nice post. I need to ask you just one thing. As you have shown records for northwind traders, If i need to show data from xyz customlist then do i need to deploy again..? or is there any shortcut to update solution..?

  • Anonymous
    March 21, 2011
    @anonymous - yes you would need to update the service reference to the new service you wanted to use (in order to update the client proxy classes) and then redeploy.

  • Anonymous
    April 22, 2011
    That was good sample for start :) Thank you

  • Anonymous
    April 24, 2011
    The comment has been removed

  • Anonymous
    January 10, 2012
    The comment has been removed

  • Anonymous
    April 19, 2012
    Beth this is fantastic post. In my case I would would like to display a table in my UserControl that is populated with items in a SharePoint list after some processing. Since, the table you drag from the toolbox is going to be static at design time i.e I can't see how I can dynamically create rows and cells at runtime as I traverse my data. In this case should I be using a listview or Gridview and if so ... Can I easily apply my custom CSS? Thanks Daniel

  • Anonymous
    March 20, 2014
    unable to start debugging on the web server visual studio 2012 not able to debug SharePoint 2013 webpart Plz Give Me Some Solution For This Error !!! As Early As Possisible

  • Anonymous
    March 20, 2014
    Hi  Beth unable to start debugging on the web server visual studio 2012 not able to debug SharePoint 2013 webpart Plz Give Me Some Solution For This Error !!! As Early As Possisible

  • Anonymous
    October 08, 2014
    /hai can i ask how to create the dynamic stock inventory item using the vb.net framework 4.0