Building Web Parts the Smart WayStarting with the SharePoint SmartPartPatrick Tisseghem
Applies to:U2U Jan Tielens U2U
Building web parts is one of the main extensibility points when you work within a Windows SharePoint Services environment. The development steps of building SharePoint web parts is well-documented in books, in the Windows SharePoint Services SDK and in a whole set of articles, tutorials and walkthroughs available from the SharePoint community or from Microsoft directly itself. One of the major disadvantages of following the traditional web part development steps is that building web parts this way requires extensive coding with respect to the UI you want to provide within the web part. At the time of writing, there is no designer available for developers to create the body of a web part in a very WYSIWYG manner. This article describes another approach to building SharePoint web parts. The approach consists of making use of ASP.NET user controls to make up the body of the SharePoint web part. The technique leads to a dramatic increase in the productivity of anybody creating web parts. The article ‘Building Web Parts for Windows SharePoint Services - Part II : Web Parts and User Controls’ published here on the Belux MSDN site last year describes the basic steps. The idea of using ASP.NET user controls in web part development received a lot of adoption in the SharePoint community and has evolved in a generic framework called the SmartPart. In this article we will highlight what the SmartPart is and how to use it when involved in SharePoint web part development. Contents: What is the SmartPart?SharePoint web part developers can download the web part templates for Visual Studio .NET from the Microsoft download site. By installing these templates, one gets a base infrastructure to start with. However, most of the work still needs to be done by the web part developer. The biggest job is the creation of the user interface of the web part. Everything needs to be constructed at run-time since there is no designer helping with the creation of the web part UI. If you need a button on the web part, you will have to create the button object at run-time and take care of the event-handling and the rendering of the HTML. So, the drawback of the whole approach is that you have to develop your web part completely in code focusing very much on the non-business functionality of your web part. The SmartPart has been created to improve the productivity of SharePoint web part developers by leveraging the ASP.NET techniques and skills they normally master. As mentioned in the introduction, it builds on Patrick Tisseghem’s article last year introducing a technique of leveraging the use of ASP.NET user controls making up the body of web parts. Jan Tielens, together with Fons Sonnemans, and with the help of many people within the SharePoint community (including Maxim Karpov and others) have created the SmartPart. The SmartPart allows developers to create ASP.NET Web user controls and use these controls in SharePoint development. ASP.NET web user controls can be created by using the familiar designers available within Visual Studio .NET. So you can actually drag-and-drop controls, double-click to add event handlers. In summary, all the things you would expect in your development cycle. Developers using the SmartPart can again focus on their business code and don’t need to be experts in SharePoint. They can leverage their ASP.NET skills and in many cases, using the SmartPart, reuse existing user controls within the SharePoint sites very quickly ![]() How do I get the SmartPart?The SmartPart is an open source project. This means that you can download and use it for free! The SmartPart project is hosted on a GotDotNet Workspace, which you can visit by browsing for http://www.smartpart.info. Being on the GotDotNet workspace, navigate to the releases section of the workspace and download the latest version of the SmartPart. At the time of writing, the latest version is version 1.0.0.0. The download is a ZIP file which contains:
![]() Installing the SmartPartThere are two deployment scenarios for the SmartPart. You can during the installation decide to deploy the SmartPart in the global assembly cache (GAC), or decide to deploy the SmartPart as a private assembly associated with your SharePoint virtual server. The first scenario is the easiest one and is recommended. The deployment as a private assembly is a little bit more complicated since you have to change the security policy files associated with your SharePoint config file. For the sake of this article we will focus on the easiest and probably the most common scenario.
![]() Creating your first SmartPart projectTo demonstrate the basic steps of working with the SmartPart, we will guide you through a simple example. Follow the next steps to come up with a web part on your team site that displays the text typed into a textbox when the user clicks on a button. Step 1 – Create the ASP.NET user controlTo start you do not worry about SharePoint at all. You create a normal ASP.NET web application in which you will focus on building an ASP.NET user control and test it with a normal web page. Start Visual Studio.NET and create a new web project. Note: In our case, the web application is hosted on a virtual server listening to port 100 while the SharePoint sites are hosted on the default web site (listening to port 80). The ASP.NET user control can of course be developed on another machine than the one that hosts your SharePoint sites. ![]() Add a new web user control to the project, by choosing “Add Web User Control” from the Project menu. We have chosen to name it GreetingsControl.ascx for this example. ![]() The user control is very simple. We just have a text box, a button and a label on it. There is one line of code as the event-handler for the button. When clicking the button, a string is concatenated with the content of the text box and outputted in the label. ![]() private void buttonGreet_Click(object sender, System.EventArgs e)
{
labelMessage.Text = "Welcome " + textBoxMessage.Text;
}We can test the user control by a drag and drop operation of the ASCX file from the solution explorer onto the ASPX form. View the ASP.NET page in the browser and test the button. ![]() All of course very simple if you know your way around with ASP.NET. Your challenge now is to make the same functionality available as a web part within SharePoint. If you have not done any SharePoint development yet, this might seem like a daunting task. The SmartPart can help you accomplishing this without having to worry too much about your SharePoint skills. Step 2 – Deploying the ASP.NET user controlTwo components of the project you have started in step 2 need to be deployed on the SharePoint server. To start, the code-behind DLL (the result of the building of the project) can be deployed either in the GAC or as a private assembly for the SharePoint virtual server. We will opt for the latter approach. Just make a new subfolder (named Bin) of the folder that is associated with the virtual server hosting your SharePoint site. In our case this is the c:\inetpub\wwwroot folder since we have SharePoint up-and-running on the default web site. Copy the web application assembly in that new Bin folder. Secondly, the ASCX file associated with your user control also needs to be made available on the SharePoint server. There are two possibilities here. We will start with the simple one and in the next example we will cover another approach. The ASCX file (in our case greetingcontrol.ascx) can be dropped in the wpresource folder you will find in the folder associated with your virtual server. ![]() Step 3 – Using the SmartPartYou are ready now to jump to your SharePoint team site and the web part page where you want to have your user control wrapped into a web part. Drag and drop the SmartPart 1.0.0.0 web part on the home page. You can ignore the SmartPart List web part for now. ![]() To finalize this first example, you simple have to click the open the tool pane link in the web part and provide the path to the greetingscontrol.ascx file. ![]() The end result will be immediately visible when clicking
the OK button in the properties pane. ![]() So, without having done any SharePoint-related development, you have accomplished what was asked at the beginning. Your SharePoint site now hosts a web part that can greet people. As a starter this is probably a bit too simple for most of you, but it illustrates very well the effort it takes to build a web part when you start to use the SmartPart. The next example is going to be a bit more complicated and will require some interaction with content that is stored in a SharePoint events list. Using this second example you will experience the real power of the SmartPart. ![]() Talking to SharePoint from your SmartPartThis second example will require our user control to communicate with SharePoint through its object model. The goal is to display in a calendar control the different seminars or presentations that are stored in SharePoint in a normal events list. Step 1 – The SharePoint ListBefore starting with the user control development, we need to have a list in SharePoint storing the presentations we want to get displayed in the calendar control. This is a normal list based on the events list in SharePoint. ![]() Step 2 – Creating the Calendar ASP.NET User ControlThe second ASP.NET user control to create (in the same project as the one we have used in the first example) only consists out of a calendar control you drag and drop from the toolbox. Select maybe a template for the calendar using the auto format option in the properties box. By default, the dates are selectable. You can change this by implementing the DayRender event and by setting the IsSelectable property of a rendered date to false. private void Calendar1_DayRender(object sender,
System.Web.UI.WebControls.DayRenderEventArgs e)
{
e.Day.IsSelectable = false;
}We will come back to this event since this is the place where we will have the lookup in our SharePoint list to check whether one of our presentations is scheduled on the day to be rendered. To test the ASP.NET user control, we simply can drag and drop it again on our web form. ![]() Step 3 – Deploying the ASP.NET User Control as Web PartWe could follow the same steps as before to deploy the user control and make it available within SharePoint. However, there is also a SmartPart List web part within your virtual server gallery of web parts. What is the purpose of this version of the SmartPart? There is actually no real difference with the one you have used before except that this version of the SmartPart provides you with a list of user controls you can select one from. So you do not have to type anymore the path to the user control. You loose some flexibility since you have to deploy the ASCX file now in a very specific folder in order for the SmartPart List to offer you the selection, but it avoids you typing in the user control path. The folder monitored by the SmartPart List is the UserControls folder and you have to create it since it does not exist by default. That is not the only thing you need to do. You also need to define the UserControls folder as a managed path that needs to be excluded from any SharePoint-related activity. This is an administrative procedure that is documented in Patrick’s second article discussed during the introduction. ![]() When done, you can drag and drop the SmartPart List to your web part page and open the tool pane again. The SmartPart List shows you in a combo box the list of ASCX files that are available in that usercontrols folder. In our case, we can now select the calendarcontrol from the list. ![]() Have we accomplished our goal? No, not yet. From within our user control, we need to be able to retrieve the list of presentations that are stored in that SharePoint list and use the information to adapt the calendar control. Step 4 – Connecting SharePoint with our User ControlThe developer of the ASP.NET user control has two ways of grabbing the list of presentations out of the SharePoint list. One way would be to make use of the Web services that are exposed by SharePoint. Certainly the list.asmx could be helpful in our situation here. However, since we have our ASP.NET user control wrapped into a web part, we should be able to communicate directly with the SharePoint context using the SharePoint object model. A reference to the SPWeb (that is the class that gives us access to the contents of the site such as the lists and document libraries) can be passed from the SmartPart to your user control IF you implement a specific interface. The interface to implement is the IUserControl interface available via the SmartPart assembly. ![]() So the thing to do within our user control is to first set a reference to the SmartPart assembly that is included in the zip you have downloaded. ![]() Next, you go to the user control code-behind class and implement the SmartPart.IUserControl interface. The interface is not that complex. Only one member has to be implemented. public class CalendarControl : System.Web.UI.UserControl, SmartPart.IUserControl
{
. . .
#region IUserControl Members
public Microsoft.SharePoint.SPWeb SPWeb
{
get
{
// TODO: Add CalendarControl.SPWeb getter implementation
return null;
}
set
{
// TODO: Add CalendarControl.SPWeb setter implementation
}
}
#endregion
}The member that we need to implement is the SPWeb property. It is a property that will be set by the SmartPart when it initializes the web part. You will use the reference passed by the SmartPart in order to set up a communication with SharePoint. Therefore, you must store the reference in a local private variable. The SPWeb type is part of the Microsoft.SharePoint.dll and thus a reference to that assembly also needs to be set. public class CalendarControl : System.Web.UI.UserControl, SmartPart.IUserControl
{
. . .
private Microsoft.SharePoint.SPWeb _web;
#region IUserControl Members
public Microsoft.SharePoint.SPWeb SPWeb
{
get
{
return this._web;
}
set
{
this._web = value;
}
}
#endregion
}Delegating the setup of the communication infrastructure with SharePoint to the SmartPart, we can now focus on finishing the user control by adding more code to the DayRender event-handler. The code is just a lookup in the list of presentations so that we can display the title of the presentation and the hour it starts in the rendered cell of the calendar control. Here is the code that will take care of this. After retrieving the reference to the list itself, we can loop over the different list items and get the one we need. private void Calendar1_DayRender(object sender,
System.Web.UI.WebControls.DayRenderEventArgs e)
{
e.Day.IsSelectable = false;
Microsoft.SharePoint.SPList list = _web.Lists["Seminars"];
foreach(Microsoft.SharePoint.SPListItem item in list.Items)
{
DateTime start = DateTime.Parse(item["EventDate"].ToString());
if(start.ToShortDateString() == e.Day.Date.ToShortDateString())
{
Label lbl = new Label();
lbl.Text = "<BR>" + item["LinkTitle"].ToString();
e.Cell.Controls.Add(lbl);
}
}
}After you build the user control project again, you need to simply redeploy your .NET assembly to the Bin directory. One final thing we need to do in order to get it all working is to increase the trust level in the web.config of the SharePoint site from WSS_Minimal to WSS_Medium. Since we are talking to the object model from within our code and we deploy as a private assembly, you need to take care of this to get it working. <trust level="WSS_Medium" originUrl="" /> This concludes the second example of the use of the SmartPart as container of your ASP.NET user controls. ![]() ![]() ConclusionI hope we have convinced you with this article that when you are building web parts for SharePoint, you should have a look at the SmartPart. Building web parts using the SmartPart allows you to concentrate on the stuff that matters when building web parts for SharePoint v2, the business that’s driving it and not spend too much time building the user interface. The best news is that all of this is community work and you simply get all of this for free. So, the only advice we can give you is to download the SmartPart and give it a try. ![]() About the authors
| ||||||||||||