Blogger

  • This email address is being protected from spambots. You need JavaScript enabled to view it.

    Recent items

Login

I would to share with the network the snippet code to enable the Scheduling settings via Client SharePoint Object Model APIs.

This first block provide to enable the Scheduling on all pages list of the site collection

Show/Hidden csharp code

View source
 
 
 
 public void EnablePagesSchedulingOnAllSiteCollection(CustomWebApplication wa)
        {
            try
            {
                foreach (CustomSiteCollection sc in wa.SiteCollections)
                {
                    using (ClientContext context = new ClientContext(wa.Url + sc.Url))
                    {
                        context.Credentials = new NetworkCredential(wa.UserName, wa.UserPassword, wa.UserDomain);
                        context.Load(context.Site.RootWeb, w => w.Webs, w => w.ServerRelativeUrl);
                        context.ExecuteQuery();
 
                        PageHelper.EnableScheduling(context, context.Site.RootWeb, true,sc.LanguageShortCode,logFilePath);
 
 
                    }
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("------------- Exception EnablePagesSchedulingOnAllSiteCollection: {0}", ex.Message);
                Logger.WriteLog(message, logFilePath);
            }
        }
 
 
 

 

The second block provide to enable the settings on the list page recursively

Show/Hidden csharp code

View source
 
 
 
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Publishing;
using Microsoft.SharePoint.Publishing.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Client.Common.Helpers
{
    public class PageHelper
    {
 
        public static Guid StartDateGUID
        {
            get
            {
                return new Guid("51d39414-03dc-4bd0-b777-d3e20cb350f7");
            }
        }
 
        public static Guid EndDateGUID
        {
            get
            {
                return new Guid("a990e64f-faa3-49c1-aafa-885fda79de62");
            }
        }
 
        internal static string GetPageListName(string language)
        {
            string pagesListName = string.Empty;
            switch (language)
            {
                case "it": pagesListName = "Pagine"; break;
                default: pagesListName = "Pages"; break;
            }
            return pagesListName;
        }
 
        internal static void EnableScheduling(ClientContext context, Web currWeb, bool recursive, string language, string logFilePath)
        {
            try
            {
                List pages = ListHelper.GetList(context, currWeb, GetPageListName(language), logFilePath);
                EventReceiverDefinitionCollection eventReceivers = pages.EventReceivers;
 
 
                pages.EnableModeration = true;
                pages.EnableMinorVersions = true;
 
                pages.Update();
 
 
                //To enable Scheduling in the list
                string assembly = "Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c";
                string fullName = "Microsoft.SharePoint.Publishing.Internal.ScheduledItemEventReceiver";
 
                EventReceiverType typeItemUpdating = EventReceiverType.ItemUpdating;
                EventReceiverType typeItemAdded = EventReceiverType.ItemAdded;
                string itemUpdatingERName = "Item Updating Event Handler For Scheduling";
                string itemAddedERName = "Item Added Event Handler For Scheduling";
 
                bool foundUpdating = false;
                bool foundAddedd = false;
 
                foreach (EventReceiverDefinition e in eventReceivers)
                {
                    if (string.Compare(e.ReceiverName, itemUpdatingERName, true) == 0)
                        foundUpdating = true;
                    if (string.Compare(e.ReceiverName, itemAddedERName, true) == 0)
                        foundAddedd = true;
                }
 
                if (!foundUpdating)
                {
 
                    EventReceiverDefinitionCreationInformation erItemUpdating = new EventReceiverDefinitionCreationInformation();
                    erItemUpdating.ReceiverName = itemUpdatingERName;
                    erItemUpdating.EventType = typeItemUpdating;
                    erItemUpdating.ReceiverAssembly = assembly;
                    erItemUpdating.ReceiverClass = fullName;
 
                    eventReceivers.Add(erItemUpdating);
                }
 
                if (!foundAddedd)
                {
                    EventReceiverDefinitionCreationInformation erItemAdded = new EventReceiverDefinitionCreationInformation();
                    erItemAdded.ReceiverName = itemAddedERName;
                    erItemAdded.EventType = typeItemAdded;
                    erItemAdded.ReceiverAssembly = assembly;
                    erItemAdded.ReceiverClass = fullName;
 
                    eventReceivers.Add(erItemAdded);
                }
 
                List<FieldLinkCreationInformation> fieldsToAdd = new List<FieldLinkCreationInformation>();
                fieldsToAdd.Add(new FieldLinkCreationInformation() { Field = context.Site.RootWeb.Fields.GetById(StartDateGUID) });
                fieldsToAdd.Add(new FieldLinkCreationInformation() { Field = context.Site.RootWeb.Fields.GetById(EndDateGUID) });
 
                context.Load(fieldsToAdd[0].Field, f => f.Id);
                context.Load(fieldsToAdd[1].Field, f => f.Id);
 
                context.ExecuteQuery();
 
 
                foreach (FieldLinkCreationInformation f in fieldsToAdd)
                {
                    if (pages.Fields.Where(c => c.Id == f.Field.Id).Count() == 0)
                        pages.Fields.Add(f.Field);
                    else
                    {
                        pages.Fields.Where(c => c.Id == f.Field.Id).FirstOrDefault().Hidden = false;
                        pages.Fields.Where(c => c.Id == f.Field.Id).FirstOrDefault().Update();
                    }
                }
 
                context.ExecuteQuery();
 
                foreach (ContentType ct in pages.ContentTypes)
                {
                    try
                    {
                        context.Load(ct, c => c.FieldLinks, c => c.Fields, c => c.Name);
                        context.ExecuteQuery();
 
                        foreach (FieldLinkCreationInformation f in fieldsToAdd)
                        {
 
                            if (ct.FieldLinks.Where(c => c.Id == f.Field.Id).Count() == 0)
                                ct.FieldLinks.Add(f);
                            else
                                ct.FieldLinks.Where(c => c.Id == f.Field.Id).FirstOrDefault().Hidden = false;
 
                            if (ct.Fields.Where(c => c.Id == f.Field.Id).Count() == 0)
                                ct.Fields.Add(f.Field);
                            else
                                ct.Fields.Where(c => c.Id == f.Field.Id).FirstOrDefault().Hidden = false;
                        }
                        ct.Update(true);
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLog(string.Format("Error on CT {0}: {1} ", ct.Name, ex.Message), logFilePath);
                    }
                }
 
 
                if (!pages.DefaultView.ViewFields.Contains("Scheduling Start Date"))
                {
                    pages.DefaultView.ViewFields.Add("Scheduling Start Date");
                }
 
                if (!pages.DefaultView.ViewFields.Contains("Scheduling End Date"))
                {
                    pages.DefaultView.ViewFields.Add("Scheduling End Date");
                }
 
                pages.DefaultView.Update();
                pages.Update();
                context.ExecuteQuery();
 
                Logger.WriteLog(string.Format("Publishing enabled on list Pages of site {0}.", currWeb.ServerRelativeUrl), logFilePath);
 
                if (recursive)
                {
                    context.Load(currWeb, w => w.Webs);
                    context.ExecuteQuery();
 
                    foreach (Web subWeb in currWeb.Webs)
                    {
                        EnableScheduling(context, subWeb, recursive, language, logFilePath);
                    }
                }
 
            }
            catch (Exception ex)
            {
                Logger.WriteLog(string.Format("Error during EnableScheduling on web {0}: {1}", currWeb.ServerRelativeUrl, ex), logFilePath);
            }
        }
    }
}
 

Published in SharePoint

In this example, I wanto to explain how to use the Client Object Model to retrieve User Profile Properties.

In my example, I have a list with some fields and one of this is a SPFieldUserValue (UserField is the internal name of my field).

Show/Hidden csharp code

View source
 
 
 
ClientContext clientContext = new ClientContext("htttp://intranet.domain022.dev");
clientContext.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
 
 
Site siteCol = clientContext.Site;
Microsoft.SharePoint.Client.Web web = clientContext.Web;
clientContext.Load(web, w => w.Title, w => w.Language, w => w.ServerRelativeUrl);
clientContext.ExecuteQuery();
 
 
clientContext.Load(web, c => c.Lists);
clientContext.ExecuteQuery();
 
List list = web.Lists.GetByTitle("CustomList");
clientContext.Load(list);
clientContext.ExecuteQuery();
 
 
var userInfoList = clientContext.Web.SiteUserInfoList;
clientContext.Load(userInfoList);
 
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View/>";
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(camlQuery);
clientContext.Load(items);
clientContext.ExecuteQuery();
 
foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
    clientContext.Load(item);
    clientContext.ExecuteQuery();
    
    var temp = item["UserField"];
    
    var query = new CamlQuery { ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='ID' /><Value Type='int'>" + ((FieldUserValue)temp).LookupId + "</Value></Eq></Where></Query></View>" };
    var user = userInfoList.GetItems(query);
    clientContext.Load(user);
    clientContext.ExecuteQuery();
    if (user.Count > 0)
    {
 
 
        //here I retrieve only Name property. You can iterate on all properties to view all User properties
        string name = user[0].FieldValues["Name"] as string;
        Console.WriteLine(string.Format("User found {0} with id {1}", name.Split('|').LastOrDefault(), user[0].Id));
    }
    else
    {
        Console.WriteLine(string.Format("User not found: {0} with id {1}", ((FieldUserValue)temp).LookupValue;, ((FieldUserValue)temp).LookupId.ToString()));
    }
}
 
 
 

Published in SharePoint

Hi all, here I want describe two function that use the SharePoint Client Object Model:

  1. to download a file from a SharePoint website to a local path;
  2. to upload a file from a local path to a SharePoint website.

Show/Hidden csharp code

View source
 
 
 
public static bool DownloadFile(ClientContext context, string fileRelativeUrl, string destinationPath, string fileName)
{
    try
    {
        fileRelativeUrl = fileRelativeUrl.Replace("/Images/","/PublishingImages/");
        string sourceUrl = fileRelativeUrl + fileName;
        string completeDestinationPath=destinationPath  + fileName;
        
        if (!System.IO.File.Exists(completeDestinationPath))
        {
            Directory.CreateDirectory(destinationPath);
            FileInformation spFileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, sourceUrl);
 
            using (Stream destination = System.IO.File.Create(completeDestinationPath))
            {
                for (int a = spFileInfo.Stream.ReadByte(); a != -1; a = spFileInfo.Stream.ReadByte())
                    destination.WriteByte((byte)a);
            }
        }
    }
    catch (Exception ex)
    {
        Logger.WriteLog(string.Format("Error during copying file: {0} with error {1}", fileRelativeUrl, ex.StackTrace));
        return false;
    }
    return true;
}
 
 
 
 
 
public static void UploadFile(Web currWeb, string destRelativeUrl, string file, ClientContext destContext)
{
    try
    {
        Microsoft.SharePoint.Client.File destFile = currWeb.GetFileByServerRelativeUrl(destRelativeUrl);
        bool bExists = false;
        try
        {
            destContext.Load(destFile);
            destContext.ExecuteQuery(); //Raises exception if the file doesn't exist
            bExists = destFile.Exists;  //may not be needed - here for good measure
            Logger.WriteLog(string.Format("File already exist: {0}", destRelativeUrl));
        }
        catch
        {
        }
 
        if (!bExists)
        {
            using (FileStream fs = new FileStream(file, FileMode.Open))
            {
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(destContext, destRelativeUrl, fs, false);
                Logger.WriteLog(string.Format("File copied: {0}", destRelativeUrl));
            }
        }
    }
    catch (Exception ex)
    {
        Logger.WriteLog(string.Format("Error during upload file: {0} with error {1}", file, ex));
    }
}
 
 
 

Here a wiki to help to use the SharePoint Client Object Model.

Published in SharePoint