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. 


 

Monday, March 28, 2011

Why IsPostBack Check?

Binding Data
We often bind data to Dropdown lists and Repeater etc, in ‘PageLoad’ event. Sometimes we bind data without checking page ‘IsPostBack’ value.Due to this small mistake, the changes that we made to dropdown selection will be lost. When trying to catch the selected value of the dropdown list in the ‘Post back’ event, it will be set to default value. Any novice learner of .Net will get surprised to see, if their changes were not effecting.
Here what happens is the ’Page Load’ events occurs first, and then the ‘Post back’ event. Here the drop down list (in our case) binds two times. Whenever we submit a page by clicking on the button, the first event that takes place is ‘Page Load’ event then the ‘Button click’ event. So the BindDropDown() will executes again and the changes that we made will get lost.
So here the conclusion is Data Binding operation should be done before page post back.
Here is the Sample Code:Binding the data by checking the page ‘Post Back’ event.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Page Post back and Databinding</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
<br />
<asp:DropDownList ID="ddlBooks" runat="server" EnableViewState="true" ></asp:DropDownList>
<asp:Button ID="btnSubmit" OnClick="BtnSubmitClicked" Text="Submit" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(objectsender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
List<string> books = new List<string>();
books.Add("C# fundamentals");
books.Add("Masteringin Styles");
books.Add("C#Advanced");
books.Sort();
ddlBooks.DataSource = books;
ddlBooks.DataBind();
ddlBooks.Items.Insert(0,new ListItem("Select ne","select"));
}
protected void BtnSubmitClicked(object sender, entArgs e)
{
lblStatus.Text =ddlBooks.SelectedValue;
}
}
Try to remove the IsPostBak condition and run the code.see the difference.

Another mistake we often do is forget to ‘Enable View State’ of the page. By default view state is enabled for all controls, there is no need to explicitly enable it. However, if we disable it in ‘web.config’ file, we have to explicitly enable it where ever we want. Here are some guide lines to enable view state of drop down list.

‘View State’ can be disabled/enabled in
I. Web.config file (to disable ‘view sate’ of all pages)
II. Master page
III. Aspx Page.
IV. User control
V. With in the Control itself.
Take an example of ‘drop down list’, when the view state set to false for all pages in ‘web.config’ file,
view state won’t work for all pages. After submitting the page the drop down will have no items bound to it.
To enable view state for a particular page , we have to enable it on both Master page, and the Aspx Page. If the drop down list is placed in a user control, then we have to enable the view state in the user control also, other wise the view state of the drop down will get disabled.
Even if it is set to true in all, but disabled in the control, then it get disabled but the converse is false.
Conclusion:If you want to enable view state on dropdown list when the view state get disabled in web.config file; We should explicitly enable it on the Master page, Aspx Page where it’s being declared and the user control(if it is declared in User control). Then only the viewstate of the control get enabled.
If Viewstate enabled in web.config and disabled in either of master page or Aspx Page, then viewstate of dropdown list get disabled. If the view state enabled on both Master page and Aspx Page, then no need to explicitly enable it in user control and the control itself.