Monday, 5 November 2012


Accessing Data in a SharePoint 2010 Web Part by using LINQ
Task yo complete: Ojective for this exercise is to query and displays it in a DataGrid control. To complete this task, you must do the following:
·         Create a Visual Web Part Project
·         Generate LINQ to SharePoint Proxy Code
·         Add Code to Read Data from a SharePoint List
·         Deploy and Add the Web Part to a Web Part Page
Create a Visual Web Part Project
In this task, you create a Visual Web Part project in Microsoft Visual Studio 2010.
To create the Visual Web Part
1.     Start Visual Studio 2010, click File, point to New, and then click Project.
2.     Navigate to the Visual C# node in the Installed Templates section, click SharePoint, and then click 2010.
3.     Select the Visual Web Part project template, provide a name (such as AccessSPDatawithLINQ) and a location for your project, and then click OK.
4.     In the What local site do you want to use for debugging drop-down list, select the site to use (such as http://localhost/sites/MySampleWebSite). Also select theDeploy as a farm solution option and then click Finish.
Note that after the project is created, Solution Explorer contains the visual Web Part named VisualWebPart1 

Generate LINQ to SharePoint Proxy Code
In this task, you use the spmetal.exe code-generation utility to generate the LINQ to SharePoint proxy code. The tool generates entity class code that Visual Studio 2010 uses as an interface to obtain IntelliSense and enable LINQ-based queries to be performed on SharePoint Server 2010 lists.
To generate the LINQ proxy code
1.     In Solution Explorer, right-click AccessSPDatawithLINQ and then click Open Folder in Windows Explorer.
2.     Press and hold the SHIFT key, right-click the Explorer window, and then click Open command window here to open the command window in the current project directory.
3.     In the command window, type the following command and press the ENTER key to set the path of the SharePoint Server 2010 folder.
set path=%path%;c:\program files\common files\microsoft shared\web server extensions\14\bin
4.     In the command window, type the following command and press the ENTER key to generate the LINQ to SharePoint proxy code. Replace the SharePoint site URL with your own site's URL.
spmetal.exe /web:http://localhost/sites/MySampleWebSite /namespace:AccessSPDatawithLINQ.VisualWebPart1 /code:SPLinq.cs
This command creates the SPLinq.cs file in the AccessSPDatawithLINQ project folder.
5.     Close the command window.
6.     Now add the file to the project. Switch back to the Visual Studio project screen.
7.     In Solution Explorer, right-click AccessSPDatawithLINQ, point to Add, and then click Existing Item.
8.     Select SPLinq.cs from the Add Existing Item dialog window and then click Add.
9.     In Solution Explorer, right-click References and then click Add Reference.
10. Click the Browse tab and type C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI in the File Name box.
11. Select Microsoft.SharePoint.Linq.dll and then click OK.
Add Code to Read Data from a SharePoint List
In this task, you add code to your solution that enables the visual Web Part to retrieve data from the SharePoint Server 2010 lists.
To add code to the project
1.     In Solution Explorer, expand VisualWebPart1 and then double-click VisualWebPart1UserControl.ascx. Visual Studio displays the HTML for the visual Web Part user control.
2.     Add the following code at the bottom of the existing code to construct the grid view.
HTML
<%@ 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="Title" HeaderText="Title"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="JobTitle" HeaderText="JobTitle"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="ProjectTitle" HeaderText="ProjectTitle"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="DueDate" HeaderText="DueDate"></SharePoint:SPBoundField>
  </Columns>
</SharePoint:SPGridView>

The HTML for the visual Web Part user control should resemble Figure 2 after you add the code.

3.     In Solution Explorer, right-click VisualWebPart1UserControl.ascx and then click View Code.
4.     Add the following statements to the code at the top of the code screen.

using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using System.Linq;
5.     Insert the following code inside the Page_Load method.

SPLinqDataContext dc = new SPLinqDataContext(SPContext.Current.Web.Url); 
EntityList<EmployeesItem> Employees = dc.GetList<EmployeesItem>("Employees"); 
var empQuery = from emp in Employees
               where emp.Project.DueDate < DateTime.Now.AddMonths(6)
               select new
               {
                   emp.Title,
                   emp.JobTitle,
                   ProjectTitle = emp.Project.Title,
                   DueDate = emp.Project.DueDate.Value.ToShortDateString()
               }; 
spGridView.DataSource = empQuery;
spGridView.DataBind();
Deploy and Add the Web Part to a Web Part Page
In this task, you deploy the Web Part and add it to the Home page on the SharePoint Server 2010 website.
To deploy and test the visual Web Part
1.     In Solution Explorer, right-click AccessSPDatawithLINQ and then click Deploy. This builds and deploys the visual Web Part to the SharePoint site that you specified earlier.
2.     Open Internet Explorer and browse to the SharePoint site.
3.     Click the Edit icon at the top of the Home page to start to edit the page.
4.     On the ribbon, on the Editing Tools tab, click Insert, and then click Web Part.
5.     In the Categories section, click Custom, and in the Web Parts section, click SPLinqDemoTitle, and then click Add as shown in Figure 3.
On the ribbon, click Stop Editing to save the page and stop editing.
6.     Close Internet Explorer.



Friday, 19 October 2012

Sharepoint 2010 Server Object Model


Sharepoint 2010: Server Object Model
This article explains the new object model hierarchy in SharePoint 2010, which describes about each object in below diagram.


















 We can broadly divide the object model in two parts:
Administration and Configuration Classes: These classes are generally used for administration and configuration purposes.
·         SPForm
·         SPServer
·         SPService
·         SPServiceInstance
·         SPWebService
Site Provisioning and Content Access Classes: These classes are used for programmatically provisioning sites and accessing data contained within sites, lists, and libraries.
·         SPWebApplication
·         SPSite
·         SPWeb
·         SPList
·         SPListItem
·         SPFile
·         SPFolder

SPFormSPFarm object is top level object in object model hierarchy and represents the SharePoint farm. All server side code must be executed on a server that is a member of a SharePoint farm.

We can get the instance of server form as in below code:
SPFarm sFarm = SPFarm.Local;

SPServer: The SPServer object represents a specific server within a SharePoint farm.

To list all servers in the form, we can use below code:
foreach (SPServer server in SPFarm.Local.Servers)
{
Console.WriteLine(server.DisplayName);
}

SPService: SharePoint 2010 provide platform for running services across a farm of servers. All services are derived from SPService class. Example of such services are Search service, Performance point services, Business connectivity service (BCS) etc.

SPServiceInstance: The SPServiceInstance object represents an instance of a service that
is running on a particular server.

To get the service instance, following code can be used:
foreach (SPServiceInstance service in SPServer.Local.ServiceInstances)
{
Console.WriteLine(service.TypeName);
}

SPWebService: SPWebService represents a Web service that contains one or more Web applications. This Web service allows a Web browser to access the content in SharePoint sites.


SPWebApplication: WebApplication is the topmost object in the site hierarchy, Each Web Application configured in SharePoint is represented by SPWebApplication object in object model

SharePoint runs on top of Internet Information Services (IIS) and ASP.NET. A SharePoint farm
can host many web applications, each of which is a stand-alone ASP.NET application running in its own
Application Pool.
Following code will list all the web applications running on the server form:
SPWebService webService = SPFarm.Local.Services.
OfType<SPWebService>().First();
foreach (SPWebApplication app in webService.WebApplications)
{
Console.WriteLine(app.Name);
}

SPSite: Within a web application exists one or more site collections, which are collections of
web sites. The SPSite object is one of the primary entry points to the Server Object Model and represents a collection of sites in a Web application, including a top-level Web site and all its subsites..

SPSite object can be instanciated as below:

using (SPSite oSiteCollection = new SPSite("Absolute_URL")
{
    ...
}

SPWeb: Within the object model, individual sites are represented by SPWeb objects. Please note here that SPSite object represent site collection and SPWeb represent individual sites within site collection.

Code for accessing all sites (SPWeb) in site collection (SPSite is given below:
using (SPSite site = new SPSite("YourSiteCollectionURL"))
{
foreach (SPWeb web in site.AllWebs)
{
Console.WriteLine(web.Title);
web.Dispose();
}
}

SPList: In the Server Object Model, both lists and document libraries are represented by an SPList object.
Please note that document libraries are also represented by SPDocumentLibrary
Objects and is derived from the SPList class.

Code to access all list in site collection is given below:

using (SPSite site = new SPSite("YourSiteCollectionURL "))
{
using (SPWeb root = site.RootWeb)
{
foreach (SPList list in root.Lists)
{
Console.WriteLine(list.Title);
}
} 

SPListItem: Each item in a list or library is represented by an SPListItem object  and accessed through SPList.Items collection. Please note that the Items property returns all the files in a document library, including files in subfolders, but not the folders themselves. In a document library, folders are not considered items.

Code to access list items (SPListItem) is given below:

using (SPWeb oWebsite = new SPSite("http://Server/sites/SiteCollection").OpenWeb())
{

    SPList oList = oWebsite.Lists["Projects"];

    SPListItemCollection collItem = oList.Items;

    for (int i = 0; i < oList.ItemCount; i++)
    {
        string itemName = collItem[i].Name;

        Label1.Text += itemName + "<BR>";

    }
}

SPFile: If we create a document library and upload a Word document, the SPListItem
object that represents the document will contain only the document title and a few
metadata fields. To perform work on the document, we need to use an SPFile object.


SPFolder: document libraries can also contain folders that operate in the same
way as folders in the file system.

To list all folders in the site, we can use following code:
using (SPSite site = new SPSite("YourSiteCollectionURL"))
{
using (SPWeb root = site.RootWeb)
{
foreach (SPFolder folder in folders)
{
Console.Write(folder.Name + "\t");
if (folder.DocumentLibrary != null)
{
Console.WriteLine("Corresponding library: " + folder.DocumentLibrary.Title);
}
else
Console.WriteLine(string.Empty);
}
listFolders(folder.SubFolders);
}
}
}

Hope this is informative to you. Please let me know  your feedback/comments.