/// <summary>
        /// Acts as entry point from service to place the request to upload email/attachment. Reads the web request headers and requests applicable methods based on headers.
        /// </summary>
        /// <param name="requestObject">The request object.</param>
        /// <param name="client">The client object</param>
        /// <param name="serviceRequest">The Service request object</param>
        /// <param name="soapRequest">The SOAP request</param>
        /// <param name="attachmentOrMailID">The attachment or mail identifier.</param>
        /// <param name="isMailUpload">Mail upload check</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="folderPath">The folder path.</param>
        /// <param name="isFirstCall">Determines if it is first call or not</param>
        /// <param name="message">Reference object for the message to be returned</param>
        /// <param name="originalFileName">Original file name of the attachment</param>
        /// <returns>It returns a string object, that contains the execution status of the function.</returns>
        internal static string Upload(RequestObject requestObject, Client client, ServiceRequest serviceRequest, string soapRequest, string attachmentOrMailID, bool isMailUpload, string fileName, string folderPath, bool isFirstCall, ref string message, string originalFileName)
        {
            string result = ConstantStrings.UploadFailed;
            try
            {
                if (null != requestObject && null != client && null != serviceRequest && !string.IsNullOrWhiteSpace(soapRequest) && !string.IsNullOrWhiteSpace(attachmentOrMailID) && !string.IsNullOrWhiteSpace(fileName) && !string.IsNullOrWhiteSpace(folderPath))
                {
                    string documentLibraryName = serviceRequest.DocumentLibraryName;

                    //// Make the request to the Exchange server and get the response.
                    HttpWebResponse webResponse = UploadHelperFunctionsUtility.GetWebResponse(serviceRequest.EwsUrl, serviceRequest.AttachmentToken, soapRequest, attachmentOrMailID);

                    if (!isFirstCall)
                    {
                        XmlDocument xmlDocument = RetrieveXMLDocument(webResponse);
                        string attachmentID = string.Empty;
                        //// Check original file name is empty
                        if (!string.IsNullOrWhiteSpace(originalFileName))
                        {
                            attachmentID = UploadHelperFunctionsUtility.GetAttachmentID(xmlDocument, originalFileName);
                        }
                        else
                        {
                            attachmentID = UploadHelperFunctionsUtility.GetAttachmentID(xmlDocument, fileName);
                        }
                        if (!string.IsNullOrWhiteSpace(attachmentID))
                        {
                            attachmentOrMailID = attachmentID;
                        }

                        //// Make the request to the Exchange server and get the response.
                        webResponse = UploadHelperFunctionsUtility.GetWebResponse(serviceRequest.EwsUrl, serviceRequest.AttachmentToken, ServiceConstantStrings.AttachmentSoapRequest, attachmentOrMailID);
                    }

                    //// If the response is okay, create an XML document from the response and process the request.
                    if (webResponse.StatusCode == HttpStatusCode.OK)
                    {
                        result = UploadFilesMail(serviceRequest.Overwrite, serviceRequest.PerformContentCheck, serviceRequest.AllowContentCheck, documentLibraryName, webResponse, isMailUpload, requestObject, client, fileName, folderPath, ref message);
                    }
                    if (string.IsNullOrWhiteSpace(message) && result.Equals(ConstantStrings.UploadFailed) && isFirstCall)
                    {
                        result = Upload(requestObject, client, serviceRequest, ServiceConstantStrings.MailSoapRequest, serviceRequest.MailId, isMailUpload, fileName, folderPath, false, ref message, originalFileName);
                    }
                }
                else
                {
                    result = ConstantStrings.UploadFailed;
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = ConstantStrings.UploadFailed;
            }
            return result;
        }
 public string GetTaxonomyData(RequestObject requestObject, Client client, TermStoreDetails details)
 {
     string returnValue = ConstantStrings.FALSE;
     try
     {
         if (null != requestObject && null != client & null != details && ValidationHelperFunctions.CheckRequestValidatorToken())
         {
             string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, null, null, null, int.Parse(ConstantStrings.ProvisionMatterCommonValidation, CultureInfo.InvariantCulture), null);
             if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
             {
                 using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                 {
                     string cacheValue = string.Empty, key = string.Empty;
                     if (details.TermSetName == ServiceConstantStrings.PracticeGroupTermSetName)
                     {
                         key = ServiceConstantStrings.CACHE_MATTER_TYPE;
                     }
                     else if (details.TermSetName == ServiceConstantStrings.ClientTermSetName)
                     {
                         key = ServiceConstantStrings.CACHE_CLIENTS;
                     }
                     cacheValue = ServiceUtility.GetOrSetCachedValue(key);
                     if (cacheValue.Equals(ConstantStrings.FALSE))
                     {
                         returnValue = TermStoreHelperFunctions.GetTaxonomyHierarchy(clientContext, details);
                         //// Check if error has returned while processing data                                
                         if (!ServiceUtility.CheckValueHasErrors(returnValue))
                         {
                             ServiceUtility.GetOrSetCachedValue(key, returnValue);
                         }
                     }
                     else
                     {
                         returnValue = cacheValue;
                     }
                 }
             }
             else
             {
                 returnValue = ProvisionMatterValidation;
             }
         }
         else
         {
             returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
         }
     }
     catch (Exception exception)
     {
         returnValue = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
     }
     return returnValue;
 }
 /// <summary>
 /// Assigns field values for specified content types to the specified matter (document library).
 /// </summary>
 /// <param name="requestObject">Request Object containing SharePoint App Token</param>
 /// <param name="matterMetadata">Object containing metadata for Matter</param>
 /// <param name="clientContext">SP client context</param>
 /// <param name="contentTypeCollection">Collection of content types</param>
 /// <param name="client">Client Object</param>
 /// <param name="matter">Matter Object</param>
 /// <returns>true if success else false</returns>
 internal static string AssignContentTypeHelper(RequestObject requestObject, MatterMetadata matterMetadata, ClientContext clientContext, IList<ContentType> contentTypeCollection, Client client, Matter matter)
 {
     Web web = clientContext.Web;
     List matterList = web.Lists.GetByTitle(matter.Name);
     SetFieldValues(clientContext, contentTypeCollection, matterList, matterMetadata);
     clientContext.ExecuteQuery();
     SetDefaultContentType(clientContext, matterList, requestObject, client, matter);
     string[] viewColumnList = ServiceConstantStrings.ViewColumnList.Split(new string[] { ConstantStrings.Semicolon }, StringSplitOptions.RemoveEmptyEntries).Select(listEntry => listEntry.Trim()).ToArray();
     string strQuery = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.ViewOrderByQuery, ServiceConstantStrings.ViewOrderByColumn);
     bool isViewCreated = Lists.AddView(clientContext, matterList, viewColumnList, ServiceConstantStrings.ViewName, strQuery);
     return (string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, Convert.ToString(isViewCreated, CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentCulture)));
 }
        public string AssignContentType(RequestObject requestObject, MatterMetadata matterMetadata)
        {
            string returnValue = ConstantStrings.FALSE;
            if (null != requestObject && null != matterMetadata && null != matterMetadata.Client && null != matterMetadata.Matter && (null != requestObject.RefreshToken || null != requestObject.SPAppToken) && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                // For each value in the list of Content Type Names
                // Add that content Type to the Library
                Matter matter = matterMetadata.Matter;
                Client client = matterMetadata.Client;
                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.ProvisionMatterAssignContentType, CultureInfo.InvariantCulture), null);
                        if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
                        {
                            // Returns the selected Content types from the Site Content Types
                            IList<ContentType> contentTypeCollection = SharePointHelper.GetContentTypeData(clientContext, matter.ContentTypes, requestObject, client, matter);

                            if (null != contentTypeCollection && matter.ContentTypes.Count == contentTypeCollection.Count && !string.IsNullOrWhiteSpace(matter.Name))
                            {
                                returnValue = ProvisionHelperFunctions.AssignContentTypeHelper(requestObject, matterMetadata, clientContext, contentTypeCollection, client, matter);
                            }
                            else
                            {
                                MatterCenterException customException = new MatterCenterException(TextConstants.ErrorCodeContentTypes, TextConstants.ErrorMessageContentTypes);
                                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)
                {
                    ///// SharePoint Specific 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);
            }
            return returnValue;
        }
 /// <summary>
 /// Updates the content type of the list item and returns the updated content type based on briefcase operation. 
 /// </summary>
 /// <param name="requestObject">Request object</param>
 /// <param name="clientContext">ClientContext object</param>
 /// <param name="documentName">Document Name</param>
 /// <param name="url">URL parameter</param>
 /// <param name="operationType">Specifies the type of operation</param>
 /// <param name="contentTypeId">String form of Content type ID</param>
 /// <param name="documentLibraryName">Name of the document library</param>
 /// <returns>List item Content Type Id</returns>
 internal static string ContentTypeByName(RequestObject requestObject, ClientContext clientContext, string documentName, string url, int operationType, string contentTypeId, string documentLibraryName)
 {
     string response = string.Empty;
     try
     {
         using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(url.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken))
         {
             string itemQuery = string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.GetItemByNameQuery, documentName);
             ListItemCollection listItems = Lists.GetData(clientContext, documentLibraryName, itemQuery);
             ServiceConstantStrings.OperationTypes type = (ServiceConstantStrings.OperationTypes)operationType;
             switch (type)
             {
                 case ServiceConstantStrings.OperationTypes.Update:
                     foreach (var listitem in listItems)
                     {
                         response = Convert.ToString(listitem[ConstantStrings.OneDriveContentTypeProperty], CultureInfo.InvariantCulture);
                     }
                     break;
                 case ServiceConstantStrings.OperationTypes.Checkout:
                     foreach (var listitem in listItems)
                     {
                         listitem[ConstantStrings.OneDriveContentTypeProperty] = contentTypeId;
                         listitem.Update();
                         clientContext.ExecuteQuery();
                         response = ConstantStrings.TRUE;
                     }
                     break;
                 default:
                     response = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, TextConstants.InvalidParametersMessage);
                     break;
             }
         }
     }
     catch (Exception exception)
     {
         Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
         response = string.Concat(CultureInfo.InvariantCulture, ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message));
     }
     return response;
 }
        /// <summary>
        /// Gets the list of content types along with their properties.
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="contentTypesNames">List of Content Type Names associated with matter</param>
        /// <param name="requestObject">Request Object</param>
        /// <param name="client">Client Object</param>
        /// <param name="matter">Matter Object</param>
        /// <returns>List of content types</returns>
        internal static IList<ContentType> GetContentTypeData(ClientContext clientContext, IList<string> contentTypesNames, RequestObject requestObject = null, Client client = null, Matter matter = null)
        {
            ContentTypeCollection contentTypeCollection = null;
            IList<ContentType> selectedContentTypeCollection = new List<ContentType>();
            try
            {
                if (null != clientContext && null != contentTypesNames)
                {
                    Web web = clientContext.Web;
                    contentTypeCollection = web.ContentTypes;
                    clientContext.Load(contentTypeCollection, contentType => contentType.Include(thisContentType => thisContentType.Name).Where(currContentType => currContentType.Group == ServiceConstantStrings.OneDriveContentTypeGroup));
                    clientContext.ExecuteQuery();
                    selectedContentTypeCollection = GetContentTypeList(contentTypesNames, contentTypeCollection.ToList());
                }
            }
            catch (Exception exception)
            {
                ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }

            return selectedContentTypeCollection;
        }
        /// <summary>
        /// Populate meta-data and perform pin operation for matter or document based upon the passed object.
        /// </summary>
        /// <param name="requestObject">Request object containing SharePoint App Token</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matterData">Matter object containing Matter data</param>
        /// <param name="documentData">Document object containing Document data</param>
        /// <returns>Status of update</returns>
        internal static string PopulateMetadeta(RequestObject requestObject, Client client, MatterData matterData, DocumentData documentData)
        {
            string status = string.Empty;
            bool isMatterCall = null != matterData ? true : false;

            try
            {
                using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                {
                    status = isMatterCall ? SearchHelperFunctions.PinThisRecord(clientContext, matterData, true) : SearchHelperFunctions.PinThisRecord(clientContext, documentData, false);
                }
            }
            catch (Exception exception)
            {
                status = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return status;
        }
        /// <summary>
        /// Gets pinned matters/documents specific to user.
        /// </summary>
        /// <param name="requestObject">Request object containing SharePoint App Token</param>
        /// <param name="client">Client object containing client URL</param>
        /// <param name="listName">Name of the list</param>
        /// <param name="listColumnName">Name of the list column</param>
        /// <param name="isShowDocument">Process Document (true) or Matter (false)</param>
        /// <returns>JSON structure with the meta-data of pinned Matter/Document for requested user</returns>
        internal static string ShowPinData(RequestObject requestObject, Client client, string listName, string listColumnName, bool isShowDocument)
        {
            string result = string.Empty;
            if (null != requestObject && null != client && !string.IsNullOrWhiteSpace(listName) && !string.IsNullOrWhiteSpace(listColumnName))
            {
                ////Holds logged-in user alias
                string userAlias = string.Empty;

                ////Object to store all the list items retrieved from SharePoint list
                ListItemCollection listItems;

                ////Stores the JSON structure with the meta-data of pinned matter/document
                string userPinnedDetails = string.Empty;

                ////Stores the count of pinned matters/documents for the requested user
                int userPinnedDetailCount = 0;

                try
                {
                    ////Object to store list item details as per pinned matter/document
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                    {
                        ////Get logged in user alias
                        Users currentUserDetail = UIUtility.GetLoggedInUserDetails(clientContext);
                        userAlias = currentUserDetail.LogOnName;
                        listItems = Lists.GetData(clientContext, listName, string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.UserPinnedDetailsQuery, ServiceConstantStrings.PinnedListColumnUserAlias, userAlias, listColumnName));
                        clientContext.Load(listItems);
                        clientContext.ExecuteQuery();

                        ////ListItems are present in the list
                        if (null != listItems && listItems.Count > 0)
                        {
                            ////Since we are maintaining only single list item per user, listItems collection will have only one object; hence accessing first object
                            ////Check if column holds null or empty string. If non empty, pinned matter/document exists
                            if (!string.IsNullOrEmpty(Convert.ToString(listItems[0][listColumnName], CultureInfo.InvariantCulture)))
                            {
                                string userPinnedMatter = Convert.ToString(listItems[0][listColumnName], CultureInfo.InvariantCulture);
                                if (isShowDocument)
                                {
                                    Dictionary<string, DocumentData> userpinnedMatterCollection = JsonConvert.DeserializeObject<Dictionary<string, DocumentData>>(userPinnedMatter);
                                    userPinnedDetailCount = userpinnedMatterCollection.Count;
                                    userPinnedDetails = JsonConvert.SerializeObject(userpinnedMatterCollection.Values.Reverse(), Newtonsoft.Json.Formatting.Indented);
                                    userPinnedDetails = string.Concat(userPinnedDetails, ConstantStrings.DOLLAR, ConstantStrings.Pipe, ConstantStrings.DOLLAR, userPinnedDetailCount);
                                }
                                else
                                {
                                    Dictionary<string, MatterData> userpinnedMatterCollection = JsonConvert.DeserializeObject<Dictionary<string, MatterData>>(userPinnedMatter);
                                    userPinnedDetailCount = userpinnedMatterCollection.Count;
                                    userPinnedDetails = JsonConvert.SerializeObject(userpinnedMatterCollection.Values.Reverse(), Newtonsoft.Json.Formatting.Indented);
                                    userPinnedDetails = string.Concat(userPinnedDetails, ConstantStrings.DOLLAR, ConstantStrings.Pipe, ConstantStrings.DOLLAR, userPinnedDetailCount);
                                }
                                result = userPinnedDetails;
                            }
                            else
                            {
                                result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, ConstantStrings.NoPinnedMessage);
                            }
                        }
                        else
                        {
                            result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, ConstantStrings.NoPinnedMessage);
                        }
                    }
                }
                catch (Exception exception)
                {
                    result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            else
            {
                result = TextConstants.MessageNoInputs;
            }
            return result;
        }
 public string UpdateMatterDetails(RequestObject requestObject, Client client, Matter matter, MatterDetails matterDetails, string editMode, IList<string> userId)
 {
     string result = ConstantStrings.TRUE;
     if (null != requestObject && null != client && null != matter && null != matterDetails && (null != requestObject.RefreshToken || null != requestObject.SPAppToken) && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         IEnumerable<RoleAssignment> userPermissionOnLibrary = null;
         PropertyValues matterStampedProperties = null;
         int listItemId = -1;
         bool isEditMode = false;
         string editMatterValidation = string.Empty;
         string loggedInUserName = string.Empty;
         try
         {
             isEditMode = Convert.ToBoolean(editMode, CultureInfo.InvariantCulture);
             using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
             {
                 List<string> listExists = ProvisionHelperFunctions.CheckListsExist(clientContext, matter.Name);
                 bool hasFullPermission = false;
                 try
                 {
                     editMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, clientContext, matter, matterDetails, int.Parse(ConstantStrings.EditMatterPermission, CultureInfo.InvariantCulture), null);
                     if (string.IsNullOrWhiteSpace(editMatterValidation))
                     {
                         if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                         {
                             if (0 == matter.AssignUserEmails.Count())
                             {
                                 result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserNamesCode, TextConstants.IncorrectInputUserNamesMessage);
                             }
                             else
                             {
                                 result = EditMatterHelperFunctions.ValidateTeamMembers(clientContext, matter, userId);
                                 if (string.IsNullOrEmpty(result))
                                 {
                                     result = ConstantStrings.TRUE;
                                     if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                                     {
                                         if (Convert.ToBoolean(matter.Conflict.Identified, CultureInfo.InvariantCulture))
                                         {
                                             result = EditMatterHelperFunctions.CheckSecurityGroupInTeamMembers(clientContext, matter, userId);
                                         }
                                     }
                                     else
                                     {
                                         result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage);
                                     }
                                 }
                             }
                         }
                         else
                         {
                             result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage);
                         }
                         if (string.Equals(result, ConstantStrings.TRUE, StringComparison.OrdinalIgnoreCase))
                         {
                             // Get matter stamped properties
                             matterStampedProperties = EditMatterHelperFunctions.FetchMatterStampedProperties(clientContext, matter.Name);
                             loggedInUserName = EditMatterHelperFunctions.GetUserUpdatingMatter(clientContext);
                             bool isFullControlPresent = EditMatterHelperFunctions.ValidateFullControlPermission(matter);
                             if (isFullControlPresent)
                             {
                                 // Get matter library current permissions
                                 userPermissionOnLibrary = EditMatterHelperFunctions.FetchUserPermission(clientContext, matter.Name);
                                 // Check if OneNote library, calendar, and matter landing page exists as separate objects
                                 string originalMatterName = EditMatterHelperFunctions.GetMatterName(clientContext, matter.Name);
                                 listItemId = Lists.RetrieveItemId(clientContext, ServiceConstantStrings.MatterLandingPageRepositoryName, originalMatterName);
                                 List<string> usersToRemove = EditMatterHelperFunctions.RetrieveMatterUsers(userPermissionOnLibrary);
                                 // Provide logged in user as full control on matter
                                 // 	Check whether logged in user has full permission on new permission changes
                                 hasFullPermission = EditMatterHelperFunctions.CheckFullPermissionInAssignList(matter.AssignUserEmails, matter.Permissions, loggedInUserName);
                                 EditMatterHelperFunctions.AssignRemoveFullControl(clientContext, matter, loggedInUserName, listItemId, listExists, true, hasFullPermission);
                                 if (listExists.Contains(matter.Name))
                                 {
                                     result = EditMatterHelperFunctions.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name, -1, isEditMode);
                                 }
                                 if (listExists.Contains(matter.Name + ServiceConstantStrings.OneNoteLibrarySuffix))
                                 {
                                     result = EditMatterHelperFunctions.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + ServiceConstantStrings.OneNoteLibrarySuffix, -1, isEditMode);
                                 }
                                 if (listExists.Contains(matter.Name + ServiceConstantStrings.CalendarNameSuffix))
                                 {
                                     result = EditMatterHelperFunctions.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + ServiceConstantStrings.CalendarNameSuffix, -1, isEditMode);
                                 }
                                 if (listExists.Contains(matter.Name + ServiceConstantStrings.TaskNameSuffix))
                                 {
                                     result = EditMatterHelperFunctions.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, false, matter.Name + ServiceConstantStrings.TaskNameSuffix, -1, isEditMode);
                                 }
                                 result = EditMatterHelperFunctions.UpdatePermission(clientContext, matter, usersToRemove, loggedInUserName, true, ServiceConstantStrings.MatterLandingPageRepositoryName, listItemId, isEditMode);
                                 // Update matter metadata
                                 result = EditMatterHelperFunctions.UpdateMatterStampedProperties(clientContext, matterDetails, matter, matterStampedProperties, isEditMode);
                             }
                             else
                             {
                                 result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.IncorrectInputSelfPermissionRemoval, ServiceConstantStrings.ErrorEditMatterMandatoryPermission);
                             }
                         }
                     }
                     else
                     {
                         result = editMatterValidation;
                     }
                 }
                 catch (Exception exception)
                 {
                     MatterRevertList matterRevertListObject = new MatterRevertList()
                     {
                         MatterLibrary = matter.Name,
                         MatterOneNoteLibrary = matter.Name + ServiceConstantStrings.OneNoteLibrarySuffix,
                         MatterCalendar = matter.Name + ServiceConstantStrings.CalendarNameSuffix,
                         MatterTask = matter.Name + ServiceConstantStrings.TaskNameSuffix,
                         MatterSitePages = ServiceConstantStrings.MatterLandingPageRepositoryName
                     };
                     EditMatterHelperFunctions.RevertMatterUpdates(requestObject, client, matter, clientContext, matterRevertListObject, loggedInUserName, userPermissionOnLibrary, listItemId, isEditMode);
                     result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                 }
                 finally
                 {
                     // Remove full control for logged in users
                     EditMatterHelperFunctions.AssignRemoveFullControl(clientContext, matter, loggedInUserName, listItemId, listExists, false, hasFullPermission);
                 }
             }
         }
         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 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;
        }
 /// <summary>
 /// Configures XML code of List View web part.
 /// </summary>
 /// <param name="requestObject">Request Object</param>
 /// <param name="sitePageLib">SharePoint List of matter library</param>
 /// <param name="clientContext">SharePoint Client Context</param>
 /// <param name="objFileInfo">Object of FileCreationInformation</param>
 /// <param name="client">Client object containing Client data</param>
 /// <param name="matter">Matter object containing Matter data</param>
 /// <param name="titleUrl">Segment of URL</param>
 /// <returns>Configured ListView Web Part</returns>
 internal static string ConfigureListViewWebPart(RequestObject requestObject, List sitePageLib, ClientContext clientContext, string pageName, Client client, Matter matter, string titleUrl)
 {
     string viewName = string.Empty;
     string result = string.Empty;
     try
     {
         Uri uri = new Uri(client.Url);
         ViewCollection viewColl = sitePageLib.Views;
         clientContext.Load(
             viewColl,
             views => views.Include(
                 view => view.Title,
                 view => view.Id));
         clientContext.ExecuteQuery();
         foreach (View view in viewColl)
         {
             viewName = Convert.ToString(view.Id, CultureInfo.InvariantCulture);
             break;
         }
         viewName = string.Concat(ConstantStrings.OpeningCurlyBrace, viewName, ConstantStrings.ClosingCurlyBrace);
         string listViewWebPart = WebpartConstants.ListviewWebpart;
         listViewWebPart = string.Format(CultureInfo.InvariantCulture, listViewWebPart,
             Convert.ToString(sitePageLib.Id, CultureInfo.InvariantCulture), titleUrl,
             string.Concat(ConstantStrings.OpeningCurlyBrace, Convert.ToString(sitePageLib.Id, CultureInfo.InvariantCulture),
             ConstantStrings.ClosingCurlyBrace), viewName, string.Concat(uri.AbsolutePath, ConstantStrings.ForwardSlash,
             matter.Name, ConstantStrings.ForwardSlash, pageName));
         result = listViewWebPart;
     }
     catch (Exception exception)
     {
         ////Generic Exception
         ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
         result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
     }
     return result;
 }
        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);
        }
 /// <summary>
 /// Provides the permission levels present in the site.
 /// </summary>
 /// <param name="requestObject">object of type RequestObject</param>
 /// <param name="client">object of client</param>
 /// <param name="returnValue">value to be returned</param>
 /// <returns>permission levels</returns>
 internal static string GetPermissionLevelUtility(RequestObject requestObject, Client client, string returnValue)
 {
     try
     {
         using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
         {
             List<Role> roles = new List<Role>();
             Web web = clientContext.Web;
             clientContext.Load(web.RoleDefinitions, roledefinitions => roledefinitions.Include(thisRole => thisRole.Name, thisRole => thisRole.Id));
             clientContext.ExecuteQuery();
             roles = ProvisionHelperFunctions.GetAllowedUserPermissions(roles, web);
             returnValue = JsonConvert.SerializeObject(roles);
         }
     }
     catch (Exception exception)
     {
         ///// SharePoint Specific Exception
         returnValue = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
     }
     return returnValue;
 }
        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;
        }
        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;
        }
 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 CheckSecurityGroupExists(RequestObject requestObject, Client client, Matter matter, IList<string> userId)
 {
     string result = ConstantStrings.TRUE;
     if (null != requestObject && null != client && null != matter && (null != requestObject.RefreshToken || null != requestObject.SPAppToken || null != client.Url) && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         try
         {
             using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
             {
                 if (0 == matter.AssignUserEmails.Count())
                 {
                     result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserNamesCode, TextConstants.IncorrectInputUserNamesMessage);
                 }
                 else
                 {
                     result = EditMatterHelperFunctions.ValidateTeamMembers(clientContext, matter, userId);
                 }
                 if (string.IsNullOrEmpty(result))
                 {
                     result = ConstantStrings.TRUE;
                     if (null != matter.Conflict && !string.IsNullOrWhiteSpace(matter.Conflict.Identified))
                     {
                         if (0 == matter.AssignUserEmails.Count())
                         {
                             result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserNamesCode, TextConstants.IncorrectInputUserNamesMessage);
                         }
                         else
                         {
                             if (Convert.ToBoolean(matter.Conflict.Identified, CultureInfo.InvariantCulture))
                             {
                                 result = EditMatterHelperFunctions.CheckSecurityGroupInTeamMembers(clientContext, matter, userId);
                             }
                         }
                     }
                     else
                     {
                         result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputConflictIdentifiedCode, TextConstants.IncorrectInputConflictIdentifiedMessage);
                     }
                 }
                 else
                 {
                     return result;
                 }
             }
         }
         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 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;
 }
        /// <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;
        }
        /// <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>
        /// Function to delete the matter in case of failure.
        /// </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>
        /// <returns>Result of operation: Matter Deleted or not</returns>
        internal static string DeleteMatter(RequestObject requestObject, Client client, Matter matter)
        {
            string result = ConstantStrings.FALSE;

            if (null != requestObject && null != client && null != matter)
            {
                try
                {
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                    {
                        if (null != clientContext && !string.IsNullOrWhiteSpace(matter.Name))
                        {
                            string stampResult = Lists.GetPropertyValueForList(clientContext, matter.Name, ServiceConstantStrings.StampedPropertySuccess);
                            if (0 != string.Compare(stampResult, ConstantStrings.TRUE, StringComparison.OrdinalIgnoreCase))
                            {
                                IList<string> lists = new List<string>();
                                lists.Add(matter.Name);
                                lists.Add(string.Concat(matter.Name, ServiceConstantStrings.CalendarNameSuffix));
                                lists.Add(string.Concat(matter.Name, ServiceConstantStrings.OneNoteLibrarySuffix));
                                lists.Add(string.Concat(matter.Name, ServiceConstantStrings.TaskNameSuffix));
                                bool bListDeleted = Lists.Delete(clientContext, lists);
                                if (bListDeleted)
                                {
                                    result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.DeleteMatterCode, TextConstants.MatterDeletedSuccessfully);
                                }
                                else
                                {
                                    result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.DeleteMatterCode, ServiceConstantStrings.MatterNotPresent);
                                }
                                Uri clientUri = new Uri(client.Url);
                                string matterLandingPageUrl = string.Concat(clientUri.AbsolutePath, ConstantStrings.ForwardSlash, ServiceConstantStrings.MatterLandingPageRepositoryName.Replace(ConstantStrings.Space, string.Empty), ConstantStrings.ForwardSlash, matter.MatterGuid, ConstantStrings.AspxExtension);
                                Page.Delete(clientContext, matterLandingPageUrl);
                            }
                            else
                            {
                                result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, ServiceConstantStrings.MatterLibraryExistsCode, string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.ErrorDuplicateMatter, ConstantStrings.Matter) + ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR + ConstantStrings.MatterPrerequisiteCheck.LibraryExists);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            return result;
        }
        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>
        /// 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;
        }
 public string GetPermissionLevels(RequestObject requestObject, Client client)
 {
     string returnValue = ConstantStrings.FALSE;
     if (null != requestObject && null != client && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, null, null, null, int.Parse(ConstantStrings.ProvisionMatterCommonValidation, CultureInfo.InvariantCulture), null);
         if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
         {
             returnValue = ProvisionHelperFunctions.GetPermissionLevelUtility(requestObject, client, returnValue);
         }
         else
         {
             returnValue = ProvisionMatterValidation;
         }
     }
     else
     {
         return string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, string.Empty, TextConstants.MessageNoInputs);
     }
     return returnValue;
 }
        /// <summary>
        /// Sets the default content type based on user selection.
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="list">Name of the list</param>
        /// <param name="requestObject">Request Object</param>
        /// <param name="client">Client Object</param>
        /// <param name="matter">Matter Object</param>
        internal static void SetDefaultContentType(ClientContext clientContext, List list, RequestObject requestObject, Client client, Matter matter)
        {
            int contentCount = 0, contentSwap = 0;
            try
            {
                ContentTypeCollection currentContentTypeOrder = list.ContentTypes;
                clientContext.Load(currentContentTypeOrder);
                clientContext.ExecuteQuery();
                IList<ContentTypeId> updatedContentTypeOrder = new List<ContentTypeId>();
                foreach (ContentType contentType in currentContentTypeOrder)
                {
                    if (0 == string.Compare(contentType.Name, matter.DefaultContentType, StringComparison.OrdinalIgnoreCase))
                    {
                        contentSwap = contentCount;
                    }

                    if (0 != string.Compare(contentType.Name, ServiceConstantStrings.HiddenContentType, StringComparison.OrdinalIgnoreCase))
                    {
                        updatedContentTypeOrder.Add(contentType.Id);
                        contentCount++;
                    }
                }
                if (updatedContentTypeOrder.Count > contentSwap)
                {
                    ContentTypeId documentContentType = updatedContentTypeOrder[0];
                    updatedContentTypeOrder[0] = updatedContentTypeOrder[contentSwap];
                    updatedContentTypeOrder.RemoveAt(contentSwap);
                    updatedContentTypeOrder.Add(documentContentType);
                }
                list.RootFolder.UniqueContentTypeOrder = updatedContentTypeOrder;
                list.RootFolder.Update();
                list.Update();
                clientContext.ExecuteQuery();
            }
            catch (Exception exception)
            {
                ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
        }
 public string GetRoleData(RequestObject requestObject, Client client)
 {
     string returnValue = ConstantStrings.FALSE;
     if (null != requestObject && null != client && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, null, null, null, int.Parse(ConstantStrings.ProvisionMatterCommonValidation, CultureInfo.InvariantCulture), null);
         if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
         {
             try
             {
                 // SharePoint Helper Method to retrieve list items
                 using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                 {
                     returnValue = ServiceUtility.GetOrSetCachedValue(ServiceConstantStrings.CACHE_ROLES);
                     if (returnValue.Equals(ConstantStrings.FALSE))
                     {
                         IList<Role> roles = new List<Role>();
                         ListItemCollection collListItem = Lists.GetData(clientContext, ServiceConstantStrings.DMSRoleListName, ServiceConstantStrings.DMSRoleQuery);
                         ///// Check if NULL and greater than 0
                         roles = ProvisionHelperFunctions.GetRoleDataUtility(roles, collListItem);
                         returnValue = JsonConvert.SerializeObject(roles);
                         //// Check if return value has errors
                         if (!ServiceUtility.CheckValueHasErrors(returnValue))
                         {
                             //// Cache the value if there is no error in return value
                             ServiceUtility.GetOrSetCachedValue(ServiceConstantStrings.CACHE_ROLES, returnValue);
                         }
                     }
                 }
             }
             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;
 }
        /// <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;
        }
 public string GetUsers(RequestObject requestObject, Client client, SearchObject searchObject)
 {
     string returnValue = ConstantStrings.FALSE;
     if (null != requestObject && null != client && null != searchObject && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         string ProvisionMatterValidation = ValidationHelperFunctions.ProvisionMatterValidation(requestObject, client, null, null, null, int.Parse(ConstantStrings.ProvisionMatterCommonValidation, CultureInfo.InvariantCulture), null);
         if (string.IsNullOrWhiteSpace(ProvisionMatterValidation))
         {
             try
             {
                 searchObject.SearchTerm = (!string.IsNullOrWhiteSpace(searchObject.SearchTerm)) ? searchObject.SearchTerm : string.Empty;
                 using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                 {
                     IList<PeoplePickerUser> foundUsers = SharePointHelper.SearchUsers(clientContext, searchObject.SearchTerm);
                     IList<Users> users = new List<Users>();
                     if (null != foundUsers && 0 != foundUsers.Count)
                     {
                         users = ProvisionHelperFunctions.FilterUsers(users, foundUsers);
                     }
                     else
                     {
                         Users noResult = new Users()
                         {
                             Name = TextConstants.PeoplePickerNoResults,
                             LogOnName = string.Empty,
                             Email = string.Empty,
                             EntityType = string.Empty,
                             ProviderName = string.Empty,
                             EntityData = new EntityData()
                             {
                                 Department = string.Empty,
                                 Email = string.Empty,
                                 Title = string.Empty
                             }
                         };
                         users.Add(noResult);
                     }
                     returnValue = JsonConvert.SerializeObject(users);
                 }
             }
             catch (Exception exception)
             {
                 ///// SharePoint Specific 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;
 }
        /// <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 RetrieveMatterStampedProperties(RequestObject requestObject, Client client, Matter matter)
        {
            string result = string.Empty;
            if (null != requestObject && null != client && null != matter && !string.IsNullOrWhiteSpace(matter.Name) && (null != requestObject.RefreshToken || null != requestObject.SPAppToken) && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                PropertyValues matterStampedProperties = null;
                try
                {
                    using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                    {
                        // Get all the stamped properties from matter library
                        matterStampedProperties = EditMatterHelperFunctions.FetchMatterStampedProperties(clientContext, matter.Name);

                        Dictionary<string, object> stampedPropertyValues = matterStampedProperties.FieldValues;
                        if (0 < stampedPropertyValues.Count)
                        {
                            string matterCenterUsers = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterCenterUsers);
                            string matterCenterUserEmails = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterCenterUserEmails);
                            List<List<string>> matterCenterUserCollection = new List<List<string>>();
                            List<List<string>> matterCenterUserEmailsCollection = new List<List<string>>();
                            if (!string.IsNullOrWhiteSpace(matterCenterUsers))
                            {
                                matterCenterUserCollection = EditMatterHelperFunctions.GetMatterAssignedUsers(matterCenterUsers);
                            }
                            if (!string.IsNullOrWhiteSpace(matterCenterUserEmails))
                            {
                                matterCenterUserEmailsCollection = EditMatterHelperFunctions.GetMatterAssignedUsers(matterCenterUserEmails);
                            }
                            MatterStampedDetails matterStampedDetails = new MatterStampedDetails()
                            {
                                IsNewMatter = stampedPropertyValues.ContainsKey(ServiceConstantStrings.StampedPropertyIsConflictIdentified) ? ConstantStrings.TRUE : ConstantStrings.FALSE,
                                MatterObject = new Matter()
                                {
                                    Id = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterID),
                                    Name = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterName),
                                    Description = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterDescription),
                                    DefaultContentType = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyDefaultContentType),
                                    DocumentTemplateCount = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyDocumentTemplateCount).Split(new string[] { ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR }, StringSplitOptions.RemoveEmptyEntries).ToList(),
                                    Roles = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterCenterRoles).Split(new string[] { ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR }, StringSplitOptions.RemoveEmptyEntries).ToList(),
                                    Permissions = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyMatterCenterPermissions).Split(new string[] { ConstantStrings.DOLLAR + ConstantStrings.Pipe + ConstantStrings.DOLLAR }, StringSplitOptions.RemoveEmptyEntries).ToList(),
                                    BlockUserNames = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyBlockedUsers).Split(new string[] { ConstantStrings.Semicolon }, StringSplitOptions.RemoveEmptyEntries).ToList(),
                                    AssignUserNames = matterCenterUserCollection.ToList<IList<string>>(),
                                    AssignUserEmails = matterCenterUserEmailsCollection.ToList<IList<string>>(),
                                    Conflict = new Conflict()
                                    {
                                        CheckBy = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyConflictCheckBy),
                                        CheckOn = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyConflictCheckDate),
                                        Identified = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyIsConflictIdentified),
                                        SecureMatter = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertySecureMatter),
                                    }
                                },
                                MatterDetailsObject = EditMatterHelperFunctions.ExtractMatterDetails(stampedPropertyValues),
                                ClientObject = new Client()
                                {
                                    Id = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyClientID),
                                    Name = EditMatterHelperFunctions.GetStampPropertyValue(stampedPropertyValues, ServiceConstantStrings.StampedPropertyClientName),
                                }
                            };
                            result = JsonConvert.SerializeObject(matterStampedDetails);
                        }
                    }
                }
                catch (Exception exception)
                {
                    result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                }
            }
            return result;
        }