Apr 3, 2012

Client Object Model Part -5


We are continuing from the last post where we created some examples using Managed COM. Please read post from Part -1 to Part - 4 to see all the examples.

In this post we will create the folders inside a list or document library using COM.
Create Folders In List :

  using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                Web currentWeb = clientContext.Web;
                List list = currentWeb.Lists.GetByTitle("NewList");
                list.EnableFolderCreation = true;
                FolderCollection folderColl = list.RootFolder.Folders;
               
                clientContext.Load(currentWeb);
                clientContext.Load(list);
                clientContext.Load(folderColl);

                clientContext.ExecuteQuery();
                string folderName = "Folder1";
                string newFolderUrl = list.Title + "/" + folderName;

                Folder existingFolder = null;
                string relativURL = currentWeb.ServerRelativeUrl;
                //Check if folder exists in the list
                if (list != null)
                {
                    //Create the exact folder URL.
                    String folderUrl = String.Format("{0}{1}/{2}", currentWeb.ServerRelativeUrl, list.Title, folderName);

                    //If it is a pulishing site then
                    //String folderUrl = String.Format("{0}{1}{2}/{3}", currentWeb.ServerRelativeUrl, "Lists/", list.Title, folderName);


                    IEnumerable<Folder> existingFolders = clientContext.LoadQuery<Folder>
                        (folderColl.Where(folder => folder.ServerRelativeUrl == folderUrl));
                    clientContext.ExecuteQuery();

                    existingFolder = existingFolders.FirstOrDefault();
                }

                if (existingFolder == null)
                {
                    //Get the collection of content types.
                    ContentTypeCollection listContentTypes = list.ContentTypes;
                    clientContext.Load(listContentTypes, types => types.Include
                                     (type => type.Id, type => type.Name,
                                     type => type.Parent));


                    //Get the Folder content type.
                    var result = clientContext.LoadQuery(listContentTypes.Where
                      (c => c.Name == "Folder"));

                    clientContext.ExecuteQuery();

                    ContentType folderContentType = result.FirstOrDefault();

                    ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
                    newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;

                    newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                    newItemInfo.LeafName = folderName;
                    ListItem newListItem = list.AddItem(newItemInfo);
                    newListItem["ContentTypeId"] = folderContentType.Id.ToString();
                    newListItem["Title"] = folderName;
                    newListItem.Update();

                    clientContext.Load(list);
                    clientContext.ExecuteQuery();
                }
            };


In this following points are important to understand :

1) 1)  Get the folders collection of the list using FolderCollection
<!2 Check if the folder you are about to create already exists or not .
Note : If it is a publishing site then use folder URL as
ServerRelative URL + “/Lists/” + ListTitle + folderName
     //String folderUrl = String.Format("{0}{1}{2}/{3}", currentWeb.ServerRelativeUrl, "Lists/", list.Title, folderName);

<!3)Get the folder content type and finally create the item and assign the folder content type to the newly created item.
4) This will create folder in the list.

Check if List exists in the site :

When we try to access a list using GetListByTitle() , we are required to pass the list name as parameter, In this case if List does not exists then this throws exception, So it is always recommended to check if list exists in the site before doing any operation on the list.
Below code snippet will return List object if it exists otherwise it will return null.

  private static List CheckIfListExists()
        {
            String listTitle = "NewList";
            using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                List existingList;
                Web web = clientContext.Web;
                ListCollection lists = web.Lists;

                IEnumerable<List> existingLists = clientContext.LoadQuery(
                        lists.Where(
                        list => list.Title == listTitle)
                        );
                clientContext.ExecuteQuery();
                existingList = existingLists.FirstOrDefault();
                return existingList;
            }
        }





Happy coding :)

Client Object Model Part -4



We will continue from the last post where we were doing operations on list using managed Client object model.Please read Post from Part -1 to Part -3 to go through all the examples of COM

Here we will retrieve the items from the list using CAML query.
Retrieve Items from List using CAML query:

Code Snippet: 
  
using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                //To retrieve collection of items from the list based on CAML query.
                List lst = clientContext.Web.Lists.GetByTitle("NewList");
                string titleName = "abc";
                CamlQuery query = new CamlQuery();
                query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + titleName + "</Value></Eq></Where></Query></View>";
                ListItemCollection coll = lst.GetItems(query);
                clientContext.Load(coll);
                clientContext.ExecuteQuery();
}


In this we are retrieving items based on the title field of the list. We can use any of the field of the list for filtering the results.


Retrieve all the items from the List/Documents library including folders and subfolders :
Objective is to retrieve all the items from the list including folders and subfolders.
Code Snippet :

  //To retrieve all the items from a list/document library including folders and subfolders
                List lst1 = clientContext.Web.Lists.GetByTitle("NewList");
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"<View Scope='Recursive'/>";
                ListItemCollection coll1 = lst1.GetItems(camlQuery);
                clientContext.Load(coll1);
                clientContext.ExecuteQuery();


Important :
camlQuery.ViewXml = @"<View Scope='Recursive'/>";
This query will retrieve all the items from the list.

Happy Coding J
Continue reading Part -5

Client Object Model Part -3

In the last post we created the sample for creating the web using various available templates Part -2 .
I will recommend you to go through Part -1 to Part -2 and then continue reading to have a better understanding.
In this post we will create list using managed client object model.
Create List :
To try this sample code , you can create a console application and then create a method CreateList and pass SiteURL where you want to create the list.

using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                List targetList = null;

                ListCreationInformation NewListInfo = new ListCreationInformation
                {
                    //Can set the list template here.
                    TemplateType =  (int)ListTemplateType.GenericList,
                    Title = "NewList",
                    Url = "NewList",
                    QuickLaunchOption = QuickLaunchOptions.On // to set the quick launch property of the list.

                };

                targetList = clientContext.Web.Lists.Add(NewListInfo);
                clientContext.Load(clientContext.Web.Lists);
                clientContext.ExecuteQuery();
            }


Important : For creating the List we need to use the ListCreationInformation object and set the properties.
And finally load the newly created list and call Execute query method of the client context. Until this execute query method is called changes will not be updated on the site. This executeQuery method bundles all the request and executes them on the server. This reduces the server round trip.
This will create the list in the site and this list will be available on the quick launch menu of the site.

Add fields in the List :
Objective is to add fields in the list. In this code snippet we are creating fields of type text,Number,URL, You can create fields with other available types as well .


using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                //To retrieve collection of items from the list based on CAML query.
                List lst = clientContext.Web.Lists.GetByTitle("NewList");
                FieldCollection fields = lst.Fields;

                //Add column of type Text
                FieldType fieldType = FieldType.Text;
                fields.AddFieldAsXml(
                String.Format("<Field DisplayName='{0}' Type='{1}'></Field>", "Name",
                fieldType), true, AddFieldOptions.DefaultValue);


                //Add column of type Number
                FieldType fieldType1 = FieldType.Number;
                fields.AddFieldAsXml(String.Format("<Field DisplayName='{0}' Type='{1}'></Field>", "ProductCount",
                fieldType1), true, AddFieldOptions.DefaultValue);

                //Add column of type Number
                FieldType fieldType2 = FieldType.URL;
                fields.AddFieldAsXml(String.Format("<Field DisplayName='{0}' Type='{1}'></Field>", "SiteLink",
                fieldType2), true, AddFieldOptions.DefaultValue);


                lst.Update();
                clientContext.ExecuteQuery();
            }




Create List Item :
Our objective is to add items in the newly created list. Right now this list has only one default field Title, so we will add item in the list and set value for that field only.

 
using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                List lst = clientContext.Web.Lists.GetByTitle("NewList");
                ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
                ListItem newListItem = lst.AddItem(newItemInfo);
                newListItem["Title"] = "abc";
                newListItem.Update();
                clientContext.Load(newListItem);
                clientContext.ExecuteQuery();
            }


Important : For creating the List we need to use the ListItemCreationInformation object and set the properties.
And finally load the newly created item  and call Execute query method of the client context. Until this execute query method is called changes will not be updated on the server. This executeQuery method bundles all the request and executes them on the server. This reduces the server round trip.

Update Item in the List :
Our objective is to update the item in the list. For this first we need to access the list , then we need to access the list item. Every list item has unique auto incrementing integer value which can be used to retrieve the particular item and then update the field of the ListItem.

using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                ListItem lstItem = clientContext.Web.Lists.GetByTitle("NewList").GetItemById(2);
                lstItem["Title"] = "UpdateTitle";
                lstItem.Update();
                clientContext.ExecuteQuery();
 }

Important :
<!1)      For updating the field of type HyperIink use this code snippet

FieldUrlValue link = new FieldUrlValue();
                link.Url = "http://microsoft.com";
                link.Description = "World of Microsoft Technologies";
                lstItem["URL"] = link;
                lstItem.Update();
                clientContext.ExecuteQuery();


<!2) For updating the field of type “Person or Group “ use this code snippet
 
User user = null;
                FieldUserValue fldUserValue = new FieldUserValue();
                user = clientContext.Web.EnsureUser("domain\\userId");
                clientContext.Load(user);
                clientContext.ExecuteQuery();
                fldUserValue.LookupId = user.Id;
                lstItem["User"] = fldUserValue;
                lstItem.Update();
                clientContext.ExecuteQuery();


This way we can update the specific item from the list based on the auto incrementing ID.
Happy Coding J

Continue reading Part -4

Client Object Model Part -2

In this post we will create some examples using Managed Client Object model. Our objective here is to create the Web, List, Add Items, Update Items, Delete Items etc using the Managed COM. Please go through the Part -1 for understanding the basics of COM
Create Web :
//Create web in the root site.
            using (ClientContext clientContext = new ClientContext(SiteURL))
            {
                WebCollection webColl = clientContext.Web.Webs;
               
                WebCreationInformation newWebCreationInfo = new WebCreationInformation();
                newWebCreationInfo.Title = "New web site";
                newWebCreationInfo.Description = "Here goes the description ";
                newWebCreationInfo.Language = 1033;
                newWebCreationInfo.Url = "NewWeb1";

                newWebCreationInfo.UseSamePermissionsAsParentSite = true;
               //This template is for team site
                newWebCreationInfo.WebTemplate = "STS#0";

                Web oNewWebsite = webColl.Add(newWebCreationInfo);
                clientContext.ExecuteQuery();
            }

So this code snippet will create the web (Team site)inside a site collection. We can create any site by specifying the required WebTemplate type. Here is the list of available templates.
List of Web Templates :

                    Template ID     Template Name
                    GLOBAL#0      Global template
                    STS#0      Team Site
                    STS#1      Blank Site
                    STS#2       Document Workspace
                    MPS#0       Basic Meeting Workspace
                    MPS#1       Blank Meeting Workspace
                    MPS#2       Decision Meeting Workspace
                    MPS#3       Social Meeting Workspace
                    MPS#4       Multipage Meeting Workspace
                    CENTRALADMIN#0    Central Admin Site
                    WIKI#0      Wiki Site
                    BLOG#0      Blog
                    SGS#0       Group Work Site
                    TENANTADMIN#0    Tenant Admin Site
                    ACCSRV#0      Access Services Site
                    ACCSRV#1      Assets Web Database
                    ACCSRV#3      Charitable Contributions Web Database
                    ACCSRV#4      Contacts Web Database
                    ACCSRV#6      Issues Web Database
                    ACCSRV#5      Projects Web Database
                    BDR#0       Document Center
                    OFFILE#0      (obsolete) Records Center
                    OFFILE#1      Records Center
                    OSRV#0      Shared Services Administration Site
                    PPSMASite#0    PerformancePoint
                    BICenterSite#0     Business Intelligence Center
                    SPS#0       SharePoint Portal Server Site
                    SPSPERS#0     SharePoint Portal Server Personal Space
                    SPSMSITE#0     Personalization Site
                    SPSTOC#0      Contents area Template
                    SPSTOPIC#0     Topic area template
                    SPSNEWS#0     News Site
                    CMSPUBLISHING#0   Publishing Site
                    BLANKINTERNET#0   Publishing Site
                    BLANKINTERNET#1   Press Releases Site
                    BLANKINTERNET#2   Publishing Site with Workflow
                    SPSNHOME#0     News Site
                    SPSSITES#0     Site Directory
                    SPSCOMMU#0     Community area template
                    SPSREPORTCENTER#0  Report Center
                    SPSPORTAL#0     Collaboration Portal
                    SRCHCEN#0     Enterprise Search Center
                    PROFILES#0     Profiles
                    BLANKINTERNETCONT...  Publishing Portal
                    SPSMSITEHOST#0    My Site Host
                    ENTERWIKI#0     Enterprise Wiki
                    SRCHCENTERLITE#0  Basic Search Center
                    SRCHCENTERLITE#1  Basic Search Center
                    SRCHCENTERFAST#0   FAST Search Center
                    visprus#0      Visio Process Repository

Note: For creating publishing webs, make sure publishing features are enabled on the parent site.
Happy Coding J
Continue reading Part -3

Client Object Model Part -1

Here I am starting a series of posts on Client Object model.

Sharepoint 2010 has introduced three types of COM (Client Object Model )
1)   Managed Client Object Model -Implemented in .NET CLR
2)  ECMA script
3)  Silverlight Client object model.
Client APIs allows you to interact with SharePoint sites from script that executes in the browser i.e. it is not mandatory to install Sharepoint on the client machine where application is being run and it can communicate with Sharepoint server remotely.
 .NET managed, and Silverlight client object models provides a subset of the server object model that is defined in Microsoft.SharePoint.dll, including objects that correspond to major objects at the site-collection level or lower in the SharePoint Foundation hierarchy.
The great advantage of it is that syntax is like the SharePoint Object Model.
Syntax of two types of object model when compared looks like this.

Server side syntax
Client side syntax
SPContext
ClientContext
SPSite
Site
SPWeb
Web
SPList
List


Now to implement the client object model in the solution we need to refer  the dlls required for each type of Cilent object model.
1)      Managed Client Object Model:
Dlls required -
a)  Microsoft.SharePoint.Client.dll,
b)   Microsoft.SharePoint.Client.Runtime.dll.

Location : 14/ISAPI folder.  Usually, the location would be at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI".

b)      Microsoft.SharePoint.Client.Silverlight.Runtime.dll.

Location  :  "C:\Program Files\Common Files\Microsoft Shared\Web Server\Extensions\14\Template\LAYOUTS\ClientBin
So from the next post will start some samples of implementation of three types of client object model.

Continue reading Part -2 .