Friday, November 14, 2008

Loading and Displaying a Web User Control Within a Microsoft SharePoint 2007 (MOSS 2007) Web Part

Hi there,

Here is the source code of a custom Web Part that loads and displays a Web User Control within a Microsoft Office SharePoint Server 2007 WebPart. The Web User Control should be copied to a sub folder named "UserControls" under the root virtual folder of your Microsoft Office SharePoint Server 2007 site, and the name of the web user control should be mentioned in the web part settings tab of this web part.

You can take and use this code in whatever way you want FOR FREE :) but if you think that this code saved your day, or that you can make millions of dollars with this code, you owe me a beer :D :) ;)

Cheers!



// ------------ Start ----------------- : -

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;

namespace WebUserControlWebpart
{
/// <summary>
/// Displays a custom web user control within a
/// Microsoft Office SharePoint Server 2007 Web part.
/// </summary>
public class WebUserControlWebpart : System.Web.UI.WebControls.WebParts.WebPart
{
private const string USER_CONTROL_SUBFOLDER = @"\UserControls\";

private string m_strUserControlPath;
private string m_strUserControlName;
private string m_strErrorHTML;

private System.Web.UI.Control m_objUserControl;

/// <summary>
/// Default constructor.
/// </summary>
public WebUserControlWebpart()
{
this.m_objUserControl = null;
this.m_strUserControlPath = null;
this.m_strErrorHTML = string.Empty;
}


[Personalizable(PersonalizationScope.Shared),
WebBrowsable(true),
WebDisplayName("Web User Control Name (e.g. ucMyUserControl.ascx )"),
WebDescription("Web User Control Name (e.g. ucMyUserControl.ascx ). " +
"It should be present in a subfolder named 'UserControls', " +
"subfolder named 'UserControls', under the root under the " +
"root virtual folder."),
Category("Web Part Settings"),
DefaultValue("")]
public string UserControlName
{
get
{
return m_strUserControlName;
}
set
{
this.m_strUserControlName = value;

if(value != null && !value.Equals(string.Empty))
this.m_strUserControlPath = USER_CONTROL_SUBFOLDER + value;
}
}



/// <summary>
/// This method of the WebPart base class is overriden to
/// load a web user control and add it to the controls collection
/// of this web part, so that the said web user control can be
/// displayed within this web part. The web user control will be
/// loaded only if its path has been assigned to the
/// "m_strUserControlPath" variable of this class.
/// </summary>
protected override void CreateChildControls()
{
try
{
if (this.m_strUserControlPath != null
&& ! this.m_strUserControlPath.Equals(string.Empty))
{
this.m_objUserControl =
this.Page.LoadControl(this.m_strUserControlPath);

this.Controls.Add(m_objUserControl);
}
base.CreateChildControls();
}
catch (Exception ex)
{
this.PublishException(ex);
}
}


/// <summary>
/// This method of the WebPart class is overriden to render the
/// web user control (whose path is assigned to "m_strUserControlPath"
/// variable of this class) within this web part. If an error has
/// occured then the "m_strErrorHTML" variable of this class will
/// not be null or empty and that text/Html will be displayed instead
/// of the web user control.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlTextWriter output)
{
const string DEFAULT_TEXT =
"Please specify the name of the web user control to display";

try
{
this.EnsureChildControls();

if (this.m_strErrorHTML != null &&
!this.m_strErrorHTML.Equals(string.Empty))
output.Write(this.m_strErrorHTML);
else
{
if (this.m_objUserControl != null)
this.m_objUserControl.RenderControl(output);
else
output.Write(DEFAULT_TEXT);
}
}
catch (Exception ex)
{
this.PublishException(ex);
output.Write(this.m_strErrorHTML);
}
}

/// <summary>
/// Ruturns custom Html that can be used to display the description
/// and other information about the exception that is passed as an
/// argument.
/// </summary>
/// <param name="ex">The exception that has occured</param>
/// <returns></returns>
private string GetErrorMessage(Exception ex)
{
const string DEFAULT_ERROR_MESSAGE =
"An unexpected error has occured!";

try
{
string strErrMsg =
string.Format(
"<br /><b>{0}</b><br />Error Message = '{1}'<br />" +
"Error Source = '{2}'<br />" +
"Target Site = '{3}'<br />More Details = '{4}",
DEFAULT_ERROR_MESSAGE, ex.Message, ex.Source,
ex.TargetSite.ToString(), ex.ToString());

return strErrMsg;
}
catch
{
return DEFAULT_ERROR_MESSAGE;
}
}

/// <summary>
/// This function displays the description of any error that occurs within the webpart.
/// </summary>
/// <param name="ex">The exception that occured.</param>
private void PublishException(Exception ex)
{
this.m_strErrorHTML += GetErrorMessage(ex);
}
}
}

// ------------ End -----------------.

Followers