Malek's Moorish Tales

Meanderings about life and technology

Web Parts as Custom Web Controls (or almost...)

I will continue on the Office System series with this very simple exemple of how one can write Web Parts just as one would write any ASP.Net Custom WebControl. The only difference is that you don't override the Render Method, but the RenderWebPart method instead (this allows for the Web Part predefined functionnality like dragging and dropping the Web Part within the Web Part Page in Windows SharePoint Services sites or SharePoint Portal Server sites, as well as the integration within the Web Part Framework and use of the WebPart Tool panes ...etc.). example in C# (A reference to Microsoft.SharePoint.dll and to System.Data.dll are needed):

using System;
using
System.ComponentModel
using
System.Web.UI; using System.Web.UI.WebControls;
using
System.Xml.Serialization;
using
Microsoft.SharePoint;
using
Microsoft.SharePoint.Utilities;
using
Microsoft.SharePoint.WebPartPages;
namespace
MyWebPartsLibrary
{

[ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>"),
XmlRoot(Namespace="MyWebPartsLibrary")]
public class WebPart1 : Microsoft.SharePoint.WebPartPages.WebPart
{

private DataGrid myAuthorsGrid=new DataGrid();
protected override void RenderWebPart(HtmlTextWriter output)
{

myAuthorsGrid.DataSource=getAuthors().Table[0];
myAuthorsGrid.DataBind();
myAuthorsGrid.RenderControl(output);

}
private DataSet getAuthors()
{

System.Data.SqlClient.SqlConnection cnn = new System.Data.SqlClient.SqlConnection("data source=localhost; initial catalog=pubs; integrated security=SSPI");
System.Data.SqlClient.SqlDataAdapter adapt =
new System.Data.SqlClient.SqlDataAdapter("select * from authors", cnn);
System.Data.DataSet result =
new System.Data.DataSet();
adapt.Fill(result);
return result;

}

}

}

As for all Office System Solutions, there must be a manifest that is signed with a digital certificate (that's the basis of all security configurations and policies for Office System solutions) that references the dll as follows :

<?xml version="1.0"?>

<!-- You need only one manifest per CAB project for Web Part Deployment.-->

<!-- This manifest file can have multiple assembly nodes.-->

<WebPartManifest xmlns="http://schemas.microsoft.com/WebPart/v2/Manifest">

<Assemblies>

<Assembly FileName="MyWebPartsLibrary.dll">

<SafeControls>

<SafeControl Namespace="MyWebPartsLibrary" TypeName="*" />

</SafeControls>

</Assembly>

</Assemblies>

<DwpFiles>

<DwpFile FileName="WebPart1.dwp"/>

</DwpFiles>

</WebPartManifest>

 

To install the Web Part in SharePoint, a CAB file has to be created (Setup Project) and the utility stsadmn.exe is used for installation as follows :

stsadm –o addwppack –MyWebPartLibrary.dll

 

 

Add comment

biuquote
  • Comment
  • Preview
Loading