Create Promoted Links/My Report Library/Asset Library list in SharePoint 2013 using Client Object Model C#

I have already written a blog specifying how to create a List for SharePoint using Client Object Model. You can check that here.Though that code worked for most of the Lists, the List, Promoted Links, Report Library, and Asset Library, could not be created. They were constantly throwing the error, Invalid list template! As far as I was concerned, ListTemplates that were passed to the ListCreationInformation were correct. So why this error?? Here, I must also mention that I was trying to create these Lists on the Web template Team-Site.

The problem was I was only passing the baseTemplate to it. However, for these Lists, I needed to mention the GUID of the Feature, that contained the schema of the new List. Following is the modified code.

Namespace:

using Microsoft.SharePoint.Client;

//use one of the templateName that suits your purpose
string templateName = "Promoted Links";string templateName = "Report Library";string templateName = "Asset Library";

ClientContext ctx = new ClientContext(weburl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord); 

Web web = ctx.Web;

// Get the list template by name
ListTemplate listTemplate = web.ListTemplates.GetByName(templateName);

ctx.Load(listTemplate);
ctx.ExecuteQuery();

// Create a new object for ListCreationInformation class - used to specify the // properties of the new list
ListCreationInformation creationInfo = new ListCreationInformation();

// Specify the title of your List
creationInfo.Title = "My Custom List";

// Specify the list description, if any
creationInfo.Description = "Description";

// Set a value that specifies the feature identifier of the feature 
// that contains the list schema for the new list.
creationInfo.TemplateFeatureId = listTemplate.FeatureId;

// Set a value that specifies the list server template of the new list
creationInfo.TemplateType = listTemplate.ListTemplateTypeKind;

web.Lists.Add(creationInfo);
ctx.ExecuteQuery();
  

Create a SharePoint Site using Client Object Model C#

Required namespace:-
using Microsoft.SharePoint.Client;using Microsoft.Online.SharePoint.TenantAdministration; 

Following is the full code sample for creating a new sitecollection in SharePoint using CSOM.

bool rootSiteExist;
SP.ClientContext ctx = new ClientContext(siteUrl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);
this.ctx.Load(this.ctx.Web);

try
{
    ctx.ExecuteQuery();
    rootSiteExist = true;
}
catch (Exception)
{
    //Indicates the given sub site is missing
    //This block will be executed when the given Web is not found on the server
    
    rootSiteExist = false;
}

//Create a Site if there is no existing site with the same url.
if(!rootSiteExist)
{
    string targetURL = "https://-admin.sharepoint.com";
    SP.ClientContext adminCtx = new SP.ClientContext(siteUrl);
    adminCtx.Credentials = new SharePointOnlineCredentials(userName, passWord);

    Tenant tenant = new Tenant(context);
    adminCtx.Load(tenant, t => t.ResourceQuota, t => t.ResourceQuotaAllocated, t => t.StorageQuota, t => t.StorageQuotaAllocated);
    adminCtx.ExecuteQuery();

    double avaialableResource = tenant.ResourceQuota - tenant.ResourceQuotaAllocated;
    long availableStorageResource = tenant.StorageQuota - tenant.StorageQuotaAllocated;

    long storageMaximumLevel = 1000; //say
    double userCodeMaximumLevel = 300 //say

    if (availableStorageResource >= storageMaximumLevel)
    {
        if (avaialableResource >= userCodeMaximumLevel)
        {
            bool retryAttemted = false;
            while (true)
            {
                var properties = new SiteCreationProperties()
                {
                    CompatibilityLevel = compatibilityLevel,
                    Url = siteUrl,
                    Owner = owner,
                    Template = template,
                    StorageMaximumLevel = storageMaximumLevel,
                    UserCodeMaximumLevel = userCodeMaximumLevel,

                };
                tenant.CreateSite(properties);
                adminCtx.Load(tenant);

                try
                {
                    /*If you get an error here it means, a root site with the same url is lying in the RecycleBin of the admin Site Collection. In that case
you have to first remove the deleted site before proceeding.*/
                    
                    adminCtx.ExecuteQuery();
                    break;
                }
                catch (SP.ServerException)
                {
                    if (retryAttemted)
                        throw;

                    tenant.RemoveDeletedSite(siteUrl);
                    connect.adminCtx.ExecuteQuery();
                    retryAttemted = true;
                }
            }

            /*Now trying to connect to the newly cretaed Site with the given Url. The site may not show up immediately, hence constantly trying to connect to the site after a given time interval (wait period).*/
            
            int retryCount = 0;
            SP.Web web = null;
            
            while (true)
            {
                try
                {
                    ctx = new ClientContext(siteUrl);
                    ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

                    web = this.ctx.Web;
                    this.ctx.Load(web);
                    this.ctx.ExecuteQuery();
                    
                    break;
                }
                catch (Exception)
                {
                    ++retryCount;
                    if (retryCount <= 20)
                    {
                        Thread.Sleep(200000);
                        continue;
                    }
                    break;
                }
            }
        }
        else
        {
            //Resources are inadequate
        }
    }else    
    {
        //Storage Size is inadequate
    }
}

Programmatically create SiteColumn for a Web in SharePoint using Client Object Model

string siteUrl = "http://servername/";
SP.ClientContext ctx = new SP.ClientContext(siteUrl);
this.ctx.Load(this.ctx.Web);
SP.Web web = this.ctx.Web;

web.Fields.AddFieldAsXml(schemaXML, false, SP.AddFieldOptions.AddFieldToDefaultView);

web.Update();
SP.FieldCollection fieldCollection = web.AvailableFields;
ctx.Load(fieldCollection);
ctx.ExecuteQuery();

Upload a File to SharePoint using Client Object Model

Following is the complete process of uploading/creating a file on the SharePoint server using the Client Object Model. The following process should also be implied for some of the ListItems. Traditionally, we use ListItemCreationInformation class to create a ListItem. However, if your List is a

  • Web Page Library
  • Picture Library

then also you have to use the below process to create their ListItem otherwise, you’ll get the Microsoft.SharePoint.Client.ServerException, use the SPFileCollection.Add() to create file. This is one of such example where I am creating a ListItem for the Web Page Library List

using System;
using System.Collections.Generic;
using IO = System.IO;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
string siteUrl = "http://siteUrl";
SP.ClientContext ctx = new SP.ClientContext(siteUrl);
SP.List list = ctx.Web.Lists.GetByTitle("ListTitle");
byte[] bytes = IO.File.ReadAllBytes(strFilePath); //strFilePath is the full path of the file that needs to be uploaded

IO.MemoryStream mStream = new IO.MemoryStream(bytes);

SP.FileCreationInformation fileInfo = new SP.FileCreationInformation();
fileInfo.ContentStream = mStream;
fileInfo.Overwrite = true;
fileInfo.Url = "https://siteUrl/Subsite1/Subsite2/SitePages/TestPage.aspx";
SP.File file = list.RootFolder.Files.Add(fileInfo);

list.Update();

SP.ListItem listItem = file.ListItemAllFields;

//If you have the MetaInfo that you want to restore
listItem["MetaInfo"] = ltItemEntity.FieldValuesAsTexts["MetaInfo"];

listItem.Update();

ctx.ExecuteQuery();

To update large files, up to 2GB, check out my other blog at, https://realmpksharepoint.wordpress.com/2014/04/29/upload-large-files-to-the-sharepoint-documentlibrary-using-rpc-from-a-desktop-application-c/.

Also, you can visit the following post to upload files up to 10GB to SharePoint Online,

https://realmpksharepoint.wordpress.com/2016/07/22/upload-large-files-to-sharepoint-online/.

Upload Forms, VIews to SharePoint using Client Object Model

First thing first, we need to use the namespace, using Microsoft.SharePoint.Client.
byte[] bytes = IO.File.ReadAllBytes(strFilePath);

IO.MemoryStream mStream = new IO.MemoryStream(bytes);

SP.File.SaveBinaryDirect(this.ctx, strServerRelativeUrl, mStream, true);

Remember, SaveBinaryDirect is use to upload Forms, & Views. You can’t upload a ListItem like, Document Library by this process. For other file types, plz check my other blog (will be posting shortly)

Create, Retrieve, and Delete the View of a SharePoint List using Client Object Model

string siteUrl = "http://servername:12345/";
ClientContext ctx = new ClientContext(siteUrl);
List oList = ctx.Web.Lists.GetByTitle("ListTitle");

Retrieve Views

SP.ViewCollection viewCollection = oList.Views;
ctx.Load(viewCollection);
ctx.ExecuteQuery();

Delete all the Views

foreach (SP.View vw in viewCollection)
{
	Microsoft.SharePoint.Client.View view = oList.Views.GetByTitle(vw.Title);
	ctx.Load(view);
	view.DeleteObject(); // Delete Existing views
	ctx.ExecuteQuery();
}

Create a new View

SP.ViewCreationInformation viewCreationInformation = new SP.ViewCreationInformation();
viewCreationInformation.Title = "New View";
viewCreationInformation.ViewTypeKind = SP.ViewType.None;
viewCreationInformation.RowLimit = 30;//Make sure that the name of the fields should be equal to 1 any of the associated SiteColumns Internal Name. The Fields in the view will appear in the same order as declared here.
viewCreationInformation.ViewFields = new string[]{"Title","Created","Modified"};
viewCreationInformation.SetAsDefaultView = true;
oList.Views.Add(viewCreationInformation);

ctx.Load(oList.Views);
ctx.ExecuteQuery();

Create, Update, Delete a SharePoint List and add a new Field using Client Object Model

Create and update 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; 

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(); 

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();  

Add a field to a SharePoint list

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;
// 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<FieldNumber>(field); 
fldNumber.MaximumValue = 100; 
fldNumber.MinimumValue = 35; 
fldNumber.Update(); 

context.ExecuteQuery();