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.
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.
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:
Partial Public Class LowInventoryWebPartUserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'Webpart Code to display Low Inventory:
Dim ctx As New NorthwindEntities(New Uri("http://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()
Catch ex As Exception
Me.Label1.Text = ex.ToString
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.
Skipping package retraction because no matching package on the server was found.
Adding solution 'LowInventoryWebPart.wsp'...
Deploying solution 'LowInventoryWebPart.wsp'...
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 thisChannel 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.
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!
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
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)
Me.TextBox1.Text = ""
Me.Label1.Text = "Your task has been added to the task list"
Catch ex As Exception
Me.Label1.Text = ex.ToString
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.
When you’re done, navigate to the task list to see that your task has been added.
This project is included in the Northwind OBA solution for VS2010 located herehttp://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.