Developing a custom User Control for SharePoint 2010
The purpose of the tutorial is to demonstrate how to create a custom User Control for SharePoint using Visual Studio 2010. The example User Control generates and displays a title of the site, list and item/page if applicable, and can be placed on an Application Page, Master Page or an aspx page on SharePoint 2010 sites.
After creating the User Control, an Application Page is added to the project to demonstrate including the custom control on a page. A example is also included for adding the control to a Master Page using SharePoint Designer 2010 once the solution has been packaged and imported/deployed into the SharePoint Farm.
Creating the Custom User Control:
Open Visual Studio 2010 and start a new empty SharePoint Project. For the purpose of this demonstration, I am calling the Project "SP2010_UserControl_Example"
Select the "Deploy as a farm solution" option when asked to specify the security level for debugging.
Select the Add a new item from the Project Menu or from the Right Click menu on the Solution Explorer, then select the User Control option from the list of SharePoint 2010 templates.
I have given the name DyncamicSIteTitle.ascx. Press the Add button to add the User Control to the project.
In the new DyncamicSiteTitle.ascx file added to the project, add the following <div> tag to the page under the last line containing <% ... %>.
<div class="dynamic-title">
</div>
Inside the div element, add a Label control from the toolbox, and change the value of the ID attribute to "myLabel". Remove the default text from the label by clearing the contents of the "Text" attribute. The final markup should then look something like:
<div class="dynamic-title">
<asp:Label ID="myLabel" runat="server" Text=""></asp:Label>
</div>
Open the .ascx.cs file for the User Control (DyncamicSIteTitle.ascx.cs).
At the top of the class file, add the following using statements to include functionality that we required for the User Control.
using Microsoft.SharePoint;
using System.Text;
using System.IO;
Inside the Page_Load() Method for the class, paste the following code. Comments have been included throughout the code to help explain what it is doing:
//Get the SPWeb object for the current site using SPContext
SPWeb myWeb = SPContext.Current.Web;
//Instantiate the string variables used to store components of the dynamic title.
String displayTitle = "";
String siteTitle;
String listTitle;
String pageTitle;
String itemTitle;
//Get the title of the current site
siteTitle = myWeb.Title;
//Get the Title of the current List (If applicable)
try { listTitle = SPContext.Current.List.Title; } catch { listTitle = null; }
//Get the title / Display Name of the current List Item if applicable
try { itemTitle = SPContext.Current.ListItemDisplayName; } catch { itemTitle = null; }
//Get the title of the current page from the Page Title Master Page Placeholder (PlaceHolderPageTitle)
Control c = Page.Master.FindControl("PlaceHolderPageTitle");
//Create a StringWriter Object to store the value inside the Page Title Placeholder
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter write = new HtmlTextWriter(stringWriter))
{
//Render the control to obtain the contents of the Place Holder
c.RenderControl(write);
}
//Store the text from the StringWriter object in the itemTitle variable.
pageTitle = stringWriter.ToString();
//Start populating the displayTitle variable with the dynamic title
//Add the Title of the site as a link to the site homepage
if (siteTitle != null)
{
displayTitle += "<a href="" + myWeb.Url + "" class="dynamic-title-link">" + siteTitle + "</a>";
}
//Append the title of the current list if available as a link to the default view for the list
if (listTitle != null)
{
displayTitle += " - <a href="" + SPContext.Current.List.DefaultViewUrl + "" class="dynamic-list-link">" + listTitle + "</a>";
}
//Append the title of the item if applicable, or the title of the page (value from the Page Title Place Holder)
if (itemTitle.Length > 0)
{
displayTitle += ": <span class="dynamic-item-link">" + itemTitle + "</span>";
}
else if (pageTitle.Length > 0)
{
displayTitle += ": <span class="dynamic-item-link">" + pageTitle + "</span>";
}
//Set the text value of the myLabel control to the value stored in the displayTitle variable
myLabel.Text = "<div class="dynamic-title">" + displayTitle + "</div>";
Application Page with Custom User Control
To test and demonstrate the custom User Control, I am now going to add an Application page to the project that includes the user control in the content of the page.
Right click on the main solution from the Solution Explorer window and select Add -> New item. Select the Application page from the list, and give it a name (eg. UserControlTestPage.aspx ). This will include a reference to the layouts folder with the new Application page contained in a sub-folder with the same name as the solution.
At the top of the Application page, under the existing lines containing <% … %> add the following line. This registers the custom user control with a tagname and prefix on the page so that it can be included in the page content:
<%@ Register TagPrefix="cust" TagName="myDynamicTitle" src="~/_controltemplates/SP2010_UserControl_Example/DynamicSiteTitle.ascx" %>
If you are using a different name for your solution or User Control, update the reference to the correct User Control .ascx file.
Add the following to the Main content placeholder on the page (PlaceHolderMain):
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<cust:myDynamicTitle id="myPageTitle1" runat="server" />
</asp:Content>
Open Test Application Page by default when testing/debugging the solution (Optional)
Right click on the Application page in the Solution Explorer and select the "Set as startup item" option. This will result in the Application page loading when testing/debugging the solution in SharePoint 2010. If you choose not to complete this step, you will need to manually enter the address of the Application page into your browser once it has been deployed to the SharePoint Environment for debugging.
Save the project and select the "Start Debugging" option from the Debug menu (or press F5).
If the solution is deployed successfully, the Application page should automatically load in a browser window if you completed the optional step above. The dynamic title should be included as the only content on the Application page.
If you package the solution and import into your SharePoint 2010 environment, the custom User Control will be available for use on any aspx page, or Master Page using the same method as what was used to include the custom control on the Application page.
Add the Custom User Control to a Master Page in SharePoint 2010 using SharepOint Designer
Open the root site in your SharePoint 2010 environment using SharePoint Designer 2010
Select the Master Pages option from under the list of Site Objects on the navigation menu. Make a copy of the default Master Page v4.master, and give the copy a new name.
Similar to registering the Custom User Control on the Application page earlier in the tutorial, you need to paste the following line at the top of the Master Page under the existing @Register / @import tags:
<%@ Register TagPrefix="cust" TagName="myDynamicTitle" src="~/_controltemplates/SP2010_UserControl_Example/DynamicSiteTitle.ascx" %>
Similar to adding this tag to the Application page, you will need to ensure that the reference to the User Control (.ascx) file points to the User Control you have created. Once you have done this, you can place the following tag anywhere on your Master Page, which will display the Dynamic Title User Control created in this article:
<cust:myDynamicTitle id="myPageTitle1" runat="server" />
In this example, I have replaced the contents of the "PlaceHolderSiteName" tag with the dynamic site title user control:
<asp:ContentPlaceHolder id="PlaceHolderSiteName" runat="server">
<cust:myDynamicTitle id="myPageTitle1" runat="server" />
</asp:ContentPlaceHolder>
After saving and applying the new Master Page to a site in your site collection, the Dynamic Site Title User Control will be inserted where the Title of the site usually would be on the default (v4.master) Master Page.
Additional information about Packaging and Deploying a solution with a Custom User Control and Application Page
Components of a Custom SharePoint Solution that are included in Mapped Folders such as the ControlTemplates and Layouts folders can be included as part of the package to be deployed to a SharePoint Environment. The mapped folders included in the project become part of the Solution Package, and can be added or removed using the Package Designer. Features added to the project are also included in the package for the solution. By default, Custom User Controls are added to the ControlTemplates mapped folder and Application Pages added to the Layouts folder. When you are adding items from a solution to a feature, you will may not find some types in the list of items to add, as they are to be included as part of the package instead. Deployment paths for items in the solution can also be managed using the "Deployment Location" properties for the file if required.
Information about deploying a solution package (.WSP file) with a custom User Control is available from the following article:
Using PowerShell to deploy SharePoint Solutions (WSP)
This article covers both how to import a solution package (.wsp) into a SharePoint 2010 environment using PowerShell and the equivalent process to import a .wsp package into a SharePoint 2007 (MOSS) environment using stsadm.
As a side note to the section about creating an Application Page i SharePoint, the following provide additional information to help with Securing the application page based on user permissions:
Application Page Security for SharePoint
This article explains how to integrate security and permissions into an Application Page by validating requests using FormDigest and selecting the correct layout page base class that contains methods and properties to control access to the page. Permisisons from the SPBasePermissions Enumeration are used to implement security in some cases. The article provides some of the the basic requirements when securing Application Pages and reference to more detailed tutorials and documentation relating to securing application pages in SharePoint.
By GeorgeH on October 28, 2011 9:14PM