Showing posts with label Client Side Object Model. Show all posts
Showing posts with label Client Side Object Model. Show all posts

Thursday, 3 December 2015

How to check that a user is Admin in SharePoint CSOM

SharePoint 2013 CSOM
Use User.IsSiteAdmin property to get or set a Boolean value that specifies whether the user is a site collection administrator, for example:
using (var ctx = new ClientContext(webUri))
{
    var currentUser = ctx.Web.CurrentUser;
    ctx.Load(currentUser);
    ctx.ExecuteQuery();

    Console.WriteLine(currentUser.IsSiteAdmin);
}
SharePoint 2010 CSOM
Since User object does not expose IsSiteAdmin property in SharePoint 2010 CSOM, below is demonstrated how to determine whether current user is Site Administrator using User Information List:
using (var ctx = new ClientContext(url))
{ 
     var currentUser = ctx.Web.CurrentUser;
     ctx.Load(currentUser);
     ctx.ExecuteQuery();

     var isCurrentUserSiteAdmin = IsUserSiteAdmin(ctx, currentUser.Id);
}


public static bool IsUserSiteAdmin(ClientContext ctx,int userId)
{
   var userInfoList = ctx.Site.RootWeb.SiteUserInfoList;
   var item = userInfoList.GetItemById(userId);
   ctx.Load(item);
   ctx.ExecuteQuery();
   return (bool)item["IsSiteAdmin"];
}                  

Wednesday, 2 December 2015

C# Code to create a new permission level and add a user to the a list with that permission level.


Here is the code to  create a new permission level and add a user to  the list " UserList" 


using System;
using Microsoft.SharePoint.Client;

namespace NewRole
{
    class RoleDefinitionExample
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            Site collSite = clientContext.Site;
            Web site = clientContext.Web;

            // Set up permissions.
            BasePermissions permissions = new BasePermissions();
            permissions.Set(PermissionKind.ViewListItems);
            permissions.Set(PermissionKind.AddListItems);
            permissions.Set(PermissionKind.EditListItems);
            permissions.Set(PermissionKind.DeleteListItems);

            // Create a new role definition.
            RoleDefinitionCreationInformation rdcInfo = new RoleDefinitionCreationInformation();
            rdcInfo.Name = "Manage List Items";
            rdcInfo.Description = "Allows a user to manage list items";
            rdcInfo.BasePermissions = permissions;
            RoleDefinition roleDef = collSite.RootWeb.RoleDefinitions.Add(rdcInfo);

            // Create a new RoleDefinitionBindingCollection object.
            RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(clientContext);
            // Add the role to the collection.
            collRDB.Add(roleDef);

            // Get the list to work with and break permissions so its permissions can be managed directly.
            List targetList = site.Lists.GetByTitle("UserList");
            targetList.BreakRoleInheritance(true, false);

            // Get the RoleAssignmentCollection for the target list.
            RoleAssignmentCollection collRoleAssign = targetList.RoleAssignments;
            // Add the user to the target list and assign the user to the new RoleDefinitionBindingCollection.
            RoleAssignment rollAssign = collRoleAssign.Add(site.CurrentUser, collRDB);

            clientContext.ExecuteQuery();

            Console.WriteLine("Security modified");
        }
    }
}

Tuesday, 27 October 2015

Branding SharePoint 2013 with CSOM Code

Ever since SharePoint 2013 hit the market there has been all sorts of speculation whether sandbox solutions were deprecated (hint: as of this post, declarative ones are not officially deprecated) and the argument was always that you could use the Client Side Object Model (CSOM) to apply your branding. Well, not many folks back in 2013 had solid examples of how this would work.
Microsoft must have noticed the need for some official examples because the Patterns & Practices (PnP) team released a ton of open source examples for using CSOM to do all sorts of fun things in SharePoint including uploading and applying branding to multiple sites. In this post I’ll walk you through the steps of giving this code a try.
Before I get into the demo, do I think you should just stop making sandbox solutions for branding outright? I’m not ready to say that yet. There are certainly some pros and cons between using declarative sandbox solutions vs this CSOM method, but I’m still formulating my thoughts on what I would say for guidance. At this point, I think it’s excellent that Microsoft has stepped up and created this code that is blessed by the product team to upload and apply branding correctly with CSOM. But, on the flip side, it’s really just demo code… there is no real polish or anything like that to the user experience.
The demo (Warning a UX guy is using Visual Studio here)
  • Go grab the PnP package from GitHub: https://github.com/OfficeDev/PnP/. I’m sure there are much more developer friendly ways of doing this, but I just clicked the Download ZIP button.
GitHub
  • Unzip that sucker and navigate to PnP-master\Samples\Branding.ApplyBrandingand open Branding.ApplyBranding.sln in Visual Studio
2
  • Now you want to use the Solution Explorer on the right side of Visual Studio to opensettings.xml. This file is your configuration info for where you want the branding to go and what elements you want uploaded.
3
  • Next, you must change the branding URL to match your own SharePoint tenant or server.
4
  • You also need to change the entries under <sites>. You want to have one entry for each site or site collection with which to upload and apply the branding. Because this example includes two Page Layouts, you are going to want to make sure these sites have the SharePoint publishing features enabled. If you try this example on a basic team site you are going to get errors.
5
  • That’s all you need to change before running the demo, but you can also see that there are places to add or change the images, css, master pages and page layouts that would be uploaded. Notice that the logo.png and default.css will upload to the Style Library into a folder named gapps. In the case of the master page and the page layouts, they will upload to the Master Page Gallery into a folder also named gapps.
  • Now let’s try out the code by clicking the Start button in Visual Studio.
6
  • You should see a console window open up. Enter the Username and Password for your site and when you hit enter the code will run and you can see the results returned in the console. If there are any errors (authentication or otherwise) they should be shown in the console.
7
  • Now that the CSOM code has run, we can take a look at the new site branding (the included branding is pretty minimal but you should see a difference).
8
  • Also, you can check the Style Library and the Master Page Gallery and see that the files did in fact get uploaded.
9
That’s pretty much it for the demo. If you dig into the code, you can see that there are various methods that are called for each step that do check in/out, upload files, apply master page, add page layouts, etc. All of the code in this example is apparently blessed by the product team as being a good way to apply branding. You can also check some of the other samples and see demos of things like Alternate CSS, Themes, Display Templates, and much more.

Friday, 23 October 2015

Best Practices in SharePoint Client Side Object Model

Following are the Best Practices that should be followed while coding for SharePoint Client Object Model:

1.)Only Request What You Want (But request everything you want in one go!)

You must explicitly request every property of every object you want. This is really a fundamental basic of CSOM programming - after all, it's designed to be used across a network. If you only need a user's Title and LoginName, then only request those:
var spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title, user => user.LoginName);
However, if later on in your code, you sometimes need to send the user an email, then add their email address to the earlier request. Don't go back to the server twice! The cost of always requesting an additional property is miniscule in comparison to going all the way to the server and back an extra time later on.

We should minimize the number of times we hit the SharePoint Server.

2.) Call ExecuteQuery Sparingly

Again, an obvious one. But there are scenarios where you will be calling ExecuteQuery where you don't need to. In case you didn't know, ExecuteQuery is the method that causes all of your requests to go to the server in a single batch, so it's slow!
Take a look at this scenario. If you're creating a list, you might think you need to write code as follows:
List list = web.Lists.Add(...);
ctx.ExecuteQuery(); //Create the list
ctx.Load(list, l => l.DefaultViewUrl); // Request the new list's URL
ctx.ExecuteQuery(); // Get the new list's DefaultViewUrl
In fact, you don't need that first ExecuteQuery. It's not intuitive, but you can create the list, get its URL, and submit both requests in one go:
List list = web.Lists.Add(...);
ctx.Load(list, l => l.DefaultViewUrl);
ctx.ExecuteQuery(); // Get the new list's DefaultViewUrl
A slightly more convoluted example involves a scenario where you are indirectly calling some CSOM code, but it's behind an interface and you may be calling it multiple times. How can you protect against an ExecuteQuerycall every time this interface method is called? For example:
public interface IData { }
public class MyDataClass : IData { }

public interface IDataRetriever
{
   IData GetData(string id);
}

public class SPDataRetriever : IDataRetriever
{
   public IData GetData(string id)
   {
       //Make whatever CSOM requests you need
       ListItem li = _list.GetItemById(id);
       ctx.ExecuteQuery();
       return new MyDataClass(li);
   }
}
In our scenario, it's being consumed as follows:
data = ids.Select(id => dataRetriever.GetData(id));
Clearly, this is very inefficient since ExecuteQuery is called for every item in the enumerable. Let's refactor the code to remove the ExecuteQuery call:
public interface IDataRetriever
{
   void RequestData(string id);
   IEnumerable<IData> GetAvailableData();
}

public class SPDataRetriever : IDataRetriever
{
   private Queue<ListItem> _queue = new Queue<ListItem>();

   public void RequestData(string id)
   {
       //Make whatever CSOM requests you need
       ListItem li = _list.GetItemById(id);
       _queue.Enqueue(li);
   }

   public IEnumerable<IData> GetAvailableData()
   {
       var result = _queue.Select(li => new MyDataClass(li)).ToArray();
       
       _queue.Clear();
       return result;
   }
}
You can see it's now split into two methods: RequestData, which "enqueues" requests ready to be sent to the server - and GetAvailableData, which returns data assuming that ExecuteQuery has now been called.
We consume this code as follows:
IDataRetriever dataRetriever1 = new SPDataRetriever(ctx);
IDataRetriever dataRetriever2 = new SPDataRetriever(ctx);

foreach (string id in new[] { "id1", "id2" })
   dataRetriever1.RequestData(id);
           
foreach (string id in new[] { "id1", "id2" })
   dataRetriever2.RequestData(id);

ctx.ExecuteQuery(); //Single call to execute query

IEnumerable<IData> allData = dataRetriever1.GetAvailableData().Concat(dataRetriever2.GetAvailableData());
This is an example of the type of creative way you can help prevent performance issues by minimising the number of times you call ExecuteQuery.

3. ) Caching Data in the Session

If every page in your app is requesting the same data from SharePoint, then you can store it temporarily in the user session cache. This will prevent you having to make a round trip to the SharePoint server on every page request. Additionally, since it's in the user session cache, it is scoped to each user individually. If you want to cache application-wide data, you can store it in the Application cache. See this MSDN article for more information.
So, let's assume a scenario where each page checks whether or not the user is allowed access to it based on whether they are a site administrator:
public bool CheckPrivileges()
{
    var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    {
        var currentUser = clientContext.Web.CurrentUser;
        clientContext.Load(currentUser, u => u.IsSiteAdmin);
        clientContext.ExecuteQuery();

        return currentUser.IsSiteAdmin;
    }
}
We can simply wrap that CheckPrivileges method in another that performs session caching:
public bool CheckPrivilegesWithSessionCaching(HttpContextBase httpContext)
{
    string key = "IsSiteAdmin";
    var keys = httpContext.Session.Keys.Cast<string>().ToList();
    if(keys.Contains(key))
    {
        return (bool)httpContext.Session[key];
    }
    else
    {
        bool result = CheckPrivileges(httpContext);
        httpContext.Session[key] = result;
        return result;
    }
}
Note that if you're storing large amounts of data, this solution won't scale well (since it is 'In Memory' caching) - you could store cached data in your database instead.
Additionally, you cannot assume that data will be available in the session cache - it could be cleared by ASP.NET at any time, or, due to load balancing it could be cached differently on separate servers. As long as you go back to SharePoint to retrieve it when necessary, this shouldn't be a problem.

4.)Use CAML Query to Filter Retrieval of List Items

If you're retrieving some items from a list, it is tempting to retrieve all items and then filter it in your code. However, you can use CAML queries to perform the filtering server side. It can be a little bit awkward (coding in XML) but it's worth getting right for the potential speed increases you'll see, especially for large lists.
For example, this is the lazy way to get list items:
CamlQuery query = CamlQuery.CreateAllItemsQuery();
var items = list.GetItems(query);
And here's a formatted CAML query with a where clause:
CamlQuery query = new CamlQuery() 
{ 
    ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='{0}' /><Value Type='String'>{1}</Value></Eq></Where></Query></View>", 
                        "FirstName", "Eric") 
};
 
var items = list.GetItems(query);
Note the 'View' outer tag which is required when querying with CSOM, unlike the server object model version.
Here's another trick – you can actually get all folders, subfolders and/or files from a document library, in a single query, by specifying RecursiveAll:
CamlQuery allFoldersCamlQuery = new CamlQuery()
{
    ViewXml = "<View Scope='RecursiveAll'>"
                        + "<Query>"
                        + "<Where>"
                        + "<Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq>"
                        + "</Where>"
                        + "</Query>"
                    + "</View>"
};
In the above query, Scope is set to RecursiveAll. Also, I'm setting the field FSObjType=1 - this means that only folders are returned. If you want only items, set FSObjType=0. If you want both files and folders, omit it entirely.
You can actually go even further – retrieving all items from multiple lists, by enumerating through the lists and using a caml query on each. The important thing is that you only call ExecuteQuery once, at the end.

5. )Advanced: Parallel and Async Code

If you're using JavaScript or the CSOM library in Silverlight or Windows Phone, then you'll see that you have access to ExecuteQueryAsync. Unfortunately for the rest of us in .NET, there's only an ExecuteQuery method – synchronous. I don't know why.
What if you want to do a database request, or a different web request, or get user input, or something else at the same time as your CSOM request? Wouldn't it be handy to have that ExecuteQueryAsync? Let's see if we can create one:
public static class CSOMExtensions
{
    public static Task ExecuteQueryAsync(this ClientContext clientContext)
    {
        return Task.Factory.StartNew(() =>
        {
            clientContext.ExecuteQuery();
        });
    }
}
Well, that was a little easier than expected!
Note that this code might need a little optimisation for your particular circumstances. For example, usingTask.Factory.StartNew doesn't always create a new thread. If you're using a lot of these concurrently, you might want to avoid using the thread pool. You can read more about Task here.
Now we can do super cool parallel and async stuff! Check this out:
public async Task<ActionResult> Index()
{
    var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    {
        if (clientContext != null)
        {
            var currentUser = clientContext.Web.CurrentUser;
 
            clientContext.Load(currentUser, u => u.Title);
            Task t1 = clientContext.ExecuteQueryAsync();
 
            clientContext.Load(currentUser, u => u.Email);
            Task t2 = clientContext.ExecuteQueryAsync();
 
            await t1.ContinueWith((t) =>
            {
                ViewBag.UserName = currentUser.Title;
            });
 
            await t2.ContinueWith((t) =>
            {
                ViewBag.Email = currentUser.Email;
            });
        }
    }
    return View();
}
OK, so this is a contrived and pointless example because if you'd been paying attention, you'd know we should only call ExecuteQuery once! But let's walk through it:
  1. Firstly, the method signature has changed. This controller method is now async, and it returns a Task. This means we can now use the await keyword within the method.
  2. Within the body, we're loading Title and Email. We're calling ExecuteQueryAsync, which start (and return) new Task objects.
  3. We call ContinueWith on the Task object to run code when it completes – namely, using the property that the CSOM code requested.
  4. We use the await keyword to signify that the code is asynchronous and the Index controller method should depend on the result of this code.
Consider this next example which is a controller method called List. It's a bit more sensible: we're retrieving both database data and SharePoint list items concurrently, and combining them into ViewModel objects to return to the client.
public async Task<ActionResult> List()
{
    List<ViewModel> result = new List<ViewModel>();
 
    var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    {
        //Form the query for ListItems
        var listItems = clientContext.Web.Lists.GetByTitle(listTitle).GetItems(camlQuery);
 
        //Send the queries
        var clientTask = DB.Clients.ToListAsync();
        var spTask = clientContext.ExecuteQueryAsync();
 
        //Wait for both to complete
        await Task.WhenAll(clientTask, spTask);
 
        result = clientTask.Result.Select(c => new ViewModel(listItems)).ToList();
    }
 
    return View(result);
}
In the code above, we've only got a single blocking call instead of two, and we could potentially be doubling the speed of the method.
Well, that's all I've got for now. Clearly the client-side object model is easily abused in terms of performance, and it's very easy to suddenly realise that performance is a problem.


Thursday, 11 June 2015

Get list data from a SharePoint List when you have more than 5000 rows/records.





Here we are  retrieving the items based on listItemcollectionPosition.

One can use the ListItemCollectionPosition class to implement paging list item retrieval according to the position of items relative to their collection. Use the RowLimit element to specify the number of items to return per page. The following example loops through all the items in a SharePoint list, using the ListItemCollectionPosition property of the CamlQuery class, and the ListItemCollectionPosition property of the ListItemCollection class.



  ClientContext context = new ClientContext"Site URL");
 string username = @"username";
  string passw = @"password";
  SecureString passWord = new SecureString();
  foreach (char c in passw.ToCharArray()) passWord.AppendChar(c);
             {
     context.Credentials = new SharePointOnlineCredentials(username, passWord);

            }
  Web web = context.Web;
 try
         {
         int count = 0;
        List  Listname= context.Web.Lists.GetByTitle("name of the list");

         ListItemCollectionPosition itemPos = null;

          int intCount = 0;
          while (true)
               {
           CamlQuery cQuery = new CamlQuery();
             cQuery.ListItemCollectionPosition = itemPos;
             cQuery.ViewXml = "<View>"
               + " <RowLimit>1000</RowLimit>"
               + " </View>";

        Microsoft.SharePoint.Client.ListItemCollection items = Listname.GetItems(cQuery);
        context.Load(items);
        context.ExecuteQuery();
        itemPos = items.ListItemCollectionPosition;
        for (int iCntr = items.Count - 1; iCntr >= 0; iCntr--)

                    {

                      intCount++;
                      Microsoft.SharePoint.Client.ListItem listItem = items[iCntr];
                       listItem["Status"] = "Active";
             //Item is Retreivedinlistitem and now we are updating it to active
                      listItem.Update();
                     context.ExecuteQuery();

                    }

                    if (itemPos == null)

                    {

                        break;

                    }

                }

            }

            catch (Exception ex)

            {
               System.IO.StreamWriter file = new System.IO.StreamWriter("log Path", true);
                file.WriteLine(DateTime.Now + "    " + ex.Message);
                file.Close();



            }

Monday, 8 June 2015

Delete a list item/Row in a SharePoint List using Client Object Model

Here is  C# code to delete a particular SharePoint item  having ID = 2 from a list named  Announcements.

The whole row  with ID= 2 will be deleted



// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume that there is a list item with ID=2. 
ListItem listItem = announcementsList.GetItemById(2); 
listItem.DeleteObject(); 

context.ExecuteQuery(); } 

Update a list item using Client Object Model


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.Items.GetById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery();  

Create a new list item using Client Object Model

Create a new list item

We will be using the class  ListItemCreationInformation class. 


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// We are just creating a regular list item, so we don't need to 
// set any properties. If we wanted to create a new folder, for 
// example, we would have to set properties such as 
// UnderlyingObjectType to FileSystemObjectType.Folder. 
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 
ListItem newItem = announcementsList.AddItem(itemCreateInfo); 
newItem["Title"] = "My New Item!"; 
newItem["Body"] = "Hello World!"; 
newItem.Update(); 

context.ExecuteQuery();  

Retrieve items from a SharePoint list using Client Side Object Model


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll" 
// so that it grabs all list items, regardless of the folder they are in. 
CamlQuery query = CamlQuery.CreateAllItemsQuery(100); 
ListItemCollection items = announcementsList.GetItems(query); 

// Retrieve all items in the ListItemCollection from List.GetItems(Query). 
context.Load(items); 
context.ExecuteQuery(); 
foreach (ListItem listItem in items) 
{ 
    // We have all the list item data. For example, Title. 
    label1.Text = label1.Text + ", " + listItem["Title"]; 
} 

Add a field to a SharePoint list using Client Side Object Model

This example adds a field to a SharePoint list. add an alias to the using statement for Microsoft.SharePoint.Client namespace so you can refer to its classes unambiguously. For example, using SP = Microsoft.SharePoint.Client;.

The example uses context.CastTo to do a cast. Before executing the query, the client library does not know the real type of the returned object "field" and SharePoint.Field is the only possible type. If you know the real type, you can use the ClientContext.CastTo<RealType> method to cast the object.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

SP.List list = context.Web.Lists.GetByTitle("Announcements"); 

SP.Field field = list.Fields.AddFieldAsXml("", 
                                           true, 
                                           AddFieldOptions.DefaultValue); 
SP.FieldNumber fldNumber = context.CastTo(field); 
fldNumber.MaximumValue = 100; 
fldNumber.MinimumValue = 35; 
fldNumber.Update(); 

context.ExecuteQuery();

Delete a SharePoint list using Client Side Object Model

C#  code to delete a SharePoint list.




// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

List list = web.Lists.GetByTitle("My List"); 
list.DeleteObject(); 

context.ExecuteQuery(); 

Create and update a SharePoint list using Client Side object Model

This example creates a SharePoint list and updates it using the ListCreationInformation class.


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

ListCreationInformation creationInfo = new ListCreationInformation(); 
creationInfo.Title = "My List"; 
creationInfo.TemplateType = (int)ListTemplateType.Announcements; 
List list = web.Lists.Add(creationInfo); 
list.Description = "New Description"; 

list.Update(); 
context.ExecuteQuery(); 
Like WebCreationInformation it also inherits from class ClientValueObject of Namespace Microsoft.SharePoint.Client

Retrieve all SharePoint lists in a web using Client Side Object Model

This example retrieves all SharePoint lists in a SharePoint website. To compile this code you will need to add a using statement for System.Linq.


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server. 
context.Load(web.Lists, 
             lists => lists.Include(list => list.Title, // For each list, retrieve Title                                                            and Id. 
                                    list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the web.Lists. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 






Alternatively, we can use the LoadQuery method to store the return value in another collection, rather than use the web.Lists property. we also need to add using statements for System.Collections.Generic and System.Linq. Also, add an alias to the using statement for Microsoft.SharePoint.Client namespace so we can refer to its classes unambiguously. For example, using SP = Microsoft.SharePoint.Client;.




// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server, and put the return value in another 
// collection instead of the web.Lists. 
IEnumerable result = context.LoadQuery(web.Lists.Include( // For each list, retrieve Title and Id.
                                                                   list => list.Title, 
                                                                   list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the result. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 

Create a new SharePoint website using Client Side Object Model

We can  create a new SharePoint site as a subsite of the current website using the below given C# code .

We will use the   WebCreationInformation       class to create a new website. You will also need to add using statements for System.Collections.Generic and System.Text.


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

WebCreationInformation creation = new WebCreationInformation(); 
creation.Url = "web1"; 
creation.Title = "Hello web1"; 
Web newWeb = context.Web.Webs.Add(creation); 

// Retrieve the new web information. 
context.Load(newWeb, w => w.Title); 
context.ExecuteQuery(); 

label1.Text = newWeb.Title; 





The class WebCreationInformation inherits from class ClientValueObject of Namespace Microsoft.SharePoint.Client