Sunday, 2 September 2012

WebPart Life Cycle


WebPart Life cycle is easy to understand like ASP.Net.

OnInit: This method handles initialization of the control.
OnLoad: This event handles the Load event. This is also used for initialize the control but is not intended for loading data or other processing functionality.
CreateChildControls: This is the most popular event in web part life cycle. This creates any child controls. So if you are adding any control to display then you have to write in this method
EnsureChildControls: This method ensures that CreateChildControls has executed.
EnsureChildControls method must be called to prevent null reference exceptions.
SaveViewState: View state of the web part saved.
OnPreRender: This method handles or initiates tasks such as data loading that must complete before the control can render. 
Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.
Render: This method is used to render everything.
RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.
OnUnload: Performs the final cleanup.

/***********************************************************
* Log Details
* Author : Madan * Creation Date : 25-07-2008 (MOSS 2007)* FileName : WebPartLifeCycle.cs * Class : WebPartLifeCycle * Description : Tracking the web part life cycle. ***********************************************************************/using System;
using System.ComponentModel;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;namespace MorClsWPS.WPLifeCycle1{
[
ToolboxItemAttribute(false)]
public class WPLifeCycle1 : WebPart{//variblesprivate string strResults;
private TextBox txtContent;
private Button btnShow;
private Label lblErrMsg;
/// <summary>/// 1 st EVENT IN WEB PART /// 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.strResults += "onInit Method <br>";
base.OnInit(e);}

catch (Exception ex){

this.lblErrMsg.Text = ex.Message.ToString();}
}

/// <summary> /// 2 nd EVENT IN WEB PART /// /// 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{
strResults +=
"LoadViewState<br>";
object[] viewstate = null;
if (savedState != null){
viewstate = (
object[])savedState;
base.LoadViewState(viewstate[0]);strResults += (
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{
strResults +=
"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.txtContent = new TextBox();
this.txtContent.ID = "tbxText";
this.txtContent.Text = string.Empty;
this.Controls.Add(txtContent); //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.strResults += "button click event has fired<br>";}

catch (Exception ex){

this.lblErrMsg.Text = ex.Message.ToString();}
}

/// <summary> /// 4 th EVENT IN WEB PART /// 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.strResults += "Onload<br>";
base.OnLoad(e); }

catch (Exception ex) {

this.lblErrMsg.Text = ex.Message.ToString(); }
}

/// <summary> /// 5 th EVENT IN WEB PART/// 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.strResults += "OnPreRender<br>";
base.OnPreRender(e); }

catch (Exception ex) {

this.lblErrMsg.Text = ex.Message.ToString(); }
}

/// <summary> /// 6 th EVENT IN WEB PART /// 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.strResults += "SaveViewState<br>";
object[] viewstate = new object[2]; viewstate[0] = base.SaveViewState(); viewstate[1] =
"MyTestData";
return viewstate; }

/// 7 th EVENT IN WEB PART/// 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.strResults += "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(strResults);
writer.Write(
"</td>"); writer.Write(
"</tr>"); //row 2 writer.Write("<tr>"); writer.Write(
"<td>");
this.txtContent.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 writer.Write(txtContent.Text);
}
catch (Exception ex) {

this.lblErrMsg.Text = ex.Message.ToString(); }
}

/// <summary> /// 8 th EVENT IN WEB PART /// 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);
          }
     }
}

Build and Publish

Sandbox Solution

This is a new concept comes in SharePoint 2010.
  • A sandbox is a restricted execution environment that enables programs to access only certain resources, and that keeps problems that occur in the sandbox from affecting the rest of the server environment.

    • A user can deploy a solution package to SharePoint server farm and also the solution can be deployed to that sandbox.

      • To deploy something in the sandbox you do not need any farm level administration privileges. 

        • Sandboxed solutions can be added to a production SharePoint Server environment without the risk of affecting processes outside the sandbox.

          • The components that we can deploy in SharePoint sandbox are web part, Event receivers, feature receivers, customizing Sharepoint designer workflows,List definitions,List instances, Content Types etc.

            • And some of the thing that we can not do in sandbox are Visual web part.

            • To work with Sandbox you need to start the Microsoft SharePoint Foundation User code service. To activate this go to Central Administration --> Services on Server SP2010 and there activate Microsoft SharePoint Foundation User Code Service.

              • If you deploy in Sandbox then you do not need any IIS reset.
              • How To Hide Ribbon From Anonymous Users in Sharepoint 2010

                How To Hide Ribbon From Anonymous Users in Sharepoint 2010

                1.  Open your SharePoint v4.master page in sharepoint designer
                2. Locate this line:
                <div id="s4-ribbonrow">


                3.  Change it to:
                <div id="s4-ribbonrow" style="display:none">

                4. Now find the end of the “s4-ribbonrow” tag and add following block right after it.
                <Sharepoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl2" runat="server" PermissionsString="AddAndCustomizePages">
                <script type="text/javascript">
                                           document.getElementById("s4-ribbonrow").style.display = "block";
                </script>
                </Sharepoint:SPSecurityTrimmedControl>

                5. Save the v4.master page and publish it.

                Diffrence between Custom control, User Control and WebPart

                Web custom control are those controls which are placed into gac and user can add it in tool box.and it is difficult to create.and One Custom control can share diffrent application.

                User controls are used and create for particular application .It easy to create and for using it for dirrent application need to copy same user control on dirrent applications.

                Web part are new feature of dot net 2.0 . by using web part controls user can runtime change the size,position and layout of controls within the web parts controls,also web part gives facility to hide,edit delete controls.It is in built controls.

                Creating The Poperties with in the WebPart

                Creating The Poperties with in the WebPart

                1. Add New webpart
                2.
                using System;
                using System.ComponentModel;
                using System.Web;
                using System.Web.UI;
                using System.Web.UI.WebControls;
                using System.Web.UI.WebControls.WebParts;
                using Microsoft.SharePoint;
                using Microsoft.SharePoint.WebControls;
                namespace CustomProperties.CustomPropertiesWP
                {
                [ToolboxItemAttribute(false)]
                public class CustomPropertiesWP :WebPart
                {
                private string  strValue;
                Label lblResult;
                Button btnClick;

                [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
                System.Web.UI.WebControls.WebParts.WebDisplayName("Enter the Value"),
                System.Web.UI.WebControls.WebParts.WebDescription("Please Enter the Value"),
                System.Web.UI.WebControls.WebParts.Personalizable(
                System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
                System.ComponentModel.Category("Madan Custom Properties"),
                System.ComponentModel.DefaultValue("")]

                public string  propValue
                {
                get { return strValue; }
                set { strValue =value; }
                }
                protected override void CreateChildControls()
                {
                       lblResult = new Label();
                       btnClick = new Button();
                       btnClick.Text = "Click";
                       btnClick.Click += new EventHandler(btnClick_Click);
                      this.Controls.Add(lblResult);
                      this.Controls.Add(btnClick);
                }

                protected void btnClick_Click(object sender,EventArgs e)
                {
                      lblResult.Text = propValue.ToString();
                }       

                    }
                }
                 
                Build and Deploy