Ads

Tuesday, 2 April 2013

SharePoint2010 Client object Model With Example.


The Client Object Model (OM) is a new programming interface for SharePoint 2010 where code runs on a user’s client machine against a local object model and interacts with data on the SharePoint Server. Client OM methods can be called from JavaScript, .NET code or Silverlight code and makes building rich client applications for SharePoint easy. One API to rule them all – Yep, whether its WPF or Windows Forms or Silverlight or Javascript – your code uses Client Object Model to interact with the SharePoint site to access the data. Now, there is something common that everybody can use instead of creating their own wrapper services to access SharePoint data!


DLL used.
1.        Microsoft.SharePoint.Client
2.        Microsoft.SharePoint.Client.Runtime
DLL Path:

Path: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\

Create new window application and include give the ref. to above mentioned file. The following code I explain the different-2 ways to fetching the data using SharePoint2010 Client model.

To fetching the data using Client object model we have to create the client context using the ClientContext(@"http://home:8082");. ClientContext(@"http://home:8082") takes the URL of the site as constructor.

The bettor approach fetch the data you needs.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;

namespace ClientObMO
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //GettextPass1();
            //GetLambdaexvalues();
            // GetLambdaexForUpdatevalues();
            //GetvalueswithIqueryable();
            GetvalueswithIEnumerable();
        }

        // simple way
        public void GettextPass1()
        {
            //var ctx = new ClientContext(@"http://home:8082");
            var newtcx = new ClientContext(@"http://home:8082");
           
           // get the context of the web
            var web = newtcx.Web;

            List _List = web.Lists.GetByTitle("Site Pages");
           
            /// only load the list
            ///
           
            ///this will only load the list and it's property  you will not able to read the other values
            newtcx.Load(_List);
           
            //
            newtcx.ExecuteQuery();

            var title = _List.Title;

            var dis = _List.Description;

            MessageBox.Show("Title:" + title + " desc:" + dis);
        }

        // Lambda Ex.
        public void GetLambdaexvalues()
        {
            var newtcx = new ClientContext(@"http://home:8082");

            var web = newtcx.Web;
            // only get the title and discription  the values you want
            // rest of the values you will get error.
            newtcx.Load(web, X => X.Title, X => X.Description);
            newtcx.ExecuteQuery();

            var title = web.Title;
            var dis = web.Description;
           
            // following line give error becuase the value not load in lambda ex.
            //var content = web.ContentTypes;

            MessageBox.Show("Title:" + title + " desc:" + dis);
        }
        
        // Lambda Ex with update
        public void GetLambdaexForUpdatevalues()
        {
            var newtcx = new ClientContext(@"http://home:8082");
            var web = newtcx.Web;
            newtcx.Load(web, X => X.Title, X => X.Description);
            newtcx.ExecuteQuery();

            var title = web.Title;
            var dis = web.Description;
            // give error for getiing the values
            // MessageBox.Show(web.QuickLaunchEnabled.ToString());

            web.QuickLaunchEnabled = true;
            web.Update();
            newtcx.ExecuteQuery();
            MessageBox.Show("Title:" + title + " desc:" + dis);
        }

        // load the data Using  IQueryable
        public void GetvalueswithIQueryable()
        {
           
            var newtcx = new ClientContext(@"http://home:8082");
            var web = newtcx.Web;
            var lists = web.Lists;

            newtcx.Load(
             lists,
             list => list
                 .Include(
                     x => x.Title,
                     x => x.Hidden)
                 .Where(x => x.BaseType == BaseType.GenericList)
              );


            newtcx.ExecuteQuery();
            string str = "\n";
            foreach (var item in lists)
            {
                str =    str + item.Title + "\n";
            }

            MessageBox.Show(str);
        }

        // get values with using IEnumerable
        public void GetvalueswithIEnumerable()
        {
           
            var newtcx = new ClientContext(@"http://home:8082");
            var web = newtcx.Web;
            var lists = web.Lists;

            IEnumerable<List> _list = newtcx.LoadQuery(lists.Where(x => x.BaseType ==BaseType.GenericList));
          
            newtcx.ExecuteQuery();
            string str = "\n";
            foreach (var item in _list)
            {
                str = str + item.Title + "\n";
            }

            MessageBox.Show(str);
        }
    }
}

Get list item count in Ecma script

var selectedItems = SP.ListOperation.Selection.getSelectedItems();
var ci2 = CountDictionary(selectedItems);



Exercise 1: Retrieving Lists
References--Microsoft.SharePoint.Client       Micorosoft.SharePoint.Client.Runtime
C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\ISAPI


C#
1.      private void ShowButton_Click(object sender, EventArgs e)
2.      {
3.              //Show the hourglass wait cursor
4.              this.Cursor = Cursors.WaitCursor;
5.              ListsListBox.Items.Clear();
6.              //Get a context
7.              using (ClientOM.ClientContext ctx =
8.              new ClientOM.ClientContext(UrlTextBox.Text))
9.              {
10.                   //Get the site
11.                   ClientOM.Web site = ctx.Web;
12.                   ctx.Load(site);
13.                   //Get Lists
14.                   ctx.Load(site.Lists);
15.                   //Query
16.                   ctx.ExecuteQuery();
17.                   //Fill List
18.                   foreach (ClientOM.List list in site.Lists)
19.                   {
20.                       ListsListBox.Items.Add(list.Title);
21.                   }
22.                   //Return the cursor to normal
23.                   this.Cursor = Cursors.Default;
24.           }
25.   }

VB.NET
Private Sub ShowButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        Handles ShowButton.Click
        'Show the hourglass wait cursor
        Me.Cursor = Cursors.WaitCursor
        ListsListBox.Items.Clear()
        'Get a context
        Using ctx As New ClientOM.ClientContext(UrlTextBox.Text)
            'Get the site
            Dim site As ClientOM.Web = ctx.Web
            ctx.Load(site)
            'Get Lists
            ctx.Load(site.Lists)
            'Query
            ctx.ExecuteQuery()
            'Fill List
            For Each list As ClientOM.List In site.Lists
                ListsListBox.Items.Add(list.Title)
            Next
            'Return the cursor to normal
            Me.Cursor = Cursors.[Default]
        End Using
    End Sub

 

Check Whether a User is a Member of a SharePoint Group or Not Using ECMA Script and hide some filed according to User

<script type="text/javascript" src="../../Scripts/jquery-1.7.2.min.js"></script>

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");

var context = null;
var web = null;
var _currentUser = null;
var usersMgr=null;
var groupMgr =null;
var groupCollection=null;


function getWebUserData()
{

context = new SP.ClientContext.get_current();

web = context.get_web();

this._currentUser = web.get_currentUser();

context.load(this._currentUser);

this.groupCollection = web.get_siteGroups();

this.groupMgr = groupCollection.getById(13); // ID Of the Group

this.usersMgr= groupMgr.get_users();

context.load(this.groupCollection);

context.load(this.groupMgr);

context.load(this.usersMgr);

context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));

}


function onSuccessMethod(sender, args)
{

var isManager=false;

var listEnumerator = this.usersMgr.getEnumerator();

while (listEnumerator.moveNext())
{
var item = listEnumerator.get_current();

userName = item.get_loginName();

if(userName == this._currentUser.get_loginName())
{
isManager=true;
break;
}

}

if(isManager==true)
{
$("nobr:contains('Approval Status')").
parent('h3').parent('td').parent('tr').show();
$("nobr:contains('Approval Comments')").
parent('h3').parent('td').parent('tr').show();

}
else
{
$("nobr:contains('Approval Status')").
parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Approval Comments')").
parent('h3').parent('td').parent('tr').hide();
}


}


function onFailureMethod(sender, args)
{
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}



</Script>

Get The List Item Value in SharePoint 2010 Using ECMAScript

First Set the j query refference into your page.
<script type="text/javascript" src="../../Scripts/jquery-1.7.2.min.js"></script>

Get the query string value in the edit or display page.

<Script type="text/javascript">
function GetQueryStringParams(sParam)
{

var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}</Script>


Finaly write the ecmca sript (Which will load on page load)

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getSetListItem, "sp.js");
var itemId=GetQueryStringParams('id');
var listItem;
var list;
var clientContext;
function getSetListItem() {
this.clientContext = SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
this.list = webSite.get_lists().getByTitle("ENS Email");
this.listItem = list.getItemById(itemId);
clientContext.load(this.listItem);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess),
Function.createDelegate(this, this.OnLoadFailed));
}
}

function OnLoadSuccess(sender, args) {
var approval=false;
approval= this.listItem.get_item("Approval_x0020_Needed");
//where Approval_x0020_Needed is a yes/no field in the list
if (approval==true)
{
//to show or hide the list items
$("nobr:contains('Approval Status')").
parent('h3').parent('td').parent('tr').show();
$("nobr:contains('Approval Comments')").
parent('h3').parent('td').parent('tr').show();

}
else
{
//to show or hide the list items
$("nobr:contains('Approval Status')").
parent('h3').parent('td').parent('tr').hide();
$("nobr:contains('Approval Comments')").
parent('h3').parent('td').parent('tr').hide();

}
}
function OnLoadFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>



To set the value use following

function OnLoadSuccess(sender, args) {
var value = this.listItem.get_item("SampleOne");
this.listItem.set_item("SampleTwo", value);
this.listItem.update();
this.clientContext.load(this.listItem);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess1),
Function.createDelegate(this, this.OnLoadFailed));
}

function OnLoadSuccess1(sender, args) {
alert(this.listItem.get_item("SampleTwo"));
}
function OnLoadFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}



you can also call the function like
<input id="btnGetSetListItem" onclick="getSetListItem()" type="button" value="Get & Set List Item" />

Ecma to GetListItem and fill in dropdown

<script type=”text/ecmascript” language=”ecmascript”>

ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
var ItemContainer = { ItemList: [] };

function retrieveListItems() {

var clientContext = SP.ClientContext.get_current();
// Get the SharePoint list by giving the display name of the list.
var oList = clientContext.get_web().get_lists().getByTitle(‘Categories’);
// To retreive all items use the predefined createAllItemsQuery operation.
var camlQuery = SP.CamlQuery.createAllItemsQuery();
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onListDataLoadQuerySucceeded),
Function.createDelegate(this, this.onListDataLoadQueryFailed));
}



// Callback function if the item retrieval Async call get successful.
function onListDataLoadQuerySucceeded(sender, args) {
var listItemInfo = ”;
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
// Fill a json object with Id and Value properties.
var tempItem = { Id: oListItem.get_id(), Value: oListItem.get_item(‘Title’) };
ItemContainer.ItemList.push(tempItem);
}
// Fill the drop down with retrieved data.
fillDropDown();
}
// Callback function if item retrieval failes.
function onListDataLoadQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}


// Fill the drop down with the retrieved list item data.
function fillDropDown() {
var ddlCategory = document.getElementById(‘ddlCategory’);
if (ddlCategory != null) {
for (var i = 0; i < ItemContainer.ItemList.length; i++) {
var theOption = new Option;
theOption.value = ItemContainer.ItemList[i].Id;
theOption.text = ItemContainer.ItemList[i].Value;
ddlCategory.options[i] = theOption;
}
}
}


</script>

Get lookup value in clientcontex in sharepoint 2010 using ECMA script


<script language="ecmascript" type="text/ecmascript">

        var listItem;
        var list;
        var clientContext;

        function getLookUp() {
            this.clientContext = SP.ClientContext.get_current();
            if (this.clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("Custom");
                this.listItem = list.getItemById(5);
                clientContext.load(this.listItem);
                this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }

        function OnLoadSuccess(sender, args) {
            var lookup = this.listItem.get_item("LookupSingleValue");
            alert("Lookup Id: " + lookup.get_lookupId() + "\n Lookup Value: " + lookup.get_lookupValue());


        }

        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    <input id="btnGetLookUp" onclick="getLookUp()" type="button" value="Get Look Up" />

See Real error in SharePoint by modifying web.config file

Showing the real error message in SharePoint
There are two settings in your web.config you need to change to enable custom errors.
This web.config is located in c:\inetpub\wwwroot\VirtualDirectories. In that folder you have 2 possible folder names: folder names with a number and folder names with a name. If you are using hostnames then the web.config file you are looking for is contains in the folder. If you are not using hostnames, the name of the folder corresponds to the port your web application is running on.

Open the web.config and look for the CallStack=”false” attribute. Put it to true.
Then search for the CustomErrors=”on” tag and change it to off.

Once those two actions are done you will see a more detailed error message.

Programatically Modifying-Web-Config-File : C# to Change web.config
Sometimes as per requirement, we need to add third party DLL's to our SharePoint solution in order to achieve some functionality that is not available in SharePoint. But in order to use this third party DLL in our application, we sometimes need to follow the below outlined steps.
In order to place the DLL in the bin folder of the sharepoint site, we would have to modify the Trust Level attribute from WSS_Minimal to Full in the web config file of the SharePoint site.

Here is the code snipet to make the above mentioned changes in the web config file programmatically. For this example, I am placing the code snipet in the feature activated event of a Feature present in the solution, having scope of web application.
// Gets the current webapplication from feature properties.                        SPWebApplication webApp = properties.Feature.Parent as SPWebApplication 
   // Declairs the webConfigmodification variable.
   SPWebConfigModification myModification = newSPWebConfigModification("level", "configuration/system.web/trust");
   //Gets a collection of web config modification.
   System.Collections.ObjectModel.Collection<SPWebConfigModification> allModifications = webApp.WebConfigModifications;

         myModification.Value = "Full";
         myModification.Owner = "OwnerName";
         myModification.Sequence = 1;    
         myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute; 
         allModifications.Add(myModification); // Add the modifications.

   SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
   webApp.Update(); // Update the Web application.


Removing-web-config-modifications-made-by-user: C# to Change web.config

Sometimes it is required to make modifications in the web config file of a sharepoint site in order to achieve some functionality. For doing this it is suggested to place the code spinet in the feature activated event of a feature, so that whenever activating that feature in the sharepoint site the required changes in the web config file are made automatically.
To know more on how to modify web config file, please refer C# to Change web.config
Its very important from the security point of view to remove all the modifications made by a user while deactivating the feature. The below code snipet will help you to achieve this. Put these code snipet in the feature deactivating event of the same feature which made those modifications.
// Get the current web application from featutre property.
SPWebApplication webApp = properties.Feature.Parent asSPWebApplication;
// Declairs the webConfigmodification variable.
Collection<SPWebConfigModification> modificationCollection = webApp.WebConfigModifications;
// Declairs the webConfigmodification variable.
Collection<SPWebConfigModification> removeCollection = newCollection<SPWebConfigModification>();
int count = modificationCollection.Count;

for (int i = 0; i < count; i++)
   {
      SPWebConfigModification modification = modificationCollection[i];
         // check and get all the recent modifications made by "TwitterWebPart" owner.
         if (modification.Owner == "OwnerName")
                  {
                        removeCollection.Add(modification); // collect modifications to delete
                  }
   }
// now delete the modifications from the web application
if (removeCollection.Count > 0)
         {
            foreach (SPWebConfigModification modificationItem in removeCollection)
               {                .
                   webApp.WebConfigModifications.Remove(modificationItem);  //remove the modifications from web config
               }
        }
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApp.Update();

Ads