/// <summary>
        /// Assigns permissions to users on the specified list item.
        /// </summary>
        /// <param name="clientcontext">Client context object</param>
        /// <param name="listName">Site pages library</param>
        /// <param name="users">List of users</param>
        /// <param name="permission">Permission to grant</param>
        /// <param name="listItemId">Unique list item Id for permissions assignment</param>
        /// <returns>Status of permission assignment</returns>
        internal static string AssignUserPermissionsToItem(ClientContext clientcontext, string listName, List <string> users, string permission, int listItemId)
        {
            {
                string returnvalue = "false";
                try
                {
                    List <string> permissions = new List <string>();
                    permissions.Add(permission);
                    Web web = clientcontext.Web;
                    clientcontext.Load(web.RoleDefinitions);
                    ListItem listItem = web.Lists.GetByTitle(listName).GetItemById(listItemId);
                    clientcontext.Load(listItem, item => item.HasUniqueRoleAssignments);
                    clientcontext.ExecuteQuery();
                    if (listItem.HasUniqueRoleAssignments)
                    {
                        if (null != permissions && null != users) //matter.permissions=read/limited access/contribute/ full control/ view only
                        {
                            foreach (string rolename in permissions)
                            {
                                try
                                {
                                    RoleDefinitionCollection roleDefinitions = clientcontext.Web.RoleDefinitions;
                                    RoleDefinition           role            = (from roleDef in roleDefinitions
                                                                                where roleDef.Name == rolename
                                                                                select roleDef).First();

                                    foreach (string user in users)
                                    {
                                        //get the user object
                                        Principal userprincipal = clientcontext.Web.EnsureUser(user);
                                        //create the role definition binding collection
                                        RoleDefinitionBindingCollection roledefinitionbindingcollection = new RoleDefinitionBindingCollection(clientcontext);
                                        //add the role definition to the collection
                                        roledefinitionbindingcollection.Add(role);
                                        //create a role assignment with the user and role definition
                                        listItem.RoleAssignments.Add(userprincipal, roledefinitionbindingcollection);
                                    }
                                    //execute the query to add everything
                                    clientcontext.ExecuteQuery();
                                }
                                catch (Exception exception)
                                {
                                    MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                                    throw; // Check
                                }
                            }
                        }
                        // success. return a success code
                        returnvalue = "true";
                    }
                }
                catch (Exception exception)
                {
                    MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "assigning Permission"));
                    MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                    throw;
                }
                return(returnvalue);
            }
        }
        /// <summary>
        /// Function is used to Configure XML of web parts
        /// </summary>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="clientContext">SharePoint Client Context</param>
        /// <param name="sitePageLib">SharePoint List of matter library</param>
        /// <param name="objFileInfo">Object of FileCreationInformation</param>
        /// <param name="uri">To get URL segments</param>
        /// <param name="web">Web object of the current context</param>
        /// <returns>List of Web Parts</returns>
        internal static string[] ConfigureXMLCodeOfWebParts(Client client, Matter matter, ClientContext clientContext, List sitePageLib, FileCreationInformation objFileInfo, Uri uri, Web web)
        {
            string[] result = null;
            try
            {
                sitePageLib = web.Lists.GetByTitle(matter.MatterName);
                clientContext.Load(sitePageLib);
                clientContext.ExecuteQuery();

                ////Configure list View Web Part XML
                string   listViewWebPart         = ConfigureListViewWebPart(sitePageLib, clientContext, objFileInfo, client, matter, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, matter.MatterName, Constants.Backslash, objFileInfo.Url));
                string[] contentEditorSectionIds = ConfigurationManager.AppSettings["MatterLandingPageSections"].Split(',');
                ////Configure content Editor Web Part of user information XML
                string contentEditorWebPartTasks = string.Empty;
                if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
                {
                    contentEditorWebPartTasks = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.TaskPanel, CultureInfo.InvariantCulture)]));
                }

                string calendarWebpart = string.Empty, rssFeedWebPart = string.Empty, rssTitleWebPart = string.Empty;
                if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
                {
                    rssFeedWebPart  = string.Format(CultureInfo.InvariantCulture, Constants.RssFeedWebpart, HttpUtility.UrlEncode(matter.MatterName));
                    rssTitleWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.RSSTitlePanel, CultureInfo.InvariantCulture)]));
                }

                ////Configure calendar Web Part XML
                if (Convert.ToBoolean(ConfigurationManager.AppSettings["TaskListCreationEnabled"], CultureInfo.InvariantCulture))
                {
                    ////If create calendar is enabled configure calendar Web Part XML; else don't configure
                    calendarWebpart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.CalendarPanel, CultureInfo.InvariantCulture)]));
                }

                string matterInformationSection = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.InformationPanel, CultureInfo.InvariantCulture)]));
                string cssLink                 = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["MatterLandingCSSFileName"], ConfigurationManager.AppSettings["MatterLandingFolderName"]);
                string cssLinkCommon           = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["CommonCSSFileName"], ConfigurationManager.AppSettings["CommonFolderName"]);
                string jsLinkMatterLandingPage = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["MatterLandingJSFileName"], ConfigurationManager.AppSettings["MatterLandingFolderName"]);
                string jsLinkJQuery            = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["JQueryFileName"], ConfigurationManager.AppSettings["CommonFolderName"]);
                string jsCommonLink            = string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["CommonJSFileName"], ConfigurationManager.AppSettings["CommonFolderName"]);
                string headerWebPartSection    = string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.HeaderPanel, CultureInfo.InvariantCulture)]);
                string footerWebPartSection    = string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.FooterPanel, CultureInfo.InvariantCulture)]);
                headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.StyleTag, cssLink), headerWebPartSection);
                headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.StyleTag, cssLinkCommon), headerWebPartSection);
                headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTagWithContents, string.Format(CultureInfo.InvariantCulture, Constants.matterLandingStampProperties, matter.MatterName, matter.MatterGuid)), headerWebPartSection);
                footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTag, jsLinkMatterLandingPage), footerWebPartSection);
                footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTag, jsCommonLink), footerWebPartSection);
                footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, Constants.ScriptTag, jsLinkJQuery), footerWebPartSection);
                string   headerWebPart  = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, headerWebPartSection);
                string   footerWebPart  = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, footerWebPartSection);
                string   oneNoteWebPart = string.Format(CultureInfo.InvariantCulture, Constants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, Constants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Constants.MatterLandingSection.OneNotePanel, CultureInfo.InvariantCulture)]));
                string[] webParts       = { headerWebPart, matterInformationSection, oneNoteWebPart, listViewWebPart, rssFeedWebPart, rssTitleWebPart, footerWebPart, calendarWebpart, contentEditorWebPartTasks };
                result = webParts;
            }
            catch (Exception exception)
            {
                MatterProvisionHelperFunction.DeleteMatter(clientContext, matter);
                MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
            }
            return(result);
        }
        /// <summary>
        /// Breaks item level permission.
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="listName">Site pages library</param>
        /// <param name="copyPermissionsFromParent">Copy parent permissions</param>
        /// <param name="listItemId">List item Id to break permission</param>
        /// <returns></returns>
        internal static bool BreakItemPermission(ClientContext clientContext, string listName, bool copyPermissionsFromParent, int listItemId)
        {
            bool flag = false;

            try
            {
                Web      web      = clientContext.Web;
                ListItem listItem = web.Lists.GetByTitle(listName).GetItemById(listItemId);
                clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
                clientContext.ExecuteQuery();
                if (!listItem.HasUniqueRoleAssignments)
                {
                    listItem.BreakRoleInheritance(copyPermissionsFromParent, true);
                    listItem.Update();
                    clientContext.ExecuteQuery();
                    flag = true;
                }
            }
            catch (Exception exception)
            {
                MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
                throw;
            }
            return(flag);
        }
        /// <summary>
        /// Add Calendar Web Part to client site
        /// </summary>
        /// <param name="clientContext">SharePoint Client Context</param>
        /// <param name="matter">Matter object containing Matter data</param>
        internal static void AddCalendarList(ClientContext clientContext, Matter matter)
        {
            string calendarName = string.Concat(matter.MatterName, ConfigurationManager.AppSettings["CalendarNameSuffix"]);

            try
            {
                Web web = clientContext.Web;
                clientContext.Load(web, item => item.ListTemplates);
                clientContext.ExecuteQuery();
                ListTemplate listTemplate = null;
                foreach (var calendar in web.ListTemplates)
                {
                    if (calendar.Name == Constants.CalendarName)
                    {
                        listTemplate = calendar;
                    }
                }

                ListCreationInformation listCreationInformation = new ListCreationInformation();
                listCreationInformation.TemplateType = listTemplate.ListTemplateTypeKind;
                listCreationInformation.Title        = calendarName;
                // Added URL property for URL consolidation changes
                listCreationInformation.Url = Constants.TitleListPath + matter.MatterGuid + ConfigurationManager.AppSettings["CalendarNameSuffix"];
                web.Lists.Add(listCreationInformation);
                web.Update();
                clientContext.ExecuteQuery();
                MatterProvisionHelperFunction.BreakPermission(clientContext, matter.MatterName, matter.CopyPermissionsFromParent, calendarName);
            }
            catch (Exception exception)
            {
                //// Generic Exception
                MatterProvisionHelperFunction.DeleteMatter(clientContext, matter);
                MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
            }
        }
        /// <summary>
        /// Creates Matter Landing Page on matter creation
        /// </summary>
        /// <param name="clientContext">Client Context</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <returns>true if success else false</returns>
        internal static string CreateMatterLandingPage(ClientContext clientContext, Client client, Matter matter)
        {
            string response = string.Empty;

            if (null != clientContext && null != client && null != matter)
            {
                try
                {
                    using (clientContext)
                    {
                        Uri uri = new Uri(client.ClientUrl);
                        Web web = clientContext.Web;
                        FileCreationInformation objFileInfo = new FileCreationInformation();
                        List sitePageLib = null;
                        //// Create Matter Landing Web Part Page
                        objFileInfo.Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, Constants.AspxExtension);
                        response        = CreateWebPartPage(sitePageLib, clientContext, objFileInfo, matter, web);
                        if (Constants.TRUE == response)
                        {
                            //// Configure All Web Parts
                            string[] webParts = ConfigureXMLCodeOfWebParts(client, matter, clientContext, sitePageLib, objFileInfo, uri, web);
                            Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, ConfigurationManager.AppSettings["MatterLandingPageRepository"].Replace(Constants.SPACE, string.Empty), Constants.Backslash, objFileInfo.Url));
                            clientContext.Load(file);
                            clientContext.ExecuteQuery();

                            LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                            WebPartDefinition     webPartDefinition     = null;

                            string[] zones = { Constants.HeaderZone, Constants.TopZone, Constants.RightZone, Constants.TopZone, Constants.RightZone, Constants.RightZone, Constants.FooterZone, Constants.RightZone, Constants.RightZone };
                            AddWebPart(clientContext, limitedWebPartManager, webPartDefinition, webParts, zones);
                        }
                        else
                        {
                            response = Constants.FALSE;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ////Generic Exception
                    MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "creating Matter Landing page"));
                    MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + ex.Message + "\nStacktrace: " + ex.StackTrace);
                    throw;
                }

                return(response);
            }
            else
            {
                return(string.Format(CultureInfo.InvariantCulture, Constants.ServiceResponse, string.Empty, Constants.MessageNoInputs));
            }
        }