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

List of SharePoint Lists BaseTemplateType

SharePoint has many Lists. Following is a list of BaseTemplateType of some of the SharePoint List that I know for a quick reference.

Notused -1
NoListTemplate 0
GenericList 100
DocumentLibrary 101
Survey 102
Links 103
Announcements 104
Contacts 105
Events 106
Tasks 107
DiscussionBoard 108
PictureLibrary 109
DataSources 110
WebTemplateCatalog 111
UserInformation 112
WebPartCatalog 113
ListTemplateCatalog 114
XMLForm 115
MasterPageCatalog 116
NoCodeWorkflows 117
WorkflowProcess 118
WebPageLibrary 119
CustomGrid 120
SolutionCatalog 121
NoCodePublic 122
ThemeCatalog 123
DesignCatalog 124
AppDataCatalog 125
DataConnectionLibrary 130
WorkflowHistory 140
GanttTasks 150
HelpLibrary 151
AccessRequest 160
PromotedLinks 170
TasksWithTimelineAndHierarchy 171
MaintenanceLogs 175
Meetings 200
Agenda 201
MeetingUser 202
Decision 204
MeetingObjective 207
TextBox 210
ThingsToBring 211
HomePageLibrary 212
Posts 301
Comments 302
Categories 303
Facility 402
Whereabouts 403
CallTrack 404
Circulation 405
Timecard 420
Holidays 421
StatusList 432
ReportLibrary 433
IMEDic 499
Microfeed 544
AnnouncementTiles 563
ExternalList 600
MySiteDocumentLibrary 700
PublishingPageLibrary 850
AssetLibrary 851
IssueTracking 1100
AdminTasks 1200
HealthRules 1220
HealthReports 1221
DeveloperSiteDraftApps 1230
PersonalDocumentLibrary 2002
PrivateDocumentLibrary 2003
AccessApp 3100
Sharing Links 3300
wfsvc 4501

Again it’s not a complete list, it’s just a list of all the SharePoint List BaseTemplateType that I am aware of. I might have to further modify it in the future.


Update a LookupField value for a SharePoint ListItem using Client Object Model C#

A lookup data in a SharePoint can be treated as a choice options that has been maintained in a different List. Hence if one of your field in your List is a lookup then, its value should be the ID[integer] the actual Lookup-Item (i.e., the list item id of the List as a LookUp).

For ex, in a blog site, List, Category has been used as lookup field for the List Post. By default, in SP2013, you’ll get three items for Categories. Say, their Ids are 1,2, & 3.

  • Events[1]
  • Ideas[2]
  • Opinions[3]
Now if you want to change the Category field of a Post, then, you have to pass the ID of the item and not the text value.

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

this.ctx.Load(this.ctx.Web);
SP.ListCollection listCol = web.Lists;
ctx.Load(listCol);

SP.List list = listCollection.GetByTitle("ListTitle");

SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml = "";
SP.ListItemCollection listItemCollection = list.GetItems(camlQuery);
this.ctx.Load(listItemCollection);
this.ctx.ExecuteQuery();

SP.ListItem listItem = listItemCollection.FirstOrDefault(t => t.DisplayName == "NameOfTheListItem");
this.ctx.Load(listItem.FieldValuesAsText); 
this.ctx.ExecuteQuery();

//[Say, for one of the Id mentioned above.]
listItem.FieldValuesAsText["PostCategory"] = 2; 

listItem.Update(); 
this.ctx.ExecuteQuery(); 

To get the id of the listItem Ideas, you’ll have to re-connect to the SharePoint server and get the ID for the text Ideas from the List Category.

NOTE: Here, I have faced a strange issue. If I update any value of the Post Item before updating the lookupField value then the previous made changes were getting overwritten. So I have to ensure that the lookupField value should always get updated first before any other field.

Create a ListItem with Attachment using Client Object Model

FieldValuesAsTexts is a Dictionary which has been populated with some values.
using System;
using IO = System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Text;
using System.Threading;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;


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

SP.ListItemCreationInformation listItemCreationInfo = new SP.ListItemCreationInformation();
SP.ListItem oListItem = list.AddItem(listItemCreationInfo);

foreach (string key in FieldValuesAsTexts.Keys)
{
    if (ValidateKey(key))
    {
        string strKey = fieldEntities.FirstOrDefault(t => t.FieldName == key).FieldInternalName;
        if (FieldValuesAsTexts[key] != String.Empty)
        {
            string strVal = FieldValuesAsTexts[key];
            
            //You can not have a Yes/No value for a field/column whose type is bit. Hence replacing it with 1/0
            strVal = (strVal.ToLower().Trim() == "yes") ? "1" : (strVal.ToLower().Trim() == "no") ? "0" : strVal;
            oListItem[strKey] = strVal;
        }
    }
}
                
//This will create ListItem before adding attachments
oListItem.Update();

//Let's say we have a custom class called AttachmentEntity and AttachmentsCollection is the //collection of the class Attachments.

if (listItemEntity.Attachments != null)
{
    foreach (AttachmentEntity attachEntity in AttachmentsCollection)
    {
        string strFilePath = GetAbsoluteFilePath(strDirectoryPath, attachEntity.FileName);
        strFilePath = String.Concat(strFilePath, "\\", attachEntity.FileName);

        byte[] bytes = IO.File.ReadAllBytes(strFilePath);

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

        SP.AttachmentCreationInformation aci = new SP.AttachmentCreationInformation();
        aci.ContentStream = mStream;
        aci.FileName = attachEntity.FileName;

        SP.Attachment attachment = oListItem.AttachmentFiles.Add(aci);

        oListItem.Update();
    }
}
ctx.ExecuteQuery();

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

Create, Update, Delete a List Item in SharePoint 2013 by Client Object Model

Create List Item:

Add the references Microsoft.SharePoint.dll and Microsoft.SharePoint.Client.dll.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace CreateListItem
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://servername:7777/";
            ClientContext clientContext = new ClientContext(siteUrl);
            List oList = clientContext.Web.Lists.GetByTitle("ListTitle");
            ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();
            ListItem oListItem = oList.AddItem(listCreationInformation);
            oListItem["Title"] = "Hello World";
            oListItem.Update();
            clientContext.ExecuteQuery();
        }
    }
}

Update List Item:

Add the references Microsoft.SharePoint.dll and Microsoft.SharePoint.Client.dll.

using System;
using System.Collections.Generic; 
using System.Linq;
using System.Text; 
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

namespace UpdateListItem
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://servername:7777/";
            ClientContext clientContext = new ClientContext(siteUrl);
            List oList = clientContext.Web.Lists.GetByTitle("ListTitle");
            ListItem oListItem = oList.GetItemById(1);
            oListItem["Title"] = "Hello World Updated.";
            oListItem.Update();
            clientContext.ExecuteQuery();
        }
    }
}

Delete List Item:

Add the references Microsoft.SharePoint.dll and Microsoft.SharePoint.Client.dll.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.SharePoint; 
using Microsoft.SharePoint.Client;

namespace UpdateListItem
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://servername:7777/";
            ClientContext clientContext = new ClientContext(siteUrl);
            List oList = clientContext.Web.Lists.GetByTitle("ListTitle");
            ListItem oListItem = oList.GetItemById(1);         
            oListItem.DeleteObject();
            clientContext.ExecuteQuery();
        }
    }
}