Saturday, July 12, 2008

Using User Control in Sharepoint Web Parts

Web parts are more complicated to implement than user controls. So often people will desire to use user control in web parts. In this case, I will create a user control which contains a repeater to show some information within a custom news list in a MOSS site.

Steps:

1. Create a user control called News.ascx. Make sure you specify this user control to inherit from the solution assembly. By the way, if you do not have a solution set up yet, I recommend you try out
STSDEV, this is what I am using in this example.

News.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="News.ascx.cs" Inherits="ATSDeploymentSolution.News,ATSDeploymentSolution, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ca6621b7467269f9" %>

<asp:Repeater ID="repNews" runat="server">

<HeaderTemplate>

<div>

</HeaderTemplate>

<ItemTemplate>

<div><%# Eval("ID") %>: <%# Eval("Title") %></div>

</ItemTemplate>

<FooterTemplate>

</div>

</FooterTemplate>

</asp:Repeater>



News.ascx.designer.cs

//------------------------------------------------------------------------------

// <auto-generated>

// This code was generated by a tool.

// Runtime Version:2.0.50727.1433

//

// Changes to this file may cause incorrect behavior and will be lost if

// the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------

Namespace ATSDeploymentSolution

{

/// <summary>

/// SimpleList class.

/// </summary>

/// <remarks>

/// Auto-generated class.

/// </remarks>

public partial class News {

protected global::System.Web.UI.WebControls.Repeater repNews;

}

}



News.ascx.cs

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Microsoft.SharePoint;

Namespace ATSDeploymentSolution

{

public partial class News : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Bind();

}

}

private void Bind()

{

using (SPSite site = new SPSite("http://w2k3sharepoint:43490"))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["ATSNews"];

repNews.DataSource = list.Items.GetDataTable();

repNews.DataBind();

}

}

}

}

}



2. Put this user control under the CONTROLTEMPLATES folder which is used to store all the user controls under the 12 hive. You can also notice from this image that I have created a feature called ATSDeploymentSolution which contains a bunch of web parts. ATSHomeNewsWebPart is the web part we will use to load the user control from.



3. Modify the manifest.xml to include this template file. The modified part is highlighed in red.

<?xml version="1.0" encoding="utf-8"?>

<!--Manifest created STSDEV utility at 22/05/2008 11:42:17 AM-->

<Solution SolutionId="4508B2DF-131A-4C52-A806-7C92AFD703A3" ResetWebServer="True" xmlns="http://schemas.microsoft.com/sharepoint/">

<!--Feature Manifest files-->

<FeatureManifests>

<FeatureManifest Location="ATSDeploymentSolution\feature.xml" />

<FeatureManifest Location="ATSWorkflow\feature.xml" />

<FeatureManifest Location="ATSNewsletterListEvents\feature.xml" />

</FeatureManifests>

<!--TEMPLATE files-->

<TemplateFiles>

<TemplateFile Location="IMAGES\ATSDeploymentSolution\AfricanPith32.gif" />

<TemplateFile Location="IMAGES\ATSDeploymentSolution\Thumbs.db" />

<TemplateFile Location="ControlTemplates\SimpleList.ascx" />

<TemplateFile Location="ControlTemplates\News.ascx" />

</TemplateFiles>

<!--Assembly files-->

<Assemblies>

<Assembly Location="ATSDeploymentSolution.dll" DeploymentTarget="GlobalAssemblyCache">

<SafeControls>

<SafeControl Assembly="ATSDeploymentSolution, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ca6621b7467269f9" Namespace="ATSDeploymentSolution" TypeName="*" Safe="True" />

</SafeControls>

</Assembly>

</Assemblies>

</Solution>


4. Specify the path of news.ascx in the SolutionPackage.ddf. The modified part is highlighed in red.

; Generated by STSDEV at 22/05/2008 11:42:17 AM

.OPTION EXPLICIT

.Set CabinetNameTemplate=ATSDeploymentSolution.wsp

.set DiskDirectoryTemplate=CDROM

.Set CompressionType=MSZIP

.Set UniqueFiles=off

.Set Cabinet=on

.Set DiskDirectory1=DeploymentFiles

;*** Solution manifest

DeploymentFiles\manifest.xml

;*** Assembly files

bin/debug/ATSDeploymentSolution.dll

;*** add files for ATSDeploymentSolution feature

.Set DestinationDir=ATSDeploymentSolution

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\Feature.xml

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts.xml

;*** add files for ATSDeploymentSolution\WebParts feature

.Set DestinationDir=ATSDeploymentSolution\WebParts

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSCompanySearchWebPart.webpart

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSEventSearchWebPart.webpart

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSGlobalSearchWebPart.webpart

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSHidePageWebPart.webpart

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSNewsletterSearchWebPart.webpart

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSNewsSearchWebPart.webpart

RootFiles\TEMPLATE\FEATURES\ATSDeploymentSolution\WebParts\ATSHomeNewsWebPart.webpart

;*** add files for ATSWorkflow feature

.Set DestinationDir=ATSWorkflow

RootFiles\TEMPLATE\FEATURES\ATSWorkflow\Feature.xml

RootFiles\TEMPLATE\FEATURES\ATSWorkflow\Workflow.xml

;*** add files for ATSNewsletterListEvents feature

.Set DestinationDir=ATSNewsletterListEvents

RootFiles\TEMPLATE\FEATURES\ATSNewsletterListEvents\Feature.xml

;***********************************

;*** Begin TemplateFiles section ***

;***********************************

.Set DestinationDir=IMAGES\ATSDeploymentSolution

RootFiles\TEMPLATE\IMAGES\ATSDeploymentSolution\AfricanPith32.gif

RootFiles\TEMPLATE\IMAGES\ATSDeploymentSolution\Thumbs.db

.Set DestinationDir="ControlTemplates"

RootFiles\TEMPLATE\ControlTemplates\SimpleList.ascx

RootFiles\TEMPLATE\ControlTemplates\News.ascx



5. Create the web part to load the user control we created.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

Namespace ATSDeploymentSolution

{

public class ATSHomeNewsWebPart : WebPart

{

News _news = null;

protected override void CreateChildControls()

{

base.CreateChildControls();

_news = (News)Page.LoadControl("~/_controltemplates/News.ascx");

Controls.Add(_news);

}

}

}



6. Create the webpart xml file and put it under the WebParts folder of the ATSDeploymentSolution Feature.

<?xml version="1.0" encoding="utf-8"?>

<!--Created by STSDEV at 8/05/2008 10:56:56 AM-->

<webParts>

<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">

<metaData>

<type name="ATSDeploymentSolution.ATSHomeNewsWebPart, ATSDeploymentSolution, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ca6621b7467269f9" />

<importErrorMessage>Error importing Web Part</importErrorMessage>

</metaData>

<data>

<properties>

<property name="Title" type="string">ATSHomeNewsWebPart</property>

<property name="Description" type="string">A webpart for news on the home page.</property>

<property name="ChromeState" type="chromestate">Normal</property>

<property name="AllowZoneChange" type="bool">True</property>

<property name="AllowHide" type="bool">True</property>

<property name="ExportMode" type="exportmode">All</property>

</properties>

</data>

</webPart>

</webParts>



7. Add ATSHomeNewsWebPart.webpart to the SolutionPackage.ddf file. This is highlighted in blue in the above code.

8. Add ATSHomeNewsWebPart.webpart to the Feature.xml of the ATSDeploymentSolution Feature. Highlighted in red.

<?xml version="1.0" encoding="utf-8"?>

<!--Created by STSDEV at 8/05/2008 11:12:24 AM-->

<Feature

Id="E152D451-1D60-4457-A3CE-C9FF4B110092"

Title="ATS Web Parts Feature"

Description="This SharePoint solution was created by the Sam Fu."

Version="1.0.0.0"

Scope="Site"

Hidden="false"

ImageUrl="ATSTestSolution\AfricanPith32.gif" xmlns="http://schemas.microsoft.com/sharepoint/">

<ElementManifests>

<ElementManifest

Location="WebParts.xml" />

<ElementFile

Location="WebParts\ATSCompanySearchWebPart.webpart" />

<ElementFile

Location="WebParts\ATSGlobalSearchWebPart.webpart" />

<ElementFile

Location="WebParts\ATSNewsSearchWebPart.webpart" />

<ElementFile

Location="WebParts\ATSNewsletterSearchWebPart.webpart" />

<ElementFile

Location="WebParts\ATSEventSearchWebPart.webpart" />

<ElementFile

Location="WebParts\ATSHidePageWebPart.webpart" />

<ElementFile

Location="WebParts\ATSHomeNewsWebPart.webpart" />

</ElementManifests>

</Feature>



9. Add ATSHomeNewsWebPart.webpart to the WebParts.xml which is the ElementManifest of the ATSDeploymentSolution Feature. Highlighted in red.

<?xml version="1.0" encoding="utf-8"?>

<!--Created by STSDEV at 8/05/2008 10:56:56 AM-->

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Module Name="ATSDeploymentSolution" List="113" Url="_catalogs/wp" Path="WebParts" RootWebOnly="True">

<File Url="ATSCompanySearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

<File Url="ATSGlobalSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

<File Url="ATSNewsSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

<File Url="ATSNewsletterSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

<File Url="ATSEventSearchWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

<File Url="ATSHidePageWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

<File Url="ATSHomeNewsWebPart.webpart" Type="GhostableInLibrary">

<Property Name="Group" Value="ATSDeploymentSolution" />

</File>

</Module>

</Elements>



10. Since I have deployed the solution before, I will choose DebugReploy from the Visual studio and build the solution. If you have deployed this web part before, you need to choose DebugUpgrade and build.

11. Add the web part to the page you want. This is the News List I had:



Here is the result:


Using user control in web parts

  • As you can see from the above example, using user control in web parts works just fine.
  • All you have to do is in CreateChildControls, load the user control and add it to the control tree.
  • And In OnPreRender, you can set public properties of the user control just like any other control.
  • Pros of using user control in web parts
    • Re-use user controls from other application
    • Easier for development than web parts
  • Cons
    • You now have a dependency between the news.ascx file and the solution assembly. If news.ascx is used in lots of different web parts, you may have a versioning issue.
  • You can also use SmartPart for loading user control in MOSS. It allows you to choose which user control to load at run time in the browser. Of course, you could extend the above example to do the same thing as well.
blog comments powered by Disqus