Search This Blog

Sunday, July 27, 2014

Visual Web Part && Visual Web Part User Control Life Cycle

Visual Web Part Life Cycle
I did create one visual web part with name “SimpleVisualWebPart”. It has the following code to display the sequence of life cycle events.
SimpleVisualWebPart.cs

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;
using System.Diagnostics;

namespace SPVisualWebParts.SimpleVisualWebPart
{
    [ToolboxItemAttribute(false)]
    public class SimpleVisualWebPart : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/SPVisualWebParts/SimpleVisualWebPart/SimpleVisualWebPartUserControl.ascx";
        private Label labelEvents = default(Label);
        private SimpleVisualWebPartUserControl control;
        string controlEvents;

        protected override void CreateChildControls()
        {
            control = Page.LoadControl(_ascxPath) as SimpleVisualWebPartUserControl;
            Debug.WriteLine("SimpleVisualWebPart - CreateChildControls");
            Controls.Add(control);          
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Debug.WriteLine("SimpleVisualWebPart - OnInit");
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Debug.WriteLine("SimpleVisualWebPart - OnLoad");
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            Debug.WriteLine("SimpleVisualWebPart - LoadViewState");
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            Debug.WriteLine("SimpleVisualWebPart - OnPreRender");
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
            Debug.WriteLine("SimpleVisualWebPart - RenderContents");
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
            Debug.WriteLine("SimpleVisualWebPart - OnUnload");
        }

        protected override object SaveControlState()
        {
            Debug.WriteLine("SimpleVisualWebPart - SaveControlState");
            return base.SaveControlState();

        }

        protected override object SaveViewState()
        {
            Debug.WriteLine("SimpleVisualWebPart - SaveViewState");
            return base.SaveViewState();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Debug.WriteLine("SimpleVisualWebPart - Render");
            base.Render(writer);
        }

        public override void Dispose()
        {
            Debug.WriteLine("SimpleVisualWebPart - Dispose");
            base.Dispose();
        }
    }
}


SimpleVisualWebPartUserControl.ascx.cs

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

namespace SPVisualWebParts.SimpleVisualWebPart
{
    public partial class SimpleVisualWebPartUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - Page_Load");
        }      

        protected override void OnInit(EventArgs e)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - OnInit");
            base.OnInit(e);
        }

        protected override void LoadViewState(object savedState)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - LoadViewState");
            base.LoadViewState(savedState);
        }

        protected override void OnLoad(EventArgs e)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - OnLoad");
            base.OnLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - OnPreRender");
            base.OnPreRender(e);
        }

        protected override object SaveViewState()
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - SaveViewState");
            return base.SaveViewState();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - Render");
            base.Render(writer);
        }

        public override void Dispose()
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - Dispose");
            base.Dispose();
        }

        protected override void OnUnload(EventArgs e)
        {
            Debug.WriteLine("SimpleVisualWebPartUserControl - OnUnload");
            base.OnUnload(e);
        }
    }
}


I have captured entire life cycle events in the output window. Here is the output of sequence of life cycle events for the visual web part.
Output:

SimpleVisualWebPart                                    - OnInit
SimpleVisualWebPart                                    - OnLoad
SimpleVisualWebPart                                    - CreateChildControls
SimpleVisualWebPartUserControl                            - OnInit
SimpleVisualWebPartUserControl                            - OnLoad
SimpleVisualWebPartUserControl                            - Page_Load
SimpleVisualWebPart                                    - OnPreRender
SimpleVisualWebPartUserControl                            - OnPreRender
SimpleVisualWebPart                                    - SaveViewState
SimpleVisualWebPartUserControl                            - SaveViewState
SimpleVisualWebPart                                    - Render
SimpleVisualWebPartUserControl                            - Render
SimpleVisualWebPart                                    - RenderContents
SimpleVisualWebPartUserControl                            - OnUnload
SimpleVisualWebPartUserControl                            - Dispose
SimpleVisualWebPart                                    - OnUnload
SimpleVisualWebPart                                    - Dispose

Web Part Life cycle
Event Phase
Description
Method or event to override
OnInitConfiguration values set using WebBrowsable properties and those in web part taskInit event (OnInit method)
LoadViewStateThe view state of the web part is populated over here.LoadViewState method
CreateChildControls
OnLoad
All the specified controls are created and added to the controls collection. When the page is being rendered for the first time CreateChildControls occurs after the OnLoad event.  In case of postback it is called before the OnLoad() event.  We can make use of EnsureChildControls() – It checks to see if the CreateChildControls() has yet been called, and if it has not, calls it.Load event
(OnLoad method)
User generated eventFires for events like button clickRaisePostBackEvent method
On PreRenderWe can change any web part properties before the control output is drawn.PreRender event
(OnPreRender method)
RenderContentsHTML output is generated to render the output.SaveViewState method
SaveViewStateViewState of the web part is serialized and saved.Render method
DisposePerform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.Dispose method
UnloadPerform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event.UnLoad event (On UnLoad

Web User Control Life cycle
Event Phase
Description
Method or event to override
InitializeInitialize settings needed during the lifetime of the incoming Web request.Init event (OnInit method)
Load view stateAt the end of this phase, the ViewStateproperty of a control is automatically populated. A control can override the default implementation of theLoadViewState method to customize state restoration.LoadViewState method
LoadPerform 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.Load event
(OnLoad method)
Handle postback eventsHandle the client-side event that caused the postback and raise appropriate events on the server.

Note   Only controls that process postback events participate in this phase.
RaisePostBackEvent method
PrerenderPerform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost.PreRender event
(OnPreRender method)
SaveViewStateThe 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.SaveViewState method
RenderGenerate output to be rendered to the client.Render method
DisposePerform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.Dispose method
UnloadPerform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event.UnLoad event (On UnLoad



Thursday, July 24, 2014

CAML & SPQuery in SharePoint

CAML & SPQuery in SharePoint

Using Collaborative Application Markup Language (CAML)  queries with SPQuery and SPSiteDataQuery is a faster and more efficient way of retrieving items based on known criteria compare with for each on the SPListItemsCollection and checking for the criteria.

In this tutorial I’m going to discuss how you can write CAML queries for retrieving items in SharePoint List.

Operators

These are some common operators you can use with CAML queries.

  1. Eq--Equals
  2. Neq--Not equal
  3. Gt--Greater than
  4. Geq--Greater than or equal
  5. Lt--Lower than
  6. Leq--Lower than
  7. IsNull--Is null
  8. BeginsWith--Begins with
  9. Contains--Contains

Get All Items

This is discussed in SharePoint List C# Part 1. There you can write the query as follows. There you can get all the items in the list.

myquery.Query = "";

Single Criteria

Using following query you can get all the tasks where “ID” is equal to 5.
?
1
2
3
4
5
6
<Where>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
</Where>
You can get Value Types for different common type of columns using following list

e.g. Use Value Type "Text" for column type "Single line of text".

  1. Single line of text--Text
  2. Multiple lines of text--Note
  3. Choice (menu to choose from)--Choice
  4. Number (1, 1.0, 100)--Number
  5. Date and Time--DateTime
  6. Lookup (information already on this site)--Lookup/LookupMulti
  7. Yes/No (check box)--Boolean
  8. Person or Group--User

Using AND

This will give you the items where ID = 5 and Title =  "ABC".
?
1
2
3
4
5
6
7
8
9
10
<Where><And>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>ABC</Value>
</Eq>
</And></Where>
OR

This will give you the items where ID = 5 or Title =  "ABC" 
?
1
2
3
4
5
6
7
8
9
10
<Where><OR>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>ABC</Value>
</Eq>
</OR></Where>
It is different if you want to use more than one "AND" or "OR" operator. As a example if you want to get items where ID = 5 and Title = "ABC" and created by "John", then you can write this.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<Where>
<And>
<And>
<Eq>
<FieldRef Name='ID' />
<Value Type='Counter'>5</Value>
</Eq>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>ABC</Value>
</Eq>
</And>
<Eq>
<FieldRef Name='Author' />
<Value Type='User'>John</Value>
</Eq>
</And>
</Where>