Monday, 30 January 2017

SharePoint Alerts CSOM

SharePoint Alerts are a very useful feature to send alerts on either addition, modification or deletion of items on a SharePoint List. An end User can individually assign an Alert to a list.

The new Nuget Package in SharePoint for Online allows one to add alerts to a user with ease.
Below is a code snippet to view all alerts for a single user.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;


namespace SharePointCSOMAlerts
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleColor defaultForeground = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter the URL of the SharePoint Online site:");

            Console.ForegroundColor = defaultForeground;
            string webUrl = Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter the List for which you want to set alert:");

            Console.ForegroundColor = defaultForeground;
            string alertListName = Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter your user name (ex: name@mytenant.microsoftonline.com):");
            Console.ForegroundColor = defaultForeground;
            string userName = Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter your password.");
            Console.ForegroundColor = defaultForeground;
            SecureString password = GetConsoleSecurePassword();
            Console.WriteLine("Password Reading complete");

            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new SharePointOnlineCredentials(userName, password);
                //Showing web details
                Web site = context.Web;
                context.Load(site);
                context.ExecuteQuery();
                Console.WriteLine("Alerts in site:{0}", site.Title);
                context.ExecuteQuery();
                Console.WriteLine("Connection successful");

                //View all alerts
                string targetUser = "i:0#.f|membership|" + userName;
                User user = site.EnsureUser(targetUser);
                AlertCollection alerts = user.Alerts;
                context.Load(alerts);
                context.ExecuteQuery();
                Console.WriteLine(alerts.Count);
                foreach (Alert alert in alerts)
                {
                    Console.WriteLine("Alert ID: {0}\n Alert Name:{1} ", alert.ID,alert.Title);
                }

                //Adding a new Alert
                /*List alertList = site.Lists.GetByTitle(alertListName);
               

                AlertCreationInformation newAlert = new AlertCreationInformation();
                newAlert.AlertFrequency = AlertFrequency.Immediate;
                newAlert.AlertType = AlertType.List;
                newAlert.List = alertList;
                newAlert.DeliveryChannels = AlertDeliveryChannel.Email;
                newAlert.EventType = AlertEventType.AddObject;
                newAlert.Title = "NewNewsAlert" + DateTime.Now.ToShortDateString();
                newAlert.User = user;
               
                site.Alerts.Add(newAlert);
                site.Update();
                context.ExecuteQuery();
               
               Console.ForegroundColor = ConsoleColor.White;
               Console.WriteLine("Action done:: New Alert added successfully");
               */
               Console.ForegroundColor = defaultForeground;
               Console.ReadLine();
            }
        }

        /// <summary>
        /// Gets the console secure password.
        /// </summary>
        /// <returns></returns>
        private static SecureString GetConsoleSecurePassword()
        {
            SecureString pwd = new SecureString();
            while (true)
            {
                ConsoleKeyInfo i = Console.ReadKey(true);
                if (i.Key == ConsoleKey.Enter)
                {
                    break;
                }
                else if (i.Key == ConsoleKey.Backspace)
                {
                    pwd.RemoveAt(pwd.Length - 1);
                    Console.Write("\b \b");
                }
                else
                {
                    pwd.AppendChar(i.KeyChar);
                    Console.Write("*");
                }
            }
            return pwd;
        }

        /// <summary>
        /// Gets the console password.
        /// </summary>
        /// <returns></returns>
        private static string GetConsolePassword()
        {
            StringBuilder sb = new StringBuilder();
            while (true)
            {
                ConsoleKeyInfo cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }

                if (cki.Key == ConsoleKey.Backspace)
                {
                    if (sb.Length > 0)
                    {
                        Console.Write("\b\0\b");
                        sb.Length--;
                    }

                    continue;
                }

                Console.Write('*');
                sb.Append(cki.KeyChar);
            }

            return sb.ToString();
        }
    }
}

Friday, 20 January 2017

SharePoint Assign Permission to Folder

One of the common requests in SharePoint is to assign custom permissions to users, since we do not want everyone to view secure documents.

"Please note that assigning individual permission to each folder might reduce the performance of the list when the size of the list grows.Please try to redesign the solution by creating different libraries for each group rather than assigning unique permissions.
BreakRoleInheritance and RoleAssignment is the way to add custom permission"


There are 33 permission levels in SharePoint. But the following are the most commonly needed when assigning custom permissions to a user or a Group:

View Only
Contribute
Manage

The group can be an existing group like "Contoso Member" or you can create your own Group.

The picture below illustrates the steps to assign permissions to a folder using both Server Side Object Model and Client Site Code.

1. Get the Folder/List/Document Library/List for a Site
2. Call the BreakRoleInheritance
3. Use the RoleAssignment to map the User/Group to the Appropriate Permission Level.



Below is a sample SSOM code:
            string url = "http://w15-sp/PermissionDemo/Folder1";
            SPSite site = new SPSite("http://w15-sp");
            SPWeb web = site.RootWeb;
            SPFolder folder = web.GetFolder(url);
            SPGroupCollection groups = web.Groups;
            /*
            //Use following code to view all groups
            foreach (SPGroup group in groups)
            {
                Console.WriteLine(group.Name);
            }
             * */
            SPGroup group = groups.GetByName("Contoso Members");

            //Create a Role Assignment
            SPRoleAssignment role = new SPRoleAssignment((SPPrincipal)group);
            folder.Item.BreakRoleInheritance(true);

            //You can give your custom group Name
            role.RoleDefinitionBindings.Add(web.RoleDefinitions["Contribute"]);
            folder.Item.RoleAssignments.Add(role);

            Console.WriteLine("Broken Inheritance");
            Console.Read();


Below is a sample CSOM code to assign unique permissions to folder:
using (var clientContext = new ClientContext(webUrl))
            {
                clientContext.Credentials = new SharePointOnlineCredentials(userName, password);

                Web web = clientContext.Web;
                List list = web.Lists.GetByTitle("PermissionDemo");
                Folder newFolder = list.RootFolder.Folders.Add("FolderDemo");
                clientContext.ExecuteQuery();
                newFolder.ListItemAllFields.BreakRoleInheritance(false, true);
                var role = new RoleDefinitionBindingCollection(clientContext);
                role.Add(web.RoleDefinitions.GetByType(RoleType.Contributor));
                User user = web.EnsureUser(userName);
                newFolder.ListItemAllFields.RoleAssignments.Add(user, role);
                newFolder.Update();
                clientContext.ExecuteQuery();

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Action completed.Security Changed. ");
                Console.ForegroundColor = defaultForeground;
                Console.ReadLine();
            }

The details can viewed from the video below:



References:
http://www.sharepointnadeem.com/2015/03/sharepoint-csom-break-folder-permissions.html
https://technet.microsoft.com/en-us/library/cc721640.aspx