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

No comments:

Post a Comment