Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Visual Studio .NET » Developing a Web Part for Moss 2007

Developing a Web Part for Moss 2007

This article describes the step by step process to develop a web part for Moss 2007.

Page Views : 69526
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction:

We will be learning how to develop a Web Part that loads in a SharePoint site. To begin creating a web part:

  • VS.NET 2005 installed.
  • "Web Part Project Library" installed on your system.
  • Start VS.NET 2005 and create a new project.
  • Select Project Type as Visual C#-->SharePoint.
  • Visual Studio Installed templates as Web Part.
  • Change Name to Web Part Basics.
  • Change Location to e:\Webpartbasics (or appropriate drive letter).
  • Change Solution name to FileUploadWebPart.

The Render Method

The Web Part base class overrides the Render method of System.Web.UI.Control because the Web Part infrastructure needs to control the rendering of the Web Part contents. For this reason custom Web Parts must override the Render method of the Web part base class.

The Complete Web Part Code

/*Creation Log**********************************************************<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

*  Author                     : Saravanan Gajendran

*  Creation Date                : 12-01-2008

*  FileName                      : Webpartbasics.cs

*  Class                           : Webpartbasics

* Description          : Tracking the web part life cycle.

                           A Web Part is an add-on ASP.NET technology to Windows SharePoint Services
***********************************************************************/

using System;

using System.Web.UI;

using System.Xml.Serialization;

using System.Runtime.InteropServices;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.WebControls;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

namespace Webpartbasics

{

    [Guid("c07e5146-b025-4f9b-b0a4-a0fc5cb2cfd6")]

    public class Webpartbasics : System.Web.UI.WebControls.WebParts.WebPart

    {

        //varible declaration

        private string _strResult;

        private TextBox _tbxText;

        private Button _btnShow;

        private Label _lblErrMsg;

 

        /// <summary>

        /// 1 st EVENT IN WEB PART MANAGER

        /// During the initialization, configuration values that were marked as webbrowsable

        /// and set through the webpart task pane are loaded to the webpart

        /// </summary>

        /// <param name="e"></param>

        protected override void OnInit(EventArgs e)

        {

            try

            {

                this._strResult += "onInit Method <br>";

                base.OnInit(e);

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }

 

        }

        /// <summary>

        /// 2 nd EVENT IN WEB PART MANAGER

        ///

        /// Viewstate is a property inherited from System.Web.UI.Control .

        /// The viewstate is filled from the state information that was previously serialized

        /// would like to persist your own data within webpart

        /// </summary>

        /// <param name="savedState"></param>

        protected override void LoadViewState(object savedState)

        {

            try

            {

                _strResult += "LoadViewState<br>";

                object[] viewstate = null;

                if (savedState != null)

                {

                    viewstate = (object[])savedState;

                    base.LoadViewState(viewstate[0]);

                    _strResult += (string)viewstate[1] + "<br>";

                }

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }

        }        /// <summary>

        /// 3 rd EVENT IN WEB PART MANAGER

        /// All of the constituent controls are created and added to the controls collection

        /// </summary>

        protected override void CreateChildControls()

        {

            try

            {

                _strResult += "CreateChildControls<br>";       //creating error label controls

                this._lblErrMsg = new Label();

                this._lblErrMsg.ID = "lblErrMsg";

                this._lblErrMsg.Text = string.Empty;

                this.Controls.Add(_lblErrMsg);                //creating text controls

                this._tbxText = new TextBox();

                this._tbxText.ID = "tbxText";

                this._tbxText.Text = string.Empty;

                this.Controls.Add(_tbxText);                //creating button controls

                this._btnShow = new Button();

                this._btnShow.ID = "btnShow";

                this._btnShow.Text = "Check Text Value";

                this._btnShow.Click += new EventHandler(_btnShow_Click);

                this.Controls.Add(_btnShow);

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }

        }

        /// <summary>

        /// butoon click event

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void _btnShow_Click(object sender, EventArgs e)

        {

            try

            {

                this._strResult += "button click event has fired<br>";

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }

        }

        /// <summary>

        /// 4 th EVENT IN WEB PART MANAGER

        /// Perform actions common to all requests, such as setting up a database query

        /// At this point, server controls in the tree are created and initialized, the state is
             restored,

        /// and form controls reflect client-side data.

        /// </summary>

        /// <param name="e"></param>

        protected override void OnLoad(EventArgs e)

        {

            try

            {

                this._strResult += "Onload<br>";

                base.OnLoad(e);

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }

        }    
       
/// <summary>

        /// 5 th EVENT IN WEB PART MANAGER

        /// Perform any updates before the output is rendered.

        /// Any changes made to the state of the control in the pre-render phase can be  
             saved

        /// while changes made in the rendering phase are lost.

        /// </summary>

        /// <param name="e"></param>

        protected override void OnPreRender(EventArgs e)

        {

            try

            {

                this._strResult += "OnPreRender<br>";

                base.OnPreRender(e);

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }

        }  
       
/// <summary>

        /// 6 th EVENT IN WEB PART MANAGER

        /// store cutom data within a web part's viewstate

        /// The ViewState property of a control is automatically persisted to a string  
             object after this stage.

        /// This string object is sent to the client and back as a hidden variable.

        /// For improving efficiency, a control can override

        /// the SaveViewState method to modify the ViewState property.

        /// once viewstate is saved,the control webpart can be removed from the memory
             of the server.

        /// webpart receives notification that they are about removed from memory
             through dispose event

        /// </summary>

        /// <returns></returns>

        protected override object SaveViewState()

        {

 

            this._strResult += "SaveViewState<br>";

            object[] viewstate = new object[2]; viewstate[0] = base.SaveViewState();

            viewstate[1] = "MyTestData";

            return viewstate;

        }        /// <summary>

        /// 7 th EVENT IN WEB PART MANAGER

        /// Generate output to be rendered to the client.

        /// you can create user interface of your webpart using html table.

        /// You can apply your css classes here itself

        /// </summary>

        /// <param name="writer"></param>

        public override void RenderControl(HtmlTextWriter writer)

        {

            try

            {

                //this method ensure all created child controls

                EnsureChildControls();

                this._strResult += "RenderControl<br>";

                //table start

                writer.Write("<table id='tblTest'align='center' cellpadding='0' cellspacing='0' 
                border='1' width='100%'>"
);

                writer.Write("<tr>");

                writer.Write("<td>");

                writer.Write(_strResult);

                writer.Write("</td>");

                writer.Write("</tr>");                //row 2

                writer.Write("<tr>");

                writer.Write("<td>");

                this._tbxText.RenderControl(writer);

                writer.Write("</td>");

                writer.Write("</tr>");                //row 3

                writer.Write("<tr>");

                writer.Write("<td>");

                this._btnShow.RenderControl(writer);

                writer.Write("</td>");

                writer.Write("</tr>");                //row 4

                writer.Write("<tr>");

                writer.Write("<td>");

                this._lblErrMsg.RenderControl(writer);

                writer.Write("</td>");

                writer.Write("</tr>");

                writer.Write("</table>");

                //table end

            }

            catch (Exception ex)

            {

                this._lblErrMsg.Text = ex.Message.ToString();

            }  

        }

 

        /// <summary>

        /// 8 th EVENT IN WEB PART MANAGER

        ///

        /// Perform any final cleanup before the control is torn down.

        /// References to expensive resources such as database connections must be

        /// released in this phase.

        /// </summary>

        public override void Dispose()

        {

            base.Dispose();  

        }

 

        /// <summary>

        /// 9 th EVENT IN WEB PART MANAGER

        ///

        /// Perform any final cleanup before the control is torn down.

        /// Control authors generally perform cleanup in Dispose and do not handle this
             event

        /// The webpart removed from memory of the server

        /// Generally webpart developer do not need access to this event because all

        /// the clean up should have been accomplish in dispose event

        /// </summary>

        /// <param name="e"></param>

        protected override void OnUnload(EventArgs e)

       

            base.OnUnload(e);

       

    }

}
 

Deploy File Upload Web Part in the SharePoint Server

  • Right click solution file then select properties.
  • Select Debug --> Start browser with URL selects your respective SharePoint Site.

Select Signing Option

  • Ensure the strong name key and sign the assembly check box.
  • Right Click properties and select Deploy.

  • The Web Part is automatically deployed to the respective site. 
  • Deploy will take care of .Stop IIS, buliding solution, restarting solution, creating GAC, restarting IIS like that.
  • Now you should have this web part in your SharePoint page.

The final web part is added to the site. All events displayed in web part have order.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Saravanan Gajendran

Saravanan Gajendran: Is an Electronics engineer, who graduated in the  year of 2004-from  Chennai university, India, He is currently working on Microsoft .NET technology. His main experience is  based on ASP.NET,C#.NET,VB.NET,SQL server 2000,Javascript,HTML,DHTML,VSS,VSTS,WSS 3.0, MOSS 2007 with Ajax and Telerik Radcontrols. Likes to read about new technologies and books on self learning and personality development. He is very self driven and gives every job he takes up his best.Microsoft certified professional in MCP 070-315: Developing and Implementing Web Applications with Microsoft® Visual C#™ .NET and Microsoft® Visual Studio® .NET and Brain bench Certification - .NET Framework: Enterprise Application Developer Emil: saravanandotnet@hotmail.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Should you use the Sharepoint Assembly? by John On March 10, 2008
I read here http://www.andrewconnell.com/blog/archive/2008/02/18/Understanding-how-Web-Parts-are-rendered-why-to-never-use.aspx that you shouldnt' use the Sharepoint assembly when developing MOSS web parts? Is it possible to just write ASP.NET 2.0 web parts that will work both on a web page and in MOSS 2007?
Reply | Email | Modify 
Re: Should you use the Sharepoint Assembly? by Saravanan On March 27, 2008
If you creating web part project .It has deploy option using this option indirectly used share point assembly when deployment (placed your dll in GAC). If you creating class library project that time you need deploy all strong named dll in GAC Is it possible to just write ASP.NET 2.0 web parts that will work both on a web page and in MOSS 2007? It will work both web page and MOSS 2007.It is a just class file if using web page you need .aspx page also.
Reply | Email | Modify 
launching site by laxmi On March 13, 2008
Hi, could you please tel me how to launch a site oce it is created. i want to launch the site which can be accessible by everyone. i even selected "Ananymous access" but still its not working. Thanks in advance
Reply | Email | Modify 
Email Alert not available by laxmi On March 13, 2008
The Alert me option is not working and it gives an error message " Virtual server not set contact admin". even when i create a new user for the site the Send Email option is not available. I have MS office 2007 installed in my machine.
Reply | Email | Modify 
Email Alert not available by laxmi On March 13, 2008
The Alert me option is not working and it gives an error message " Virtual server not set contact admin". even when i create a new user for the site the Send Email option is not available. I have MS office 2007 installed in my machine.
Reply | Email | Modify 
by Saravanan On March 27, 2008
Reply | Email | Modify 
unable to deploy asp.net web application into shrepoint server 2007 by sankar On October 16, 2008
Hi saravanan, PLease guide me in this ....i am trying to deploy the existing web application to sharepoint server 2007...awaiting for your quick reply sreddy
Reply | Email | Modify 
room plan web part by nalaka On January 19, 2009
Hi I have idea to develop web part of room plan. This is the requirement. User should enter location and item detail of room. Those data should be store in xml file. Then room plan graphic is automatically created. Can any one know how to draw plan (image) using web part..?? Please give me some idea to start this web part . thanX. regards, nalaka
Reply | Email | Modify 
VisualStudio Add-In for web parts generation by Sasa On January 24, 2009
Although I find this article useful I would recommend a much simpler way for web parts development. Check this article to see how easilly web parts can be developed with a new VisualStudio Add-In: http://www.codeproject.com/KB/sharepoint/webparts_generator_addin.aspx
Reply | Email | Modify 
hii by Akila On October 12, 2010
hjkh
Reply | Email | Modify 
hi by Akila On October 12, 2010
nice article...
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.