Wednesday, August 24, 2011

How to open Modal Popup from Silverlight in Sharepoint 2010 using Visual Web part


In our application we are using Silverlight to display some of the site information. I have created a Silverlight Application and deployed the XAP file in the Site root using Module.
In the Silverlight application we are showing SharePoint users as hyperlinks. When we click on the user, a SharePoint dialogue should open which opens the user info page. We know that we can call java script functions from Silverlight using the command .But if use SharePoint 2010 Built in SharePoint Silverlight Web part, we cannot define the JavaScript function that relates to this Silverlight application.
So I have created a Visual Web part which holds silver light object (the XAP file) in it, the syntax is as simple as we add Silver light Object (XAP file )to the html file.
Note: If we use Visual Web Part, then the ClientContext .Current object in Silverlight will return null value.So we need to change our code from ClientContext ctx = ClientContext.Current
 to  ClientContext ctx = new ClientContext(siteCollectionUrl);

Here siteCollectionUrl will be passed to the Silverlight using initparams from the Visual Web part that holds the Silverlight Object. Below is the code.
SilverVisualWPUserControl.ascx
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SilverPropertiesTabUserControl.ascx.cs" Inherits="DLRSilverTab.SilverPropertiesTab.SilverPropertiesTabUserControl" %>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {

            var appSource = "";
            if (sender != null && sender != 0) {
                appSource = sender.getHost().Source;
            }
            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";

            errMsg += "Code: " + iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " + args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }

        function OpenDialogueWidow(url) {
            var options = SP.UI.$create_DialogOptions();
            options.width = 750;
            options.height = 650;
            options.url = url;
            options.dialogReturnValueCallback = Function.createDelegate(
                        null, portal_modalDialogClosedCallback);
            SP.UI.ModalDialog.showModalDialog(options);

           
        }

        function portal_modalDialogClosedCallback(result, value) {
           
        }

       
    </script>
   
    <div id="silverlightObject" runat="server"></div>

SilverVisualWPUserControl.ascx.cs Page_Load method
protected void Page_Load(object sender, EventArgs e)
        {
            string siteCollectionUrl = SPContext.Current.Web.Url;
           
            string html =string.Format("<object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" "
            +"style=\"display:block\" height=\"250px\" width=\"100%\"  >"
            +"<param name=\"source\" value=\"/SilverTabControl.xap\"/>"
            + "<param name=\"onerror\" value=\"onSilverlightError\" />"
            + "<param name=\"background\" value=\"white\" />"
            + "<param name=\"minRuntimeVersion\" value=\"2.0.31005.0\" />"
            + "<param name=\"initParams\" value=\"PropertyList=Property Information,PropertyContactList=Properties,PropertyID=Property_x0020_ID,PropertyIDValue=1,Duration=6000,url={0}\" />"
            + "<param name=\"autoUpgrade\" value=\"true\" />"
            + "<a href=\"http://go.microsoft.com/fwlink/?LinkID=124807\" style=\"text-decoration: none;\">"
            + "<img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" alt=\"Get Microsoft Silverlight\" style=\"border-style: none\"/>"
            + "</a></object>"
                  +"<iframe style='visibility:hidden;height:0;width:0;border:0px;' scrolling=no></iframe>",siteCollectionUrl);
            silverlightObject.InnerHtml = html;
        }


Silverlight Application MainPage.xaml.cs  How to invoke JavaScript Method to open Dialogue Window.
HyperlinkButton contactLink = new HyperlinkButton();

            contactLink.Click += new RoutedEventHandler(contactLink_Click);

            contactLink.Tag = new Uri("/_layouts/userdisp.aspx?ID=" + spUser.Id);
            contactLink.Cursor = Cursors.Hand;


void contactLink_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link= sender as HyperlinkButton;
            if(link!=null && link.Tag !=null)
            HtmlPage.Window.Invoke("OpenDialogueWidow", link.Tag.ToString());
        }

In the above Code OpenDialogueWidow is the JavaScript  function name which defined in the Visual Web part

Tuesday, August 09, 2011

SharePoint 2010 Getting List Item Attachments using Silverlight Client Object Model


I did a lot of research to get list item attachments. I have searched in forums but found no solution.
Using Client Object Model, we cannot get List Item Attachments collection, client object model will return a list item object, but the object doesn't contain the attachments collection info and supports no methods to get attachments collection.
  The alternative method is calling web service method GetAttachmentCollection from the service lists.asmx. This method returns the result in the form of XMLNode. Here is the sample code which works perfectly.
The below example Gets the list item from a given list, then Gets its first image attachment and shows it in the Silverlight Image Control.
Add the below line in the import section to import SharePoint.Client dll.
using SP = Microsoft.SharePoint.Client;

Here follows the code. This code I have copied from my Visual studio and formatted here to relate it to the post, I may forgot to declare some of the variables, but once you copy this code in to your Visual Studio, you can easily fix those compilation errors.

SP.ClientContext context;
SP.Web spWeb;
SP.Web currentWeb;
SP.List propertiesList;
string serviceUrl = string.Empty;
SP.ListItemCollection listItems;
 
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
 
private void RequestFailed(object sender, SP.ClientRequestFailedEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Error occured: " + e.Exception);
});
}
 
 
private void GetRequestSucceeded(object sender, SP.ClientRequestSucceededEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
serviceUrl = e.Request.WebRequest.RequestUri.AbsoluteUri;
serviceUrl = serviceUrl.Substring(0, serviceUrl.IndexOf("_vti_bin"));
foreach (SP.ListItem item in listItems)
{
   GetAttchmentCollection(item.Id.ToString());
}
});
}
 
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName,id);
}
 
void oClient_GetAttachmentCollectionCompleted(object sender, ServiceReference1.GetAttachmentCollectionCompletedEventArgs e)
{
XElement element = e.Result;
string attachments = element.Value;
string[] splitString = { "http" };
string[] attchmentArray = attachments.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < attchmentArray.Length; i++)
{
string extension=System.IO.Path.GetExtension(attchmentArray[i]).ToLower();
if (extension == ".png" || extension == ".jpg" || extension == ".jpeg" || extension == ".tif")
{
DownloadAttachedFileFromListItem("http" + attchmentArray[i]);
break;
}
}
}
 
 
public void DownloadAttachedFileFromListItem(string fileName)
{
using (ClientContext clientContext = new ClientContext(serviceUrl))
{
File.OpenBinaryDirect(clientContext, "/" + fileName.Replace(serviceUrl, ""), OpenBinaryFileSuccess, OpenBinaryFileFailure);
}
}
 
void OpenBinaryFileSuccess(object o, OpenBinarySucceededEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
BitmapImage bitmapimage = new BitmapImage();
bitmapimage.SetSource(e.Stream);
imgPhoto.Width = bitmapimage.PixelWidth > imgPhoto.ActualWidth ? imgPhoto.ActualWidth : bitmapimage.PixelWidth;
imgPhoto.Height = bitmapimage.PixelHeight > imgPhoto.ActualHeight ? imgPhoto.ActualHeight : bitmapimage.PixelHeight;
imgPhoto.Source = bitmapimage;
});
}
 
void OpenBinaryFileFailure(object o, OpenBinaryFailedEventArgs e)
{
}

Friday, April 08, 2011

Create a custom workflow activity

When you create a custom workflow activity you should create a separate ACTIONS file.  Editing the WSS.ACTIONS file is trouble.
Generally the message "The list of workflow actions on the server references an assembly that does not exist. Some actions will not be available. the assembly strong name is ..." occurs because the ACTIONS file doesn't match the assembly it references. Normally you would see that error because someone has extended the Workflow actions available in SPD with a custom action developed in Visual Studio.  These custom actions are loaded when your workstation reads the WSS.ACTIONS file on the server.  The file is located in the 12 hive under Template\1033\workflow.  Your WSS.Actions file contains a reference to a custom action .dll which is not available on the server.
If you have verified that the assembly strong name is correct, verify that the ACTIONS file parameters match the assembly's activity properties.  Be sure to check the "DependencyProperty.Register" methods too.

Thursday, March 31, 2011

Sharepoint 2010 Web Part and Linq

In this exercise, you will develop and deploy a Visual Web Part that reads data from a list and displays
in a DataGrid. In this exercise, you will: 

1.  Create a Visual Web Part.
2.  Generate Linq proxy code.
3.  Use a Linq provider to read data from a SharePoint list.
4.  Render the data using the SPDataGrid web control. 

Task 1 - Create a new SharePoint Project

In this task, a solution and project will be created. It will contain the rest of the development work in

1.  Open Visual Studio 2010 by going to Start Menu | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.
2.  From the menu, select File | New | Project.
3.  In the New Project dialog window, choose Visual C# | SharePoint | 2010 from the Installed Templates.
4.  Select Visual Web Part from the Project Item
5.  In the SharePoint Customization Wizard:
·         Enter your SharePoint site address for the local site.(What is the site do you want to use for debugging)
·         Set the trust level to Deploy as a farm solution.
·         Click Finish button.
6. Visual Studio will create the new SPCHOL200-Ex1 project and add the necessary files.
7. Notice that Visual Studio also creates a Visual Web Part named VisualWebPart1. Within the Solution Explorer, expand VisualWebPart1 and open VisualWebPart1.webpart.
8.Change the value of the property element with the name attribute value of Title to SPLinqDemoTitle and the value of the property element with the name attribute value of Description to SPLinqDemoPart Description. This will change the Title and Description property of the Visual Web Part once it is deployed. Save the file.
<?xml version="1.0" encoding="utf-8"?>
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="SPCHOL200_Ex1.VisualWebPart1.VisualWebPart1, $SharePoint.Project.AssemblyFullName$" />
      <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Title" type="string">SPLinqDemoTitle</property>
        <property name="Description" type="string">SPLinqDemoPart Description</property>
      </properties>
    </data>
  </webPart>
</webParts>

Task 2 - Generate LINQ-to-SharePoint proxy class to access list data

In this task, you will use the new spmetal.exe code generation utility and generate the Linq-to-SharePoint proxy code.

1.  In the Solution Explorer, right-click on the Project and select Open Folder in Windows
Explorer.
2.  Hold Shift key and right click anywhere in the Explorer Window and select Open Command
Window Here to open the command prompt window in the current project directory:
3.  Type the following command in the command prompt and press Enter to set the path to the
SharePoint 2010 folder:

set path=%path%;c:\program files\common files\microsoft shared\web server extensions\14\bin

4.  Type the following command in the command prompt and press Enter to generate the Linq-to-
SharePoint proxy code.
spmetal.exe /web:http://your web site address /namespace:Your Project name.VisualWebPart1 /code:SPLinq.cs
Note – you may get warnings about content types for list Form Templates. You can safely
ignore this warning and continue
5.  Close the command window and switch back to Visual Studio.
6.  In Visual Studio, right click on the Project and select Add | Existing Item.
7.  Select SPLinq.cs from the Add Existing Item dialog window and click Add:
8.  In the Solution Explorer, right click on References and select Add Reference.
9.  Switch to Browse tab and enter C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI in the File Name text box. Press Enter to change directories.
10. Select Microsoft.SharePoint.Linq.dll.
11. Click OK to add the reference to your project.

Task 3 - Access the SharePoint list data in Visual Web Part 
In this task, you will add code to your solution that will allow the Visual Web Part to retrieve SharePoint
list data.

1.  In Solution Explorer, expand VisualWebPart1 and double-click on VisualWebPart1UserControl.ascx.
2.  Visual Studio will open the Visual Web Part User Control.
3.  Add the following code to the user control to construct your grid view.
<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>
<SharePoint:SPGridView id="spGridView" runat="server"
AutoGenerateColumns="false">
  <HeaderStyle HorizontalAlign="Left" ForeColor="Navy" Font-Bold="true" />
  <Columns>
    <SharePoint:SPBoundField  DataField="Id"
HeaderText="Id"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="Path"
HeaderText="Path"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="Title"
HeaderText="Title"></SharePoint:SPBoundField>
  
  </Columns>
</SharePoint:SPGridView>
4. In the Solution Explorer, right click on VisualWebPart1UserControl.ascx and select View Code.
5. Add the following using statements to the code behind:
              using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using System.Linq;

6. Insert the following code inside the Page_Load method:In my application I have created a Document Library with a name “Venkat Photos” ,if you observe your SPLinq.cs file, you will observe
              var dc = new SPLinqDataContext(SPContext.Current.Web.Url);

             var venkatPhotos = dc.GetList<VenkatPhotosPicture>("Venkat Photos");

             var empQuery = from photo in venkatPhotos
                           select new
                           {
                               photo.Id,
                               photo.Path,
                               photo.Title
                           };

             spGridView.DataSource = empQuery;
             spGridView.DataBind();

Task 4 – Build and Deploy the Visual Web Part

1.  In the Solution Explorer, right click on Your Project and select Deploy. This will build and
deploy the Visual Web Part to the local SharePoint site
2.  Open Internet Explorer and browse your website
3.  Click the Edit icon in the top menu to open the SharePoint Ribbon to the Editing Tools.
5.  Switch to Insert tab in the Ribbon and click on Web Part to insert a Web Part to the page.
6.  Under Categories, Select Custom.
7.  Under Web Parts, select SPLinqDemoTitle web part.Put your cursor in the area of the page where you want the Web Part to appear. This must be a zone that accepts Web Parts.
8.  Click Add to add the web part to the page. This will add the SPLinqDemoTitle web part to the
selected layout zone.
9.  Click on Page, click the down arrow on the “Save and Close” button, and select Stop Editing
to save the page and stop editing. Click Yes when prompted to save the changes you made.
10.You will see list of items displaying on the Grid.




Tuesday, March 29, 2011

Asp.Net Page LifeCycle

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal.Each request for an .aspx page that hits IIS is handed over to HTTP Pipeline. HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content. The start point of HTTP Pipeline is the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per AppDomain hosted within the worker process. HttpRuntime class picks up an HttpApplication object from an internal pool and sets it to work on the request. It finds out what class has to handle the request. The association between the resources and handlers are stored in the configurable file of the application
Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the handler's ProcessRequest to start the process. This implementation begins by calling the method FrameworkInitialize(), which builds the control trees for the page. This is a protected and virtual member of TemplateControl class, class from which page itself derives.

Next the processRequest() makes page transits various phases: initialization, loading of viewstate and postback data, loading of page's user code and execution postback server-side events. Then page enters in render mode, the viewstate is updated and HTML generated is sent to the output console. Finally page is unloaded and request is considered completely served. 

Page_PreInit: Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.

Page_Init : This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request. Viewstate information will not be available at this stage. This Event Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.Use this event to read or initialize control properties. 
Page_PreLoad: Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance. 
Page_Load: After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how viewstate is restored.Once viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client.

At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired.

 
btnSubmit_Clicked: Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back. 
RaisePostBackEvent: Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate.
 
Page_PreRender: After PostBack event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the viewstate is stored and output is rendered. This Event Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins. 
SaveViewState: Next stage is saving view state, all the values of the controls will be saved to their own viewstate collection. The resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate hidden field.
 
Render: Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method. This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Page_Unload: This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page. At this time Response object not available. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception. If you observe the given sample, if we use Response in this event, the system raises an error that says 'Response Object not available at this stage'

To understand the page life cycle clearly, create a website and add a PageLifeCycle.aspx page to the website. Add the below lines of code to the page and view it in the browser. 
PageLifeCycle.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageLifeCycle.aspx.cs" Inherits="PageLifeCycle" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Name</td><td><asp:TextBox ID="tbName" runat="server" ></asp:TextBox></td>
</tr>
<tr>
<td>Designation</td><td><asp:DropDownList ID="ddlDesignation" runat="server" ></asp:DropDownList> </td>
</tr>
<tr>
<td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Clicked" /> </td>
</tr>
</table>
</div>
</form>
</body>
</html>


PageLifeCycle.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PageLifeCycle : System.Web.UI.Page
{
int counter = 1;


protected void Page_PreLoad(object sender, EventArgs e)
{
WriteOutput("Page_PreLoad");
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
BindDesignation();
}
WriteOutput("Page_Load");
}


private void BindDesignation()
{
List<Info> infoList = new List<Info>();
for (int i = 1; i <= 5; i++)
{
infoList.Add(new Info("Venkat"+i,"Software Engineer"+i));
}
ddlDesignation.DataSource = infoList;
ddlDesignation.DataValueField = "Designation";
ddlDesignation.DataTextField = "Designation";
ddlDesignation.DataBind();
}

protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
WriteOutput("LoadControlState");

}

protected void Page_LoadViewState(object sender, EventArgs e)
{
WriteOutput("LoadViewState");
}

protected override void LoadViewState(object viewState)
{
base.LoadViewState(viewState);
WriteOutput("LoadViewState");
}

protected override object SaveViewState()
{
WriteOutput("SaveViewState");
return base.SaveViewState();
}


protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArg)
{
base.RaisePostBackEvent(sourceControl,eventArg);
WriteOutput("RaisePostBackEvent");
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
WriteOutput("Render");
}


protected void btnSubmit_Clicked(object sender, EventArgs e)
{
WriteOutput("btnSubmit_Clicked");
}

protected void Page_PreInit(object sender, EventArgs e)
{
WriteOutput("Page_PreInit");
}
protected void Page_Init(object sender, EventArgs e)
{
WriteOutput("Page_Init");
}

protected void Page_PreRender(object sender, EventArgs e)
{
WriteOutput("Page_PreRender");
}
protected void Page_Unload(object sender, EventArgs e)
{
//WriteOutput("Page_Unload");
}


private void WriteOutput(string eventName)
{
Response.Write("Step no: " + counter++ + "--> "+eventName+"<br/>");
Response.Write("Name: " + (tbName.Text == null ? "Null" : tbName.Text + "<br/>"));
Response.Write("Designation: " + (ddlDesignation.SelectedValue == null ? "Null" : ddlDesignation.SelectedValue + "<br/><br/>"));
}

}

public class Info
{
public string Name { get; set; }
public string Designation { get; set; }
public Info(string name,string designation)
{
Name = name;
Designation = designation;
}
}

If you view the page in the browser , the below screen will be shown,

Click on the Submit Button to Postback the page, then the below screen will be shown.