Monday, November 28, 2011

Performance analysis using SharePoint 2010 developer dashboard

In this post I will explained, how we can improve rendering of a page in SharePoint using SharePoint 2010 developer dashboard.
Developer dashboard shows
1. Requests with timings for each item
2. Database queries and their response times
3. Load times for each web part on the page and pre-render time.
4. Number of web server SPRequest(s) and their timing.
5. Any critical events.
How to activate the developer dashboard
There are various ways to activate developer dashboard
1. Power Shell
2. Stsadm command
3. SharePoint object model
In this post, we will use stsadm command to activate developer dashboard.
Stsadm -o setproperty -pn developer-dashboard -pv “ondemand”
If the developer dashboard is set to OnDemand,then button appears in the top right corner just next to login name

When you click the small icon in the top right corner, the Developer Dashboard will be opened and displayed at the bottom of your page as shown in below screen shot

You can see that it has a Green border right now. That generally means its loading quick enough not to be a real problem. It can also render Yellow, which indicates that there's a slight delay and then it could render a Red border which would mean you definitely need to look into it immediately!
Page Request to the left-hand side
You can read out the Page Request, and see what loads and how long it takes to load. This is perfect to use to track down heavy-loading application or finding out what's taking so long to render the page;
How to disable Developer dashboard?
stsadm -o setproperty -pn developer-dashboard -pv “Off”

Sunday, October 23, 2011

How to hide/show the SharePoint 2010 ribbon according to SharePoint group

In this post, I will explain how to hide/show the SharePoint 2010 ribbon according to SharePoint group. Use the following code to do so
Sharepoint:SPSecurityTrimmedControl runat="server" Permissions="EditListItems">
!—Ribbon code-->
/Sharepoint:SPSecurityTrimmedControl>

How to insert data programmatically in SharePoint list using object model

In this post I will explained, how we can programmatically insert data in SharePoint list using SharePoint object model.
Step 1: Create a SharePoint list say Employee_Details with following field
a. EmployeeName
b. EmployeeID
c. JoiningDate
Step 2: Create SharePoint empty project, add visual web part and design the following UI

Step 3: Add the following code in .ascx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace VWPListOperation.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnAdd_Click(object sender, EventArgs e)
{
SPSite mysite = SPContext.Current.Site;
SPWeb myweb = mysite.OpenWeb();
SPListItemCollection listItemsCol = myweb.Lists["Employee_Details"].Items;
SPListItem item = listItemsCol.Add();
item["EmployeeName"] = txtEmployeeName.Text;
item["Title"] = txtDesi.Text;
item["EmployeeID"] = Convert.ToInt32(txtEmployeeID.Text);
if (!JoiningDateTimeControl.IsDateEmpty)
{
item["JoiningDate"] = Convert.ToDateTime(JoiningDateTimeControl.SelectedDate);
}
else
{
item["JoiningDate"] = DateTime.Now;
}
item.Update();
lblMsg.Visible = true;
}

protected void btnCancel_Click(object sender, EventArgs e)
{
txtEmployeeName.Text = String.Empty;
txtDesi.Text = String.Empty;
txtEmployeeID.Text = String.Empty;
//JoiningDateTimeControl.SelectedDate = DateTime.Now;
lblMsg.Visible = false;
}
}
}
Step 4: Following is the result


Tuesday, May 31, 2011

Creating Custom Navigation Provider in SharePoint 2010

Sometimes we need to overwrite the existing navigation provider in SharePoint and we can create/write our own navigation provider to get the data from SharePoint list. This article will help you to implement your own custom navigation provider.
Final Output:

To create custom navigation provider requires following steps
Step 1: create custom site columns, custom content types and then create custom list that used these content types to allow users to easily build hierarchies for navigation provider.

Step 2: Replace the following code in the master page


Step 3:Create new class which should be inherited from "PortalSiteMapProvider" class.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;

usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Caching;
usingMicrosoft.SharePoint;
usingMicrosoft.SharePoint.Security;
usingMicrosoft.SharePoint.Publishing;
usingMicrosoft.SharePoint.Publishing.Navigation;
usingMicrosoft.SharePoint.Administration;
usingSystem.Security.Permissions;
usingSystem.Security;
namespaceTopNavProvider
{
//Assign the neccessary security permissions. TODO - Check the permissions required.
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[SharePointPermissionAttribute(SecurityAction.LinkDemand, ObjectModel = true)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[SharePointPermissionAttribute(SecurityAction.InheritanceDemand, ObjectModel = true)]

//This inherits from the PortalSiteMapProvider class in MOSS, just because it provides some of the functions I need.
//You could just as easily write one for WSS.

public classTopNavProvider: PortalSiteMapProvider
{
//Create the in memory objects for storage and fast retreival
protectedSiteMapNodeCollectiongSiteMapNodeColl;
protectedArrayListgChildParentRelationship;
//These are only the top level nodes that will show in the top nav
protectedArrayListgTopLevelNodes;

privatePortalSiteMapNodegRootNode = null;

public override void Initialize(string pName, System.Collections.Specialized.NameValueCollectionpConfig)
{
// Verify that config isn't null
if (pConfig == null)
throw new ArgumentNullException("config is null");

// Assign the provider a default name if it doesn't have one
if (String.IsNullOrEmpty(pName))
pName = "TopNavProvider";

// Add a default "description" attribute to config if the
// attribute doesn’t exist or is empty
if (string.IsNullOrEmpty(pConfig["description"]))
{
pConfig.Remove("description");
pConfig.Add("description", "top navigation provider");
}

base.Initialize(pName, pConfig);

gChildParentRelationship = new ArrayList();
gTopLevelNodes = new ArrayList();

//Build the site map in memory
LoadTopNavigationFromList();
}

protected virtual void LoadTopNavigationFromList()
{
//Make sure to build the structure in memory only once
lock (this)
{
if (gRootNode != null)
{
return;
}
else
{
//Initialiaze for the first time
SPSite _rootSite = null;
SPWeb _rootWeb = null;
SPList _topnavList = null;

try
{
//Clear the top level nodes and the relationships
gTopLevelNodes.Clear();
gChildParentRelationship.Clear();

//instantiate sites and lists for now. This setting assumes that the list being
//read from for the global top navigation is in the root web of the site collection listed in web.config.
_rootSite = SPContext.Current.Site;
_rootWeb = _rootSite.RootWeb;
_topnavList = _rootWeb.Lists[ConfigurationManager.AppSettings["TopNavigationListName"]];

//Build the root node
//Note: Any top level site of any site collection is assigned to be the rootNode here, not neccessarily the
//top level site of the main site collection
gRootNode = (PortalSiteMapNode)this.RootNode;

//We need to pass the PortalSiteMapNode constructor a PortalWebSiteMapNode object, so here it is
//Note: This is the root node of 1 site collection, but the navigation will be shown in all site collections.
PortalWebSiteMapNode _pwsmn = gRootNode as PortalWebSiteMapNode;

if (_pwsmn != null)
{
//Get the current folder to start. The navigation heirarchy can start at that folder.
SPFolder _currentFolder = _topnavList.RootFolder.SubFolders[ConfigurationManager.AppSettings["NavigationListStartFolderName"]];
//Build the nodes
BuildListNodes(_rootWeb, _currentFolder, _pwsmn, null, true);
}
}
catch (Exception ex)
{
//There was a problem opening the site or the list.
;

}

}
}
}

protected virtual void BuildListNodes(SPWebpCurrentWeb, SPFolderpFolder, PortalWebSiteMapNodepPrtlWebSiteMapNode, PortalSiteMapNodepParentSiteMapNode, boolpRootLevel)
{
// Get the collection of items from this folder
SPQuery _qry = new SPQuery();
_qry.Folder = pFolder;
SortedList _orderedNodes = new SortedList();
int _counter = 100; //for sorting items
try
{
//Browse through the items in the folder and create PortalSiteMapNodes
SPListItemCollection _ic = pCurrentWeb.Lists[pFolder.ParentListId].GetItems(_qry);
foreach (SPListItem _subitem in _ic)
{


//Change the nodeTypes to Authored link for leaf nodes so that the GetChildNodes method is not called for those nodes.
NodeTypes _ntypes = NodeTypes.AuthoredLink;
PortalSiteMapNode _psmn = null;
Boolean _flag = false;
try
{
//Create a PortalSiteMapNode
if (_subitem.Folder != null)
_ntypes = NodeTypes.Default;
ConfigurationManager.AppSettings.Set("Current User", pCurrentWeb.CurrentUser.Name);
SPGroupCollection _gCol = pCurrentWeb.CurrentUser.Groups;

foreach (SPGroupgrp in _gCol)
{
string[] groupName = _subitem["User Group"].ToString().Split('#');

foreach (string grpName in groupName)
{
if ((grp.Name.Equals(grpName.Split(';')[0])) && (_flag == false))
{

_flag = true;
}
}
}


if (_flag == true)
{
_psmn = new PortalSiteMapNode(pPrtlWebSiteMapNode, _subitem.ID.ToString(), _ntypes,
_subitem.GetFormattedValue(ConfigurationManager.AppSettings["UrlLink"]), _subitem.Title,
_subitem.GetFormattedValue(ConfigurationManager.AppSettings["UrlDescription"]));

string _IsNewWindow = Convert.ToString(_subitem.GetFormattedValue(ConfigurationManager.AppSettings["NewWindow"]));
SiteMapNode _node = _psmn as SiteMapNode;
if (_IsNewWindow == "Yes")
{
_node["target"] = "_blank";
}


//Order the nodes
if (_subitem.Folder != null)
{
int _order = Convert.ToInt32(_subitem.GetFormattedValue(ConfigurationManager.AppSettings["FolderItemOrder"]));
_orderedNodes.Add(_order, _psmn);
}
else
{
int _order = Convert.ToInt32(_subitem.GetFormattedValue(ConfigurationManager.AppSettings["ItemOrder"]));
_orderedNodes.Add(_order, _psmn);
}
}


}

catch (Exception ex)
{
//This will happen if 2 items are assigned the same order. Push one item to the last order.
_orderedNodes.Add(_counter++, _psmn);
//No need to process
}

//if this is a folder, fetch and build the heirarchy under this folder
if (_subitem.Folder != null)
BuildListNodes(pCurrentWeb, _subitem.Folder, pPrtlWebSiteMapNode, _psmn, false);
}

//Copy nodes in the right order
foreach (object portalSiteMapNode in _orderedNodes.Values)
{
//Add the node to the different collections
if (pRootLevel)
gTopLevelNodes.Add(portalSiteMapNode);

//If the parent node is not null, add the parent and the child relationship
if (pParentSiteMapNode != null)
gChildParentRelationship.Add(new DictionaryEntry(pParentSiteMapNode.Key, portalSiteMapNode));

}
}
catch (Exception ex)
{
;
}
}

public override SiteMapNodeCollectionGetChildNodes(System.Web.SiteMapNodepNode)
{
returnComposeNodes(pNode);
}

public virtual SiteMapNodeCollectionComposeNodes(System.Web.SiteMapNodepNode)
{
//The SiteMapNodeCollection which represents the children of this node
SiteMapNodeCollection _children = new SiteMapNodeCollection();

try
{
//If an absolute rootnode, then add the top level children which are the same for every site collection
if (pNode == pNode.RootNode)
{
SPSite _rootSite = SPContext.Current.Site;
SPWeb _rootWeb = _rootSite.RootWeb;

//Serve it from cache if possible.

object _topNodes = HttpRuntime.Cache["TopNavRootNodes"];


lock (this)
{

{
gRootNode = null;
LoadTopNavigationFromList();
}

//Else generate the top level nodes from memory. This must be done regardless of option 1 above
for (int i = 0; i lessthan gTopLevelNodes.Count; i++)
{
_children.Add(gTopLevelNodes[i] as PortalSiteMapNode);
}

//Add them to the cache
HttpRuntime.Cache["TopNavRootNodes"] = _children;
}
}
else
//Else this is a subnode, get only the children of that subnode
{
string _nodeKey = pNode.Key;

lock (this)
{
{
gRootNode = null;
LoadTopNavigationFromList();
}

//Else iterate through the nodes and find the children of this node
for (int i = 0; i lessthan gChildParentRelationship.Count; i++)
{
string _nKey = ((DictionaryEntry)gChildParentRelationship[i]).Key as string;

//if this is a child
if (_nodeKey == _nKey)
{
//Get the child from the arraylist
PortalSiteMapNode _child = (PortalSiteMapNode)(((DictionaryEntry)gChildParentRelationship[i]).Value);
if (_child != null)
{
_children.Add(_child as PortalSiteMapNode);
}
else
{
throw new Exception("ArrayLists not in sync.");
}
}
}

//Add the children to the cache
HttpRuntime.Cache["TopNavRootNodes" + _nodeKey] = _children;
}
}
}
catch (Exception ex)
{
//return empty site node collection
return new SiteMapNodeCollection(); // No need to process
}

return _children;
}
}
}

Step 4: Add the entry of the class in web config file of the site

1. Add the following entry under the sitemap -> provider tag
   <siteMap defaultProvider="CurrentNavigation" enabled="true">
      <providers>
 <add name="TopNavProvider" description="Custom provider" type="CustomNavProvider.TopNavProvider, CustomNavProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=11d7cf682" NavigationType="Current" EncodeOutput="true" />
      </providers>
    </sitemap>
2. Add the following entry under app setting tag
 <add key="TopNavigationListName" value="TopNavList"/>
 <add key="CurrentLeftNavigationListName" value="CurrentLeftNavList"/>
 <add key="StaticLeftNavigationListName" value="StaticNavList"/>
 <add key="NavigationListStartFolderName" value="CoreList"/>
 <add key="UrlLink" value="Url Link"/>
 <add key="UrlDescription" value="Url Description"/>
 <add key="NewWindow" value="Open New Window"/>
 <add key="UrlAudience" value="Url Audience"/>
 <add key="ItemOrder" value="Item Order"/>
 <add key="FolderItemOrder" value="Folder Item Order"/>

Monday, May 30, 2011

How to programmatically upload a document in document library and insert metadata in document library

In this post I will explained, how we can programmatically upload a document in document library and insert metadata in document library.
Following function can be used to insert metadata and upload document in document library.
asp:FileUpload ID="FileUpLoadDoc" runat="server" />

Private void BindDataInSPList()
{
try
{
SPSite oSite = new SPSite("SiteURL");
SPWeb oWeb = oSite.OpenWeb();

oWeb.AllowUnsafeUpdates = true;
SPDocumentLibrary mylist = oWeb.Lists["DocumentLibrary"] as SPDocumentLibrary;

string fileName = System.IO.Path.GetFileName(FileUpLoadDoc.PostedFile.FileName);
//Get file extension ( *.doc OR *.docx )
string fileExtension = FileUpLoadDoc.FileName.Substring(FileUpLoadDoc.FileName.IndexOf("."));
byte[] fileBytes = FileUpLoadDoc.FileBytes;
string destUrl = mylist.RootFolder.Url + "/" + fileName;
SPFiledestFile = mylist.RootFolder.Files.Add(destUrl, fileBytes, true);
destFile.Update();
oWeb.AllowUnsafeUpdates = true;
//update metadata
destFile.Item["Name"] = txtName.Text;
destFile.Item["Address"] = txtAddress.Text;

destFile.Item.Update();
}
catch (Exception ex)
{ ; }

}

Sunday, May 29, 2011

Create Guid in Visual Studio 2010

This article will explain how to create Guid in Visual Studio 2010 using guidgen.exe tool.
Sometime Create Guid option is disabled when you start using Visual Studio 2010.


To enable the Create Guid option in Visual Studio 2010 follow the below steps
Step 1: Choose the Tools -> External Tools.
Step 2:


Click the Browse button and find the guidgen.exe in the “C:\program files\Microsoft sdks\windows\v7.0a\bin\NETFX 4.0 Tools\ “folder (VS 2010).
Click the Browse button and find the guidgen.exe in the “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\” folder (VS 2005).
Click the Browse button and find the guidgen.exe in the “C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\ “folder (VS 2008).
Then click on “OK”.
Step 3: Create Guid choose Tools -> Create Guid.

Thursday, March 31, 2011

Create Silverlight Accordion Control in SharePoint

This article will explain how to create Silverlight accordion control in SharePoint context.
Expected Output:




















Steps to create Silverlight application to be hosted on SharePoint Silverlight webpart

1. Create Silverlight application.
2. Create an entity class. This class will contain property as TeamName, Captain and CaptainImage of teams.






3. MainPage.xaml

























4. MainPage.xaml.cs


















































5. Data retrieve from SharePoint List

Tuesday, March 29, 2011

Programmatically attach workflow to List Item of SharePoint List

In this article, I will explain how to programmatically attach workflow to list item of SharePoint list. Workflow can be attached to a list while adding new item or updating the item.
Following method can be used to attach workflow to list item programmatically
Public void AttachWorkflowToListItem (string ListName, int ListItemID, SPSite oSite, SPWeb oWeb)
{
oWeb.AllowUnsafeUpdates = true;
SPList _ListName = oWeb.Lists [ListName];
SPListItem _ListItem = _ ListName.GetItemById (Convert.ToInt32 (ListItemID));
//Creates and starts a new workflow instance on a specified list item
SPWorkflowManager _manager = oSite.WorkflowManager;
// collect all workflows which are associated with the List
SPWorkflowAssociationCollection _associationCollection = _ ListName.WorkflowAssociations;
LookupAndStartWorkflow (_ListItem, _manager, _associationCollection, "WorkflowID");
}
Private static void LookupAndStartWorkflow (SPListItem ListItem, SPWorkflowManager manager, SPWorkflowAssociationCollection AssociationCollection, string WorkflowId)
{
//iterate workflow associations and lookup the workflow to be started
Foreach (SPWorkflowAssociation association in AssociationCollection)
{
//if the workflow association matches the workflow we are looking for,
//get its association data and start the workflow

if (association.Name.Equals(WorkflowId))
{
//get workflow association data
String data = association.AssociationData;
//start workflow
SPWorkflow wf = manager.StartWorkflow (ListItem, association, "open tag Data close tag Data", true);
break;
}
}
}

Monday, February 28, 2011

Programmatically add web part to SharePoint 2010 web part page

In this article, I will explain how to programmatically add web part to sharepoint web part page.
1. Select SharePoint empty project template then add Module.
2. Right click on Module ,then add ->Existing Item
Browse to “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\SiteTemplates\sts” select default.aspx page.
3. Update the elements manifest to tell where to find the custom file and where it needs to deploy.
?xml version="1.0" encoding="utf-8"?>
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
Module Name="Home" Url="" Path="">
File Path="Home\default.aspx" Url="default.aspx" IgnoreIfAlreadyExists="TRUE" Type="Ghostable">
AllUsersWebPart WebPartOrder="1"
WebPartZoneID="Left">
![CDATA[
webParts>
webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
metaData>
importErrorMessage>Cannot import this WebPart.
/importErrorMessage>
/metaData>
data>
properties>
property name="HelpUrl" type="string" />
property name="AllowClose" type="bool">True /property>
property name="ExportMode" type="exportmode">All /property>
property name="Hidden" type="bool">False /property>
property name="AllowEdit" type="bool">True /property>
property name="Direction" type="direction">NotSet /property>
property name="TitleIconImageUrl" type="string" />
property name="AllowConnect" type="bool">True /property>
property name="HelpMode" type="helpmode">Modal /property>
property name="CustomProperties" type="string" null="true" />
property name="AllowHide" type="bool">True /property>
property name="Description" type="string">Silverlight webpart /property>
property name="CatalogIconImageUrl" type="string" />
property name="MinRuntimeVersion" type="string" null="true" />
property name="ApplicationXml" type="string" />
property name="AllowMinimize" type="bool">True /property>
property name="AllowZoneChange" type="bool">True /property>
property name="CustomInitParameters" type="string" null="true"/>
property name="Height" type="unit">500px /property>
property name="Width" type="unit">
property name="Title" type="string">Home /property>
property name="TitleBar" type="string">Home /property>
property name="TitleUrl" type="string" >Home /property>
property name="Url" type="string">
/_LAYOUTS/ClientBin/SilverlighApplicationDemo.xap
/property>
property name="WindowlessMode" type="bool">True
/properties>
/data>
/webPart>
/webParts> ]]>
/AllUsersWebPart>
/File>
/Module>
/Elements>
How to uninstall an assembly from GAC (Global assembly Cache)
In this article, I will explain different ways to uninstall an assembly from GAC
1. Using the Windows interface
a. Navigate to the GAC, which is located at %System Drive%\Windows\Assembly.
b. Right-click assembly file that is included in your application, click Uninstall, and then click yes to confirm.
2. Using the command line
a. Click Start, then point to Command Prompt, and run it as administrator.
b. At the command prompt, Navigate to following path:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"
c.Enter following command gacutil /u "fully qualified assembly name".
In this command, fully qualified assembly name is the name of the assembly to uninstall from the GAC.
For e.g.
gacutil /u "FirstApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ef4b5fc568888"
Here FirstApplication is assembly name

Monday, January 31, 2011

Programmatically create custom default page for SharePoint 2010 Team site

In this article, I will explain how to programmatically create custom default page and set it to root level.

Step 1. Select SharePoint empty project template and then add Module.
Step 2.Update the elements manifest to tell where to find the custom file /Page and where it needs to deploy.

. ?xml version="1.0" encoding="utf-8"?>
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
Module Name="Home" Url="" Path="">. ?xml version="1.0" encoding="utf-8"?>
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
Module Name="Home" Url="" Path="">
File Path="Home\default.aspx" Url="default.aspx" IgnoreIfAlreadyExists="TRUE" Type="Ghostable">
/File>
/Module>
/Elements>


Step 3. Add event handler to the feature.
SPWeb oWeb = null;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
oWeb = (SPWeb)properties.Feature.Parent;
SPFolder rootfolder = oWeb.RootFolder;
rootfolder.WelcomePage = "default.aspx";
rootfolder.Update();
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
oWeb = (SPWeb)properties.Feature.Parent;
SPFolder rootfolder = oWeb.RootFolder;
rootfolder.WelcomePage = "SitePages/Home.aspx";
rootfolder.Update();
}

Monday, January 24, 2011

Method to get Current logged In user using Client object model

In this article, I will show method used to get current logged In user using client object model.

private User GetCurrentLoggedInUser()
{
Web oWebSite = ClientContext.Current.Web;
ClientContext.Current.Load(oWebSite);
ClientContext.Current.ExecuteQuery();

User oUser = oWebSite.CurrentUser;
ClientContext.Current.Load(oUser);
ClientContext.Current.ExecuteQuery();
return oUser;
}
This method return User object. so to get loggedIn user create User class object and call this method.
Private User oUser = GetCurrentLoggedInUser ();

Create Silverlight Applications to Access SharePoint 2010 List Data using Client Object Model

In this article, I will create a simple Silverlight 4 application that displays a SharePoint 2010 list data inside a datagrid control. To do so, I need to follow given steps:-
1. Create a Silverlight Application Project.
2. Add code to access SharePoint list data.
3. Deploy the solution.
4. Test the solution.

Create a Silverlight Application Project

1. Start VS 2010, Click File, point to New Project, then select Silverlight Application.

2. At the top of the screen, select .NET Framework 3.5, type SilverlightApplicationDemo in the Name box and then click ok.

3. The New Silverlight Application dialog box appears, and then unchecks the “Host the Silverlight application in a new web site” option. We don’t need it even though you can use this to host your silverlight application and select Silverlight 4 as silverlight version.

4. Add reference to the SharePoint silverlight client object model. For doing so in solution explorer, right click on Add References.

5. Next, browse to “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”, then select Microsoft.SharePoint.ClientSilverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll, and click OK.


Add Code to access SharePoint list data

1. To view data, drag a DataGrid control from the toolbox onto existing grid in the MainPage.xaml silverlight Designer. And set AutoGenerateColumns to true.
2. Open MainPage.xaml.cs and then add following statement at the top of the file.
using Microsoft.SharePoint.Client;

3. Add the following class before the MainPage class.
public class EmpInfo
{
// Public properties
public string EmpID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
4. ListItemCollection gempItemCol
ObservableCollection< EmpInfo > gEmpInfo= new ObservableCollection< EmpInfo >();

public MainPage()
{
InitializeComponent();
GetEmpData();
}
private void GetEmpData ()
{
try
{
ClientContext Context = new ClientContext(ApplicationContext.Current.Url);
Context.Load(Context.Web);
List _emps = Context.Web.Lists.GetByTitle(“emp”);
Context.Load(_channels);
CamlQuery _query = new Microsoft.SharePoint.Client.CamlQuery();
string _camlQueryXml = @"View> /View>";
_query.ViewXml = _camlQueryXml;
gempItemCol =_emps.GetItems(_query);
Context.Load(gempItemCol);
Context.ExecuteQueryAsync(OnRequestSucceeded, null);
}
catch (Exception ex)
{;}
}
private void OnRequestSucceeded (Object sender, ClientRequestSucceededEventArgs args)
{
try
{
Dispatcher.BeginInvoke(BindEmpsData);
}
catch (Exception ex)
{; }
}

private void BindEmpsData ()
{
try
{
foreach (ListItem _item in gempItemCol)
{
_ EmpID= _item.FieldValues["EmpID"] as FieldLookupValue;//if taken lookup field
String _strEmpID;
if (_EmpID == null)
_ strEmpID = string.Empty;
else
_ strEmpID = _ EmpID.LookupValue;

gEmpInfo.Add(new EmpInfo()
{
Name = Convert.ToString(_item["Name"]),
EmpID = Convert.ToString(_item.Id),
Address== Convert.ToString(_item["Address "])
});
}
lstEmployee.ItemsSource = gEmpInfo;//Bind DataGrid
}
catch (Exception ex)
{ ; }
}

Deploy the solution

1. To deploy the solution onto SharePoint, the resulting .xap file of silverlight application must be present in the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder.
2. To do so there are two ways
a) You can change the output path to “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”.
b) Manual copy and paste it in ClientBin folder.
3. Build the solution and follow any of the above approach.

Test the solution

1. Navigate to the SharePoint site.
2. Select Edit Page icon.
3. Click Insert and then click web part, select Media and Content from web part list and then click add.
4. In the silverlight web part dialog box type /_layouts/ClientBin/ SilverlightApplicationDemo.xap as URL and then click ok.