The concept of WebParts as a reusable, adaptable device for creating flexible products is one of the most important contributions of SharePoint to contemporary, web-oriented software development. WebParts were introduced in SharePoint 2001 and have been maintained through subsequent platforms. The current SharePoint version (2007) preserved the WebParts NameSpaces legacy from the 2003 version and allowed for the new NameSpaces from DotNet 3.0.
Technically speaking, WebParts are an inheritance of WebControls with extra, enhanced features to ensure their usability in web applications. One augment is the WebParts’ user control panel that allows for configurating and adapting the function and layout of the WebPart in an undemanding way. The upshot is that WebControls and WebParts operate in the same manner inside SharePoint and can run equally well in its context. The primary difference between them—apart from the control panel—is that WebParts must reside in a Web Zone ‘container’ in the Web page whereas WebControls can be localized wherever you want them. It is precisely this flexibility that makes WebControls a favored way to implement menus in the SharePoint interface.
There are a number of places in a SharePoint Portal where custom WebControls could be useful. Each page, for instance, might have a company logo and basic information. This can be realized by using the master page infrastructure; however, if the information isn’t the same for every customer (the client’s name is included in the title, for example), it is necessary to use a WebPart or a WebControl. Because the logo and relevant information are not placed in a WebZone within the page, using a WebPart is not convenient; in this case, a WebControl is the ideal solution (note that this is an example: in the real world of SharePoint, the logo and title are implemented as WebControls).
In the realm of Enterprise Content Management (ECM) and Web Content Management (WCM) projects, there are additional characteristics of WebControls waiting to be exploited. Because WebControls cannot be accessed or configured by users once they have been installed, they are not security-sensitive. Imagine a hypothetical company where management has made a request that falls outside SharePoint’s default possibilities; in this instance, it involves a web content page whereby a particular user group should be advised of a disclaimer clause. Creating the text can be achieved by using a WebControl precisely in the targeted page informing the current user as to his/her user group status and displaying the disclaimer clause when appropriate.
Creating a WebControl
WebControls are created as a DotNet 2.0 or 3.0 managed Web Control Library in Visual Studio; it is possible to use Visual Studio 2005 or 2008 for the task, but the example code will be created using the 2008 version. The first step is to open a new project of the type “ASP.NET Server Control” in Visual Studio and, standard procedure, configure the name of the project and the class and add the references and “using” statements for SharePoint. In the example, the WebControl project will be named “Disclaimer” and the working class “DisclaimerWebCustomControl”:
Figure 1: Visual Studio with the generated WebControl project
To configure the users group, the WebControl will have a custom property (“DisplayForGroup”). the disclaimer text will also be configured and saved in the property (“DisclaimerText”). The Visual Studio template generates a default “Text” property that can be used for the first property of the sample:
[Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string DisplayForGroup { get { String s = (String)ViewState["DisplayForGroup"]; return ((s == null) ? String.Empty : s); } set { ViewState["DisplayForGroup"] = value; } }
And the second property takes a similar shape:
[Bindable(true)] [Category("DisclaimerText")] [DefaultValue("Disclaimer: This is a Disclaimer")] [Localizable(true)] public string DisclaimerText { get { String s = (String)ViewState["DisclaimerText"]; return ((s == null) ? String.Empty : s); } set { ViewState["DisclaimerText"] = value; } }
The main function only looks at the current user and his/her groups, compares it with the group in the property, and displays the disclaimer if the user belongs to the target group:
protected override void RenderContents(HtmlTextWriter output) { SPWeb myWeb = SPControl.GetContextWeb(Context); foreach (SPGroup myGroup in myWeb.CurrentUser.Groups) { if (myGroup.Name.ToLower() == DisplayForGroup.ToLower()) Write(DisclaimerText); } }
As always, take special care in error handling: If an exception occurs and it is not dealt with, the stability of the system can be compromised. Every potential error-prone situation must be addressed with care and resolved with finesse. Exceptions can be shown on the page or logged to the Server’s Event Viewer.
Finally, open the “AssemblyInfo.cs” file from the “Properties” directory of the Visual Studio project and change the “assembly: AssemblyVersion” to “1.0.0.0”.
Sign the assembly with a safe name: In Visual Studio, select the properties of the project, go to the “Signing” tab and select the check box “Sign the assembly”. After choosing “New” from the “Choose a strong name key file” combo box, insert a name in the “Key file name” spot, uncheck “Protect my key file with a password”, and accept all the changes.
After compilation, the assembly can be installed in the GAC or in the bin directory of the IIS root of the SharePoint Application. In this example, the second approach will be employed: copy the assembly to the directory “C:InetpubwwwrootwssVirtualDirectories80bin” in the server. Note that the name of the IIS root can be different (the name was produced at the time of configuration when the Application was created), and that the “bin” directory is not created by default (you can add it, if it is not present).
WebControls can be debugged as any other DotNet component: Install and configure the control in a page (described in the next section), run the page at least one time, and then you will able to attach the worker process (“w3wp.exe”) to the debugger in Visual Studio.
Installating and Configurating the WebControl
WebControls need to be installed and configured in the hosting content aspx file. In the SharePoint Site where the page is shown, create a new “Basic Page” (“Site Actions” – “Create”), selecting a name and the Library where the page will reside. Then, proceed to the chosen Library and download a copy of the created “Basic Page” to the local machine. Open the copy using an ASCII text editor (or Visual Studio), and add a registration statement at the beginning of the page:
<%@ Register TagPrefix=" DisclaimerControl" Namespace="Disclaimer.DisclaimerWebCustomControl" Assembly="Disclaimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f86952eb89b3f2ea" %>
The “PublicKeyToken” can be found with the “sn” Visual Studio tool with the parameter “-T”. At the point on the page where the disclaimer will be displayed, an instance of the WebControl can be added, in this case, at the end of the Content PlaceHolder table:
<tr> <td> <DISCLAIMERCONTROL:DisclaimerWebCustomControl DisplayForGroup="Viewers" DisclaimerText="This is the Disclaimer Text" runat="server" /> </td> </tr>
The instance of the control shows the text of the “DisclaimerText” property to the users who belong to the group configured in the “DisplayForGroup”.
The control must be registered as a safe control in the web.config file of the IIS root Application to be allowed access. Open the “C:InetpubwwwrootwssVirtualDirectories80web.config” file (the path can be different in each server), and add a new entry in the “<SafeControls>” section:
<SafeControl Assembly="Disclaimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f86952eb89b3f2ea" Namespace="Disclaimer" TypeName="*" Safe="True" />
This is achieved using the same parameters as in the registration in the .aspx page. If the code requires special rights, it is possible that the “trust level” of the web.config needs to be adapted or, preferably, that a custom policy grants only the necessary rights.
From the Library where the WebPage was created, upload the edited .aspx page (the original .aspx will be overwritten). If an individual who is included in the configured users group uses the page, the disclaimer will be shown:
Figure 2: The page with the disclaimer text
Note: A user outside the authorized group views the same page minus the disclaimer.
Be aware that WebControls, as with WebParts, run under SharePoint and the user context. Consequently, user rights are determined by SharePoint and a “normal” user is unable to read or modify certain information in the system. But all the ‘tricks of the trade’ used with WebParts can be also be applied to WebControls, and any of the Impersonator possibilities present in SharePoint can be exploited.
Of Note
In the example, you used a SharePoint aspx “Basic Page”, because it is easy to manipulate without risk to the system. The downside of this approach is that you need to modify each newly created page to add the WebControl; to avoid this problem, create a template with the WebControl already in place. Applying the same principle, it’s possible to use a SharePoint “Web Part Page” that contains more (sub) templates that are easier to modify than the “Basic Page”.
One or more of the default aspx SharePoint pages may also be used. They reside in the “12 hive” of the file system in the server (“C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12TEMPLATELAYOUTS”); they can be edited with any ASCII text editor (Notepad or Visual Studio). This brings the WebControl directly into the SharePoint structure; Microsoft does not recommend this approach because future Service Packs can override the modified ASPX pages without warning.
SharePoint uses numerous WebControls to manipulate information in the pages. They are located in the code of the ASPX pages in the aforementioned “12 hive” and, of course, they can be reused: Take the already made registration from the beginning of the page, place the control wherever you need it; it will begin to work. Be aware that there are two types of controls: the WebControls for WSS (Microsoft.SharePoint.WebControls) and the controls for MOSS (Microsoft.SharePoint.Portal.WebControls); the controls from the WSS system can be used in a MOSS installation, but the other way around is not possible.
Modifications in the parameters of existing and placed WebControls in default aspx pages are also possible, with the same warning as before: A future Service Pack can roll back the modifications. Normally, the default WebControls in SharePoint does not use all the programmed parameters or they use it in a “default” way. If you need to edit parameters, open the ASPX page and modify it. An example of this approach is the modification of the “MyProfile” in “My Site” in MOSS: The control “ProfilePropertyLoader” in the “editprofile.aspx” page takes care of the data presentation in the window; this control contains many parameters not used in the default page presentation, but you can exploit them to modify the layout and, for example, render the information in sections as appears in the Profile DataBase screen in Central Administration.
Default SharePoint WebControls can be reused. If you need to add or delete functionality in default WebControls, it is—in general—possible to subclass them in Visual Studio through inheritance. The only condition is that the original WebControl has not been marked as “sealed”. Again, if a Service Pack modifies the control interface and the subclass uses the original, the new control will not function. Another disappointment is the lack of information available from Microsoft: The SharePoint SDK gives only summary information about the implemented WebControls, thus developers are on their own to discover the correct configuration parameters.
Finally, because WebParts inherit from WebControls, they can be “appropriated” to function as WebControls: Install the WebPart in the conventional way in SharePoint; and, in the target ASPX page, register the WebPart in the same way as a WebControl:
<%@ Register Tagprefix="[TagName]" Namespace="[NameSpace WebPart]" Assembly="[Name assembly WebPart], Version=[Version WebPart], Culture=neutral, PublicKeyToken=[KeyToken WebPart]" %>
And in the location where it will be used, add the WebPart as a WebControl:
<[TagName]:[ClassName] id="MyWebPartId" runat="server"> <WebPart > <Title>Title-WebPart</Title> <FrameType>None</FrameType> </WebPart> </[TagName]:[ClassName]>
For the properties of the WebPart within the registration (“Title” and “FrameType” in the example), use the same value as for the registration of the WebPart (file “.webpart” for SharePoint 2007 of “.dwp” for 2003). The configuration panel of the WebPart, obviously, cannot be used, but this is a nice way to reuse functionality in an easy way.
Summary
In the preceding pages, developers have been offered a versatile tool to automate tasks under SharePoint. WebControls go into motion when activity is occurring in the Portal and do mechanized tasks in the Interface. In the SharePoint infrastructure, WebControls are equivalents to WebParts; moreover, as shall become evident, WebControls have unique benefits for developers and designers. However, as with all systems, there are downsides that must be examined as well.
WebControls are the basis for WebParts and are able to maneuver in places WebParts cannot reach, namely, outside the Web Zones. For ECM systems, they also guarantee assignments are done without human intervention; thus ensuring enterprise rules are strictly enforced. WebControls create reusable components that can be applied across the Portal and shared among different pages; additionally they can inherit from another control and extend that functionality.
Download the Code
You can download the code that accompanies this article here.
About the Author
Gustavo Velez is a MCSD Senior Application Developer for Winvision (http://www.winvision.nl), a Microsoft Gold Partner in the Netherlands. He has many years of experience developing Windows and Office applications, and more than five years of daily programming experience with SharePoint. The author’s articles can be found in many of the leading trade magazines in English, Dutch, and Spanish. He is also pleased to be Webmaster of http://www.gavd.net/servers, the only Spanish-language site dedicated to SharePoint. Spanish-language readers may want to consult Velez’s new book, Programación con SharePoint 2007 (http://www.dotnetmania.com/CTdnm/index.html).