Creating your own custom Base Class with your own MOSS Web Part

Wink I had a requirement that required me to create a custom base for web parts to provide a common library for web part development within MOSS. I started to research on how this could be done and found very little information that explained the whole process of trying to achieve this and literally any form of reference to this topic in the 3.0 WSS SDK August 2007 did not exist. So I needed to do something to assist the development community.

So lets cut the chase and start showing you how this is done.

Firstly we need to create a new class project within Visual Studio and lets call this WebPartBase. In this example we will retrieve the webpart id and title of the webpart and place this in a protected string called WebPartID and WebPartTitle, I have also included some of the site properties into the base class. Our Base class will inherit from the System.Web.UI.WebControls.WebParts.WebPart base class, which is the base class Microsoft provide you to inherit for developing web parts. Our custom web part will inherit our custom base class, which for the purpose of the blog will only be two properties from the webpart and three properties from the Site object and place them into a strings. As soon as we inherit our base class we automatically inherit these strings into our web part. When we put this into perspective, you have the whole .Net framework their available to you as a developer that could be used as a library for comon tasks that you may require for all your web part development. e.g. Application Logging, Standardise on variable name's across your Line of Business applications for all web parts, custom behaviour across the board for all web parts, etc. I think you get the picture. Wink

Lets Get Started.

1. Create New Class Project within Visual Studio 2005 and call this WebPartBase.

Add the following bit of code into your WebPartBase class so it should like something like this.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;


using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;


namespace bobby.habib.base
{

    public class PortletBase : System.Web.UI.WebControls.WebParts.WebPart
    {
        /// <summary>
        /// Public default constructor.
        /// </summary>
        public PortletBase()
        {

        }

            #region Web Part Settings

            protected string WebPartID
            {
                get
                {
                    return base.ID;
                }
            }

            protected string WebPartTitle
            {
                get
                {
                    return base.DisplayTitle;
                }
            }

            #endregion

            #region Site Settings

            protected string SiteID
            {
                get
                {
                    try
                    {
                        SPWeb oSite = SPControl.GetContextWeb(Context);
                        try
                        {

                            return oSite.ID.ToString();
                        }
                        catch (Exception exm)
                        {
                            throw new Exception(exm.Message);
                        }
                        finally
                        {
                            oSite.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                   
                }
            }

            protected string SiteTitle
            {
                get
                {
                    try
                    {
                        SPWeb oSite = SPControl.GetContextWeb(Context);
                        try
                        {

                            return oSite.Title;
                        }
                        catch (Exception exm)
                        {
                            throw new Exception(exm.Message);
                        }
                        finally
                        {
                            oSite.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }

                }
            }

            protected string SiteName
            {
                get
                {
                    try
                    {
                        SPWeb oSite = SPControl.GetContextWeb(Context);
                        try
                        {

                            return oSite.Name;
                        }
                        catch (Exception exm)
                        {
                            throw new Exception(exm.Message);
                        }
                        finally
                        {
                            oSite.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }

                }
            }

        #endregion

 

        }
}

2. Complie this code. You will notice that we automatically will inherit a number of values that could be used, as part of your framework library for web part development.

    • WebPartID
    • WebPartTitle
    • SiteID
    • SiteTitle
    • SiteName

3. The next step is to now create a web part that will inherit from the custom base class we have just built, rather then using the System.Web.UI.WebControls.WebParts.WebPart base class. So lets create a new web part using visual studio, when creating your web part you must add a reference in your web part project to the custom base class we have just created.

Your web part project should look like this;

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

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using bobby.habib.base;


namespace Bobby.Habib.WebParts.BaseTest

{
 
    public class BobbyHTest : PortletBase
    {
        public BobbyHTest()
        {
            this.ExportMode = WebPartExportMode.All;
        }
       
        #region GUI Controls
           
            // GUI Panels
            private Panel _MainPanel;

        #endregion
       


        protected override void Render(HtmlTextWriter writer)
        {
            _MainPanel.RenderControl(writer);
        }

        protected override void CreateChildControls()
        {

            #region Control Declaration

                _MainPanel = new Panel();

            #endregion

            Table outerTable = new Table();
            outerTable.CellPadding = 0;
            outerTable.CellSpacing = 0;
            outerTable.Width = 400;

            // Row 1

            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Width = 800;
            string strTxT = string.Empty;
            strTxT = strTxT + "<b>Web Part Information</b><br>";
            strTxT = strTxT + "base.ID - " + WebPartID + "<br>";
            strTxT = strTxT + "base.Title - " + WebPartTitle + "<br>";
            strTxT = strTxT + "<b>Site Information</b><br>";
            strTxT = strTxT + "Site ID - " + SiteID + "<br>";
            strTxT = strTxT + "Site Name - " + SiteName + "<br>";
            strTxT = strTxT + "Site Title - " + SiteTitle + "<br>";
            strTxT = strTxT + "Display Title - " + WebPartTitle + "<br>";

            cell.Text = strTxT;

            row.Cells.Add(cell);
            outerTable.Rows.Add(row);
            _MainPanel.Controls.Add(outerTable);
            base.CreateChildControls();
        }
    }
}

4. Compile the above code.

5. If you have the Visual Studio 2005 and have installed Visual Studio 2005 extensions for WSS3, you could go into the web part project properties and do the following;

    • In the Debug Tab in the project properties, click on the radio button that says "Start Browser with URL:" and enter the URL for your MOSS environment.
    • Assign a Strong Name Key to your base class and you could assign a Strong Name Key to your web part if you wouyld like to place this in the GAC.
    • In the SharePoint Solution Tab, complete the Solution, Feature and Element information. This behined the scences updates the values you enter in your solution, feature and element xml files that will be used during the deployment mechanism.
    • Hit F5 only and this will rebuild the project and deploy the solution into MOSS by creating a .wsp file and deploys the .wsp file.

6. You may need to copy your custom  base class to the GAC, if you have not configured your solution files to copy the base class into the GAC. If during the time of deployment you find that the project starts error during the deployment. The likely cause is your web part cannot see the custom base class in the GAC and throws a reflection error. Ensure that the base class is in the GAC and is registred as a safe control in the web.config file of the site you are trying to deploy too.

7. Add the web part into a site page in MOSS and you will see the property values being displayed in the web part, that have been inherited from our custom base class.

I hope this helps a developer. Stick out tongue 

 

 

 


Posted on SharePoint Blogs Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Read the complete post at http://www.sharepointblogs.com/bobbyhabib/archive/2007/10/16/creating-your-own-custom-base-class-with-your-own-web-part.aspx

Published Monday, October 15, 2007 7:10 PM by SharePoint Blogs
Filed under: , ,