Thursday, July 15, 2010

Create custom web part in .net

In order to deploy webparts on sharepoint server, one approach is to create a custom web part and then just keep including the custom web part on the page and giving the path of you own user control in it as parameter.
Create a project in VS -

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;

namespace GeneralWebPart
{
public class GeneralWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
public GeneralWebPart()
{ }

private Control _childControl = null;
private string _userControlVirtualPath = string.Empty;
private string _errMessage = string.Empty;

[
Personalizable(),
Category("Virtual Path"),
DefaultValue(""),
WebBrowsable(true),
WebDisplayName("User Control Virtual Path"),
WebDescription("User Control Virtual Path")
]
public string UserControlVirtualPath
{
get { return _userControlVirtualPath; }
set { _userControlVirtualPath = value; }
}
protected override void CreateChildControls()
{
base.CreateChildControls();

if (_userControlVirtualPath != string.Empty)
{
if (_childControl != null) return;
_childControl = Page.LoadControl(_userControlVirtualPath);
if (_childControl != null)
Controls.AddAt(0, _childControl);
}
}

protected override void RenderWebPart(HtmlTextWriter output)
{
if (_errMessage != string.Empty)
output.Write(_errMessage);
if (_userControlVirtualPath != string.Empty ||
_userControlVirtualPath.Equals("") == false)
RenderChildren(output);
}

protected override void RenderChildren(HtmlTextWriter output)
{
try
{
this.EnsureChildControls();
if (this._childControl != null)
this._childControl.RenderControl(output);
}
catch (Exception ex)
{
_errMessage = string.Format(
"Exception Message (RenderWebPart) = {0}
", ex.Message);
}
}
}
}


Deploy this on the server. Moving forward give the path of your user control in this web part.
In order to deploy this, copy the dll to the GAC, make an entry in the web.config's safe controls section. After you add this to the safe controls section, the web part is available in the list of web parts. You can then include it in your web parts.

No comments:

Post a Comment