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

Monday, 4 July 2016

Converting to JSON

I was given a SharePoint 2010 requirement..And...Oh...I actually felt terrible to not work in SharePoint 2013, if not SharePoint 2016.But, thankfully, the below code is valid for SharePoint 2013.
Hopefully, things are better in SharePoint 2016 to read data from external domain and get the results in JSON which can be used for various purposes. A reference to SharePoint.Client and System.Web.Extentions need to be added. Below are two codes, one to convert a data to JSON and the other code to read SharePoint list and return in JSON format.
Code 1: Read data and convert to JSON
using System;


using System.Collections.Generic;


using System.Linq;


using System.Text;


using System.Threading.Tasks;


using System.Web.Script.Serialization;







//References::http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4


//https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx


namespace MSDNJsonData






{
public class MyDate





{
public int year;

public int month;

public int day;






}
public class Lad





{
public string firstName;

public string lastName;

public MyDate dateOfBirth;






}
class Program





{
static void Main(string[] args)






{
var obj = new Lad





{
firstName = "Thangu",

lastName = "Not Applicable",

dateOfBirth = new MyDate





{


year = 2016,


month = 7,


day = 04


}


};
var json = new JavaScriptSerializer().Serialize(obj);

Console.WriteLine(json);

Console.Read();






}


}


}


Code 2: To read SharePoint and return data in JSON format.
using System;


using System.Collections.Generic;


using System.Linq;


using System.Text;


using Microsoft.SharePoint.Client;


using System.Web.Script.Serialization;






 


 


 
namespace ConsoleApplicationReadSPList






{
using ServiceReference1;

public class SPAnnouncement





{
public string Title;






}
public class SPEmailGroup





{
public string Email;

public string MailGroup;//A lookup column






}



class Program





{
static void Main(string[] args)






{



string websiteUrl = http://xxx.sharepoint.com;

ServiceReference1.XXX context = new ServiceReference1.XXX(new Uri(websiteUrl + "/_vti_bin/listdata.svc"));

context.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Starting with ClientContext, the constructor requires a URL to the


// server running SharePoint.


ClientContext clientcontext = new ClientContext(websiteUrl);

// Assume the web has a list named "Announcements".


List announcementsList = clientcontext.Web.Lists.GetByTitle("Announcements");

// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"


// so that it grabs all list items, regardless of the folder they are in.


CamlQuery query = CamlQuery.CreateAllItemsQuery(100);

ListItemCollection items = announcementsList.GetItems(query);

// Retrieve all items in the ListItemCollection from List.GetItems(Query).





clientcontext.Load(items);


clientcontext.ExecuteQuery();
foreach (ListItem listItem in items)






{
// We have all the list item data. For example, Title.


Console.WriteLine(listItem["Title"]);

var obj = new SPAnnouncement





{
Title = listItem["Title"].ToString()






};
var json = new JavaScriptSerializer().Serialize(obj);

Console.WriteLine(json);









}
//Reading another list with two values


// Assume the web has a list named "Announcements".


List emailList = clientcontext.Web.Lists.GetByTitle("EmailGroup");

// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"


// so that it grabs all list items, regardless of the folder they are in.


CamlQuery query2 = CamlQuery.CreateAllItemsQuery(100);

ListItemCollection items2 = emailList.GetItems(query);

// Retrieve all items in the ListItemCollection from List.GetItems(Query).





clientcontext.Load(items2);


clientcontext.ExecuteQuery();
foreach (ListItem listItem2 in items2)






{
// We have all the list item data. For example, Title.


Console.WriteLine(listItem2["Email"]);

var mail = listItem2["MailGroup"] as FieldLookupValue;

var obj2 = new SPEmailGroup





{
Email = listItem2["Email"].ToString(),






MailGroup = mail.LookupValue


};
var json2 = new JavaScriptSerializer().Serialize(obj2);

Console.WriteLine(json2);






}
Console.Read();






}


}


}