/// <summary>
 /// Checks if the lists exist
 /// </summary>
 /// <param name="clientContext">Client context</param>
 /// <param name="matterName">List name</param>
 /// <returns></returns>
 internal static List<string> CheckListsExist(ClientContext clientContext, string matterName, MatterConfigurations matterConfigurations = null)
 {
     List<string> lists = new List<string>();
     lists.Add(matterName);
     lists.Add(matterName + ServiceConstantStrings.OneNoteLibrarySuffix);
     if (null == matterConfigurations || matterConfigurations.IsCalendarSelected)
     {
         lists.Add(matterName + ServiceConstantStrings.CalendarNameSuffix);
     }
     if (null == matterConfigurations || matterConfigurations.IsTaskSelected)
     {
         lists.Add(matterName + ServiceConstantStrings.TaskNameSuffix);
     }
     List<string> listExists = Lists.Exists(clientContext, new ReadOnlyCollection<string>(lists));
     return listExists;
 }
 /// <summary>
 /// Save configurations value to SharePoint list
 /// </summary>
 /// <param name="matterConfigurations">Matter configurations</param>
 /// <param name="clientContext">ClientContext object</param>
 /// <param name="cachedItemModifiedDate">Date and time when user loaded the client settings page to configure default values</param>
 /// <returns>true or error</returns>
 internal static string SaveConfigurationToList(MatterConfigurations matterConfigurations, ClientContext clientContext, string cachedItemModifiedDate)
 {
     string result = string.Empty;
     try
     {
         string listQuery = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.MatterConfigurationsListQuery, SearchConstants.ManagedPropertyTitle, ServiceConstantStrings.MatterConfigurationTitleValue);
         ListItemCollection collection = Lists.GetData(clientContext, ServiceConstantStrings.MatterConfigurationsList, listQuery);
         // Set the default value for conflict check flag
         matterConfigurations.IsContentCheck = ServiceConstantStrings.IsContentCheck;
         if (0 == collection.Count)
         {
             List<string> columnNames = new List<string>() { ServiceConstantStrings.MatterConfigurationColumn, SearchConstants.ManagedPropertyTitle };
             List<object> columnValues = new List<object>() { Encoder.HtmlEncode(JsonConvert.SerializeObject(matterConfigurations)), ServiceConstantStrings.MatterConfigurationTitleValue };
             Web web = clientContext.Web;
             List list = web.Lists.GetByTitle(ServiceConstantStrings.MatterConfigurationsList);
             Lists.AddItem(clientContext, list, columnNames, columnValues);
         }
         else
         {
             bool response = Lists.CheckItemModified(collection, cachedItemModifiedDate);
             if (response)
             {
                 foreach (ListItem item in collection)
                 {
                     item[ServiceConstantStrings.MatterConfigurationColumn] = Encoder.HtmlEncode(JsonConvert.SerializeObject(matterConfigurations));
                     item.Update();
                     break;
                 }
             }
             else
             {
                 result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.IncorrectTeamMembersCode, ServiceConstantStrings.IncorrectTeamMembersMessage + ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR);
             }
         }
         if (string.IsNullOrWhiteSpace(result))
         {
             clientContext.ExecuteQuery();
             result = ConstantStrings.TRUE;
         }
     }
     catch (Exception exception)
     {
         result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
     }
     return result;
 }
        /// <summary>
        /// Creates an item in the specific list with the list of users to whom the matter will be shared.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object</param>
        /// <param name="matterDetails">Details of matter</param>
        /// <param name="matterLandingFlag">Flag to determine if Matter landing page exists</param>
        /// <param name="matterConfigurations">Object holding configuration for the matter</param>
        /// <returns>true if success else false</returns>
        internal static string ShareMatter(RequestObject requestObject, Client client, Matter matter, MatterDetails matterDetails, string matterLandingFlag, MatterConfigurations matterConfigurations)
        {
            string returnFlag = ConstantStrings.FALSE;

            if (null != requestObject && null != client && null != matter && null != matterDetails)
            {
                try
                {

                    Uri mailListURL = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", ConstantStrings.ProvisionMatterAppURL, ConstantStrings.ForwardSlash, ConstantStrings.Lists, ConstantStrings.ForwardSlash, ConstantStrings.SendMailListName));
                    string centralMailListURL = Convert.ToString(mailListURL, CultureInfo.InvariantCulture);
                    string mailSiteURL = centralMailListURL.Substring(0, centralMailListURL.LastIndexOf(string.Concat(ConstantStrings.ForwardSlash, ConstantStrings.Lists, ConstantStrings.ForwardSlash), StringComparison.OrdinalIgnoreCase));
                    ///// Retrieve the specific site where the Mail List is present along with the required List Name
                    if (null != mailListURL && null != client.Url)
                    {
                        if (!string.IsNullOrWhiteSpace(mailSiteURL))
                        {
                            returnFlag = ProvisionHelperFunctions.ShareMatterUtility(requestObject, client, matter, matterDetails, mailSiteURL, centralMailListURL, matterLandingFlag, matterConfigurations);
                        }
                    }
                }

                catch (Exception exception)
                {
                    Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            return returnFlag;
        }
        /// <summary>
        /// Saves the matter details in centralized list.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="matterListName">Name of list where matter creation entry is logged</param>
        /// <param name="matterConfigurations">matterConfigurations object consist of configuration of matter</param>
        /// <param name="clientContext">Client context</param>
        /// <returns>true if success else false</returns>
        internal static string SaveMatterDetails(RequestObject requestObject, Client client, Matter matter, string matterListName, MatterConfigurations matterConfigurations, ClientContext clientContext)
        {
            string returnFlag = ConstantStrings.FALSE;
            try
            {
                if (!string.IsNullOrWhiteSpace(matterListName) && null != requestObject && null != matter && null != client)
                {
                    FieldUserValue tempUser = null;
                    List<FieldUserValue> blockUserList = null;
                    List<List<FieldUserValue>> assignUserList = null;

                    List<string> columnNames = new List<string>()
                        {
                            ServiceConstantStrings.MattersListColumnTitle,
                            ServiceConstantStrings.MattersListColumnClientName,
                            ServiceConstantStrings.MattersListColumnClientID,
                            ServiceConstantStrings.MattersListColumnMatterName,
                            ServiceConstantStrings.MattersListColumnMatterID
                        };
                    List<object> columnValues = new List<object>()
                        {
                            string.Concat(client.Name, ConstantStrings.Underscore, matter.Name),
                            client.Name,
                            client.Id,
                            matter.Name,
                            matter.Id
                        };

                    if (matterConfigurations.IsConflictCheck)
                    {

                        if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.CheckBy))
                        {
                            tempUser = SharePointHelper.ResolveUserNames(clientContext, new List<string>() { matter.Conflict.CheckBy }).FirstOrDefault();
                            columnNames.Add(ServiceConstantStrings.MattersListColumnConflictCheckBy);
                            columnValues.Add(tempUser);
                            if (!string.IsNullOrWhiteSpace(matter.Conflict.CheckOn))
                            {
                                columnNames.Add(ServiceConstantStrings.MattersListColumnConflictCheckOn);
                                columnValues.Add(Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture));
                            }

                            columnNames.Add(ServiceConstantStrings.MattersListColumnConflictIdentified);
                            columnValues.Add(Convert.ToBoolean(matter.Conflict.Identified, CultureInfo.InvariantCulture));
                        }

                        if (null != matter.BlockUserNames)
                        {
                            blockUserList = new List<FieldUserValue>();
                            blockUserList = SharePointHelper.ResolveUserNames(clientContext, matter.BlockUserNames).ToList();
                            columnNames.Add(ServiceConstantStrings.MattersListColumnBlockUsers);
                            columnValues.Add(blockUserList);
                        }
                    }

                    if (null != matter.AssignUserEmails)
                    {
                        assignUserList = new List<List<FieldUserValue>>();
                        foreach (IList<string> assignUsers in matter.AssignUserEmails)
                        {
                            List<FieldUserValue> tempAssignUserList = SharePointHelper.ResolveUserNames(clientContext, assignUsers).ToList();
                            assignUserList.Add(tempAssignUserList);
                        }

                        if (0 != assignUserList.Count && null != matter.Roles && 0 != matter.Roles.Count)
                        {
                            int assignPosition = 0;
                            List<FieldUserValue> managingAttorneyList = new List<FieldUserValue>();
                            List<FieldUserValue> teamMemberList = new List<FieldUserValue>();
                            foreach (string role in matter.Roles)
                            {
                                switch (role)
                                {
                                    case ConstantStrings.ManagingAttorneyValue:
                                        managingAttorneyList.AddRange(assignUserList[assignPosition]);
                                        break;
                                    default:
                                        teamMemberList.AddRange(assignUserList[assignPosition]);
                                        break;
                                }

                                assignPosition++;
                            }

                            columnNames.Add(ServiceConstantStrings.MattersListColumnManagingAttorney);
                            columnValues.Add(managingAttorneyList);
                            columnNames.Add(ServiceConstantStrings.MattersListColumnSupport);
                            columnValues.Add(teamMemberList);
                        }
                    }

                    Microsoft.SharePoint.Client.Web web = clientContext.Web;
                    List matterList = web.Lists.GetByTitle(matterListName);
                    // To avoid the invalid symbol error while parsing the JSON, return the response in lower case
                    returnFlag = Convert.ToString(Lists.AddItem(clientContext, matterList, columnNames, columnValues), CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentUICulture);
                }
            }
            catch (Exception exception)
            {
                //// SharePoint Specific Exception
                ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }

            return returnFlag;
        }
        /// <summary>
        /// Utility function to create matter.
        /// </summary>
        /// <param name="requestObject">object of type request object</param>
        /// <param name="client">object of client</param>
        /// <param name="matter">object of matter type</param>
        /// <param name="clientContext">client context information</param>
        /// <param name="matterURL">URL of matter</param>
        /// <returns>Matter URL</returns>
        internal static string CreateMatterUtility(RequestObject requestObject, Client client, Matter matter, ClientContext clientContext, string matterURL, MatterConfigurations matterConfigurations)
        {
            try
            {
                Uri centralListURL = new Uri(string.Concat(ServiceConstantStrings.CentralRepositoryUrl, ConstantStrings.ForwardSlash, ConstantStrings.Lists, ConstantStrings.ForwardSlash, ServiceConstantStrings.DMSMatterListName)); // Central Repository List URL
                IList<string> documentLibraryFolders = new List<string>();
                Dictionary<string, bool> documentLibraryVersioning = new Dictionary<string, bool>();
                Uri clientUrl = new Uri(client.Url);

                ListInformation listInformation = new ListInformation();
                listInformation.name = matter.Name;
                listInformation.description = matter.Description;
                listInformation.folderNames = matter.FolderNames;
                listInformation.isContentTypeEnable = true;
                listInformation.versioning = new VersioningInfo();
                listInformation.versioning.EnableVersioning = ServiceConstantStrings.IsMajorVersionEnable;
                listInformation.versioning.EnableMinorVersions = ServiceConstantStrings.IsMinorVersionEnable;
                listInformation.versioning.ForceCheckout = ServiceConstantStrings.IsForceCheckOut;
                listInformation.Path = matter.MatterGuid;

                Lists.Create(clientContext, listInformation);

                documentLibraryVersioning.Add("EnableVersioning", false);
                documentLibraryFolders.Add(matter.MatterGuid);
                listInformation.name = matter.Name + ServiceConstantStrings.OneNoteLibrarySuffix;
                listInformation.folderNames = documentLibraryFolders;
                listInformation.versioning.EnableVersioning = false;
                listInformation.versioning.EnableMinorVersions = false;
                listInformation.versioning.ForceCheckout = false;
                listInformation.Path = matter.MatterGuid + ServiceConstantStrings.OneNoteLibrarySuffix;
                Lists.Create(clientContext, listInformation);

                bool isCopyRoleAssignment = CopyRoleAssignment(matter.Conflict.Identified, matter.Conflict.SecureMatter);
                //create calendar list if create calendar flag is enabled and break its permissions
                string calendarName = string.Concat(matter.Name, ServiceConstantStrings.CalendarNameSuffix);
                string taskListName = string.Concat(matter.Name, ServiceConstantStrings.TaskNameSuffix);
                if (ServiceConstantStrings.IsCreateCalendarEnabled && matterConfigurations.IsCalendarSelected)
                {
                    ListInformation calendarInformation = new ListInformation();
                    calendarInformation.name = calendarName;
                    calendarInformation.isContentTypeEnable = false;
                    calendarInformation.templateType = ConstantStrings.CalendarName;
                    calendarInformation.Path = ServiceConstantStrings.TitleListsPath + matter.MatterGuid + ServiceConstantStrings.CalendarNameSuffix;

                    if (Lists.Create(clientContext, calendarInformation))
                    {
                        Lists.BreakPermission(clientContext, calendarName, isCopyRoleAssignment);
                    }
                    else
                    {
                        MatterCenterException customException = new MatterCenterException(TextConstants.ErrorCodeAddCalendarList, TextConstants.ErrorMessageAddCalendarList);
                        throw customException; // Throw will direct to current function's catch block (if present). If not present then it will direct to parent catch block. Parent will be the calling function
                    }
                }
                if (matterConfigurations.IsTaskSelected)
                {
                    ListInformation taskListInformation = new ListInformation();
                    taskListInformation.name = taskListName;
                    taskListInformation.isContentTypeEnable = false;
                    taskListInformation.templateType = ConstantStrings.TaskListTemplateType;
                    taskListInformation.Path = ServiceConstantStrings.TitleListsPath + matter.MatterGuid + ServiceConstantStrings.TaskNameSuffix;
                    if (Lists.Create(clientContext, taskListInformation))
                    {
                        Lists.BreakPermission(clientContext, taskListName, isCopyRoleAssignment);
                    }
                    else
                    {
                        MatterCenterException customException = new MatterCenterException(TextConstants.ErrorCodeAddTaskList, TextConstants.ErrorMessageAddTaskList);
                        throw customException; // Throw will direct to current function's catch block (if present). If not present then it will direct to parent catch block. Parent will be the calling function
                    }
                }
                string oneNoteUrl = string.Concat(clientUrl.AbsolutePath, ConstantStrings.ForwardSlash, matter.MatterGuid, ServiceConstantStrings.OneNoteLibrarySuffix, ConstantStrings.ForwardSlash, matter.MatterGuid);
                matterURL = Lists.AddOneNote(clientContext, client.Url, oneNoteUrl, matter.MatterGuid, matter.Name);
                matterURL = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, client.Url);
                if (null != matter.Conflict)
                {
                    //Break permission for Matter library
                    Lists.BreakPermission(clientContext, matter.Name, isCopyRoleAssignment);

                    //Break permission for OneNote document library
                    string oneNoteLibraryName = string.Concat(matter.Name, ServiceConstantStrings.OneNoteLibrarySuffix);
                    Lists.BreakPermission(clientContext, oneNoteLibraryName, isCopyRoleAssignment);
                }
                string roleCheck = ValidationHelperFunctions.RoleCheck(requestObject, matter, client);
                if (string.IsNullOrEmpty(roleCheck))
                {
                    string centralList = Convert.ToString(centralListURL, CultureInfo.InvariantCulture);
                    string matterSiteURL = centralList.Substring(0, centralList.LastIndexOf(string.Concat(ConstantStrings.ForwardSlash, ConstantStrings.Lists, ConstantStrings.ForwardSlash), StringComparison.OrdinalIgnoreCase));
                    string matterListName = centralList.Substring(centralList.LastIndexOf(ConstantStrings.ForwardSlash, StringComparison.OrdinalIgnoreCase) + 1);
                    ClientContext listClientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(matterSiteURL), requestObject.RefreshToken);
                    ProvisionHelperFunctions.SaveMatterDetails(requestObject, client, matter, matterListName, matterConfigurations, listClientContext);
                }
                else
                {
                    matterURL = roleCheck;
                }
            }
            catch (Exception exception)
            {
                ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                matterURL = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return matterURL;
        }
        public string SaveMatterConfigurations(RequestObject requestObject, string siteCollectionPath, MatterConfigurations matterConfigurations, IList<string> userId, string cachedItemModifiedDate)
        {
            string result = string.Empty;
            if (null != requestObject && !string.IsNullOrWhiteSpace(siteCollectionPath) && null != matterConfigurations && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                try
                {
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(siteCollectionPath), requestObject.RefreshToken))
                    {
                        Matter matter = new Matter();
                        matter.AssignUserNames = SettingsHelper.GetUserList(matterConfigurations.MatterUsers);
                        matter.AssignUserEmails = SettingsHelper.GetUserList(matterConfigurations.MatterUserEmails);

                        if (0 < matter.AssignUserNames.Count)
                        {
                            result = EditMatterHelperFunctions.ValidateTeamMembers(clientContext, matter, userId);
                        }
                        if (string.IsNullOrEmpty(result))
                        {
                            result = SettingsHelper.SaveConfigurationToList(matterConfigurations, clientContext, cachedItemModifiedDate);
                            bool tempResult = false;
                            if (Boolean.TryParse(result, out tempResult))
                            {
                                if (tempResult)
                                {
                                    string listQuery = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.MatterConfigurationsListQuery, SearchConstants.ManagedPropertyTitle, ServiceConstantStrings.MatterConfigurationTitleValue);
                                    ListItem settingsItem = Lists.GetData(clientContext, ServiceConstantStrings.MatterConfigurationsList, listQuery).FirstOrDefault();
                                    if (null != settingsItem)
                                    {
                                        cachedItemModifiedDate = Convert.ToString(settingsItem[ServiceConstantStrings.ColumnNameModifiedDate], CultureInfo.InvariantCulture);
                                    }
                                    result = string.Concat(result, ConstantStrings.Pipe, ConstantStrings.DOLLAR, ConstantStrings.Pipe, cachedItemModifiedDate);
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            else
            {
                result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
            }
            return result;
        }
        public string GetDefaultMatterConfigurations(RequestObject requestObject, string siteCollectionPath)
        {
            string result = string.Empty, settingsUpdatedDate = string.Empty;
            int errorCodeModifiedDate = 0;  // Error code to be set if no list item found in Matter Configuration list
            if (null != requestObject && !string.IsNullOrWhiteSpace(siteCollectionPath) && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                try
                {
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(siteCollectionPath), requestObject.RefreshToken))
                    {
                        if (Lists.CheckPermissionOnList(ServiceUtility.GetClientContext(null, new Uri(siteCollectionPath), requestObject.RefreshToken), ServiceConstantStrings.MatterConfigurationsList, PermissionKind.EditListItems))
                        {
                            string listQuery = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.MatterConfigurationsListQuery, SearchConstants.ManagedPropertyTitle, ServiceConstantStrings.MatterConfigurationTitleValue);
                            ListItem settingsItem = Lists.GetData(clientContext, ServiceConstantStrings.MatterConfigurationsList, listQuery).FirstOrDefault();
                            if (null != settingsItem)
                            {
                                settingsUpdatedDate = Convert.ToString(settingsItem[ServiceConstantStrings.ColumnNameModifiedDate], CultureInfo.InvariantCulture);
                                result = HttpUtility.HtmlDecode(string.Concat(Convert.ToString(settingsItem[ServiceConstantStrings.MatterConfigurationColumn], CultureInfo.InvariantCulture), ConstantStrings.Pipe, ConstantStrings.DOLLAR, ConstantStrings.Pipe, settingsUpdatedDate));
                            }
                            else
                            {
                                settingsUpdatedDate = Convert.ToString(errorCodeModifiedDate, CultureInfo.InvariantCulture);
                            }
                        }
                        else
                        {
                            result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.UserNotSiteOwnerCode, ServiceConstantStrings.UserNotSiteOwnerMessage);
                        }
                    }
                }
                catch (Exception exception)
                {
                    result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            else
            {
                result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
            }

            if (string.IsNullOrEmpty(result))
            {
                MatterConfigurations configurations = new MatterConfigurations();
                configurations.IsCalendarSelected = true;
                configurations.IsConflictCheck = true;
                configurations.IsEmailOptionSelected = true;
                configurations.IsMatterDescriptionMandatory = true;
                configurations.IsRestrictedAccessSelected = true;
                configurations.IsRSSSelected = true;
                configurations.IsTaskSelected = true;
                result = JsonConvert.SerializeObject(configurations);
                result = string.Concat(result, ConstantStrings.Pipe, ConstantStrings.DOLLAR, ConstantStrings.Pipe, settingsUpdatedDate);
            }
            return result;
        }
        /// <summary>
        /// Validates meta-data of a matter and returns the validation status (success/failure).
        /// </summary>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="clientContext">Client context object for SharePoint</param>  
        /// <param name="methodNumber">Number indicating which method needs to be validated</param>     
        /// <returns>A string value indicating whether validations passed or fail</returns>
        internal static string MatterMetadataValidation(Matter matter, ClientContext clientContext, int methodNumber, MatterConfigurations matterConfigurations)
        {
            string matterNameValidation = MatterNameValidation(matter);
            if (!string.IsNullOrWhiteSpace(matterNameValidation))
            {
                return matterNameValidation;
            }
            if (int.Parse(ConstantStrings.ProvisionMatterCreateMatter, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.ProvisionMatterAssignContentType, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.ProvisionMatterUpdateMetadataForList, CultureInfo.InvariantCulture) == methodNumber)
            {
                if (string.IsNullOrWhiteSpace(matter.Id))
                {
                    return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputMatterIdCode, TextConstants.IncorrectInputMatterIdMessage);
                }
                else
                {
                    var matterId = Regex.Match(matter.Id, ConstantStrings.SpecialCharacterExpressionMatterId, RegexOptions.IgnoreCase);
                    if (int.Parse(ServiceConstantStrings.MatterIdLength, CultureInfo.InvariantCulture) < matter.Id.Length || !matterId.Success)
                    {
                        return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputMatterIdCode, TextConstants.IncorrectInputMatterIdMessage);
                    }
                }
            }
            if (int.Parse(ConstantStrings.ProvisionMatterCreateMatter, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.ProvisionMatterShareMatter, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.ProvisionMatterMatterLandingPage, CultureInfo.InvariantCulture) == methodNumber)
            {
                string matterDetailsValidationResponse = MatterDetailsValidation(matter, clientContext, methodNumber, matterConfigurations);
                if (!string.IsNullOrEmpty(matterDetailsValidationResponse))
                {
                    return matterDetailsValidationResponse;
                }
            }
            try
            {
                if (!(int.Parse(ConstantStrings.ProvisionMatterCheckMatterExists, CultureInfo.InvariantCulture) == methodNumber) && !(int.Parse(ConstantStrings.ProvisionMatterAssignContentType, CultureInfo.InvariantCulture) == methodNumber))
                {
                    if (0 >= matter.AssignUserNames.Count())
                    {
                        return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserNamesCode, TextConstants.IncorrectInputUserNamesMessage);
                    }
                    else
                    {
                        IList<string> userList = matter.AssignUserNames.SelectMany(x => x).Distinct().ToList();
                        SharePointHelper.ResolveUserNames(clientContext, userList).FirstOrDefault();
                    }
                }
            }
            catch (Exception)
            {
                return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserNamesCode, TextConstants.IncorrectInputUserNamesMessage);
            }

            if (int.Parse(ConstantStrings.ProvisionMatterAssignUserPermissions, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.ProvisionMatterMatterLandingPage, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.EditMatterPermission, CultureInfo.InvariantCulture) == methodNumber)
            {
                string CheckUserPermissionResponse = CheckUserPermission(matter);
                if (!string.IsNullOrEmpty(CheckUserPermissionResponse))
                {
                    return CheckUserPermissionResponse;
                }
            }
            if (int.Parse(ConstantStrings.ProvisionMatterAssignContentType, CultureInfo.InvariantCulture) == methodNumber || int.Parse(ConstantStrings.ProvisionMatterShareMatter, CultureInfo.InvariantCulture) == methodNumber)
            {
                string validateContentTypeResponse = ValidateContentType(matter);
                if (!string.IsNullOrEmpty(validateContentTypeResponse))
                {
                    return validateContentTypeResponse;
                }
            }
            return string.Empty;
        }
 public string CreateMatter(RequestObject requestObject, Client client, Matter matter, MatterConfigurations matterConfigurations, IList<string> userId, bool isErrorOccurred)
 {
     try
     {
         string result = string.Empty;
         if (null != requestObject && null != client && null != matter && (null != requestObject.RefreshToken || null != requestObject.SPAppToken || null != client.Url) && ValidationHelperFunctions.CheckRequestValidatorToken())
         {
             using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
             {
                 if (Lists.CheckPermissionOnList(ServiceUtility.GetClientContext(null, new Uri(client.Url), requestObject.RefreshToken), ServiceConstantStrings.MatterConfigurationsList, PermissionKind.EditListItems))
                 {
                     string matterURL = ConstantStrings.FALSE;
                     string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, null, int.Parse(ConstantStrings.ProvisionMatterCreateMatter, CultureInfo.InvariantCulture), matterConfigurations);
                     if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                     {
                         string matterValidation = CheckMatterExists(requestObject, client, matter, isErrorOccurred, matterConfigurations);
                         if (matterValidation.ToUpperInvariant().Contains(ConstantStrings.TRUE.ToUpperInvariant()))
                         {
                             if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                             {
                                 if (Convert.ToBoolean(matter.Conflict.Identified, CultureInfo.InvariantCulture))
                                 {
                                     matterURL = EditMatterHelperFunctions.CheckSecurityGroupInTeamMembers(clientContext, matter, userId);
                                     if (string.Equals(matterURL, ConstantStrings.FALSE, StringComparison.OrdinalIgnoreCase))
                                     {
                                         matterURL = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage);
                                     }
                                 }
                                 else
                                 {
                                     matterURL = ConstantStrings.TRUE;
                                 }
                                 if (string.Equals(matterURL, ConstantStrings.TRUE, StringComparison.OrdinalIgnoreCase))
                                 {
                                     matterURL = ProvisionHelperFunctions.CreateMatterUtility(requestObject, client, matter, clientContext, matterURL, matterConfigurations);
                                 }
                             }
                         }
                         else
                         {
                             matterURL = matterValidation;
                         }
                         result = matterURL;
                     }
                     else
                     {
                         result = ProvisionMatterValidation;
                     }
                 }
                 else
                 {
                     result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.UserNotSiteOwnerCode, ServiceConstantStrings.UserNotSiteOwnerMessage);
                 }
             }
         }
         else
         {
             result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
         }
         return result;
     }
     catch (Exception exception)
     {
         return Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
     }
 }
 public string CheckMatterExists(RequestObject requestObject, Client client, Matter matter, bool hasErrorOccurred, MatterConfigurations matterConfigurations = null)
 {
     string returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.DeleteMatterCode, ConstantStrings.TRUE);
     if (null != requestObject && null != client && null != matter && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, null, matter, null, int.Parse(ConstantStrings.ProvisionMatterCheckMatterExists, CultureInfo.InvariantCulture), null);
         if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
         {
             try
             {
                 if (!hasErrorOccurred)
                 {
                     using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                     {
                         List<string> listExists = ProvisionHelperFunctions.CheckListsExist(clientContext, matter.Name, matterConfigurations);
                         if (0 < listExists.Count)
                         {
                             string listName = !string.Equals(matter.Name, listExists[0]) ? listExists[0].Contains(ConstantStrings.Underscore) ? listExists[0].Split(ConstantStrings.Underscore[0]).Last() : ConstantStrings.Matter : ConstantStrings.Matter;
                             returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.MatterLibraryExistsCode, string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.ErrorDuplicateMatter, listName) + ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR + ConstantStrings.MatterPrerequisiteCheck.LibraryExists);
                         }
                         else
                         {
                             Uri clientUri = new Uri(client.Url);
                             string requestedUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}", clientUri.AbsolutePath, ConstantStrings.ForwardSlash, ServiceConstantStrings.MatterLandingPageRepositoryName.Replace(ConstantStrings.Space, string.Empty), ConstantStrings.ForwardSlash, matter.Name, ConstantStrings.AspxExtension);
                             if (ConstantStrings.TRUE == SearchHelperFunctions.PageExists(requestedUrl, clientContext))
                             {
                                 returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.MatterLandingExistsCode, ServiceConstantStrings.ErrorDuplicateMatterLandingPage + ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR + ConstantStrings.MatterPrerequisiteCheck.MatterLandingPageExists);  // Return when matter landing page is present
                             }
                         }
                     }
                 }
                 else
                 {
                     returnValue = ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                 }
             }
             catch (Exception exception)
             {
                 returnValue = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
             }
         }
         else
         {
             returnValue = ProvisionMatterValidation;
         }
     }
     else
     {
         returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
     }
     return returnValue;
 }
        public string AssignUserPermissions(RequestObject requestObject, Client client, Matter matter, MatterConfigurations matterConfigurations)
        {
            string returnValue = ConstantStrings.FALSE;
            if (null != requestObject && null != client && null != matter && null != client.Url && null != matterConfigurations && (null != requestObject.RefreshToken || null != requestObject.SPAppToken) && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                try
                {
                    string calendarName = string.Concat(matter.Name, ServiceConstantStrings.CalendarNameSuffix);
                    string oneNoteLibraryName = string.Concat(matter.Name, ServiceConstantStrings.OneNoteLibrarySuffix);
                    string taskLibraryName = string.Concat(matter.Name, ServiceConstantStrings.TaskNameSuffix);
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                    {

                        string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, null, int.Parse(ConstantStrings.ProvisionMatterAssignUserPermissions, CultureInfo.InvariantCulture), null);
                        if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                        {

                            if (!string.IsNullOrWhiteSpace(matter.Name))
                            {
                                //Assign permission for Matter library
                                returnValue = Convert.ToString(Lists.SetPermission(clientContext, matter.AssignUserEmails, matter.Permissions, matter.Name), CultureInfo.CurrentCulture);

                                //Assign permission for OneNote library
                                Lists.SetPermission(clientContext, matter.AssignUserEmails, matter.Permissions, oneNoteLibraryName);

                                // Assign permission to calendar list if it is selected
                                if (ServiceConstantStrings.IsCreateCalendarEnabled && matterConfigurations.IsCalendarSelected)
                                {
                                    string returnValueCalendar = Convert.ToString(Lists.SetPermission(clientContext, matter.AssignUserEmails, matter.Permissions, calendarName), CultureInfo.CurrentCulture);
                                    if (!Convert.ToBoolean(returnValueCalendar, CultureInfo.InvariantCulture))
                                    {
                                        MatterCenterException customException = new MatterCenterException(TextConstants.ErrorCodeCalendarCreation, TextConstants.ErrorMessageCalendarCreation);
                                        throw customException; // Throw will direct to current function's catch block (if present). If not present then it will direct to parent catch block. Parent will be the calling function
                                    }
                                }

                                // Assign permission to task list if it is selected
                                if (matterConfigurations.IsTaskSelected)
                                {
                                    string returnValueTask = Convert.ToString(Lists.SetPermission(clientContext, matter.AssignUserEmails, matter.Permissions, taskLibraryName), CultureInfo.CurrentCulture);
                                    if (!Convert.ToBoolean(returnValueTask, CultureInfo.InvariantCulture))
                                    {
                                        MatterCenterException customException = new MatterCenterException(TextConstants.ErrorMessageTaskCreation, TextConstants.ErrorCodeAddTaskList);
                                        throw customException; // Throw will direct to current function's catch block (if present). If not present then it will direct to parent catch block. Parent will be the calling function
                                    }
                                }
                            }
                        }
                        else
                        {
                            returnValue = ProvisionMatterValidation;
                            ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                        }
                    }
                }
                catch (Exception exception)
                {
                    ///// Web Exception
                    ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                    returnValue = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            else
            {
                returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
            }
            // To avoid the invalid symbol error while parsing the JSON, return the response in lower case
            return returnValue.ToLower(CultureInfo.CurrentUICulture);
        }
        public string UpdateMetadataForList(RequestObject requestObject, Client client, Matter matter, MatterDetails matterDetails, MatterProvisionFlags matterProvisionChecks, MatterConfigurations matterConfigurations)
        {
            string result = ConstantStrings.FALSE;
            string properties = ConstantStrings.FALSE;
            string ProvisionMatterValidation = string.Empty;
            if (null != requestObject && null != client && null != matter && null != matterDetails && (null != requestObject.RefreshToken || null != requestObject.SPAppToken) && (null != matterProvisionChecks) && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                {
                    string shareMatterFlag = string.Empty;
                    ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, matterDetails, int.Parse(ConstantStrings.ProvisionMatterUpdateMetadataForList, CultureInfo.InvariantCulture), matterConfigurations);
                    if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                    {
                        try
                        {
                            var props = clientContext.Web.Lists.GetByTitle(matter.Name).RootFolder.Properties;
                            Dictionary<string, string> propertyList = new Dictionary<string, string>();
                            propertyList = ProvisionHelperFunctions.SetStampProperty(client, matter, matterDetails);
                            clientContext.Load(props);
                            clientContext.ExecuteQuery();
                            Lists.SetPropertBagValuesForList(clientContext, props, matter.Name, propertyList);
                            if (matterProvisionChecks.SendEmailFlag)
                            {
                                shareMatterFlag = ProvisionHelperFunctions.ShareMatter(requestObject, client, matter, matterDetails, matterProvisionChecks.MatterLandingFlag, matterConfigurations);
                            }
                            else
                            {
                                shareMatterFlag = ConstantStrings.TRUE;
                            }
                            properties = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, shareMatterFlag);
                        }

                        catch (Exception exception)
                        {
                            properties = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                            ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                        }
                    }
                    else
                    {
                        ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                        properties = ProvisionMatterValidation;
                    }
                    result = properties;
                }
            }
            else
            {
                result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
            }
            return result;
        }
 /// <summary>
 /// Validates the inputs for matter provision app and returns the validation status (success/failure).
 /// </summary>
 /// <param name="requestObject">Request Object containing SharePoint App Token</param>
 /// <param name="client">Client object containing Client data</param>
 /// <param name="clientContext">Client context object for SharePoint</param>
 /// <param name="matter">Matter object containing Matter data</param>
 /// <param name="matterDetails">Matter details object which has data of properties to be stamped</param>
 /// <param name="methodNumber">Number indicating which method needs to be validated</param>
 /// <returns>A string value indicating whether validations passed or fail</returns>
 internal static string ProvisionMatterValidation(RequestObject requestObject, Client client, ClientContext clientContext, Matter matter, MatterDetails matterDetails, int methodNumber, MatterConfigurations matterConfigurations)
 {
     if (int.Parse(ConstantStrings.ProvisionMatterCreateMatter, CultureInfo.InvariantCulture) <= methodNumber && int.Parse(ConstantStrings.EditMatterPermission, CultureInfo.InvariantCulture) >= methodNumber && !Lists.CheckPermissionOnList(ServiceUtility.GetClientContext(null, new Uri(ConstantStrings.ProvisionMatterAppURL), requestObject.RefreshToken), ConstantStrings.SendMailListName, PermissionKind.EditListItems))
     {
         return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.IncorrectInputUserAccessCode, ServiceConstantStrings.IncorrectInputUserAccessMessage);
     }
     else
     {
         if (null != requestObject)
         {
             if (string.IsNullOrWhiteSpace(requestObject.RefreshToken) && string.IsNullOrWhiteSpace(requestObject.SPAppToken))
             {
                 return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputRequestObjectCode, TextConstants.IncorrectInputRequestObjectMessage);
             }
         }
         if (null != client)
         {
             string result = ValidateClientInformation(client, methodNumber);
             if (!string.IsNullOrEmpty(result))
             {
                 return result;
             }
         }
         if (null != matter)
         {
             string MatterMetadataValidationResponse = MatterMetadataValidation(matter, clientContext, methodNumber, matterConfigurations);
             if (!string.IsNullOrEmpty(MatterMetadataValidationResponse))
             {
                 return MatterMetadataValidationResponse;
             }
             if (int.Parse(ConstantStrings.EditMatterPermission, CultureInfo.InvariantCulture) == methodNumber)
             {
                 string roleCheck = ValidationHelperFunctions.RoleCheck(requestObject, matter, client);
                 if (!string.IsNullOrEmpty(roleCheck))
                 {
                     return roleCheck;
                 }
             }
             if (null != matter.Permissions)
             {
                 bool isFullControlPresent = EditMatterHelperFunctions.ValidateFullControlPermission(matter);
                 if (!isFullControlPresent)
                 {
                     return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.IncorrectInputUserAccessCode, ServiceConstantStrings.ErrorEditMatterMandatoryPermission);
                 }
             }
         }
         if (null != matterDetails && !(int.Parse(ConstantStrings.EditMatterPermission, CultureInfo.InvariantCulture) == methodNumber))
         {
             if (string.IsNullOrWhiteSpace(matterDetails.PracticeGroup))
             {
                 return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputPracticeGroupCode, TextConstants.IncorrectInputPracticeGroupMessage);
             }
             if (string.IsNullOrWhiteSpace(matterDetails.AreaOfLaw))
             {
                 return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputAreaOfLawCode, TextConstants.IncorrectInputAreaOfLawMessage);
             }
             if (string.IsNullOrWhiteSpace(matterDetails.SubareaOfLaw))
             {
                 return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputSubareaOfLawCode, TextConstants.IncorrectInputSubareaOfLawMessage);
             }
             try
             {
                 if (string.IsNullOrWhiteSpace(matterDetails.ResponsibleAttorney))
                 {
                     return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputResponsibleAttorneyCode, TextConstants.IncorrectInputResponsibleAttorneyMessage);
                 }
                 else
                 {
                     IList<string> userNames = matterDetails.ResponsibleAttorney.Split(';').ToList<string>();
                     SharePointHelper.ResolveUserNames(clientContext, userNames).FirstOrDefault();
                 }
             }
             catch (Exception)
             {
                 return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputResponsibleAttorneyCode, TextConstants.IncorrectInputResponsibleAttorneyMessage);
             }
         }
     }
     return string.Empty;
 }
        /// <summary>
        /// Validates details of a matter and returns the validation status.
        /// </summary>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="clientContext">Client context object for SharePoint</param>  
        /// <param name="methodNumber">Number indicating which method needs to be validated</param>        
        /// <returns>A string value indicating whether validations passed or fail</returns>
        internal static string MatterDetailsValidation(Matter matter, ClientContext clientContext, int methodNumber, MatterConfigurations matterConfigurations)
        {
            if (matterConfigurations.IsMatterDescriptionMandatory)
            {
                if (string.IsNullOrWhiteSpace(matter.Description))
                {
                    return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputMatterDescriptionCode, TextConstants.IncorrectInputMatterDescriptionMessage);
                }
                else
                {
                    var matterDescription = Regex.Match(matter.Description, ConstantStrings.SpecialCharacterExpressionMatterDescription, RegexOptions.IgnoreCase);
                    if (int.Parse(ServiceConstantStrings.MatterDescriptionLength, CultureInfo.InvariantCulture) < matter.Description.Length || !matterDescription.Success)
                    {
                        return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputMatterDescriptionCode, TextConstants.IncorrectInputMatterDescriptionMessage);
                    }
                }
            }
            if (matterConfigurations.IsConflictCheck)
            {
                DateTime conflictCheckedOnDate;
                bool isValidDate = DateTime.TryParse(matter.Conflict.CheckOn, out conflictCheckedOnDate);
                if (!isValidDate || 0 > DateTime.Compare(DateTime.Now, conflictCheckedOnDate))
                {
                    return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictDateCode, TextConstants.IncorrectInputConflictDateMessage);
                }
                if (string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                {
                    return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage);
                }
                else
                {
                    try
                    {
                        if (0 > string.Compare(ConstantStrings.FALSE, matter.Conflict.Identified, StringComparison.OrdinalIgnoreCase))
                        {
                            if (0 >= matter.BlockUserNames.Count())
                            {
                                return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputBlockUserNamesCode, TextConstants.IncorrectInputBlockUserNamesMessage);
                            }
                            else
                            {
                                SharePointHelper.ResolveUserNames(clientContext, matter.BlockUserNames).FirstOrDefault();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputBlockUserNamesCode, TextConstants.IncorrectInputBlockUserNamesMessage);
                    }

                }
                if (string.IsNullOrWhiteSpace(matter.Conflict.CheckBy))
                {
                    return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictCheckByCode, TextConstants.IncorrectInputConflictCheckByMessage);
                }
                else
                {
                    try
                    {
                        SharePointHelper.ResolveUserNames(clientContext, new List<string>() { matter.Conflict.CheckBy }).FirstOrDefault();
                    }
                    catch (Exception)
                    {
                        return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictCheckByCode, TextConstants.IncorrectInputConflictCheckByMessage);
                    }
                }
            }
            if (int.Parse(ConstantStrings.ProvisionMatterCreateMatter, CultureInfo.InvariantCulture) == methodNumber && 0 >= matter.Roles.Count())
            {
                return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserRolesCode, TextConstants.IncorrectInputUserRolesMessage);
            }
            return string.Empty;
        }
        /// <summary>
        /// Function to share the matter.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object</param>
        /// <param name="matterDetails">Matter object containing Matter data details</param>
        /// <param name="mailSiteURL">URL of the site</param>
        /// <param name="centralMailListURL">URL of the Send Mail list</param>
        /// <param name="matterLandingFlag">Flag to determine if Matter landing page exists</param>
        /// <param name="matterConfigurations">Object holding configuration for the matter</param>
        /// <returns>Result of operation: Matter Shared successfully or not</returns>        
        internal static string ShareMatterUtility(RequestObject requestObject, Client client, Matter matter, MatterDetails matterDetails, string mailSiteURL, string centralMailListURL, string matterLandingFlag, MatterConfigurations matterConfigurations)
        {
            string shareFlag = ConstantStrings.FALSE;
            string mailListName = centralMailListURL.Substring(centralMailListURL.LastIndexOf(ConstantStrings.ForwardSlash, StringComparison.OrdinalIgnoreCase) + 1);
            string matterLocation = string.Concat(client.Url, ConstantStrings.ForwardSlash, matter.Name);
            string ProvisionMatterValidation = string.Empty;
            if (!string.IsNullOrWhiteSpace(mailSiteURL))
            {
                using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(mailSiteURL), requestObject.RefreshToken))
                {

                    ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, null, int.Parse(ConstantStrings.ProvisionMatterShareMatter, CultureInfo.InvariantCulture), matterConfigurations);
                    if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                    {
                        // Get the current logged in User
                        clientContext.Load(clientContext.Web.CurrentUser);
                        clientContext.ExecuteQuery();
                        string matterMailBody, blockUserNames;
                        // Generate Mail Subject
                        string matterMailSubject = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailSubject, matter.Id, matter.Name, clientContext.Web.CurrentUser.Title);

                        // Logic to Create Mail body
                        // Step 1: Create Matter Information
                        // Step 2: Create Team Information
                        // Step 3: Create Access Information
                        // Step 4: Create Conflict check Information based on the conflict check flag and create mail body

                        // Step 1: Create Matter Information
                        string defaultContentType = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailDefaultContentTypeHtmlChunk, matter.DefaultContentType);
                        string matterType = string.Join(";", matter.ContentTypes.ToArray()).TrimEnd(';').Replace(matter.DefaultContentType, defaultContentType);

                        // Step 2: Create Team Information
                        string secureMatter = ConstantStrings.FALSE.ToUpperInvariant() == matter.Conflict.SecureMatter.ToUpperInvariant() ? ConstantStrings.NO : ConstantStrings.YES;
                        string mailBodyTeamInformation = string.Empty;
                        mailBodyTeamInformation = TeamMembersPermissionInformation(matterDetails, mailBodyTeamInformation);

                        // Step 3: Create Access Information
                        if (ConstantStrings.TRUE == matterLandingFlag)
                        {
                            matterLocation = string.Concat(client.Url, ConstantStrings.ForwardSlash, ServiceConstantStrings.MatterLandingPageRepositoryName.Replace(ConstantStrings.Space, string.Empty), ConstantStrings.ForwardSlash, matter.MatterGuid, ConstantStrings.AspxExtension);
                        }
                        string oneNotePath = string.Concat(client.Url, ConstantStrings.ForwardSlash, matter.MatterGuid, ServiceConstantStrings.OneNoteLibrarySuffix, ConstantStrings.ForwardSlash, matter.MatterGuid, ConstantStrings.ForwardSlash, matter.MatterGuid);

                        // Step 4: Create Conflict check Information based on the conflict check flag and create mail body
                        if (matterConfigurations.IsConflictCheck)
                        {
                            string conflictIdentified = ConstantStrings.FALSE.ToUpperInvariant() == matter.Conflict.Identified.ToUpperInvariant() ? ConstantStrings.NO : ConstantStrings.YES;
                            blockUserNames = string.Join(";", matter.BlockUserNames.ToArray()).Trim().TrimEnd(';');

                            blockUserNames = !String.IsNullOrEmpty(blockUserNames) ? string.Format(CultureInfo.InvariantCulture, "<div>{0}: {1}</div>", "Conflicted User", blockUserNames) : string.Empty;
                            matterMailBody = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyMatterInformation, client.Name, client.Id, matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyConflictCheck, ConstantStrings.YES, matter.Conflict.CheckBy, Convert.ToDateTime(matter.Conflict.CheckOn, CultureInfo.InvariantCulture).ToString(ServiceConstantStrings.MatterCenterDateFormat, CultureInfo.InvariantCulture), conflictIdentified) + string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, matterLocation, matter.Name);
                        }
                        else
                        {
                            blockUserNames = string.Empty;
                            matterMailBody = string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyMatterInformation, client.Name, client.Id, matter.Name, matter.Id, matter.Description, matterType) + string.Format(CultureInfo.InvariantCulture, TextConstants.MatterMailBodyTeamMembers, secureMatter, mailBodyTeamInformation, blockUserNames, client.Url, oneNotePath, matter.Name, matterLocation, matter.Name);
                        }

                        Web web = clientContext.Web;
                        List mailList = web.Lists.GetByTitle(mailListName);
                        List<FieldUserValue> userList = new List<FieldUserValue>();
                        List<FieldUserValue> userEmailList = ProvisionHelperFunctions.GenerateMailList(matter, clientContext, ref userList);
                        ///// Add the Matter URL in list
                        FieldUrlValue matterPath = new FieldUrlValue()
                        {
                            Url = string.Concat(client.Url.Replace(String.Concat(ConstantStrings.HTTPS, ConstantStrings.COLON, ConstantStrings.ForwardSlash, ConstantStrings.ForwardSlash), String.Concat(ConstantStrings.HTTP, ConstantStrings.COLON, ConstantStrings.ForwardSlash, ConstantStrings.ForwardSlash)), ConstantStrings.ForwardSlash, matter.Name, ConstantStrings.ForwardSlash, matter.Name),
                            Description = matter.Name
                        };
                        List<string> columnNames = new List<string>() { ServiceConstantStrings.ShareListColumnMatterPath, ServiceConstantStrings.ShareListColumnMailList, TextConstants.ShareListColumnMailBody, TextConstants.ShareListColumnMailSubject };
                        List<object> columnValues = new List<object>() { matterPath, userEmailList, matterMailBody, matterMailSubject };
                        // To avoid the invalid symbol error while parsing the JSON, return the response in lower case
                        shareFlag = Convert.ToString(Lists.AddItem(clientContext, mailList, columnNames, columnValues), CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentUICulture);
                    }
                }
            }
            return shareFlag;
        }
        /// <summary>
        /// Configures XML of web parts.
        /// </summary>
        /// <param name="requestObject">Request Object</param>
        /// <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(RequestObject requestObject, Client client, Matter matter, ClientContext clientContext, string pageName, Uri uri, Web web, MatterConfigurations matterConfigurations)
        {
            string[] result = null;
            try
            {
                List sitePageLib = web.Lists.GetByTitle(matter.Name);
                clientContext.Load(sitePageLib);
                clientContext.ExecuteQuery();

                ////Configure list View Web Part XML
                string listViewWebPart = ConfigureListViewWebPart(requestObject, sitePageLib, clientContext, pageName, client, matter, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, ConstantStrings.ForwardSlash, matter.Name, ConstantStrings.ForwardSlash, pageName));
                string[] contentEditorSectionIds = WebpartConstants.MatterLandingPageSections.Split(Convert.ToChar(ConstantStrings.Comma, CultureInfo.InvariantCulture));

                ////Configure content Editor Web Part of user information XML
                string contentEditorWebPartTasks = string.Empty;
                if (matterConfigurations.IsTaskSelected)
                {
                    contentEditorWebPartTasks = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.TaskPanel, CultureInfo.InvariantCulture)]));
                }

                string calendarWebpart = string.Empty, rssFeedWebPart = string.Empty, rssTitleWebPart = string.Empty;
                if (matterConfigurations.IsRSSSelected)
                {
                    rssFeedWebPart = string.Format(CultureInfo.InvariantCulture, WebpartConstants.RssFeedWebpart, HttpUtility.UrlEncode(matter.Name));
                    rssTitleWebPart = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.RSSTitlePanel, CultureInfo.InvariantCulture)]));
                }

                ////Configure calendar Web Part XML
                if (matterConfigurations.IsCalendarSelected)
                {
                    ////If create calendar is enabled configure calendar Web Part XML; else dont configure
                    calendarWebpart = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.CalendarPanel, CultureInfo.InvariantCulture)]));
                }

                string matterInformationSection = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.InformationPanel, CultureInfo.InvariantCulture)]));
                string cssLink = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.MatterLandingCSSFileName, ServiceConstantStrings.MatterLandingFolderName);
                string commonCssLink = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.CommonCSSFileLink, ServiceConstantStrings.CommonFolderName);
                string jsLinkMatterLandingPage = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.MatterLandingJSFileName, ServiceConstantStrings.MatterLandingFolderName);
                string jsLinkJQuery = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.JQueryFileName, ServiceConstantStrings.CommonFolderName);
                string jsLinkCommon = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.CommonJSFileLink, ServiceConstantStrings.CommonFolderName);
                string headerWebPartSection = string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.HeaderPanel, CultureInfo.InvariantCulture)]);
                string footerWebPartSection = string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.FooterPanel, CultureInfo.InvariantCulture)]);
                headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, WebpartConstants.StyleTag, cssLink), headerWebPartSection);
                headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, WebpartConstants.StyleTag, commonCssLink), headerWebPartSection);
                headerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, WebpartConstants.ScriptTagWithContents, string.Format(CultureInfo.InvariantCulture, WebpartConstants.matterLandingStampProperties, matter.Name, matter.MatterGuid)), headerWebPartSection);
                footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, WebpartConstants.ScriptTag, jsLinkMatterLandingPage), footerWebPartSection);
                footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, WebpartConstants.ScriptTag, jsLinkCommon), footerWebPartSection);
                footerWebPartSection = string.Concat(string.Format(CultureInfo.InvariantCulture, WebpartConstants.ScriptTag, jsLinkJQuery), footerWebPartSection);
                string headerWebPart = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, headerWebPartSection);
                string footerWebPart = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, footerWebPartSection);
                string oneNoteWebPart = string.Format(CultureInfo.InvariantCulture, WebpartConstants.ContentEditorWebPart, string.Format(CultureInfo.InvariantCulture, WebpartConstants.MatterLandingSectionContent, contentEditorSectionIds[Convert.ToInt32(Enumerators.MatterLandingSection.OneNotePanel, CultureInfo.InvariantCulture)]));
                string[] webParts = { headerWebPart, matterInformationSection, oneNoteWebPart, listViewWebPart, rssFeedWebPart, rssTitleWebPart, footerWebPart, calendarWebpart, contentEditorWebPartTasks };
                result = webParts;
            }
            catch (Exception exception)
            {
                //// Generic Exception
                ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                string[] arr = new string[1];
                arr[0] = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = arr;
            }
            return result;
        }
        public string CreateMatterLandingPage(RequestObject requestObject, Client client, Matter matter, MatterConfigurations matterConfigurations)
        {
            int matterLandingPageId;
            string response = string.Empty;
            string result = string.Empty;
            if (null != requestObject && null != client && null != matter && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                try
                {
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                    {
                        string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, null, int.Parse(ConstantStrings.ProvisionMatterMatterLandingPage, CultureInfo.InvariantCulture), matterConfigurations);
                        if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                        {
                            Uri uri = new Uri(client.Url);
                            Web web = clientContext.Web;

                            //// Create Matter Landing Web Part Page
                            string pageName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, ConstantStrings.AspxExtension);
                            matterLandingPageId = Page.CreateWebPartPage(clientContext, pageName, ConstantStrings.DefaultLayout, ConstantStrings.MasterPageGallery, ServiceConstantStrings.MatterLandingPageRepositoryName, matter.Name);
                            if (0 <= matterLandingPageId)
                            {
                                bool isCopyRoleAssignment = ProvisionHelperFunctions.CopyRoleAssignment(matter.Conflict.Identified, matter.Conflict.SecureMatter);
                                Lists.BreakItemPermission(clientContext, ServiceConstantStrings.MatterLandingPageRepositoryName, matterLandingPageId, isCopyRoleAssignment);
                                Lists.SetItemPermission(clientContext, matter.AssignUserEmails, ServiceConstantStrings.MatterLandingPageRepositoryName, matterLandingPageId, matter.Permissions);
                                //// Configure All Web Parts
                                string[] webParts = MatterLandingHelperFunction.ConfigureXMLCodeOfWebParts(requestObject, client, matter, clientContext, pageName, uri, web, matterConfigurations);
                                Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, ConstantStrings.ForwardSlash, ServiceConstantStrings.MatterLandingPageRepositoryName.Replace(ConstantStrings.Space, string.Empty), ConstantStrings.ForwardSlash, pageName));
                                clientContext.Load(file);
                                clientContext.ExecuteQuery();
                                LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                                WebPartDefinition webPartDefinition = null;
                                string[] zones = { ConstantStrings.HeaderZone, ConstantStrings.TopZone, ConstantStrings.RightZone, ConstantStrings.TopZone, ConstantStrings.RightZone, ConstantStrings.RightZone, ConstantStrings.FooterZone, ConstantStrings.RightZone, ConstantStrings.RightZone };
                                Page.AddWebPart(clientContext, limitedWebPartManager, webPartDefinition, webParts, zones);
                                response = ConstantStrings.TRUE;
                            }
                            else
                            {
                                MatterCenterException customException = new MatterCenterException(ServiceConstantStrings.ErrorCodeMatterLandingPageExists, ServiceConstantStrings.ErrorCodeMatterLandingPageExists);
                                throw customException; // Throw will direct to current function's catch block (if present). If not present then it will direct to parent catch block. Parent will be the calling function
                            }
                        }
                        else
                        {
                            response = ProvisionMatterValidation;
                            ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                        }
                    }

                    result = response;
                }
                catch (Exception exception)
                {
                    ////Generic Exception
                    ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                    result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            else
            {
                result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
            }
            return result;
        }