Value was either too large or too small for an Int32

Value was either too large or too small for an Int32

In one of my previous post I had demonstrated how to, Download Large Files from SharePoint Online. While the file download is working perfectly fine, but, I was constantly getting the following error while trying to load/access it’s properties,

Value was either too large or too small for an Int32

Continue reading

Check-In/Check-Out and Publish/UnPublish files in SharePoint 2013 using the Client Object Model C#


string siteUrl = "http://servername:12345/";
SP.ClientContext ctx = new SP.ClientContext(siteUrl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);
this.ctx.Load(this.ctx.Web);
SP.Web web = this.ctx.Web;
SP.File file = web.getFileByServerRelativeUrl("serverrelativeUrlOfTheFile");

//CheckIn the file
file.CheckIn(String.Concat("File CheckingIn at ", DateTime.Now.ToLongDateString()), SP.CheckinType.MajorCheckIn);

//CheckOut the File
file.CheckOut();

//Publish the file
file.Publish(String.Concat("File Publishing at ", DateTime.Now.ToLongDateString()));

//UnPublish the file
file.UnPublish(String.Concat("File UnPublishing at ", DateTime.Now.ToLongDateString()));

Remember, before making any changes to the state of the file it is always advisable to first check its current state/level. You can check the current state of the file i.e., if the file is currently CheckedOut, Drafted (CheckedIn), OR, Published. You can easily do that by checking the FileLevel value of the file you’re querying. FileLevel is an enum which specifies the publishing level for a file. MoreInfo

***

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

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

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