/// <summary>
 /// Discard individual document from Matter Center
 /// </summary>
 /// <param name="requestObject">Request object</param>
 /// <param name="mailAttachmentDetails">Attachment object</param>
 /// <returns>Status of discarding individual document</returns>
 internal static string DiscardCheckout(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails)
 {
     string result = ConstantStrings.FALSE;
     ClientContext clientContext;
     try
     {
         using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(mailAttachmentDetails.FullUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken))
         {
             Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(mailAttachmentDetails.FullUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].TrimEnd(ConstantStrings.Semicolon[0]));
             clientContext.Load(file);
             clientContext.ExecuteQuery();
             if (file.CheckOutType != CheckOutType.None)
             {
                 file.UndoCheckOut();
                 result = string.Concat(ConstantStrings.TRUE, ConstantStrings.Comma, ConstantStrings.Space, file.Name);
             }
             clientContext.ExecuteQuery();
         }
     }
     catch (Exception exception)
     {
         Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
         result = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message));
     }
     return result;
 }
        public string DiscardCheckOutChanges(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails)
        {
            string result = null;
            try
            {
                if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken())
                {
                    ///// full URL, relative URL
                    string[] allAttachmentUrl = mailAttachmentDetails.FullUrl.Split(';');

                    foreach (string attachmentUrl in allAttachmentUrl)
                    {
                        if (!string.IsNullOrWhiteSpace(attachmentUrl))
                        {
                            MailAttachmentDetails sendDocumentUrl = new MailAttachmentDetails();
                            sendDocumentUrl.FullUrl = attachmentUrl;
                            result = BriefcaseHelperFunction.DiscardCheckout(requestObject, sendDocumentUrl);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message));
            }
            return result;
        }
        /// <summary>
        /// Discards checkout from the documents
        /// </summary>
        /// <param name="requestObject">Request object</param>
        /// <param name="allAttachmentUrl">List of attachment URL</param>
        /// <returns>Status of discarding check out</returns>
        internal static string DiscardDocumentCheckout(RequestObject requestObject, string[] allAttachmentUrl)
        {
            int currentCount = 0;
            string result = ConstantStrings.FALSE;

            try
            {
                foreach (string attachmentUrl in allAttachmentUrl)
                {
                    if (!string.IsNullOrWhiteSpace(attachmentUrl))
                    {
                        MailAttachmentDetails sendDocumentUrl = new MailAttachmentDetails();
                        sendDocumentUrl.FullUrl = attachmentUrl;
                        if (currentCount >= MailAttachmentDetails.CheckoutFailedPosition)
                        {
                            result = DiscardCheckout(requestObject, sendDocumentUrl);
                        }
                    }
                    currentCount++;
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message));
            }
            return result;
        }
        public Stream SaveEmail(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails)
        {
            Stream result = null;
            try
            {
                if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken())
                {
                    ///// filename, stream
                    Dictionary<string, Stream> collectionOfAttachments = new Dictionary<string, Stream>();
                    ///// full URL, relative URL
                    string[] allAttachmentUrl = mailAttachmentDetails.FullUrl.Split(';');
                    ClientContext clientContext;
                    bool attachmentFlag = mailAttachmentDetails.IsAttachmentCall;
                    if (attachmentFlag)
                    {
                        foreach (string attachmentUrl in allAttachmentUrl)
                        {
                            if (!string.IsNullOrWhiteSpace(attachmentUrl))
                            {
                                // Do not use 'using' to generate client context here since it will dispose the object before other functions get executed
                                clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken);
                                Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1]);
                                ClientResult<System.IO.Stream> fileStream = file.OpenBinaryStream();
                                ///// Load the Stream data for the file
                                clientContext.Load(file);
                                clientContext.ExecuteQuery();

                                ///// In order to allow for multiple files with the same name, we provide a GUID tag to ensure unique keys in the dictionary
                                string uniqueKeyWithDate = attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].Substring(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].LastIndexOf(Convert.ToChar(ConstantStrings.BackwardSlash, CultureInfo.InvariantCulture)) + 1) + ConstantStrings.DOLLAR + Guid.NewGuid();
                                collectionOfAttachments.Add(uniqueKeyWithDate, fileStream.Value);
                            }
                        }
                    }

                    result = MailHelperFunctions.GenerateEmail(collectionOfAttachments, allAttachmentUrl, attachmentFlag);
                }
                else
                {
                    result = BriefcaseHelperFunction.ReturnErrorFile(TextConstants.MessageNoInputs);
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = BriefcaseHelperFunction.ReturnErrorFile(string.Concat(ConstantStrings.ServiceResponse, exception.HResult, exception.Message));
            }
            return result;
        }
        /// <summary>
        /// Helper function to perform Check Out, Detach, and Update document functionality.
        /// </summary>
        /// <param name="requestObject">The Web request object.</param>
        /// <param name="syncDetails">SyncDetails object</param>
        /// <param name="commonResponse">Holds response for briefcase detach operation</param>
        /// <param name="clientContext">Client context object for connection between SP & client</param>
        /// <param name="status">Sets status for send to briefcase operation</param>
        private void GetContextInList(RequestObject requestObject, SyncDetails syncDetails, ref CommonResponse commonResponse, ClientContext clientContext, ref string status)
        {
            List list = clientContext.Web.Lists.GetById(new Guid(syncDetails.ListId));
            foreach (int itemid in syncDetails.ItemId)
            {
                ListItemCollection listItems = BriefcaseHelperFunction.GetListItemCollection(clientContext, itemid);
                MailAttachmentDetails mailattachmentDetails = new MailAttachmentDetails();
                ServiceConstantStrings.OperationTypes operationType = (ServiceConstantStrings.OperationTypes)syncDetails.Operation;
                if (operationType == ServiceConstantStrings.OperationTypes.Detach)
                {
                    commonResponse = BriefcaseHelperFunction.DetachOperation(commonResponse, clientContext, list, listItems);
                }
                else
                {
                    foreach (var listItem in listItems)
                    {
                        mailattachmentDetails.FullUrl = Convert.ToString(listItem[ServiceConstantStrings.OneDriveSiteColumn], CultureInfo.InvariantCulture);
                        mailattachmentDetails.IsOverwrite = 1;
                    }

                    switch (operationType)
                    {
                        case ServiceConstantStrings.OperationTypes.Update:
                            status = this.SendToBriefcase(requestObject, mailattachmentDetails, false);
                            commonResponse = BriefcaseHelperFunction.UpdateOperationStatus(commonResponse, status);
                            break;
                        case ServiceConstantStrings.OperationTypes.Checkout:
                            status = this.CheckOutDocument(requestObject, mailattachmentDetails);
                            commonResponse = BriefcaseHelperFunction.CheckoutOperationStatus(commonResponse, status);
                            commonResponse.Status.Add(Convert.ToBoolean(status.Split(',')[0], CultureInfo.InvariantCulture));
                            break;
                    }
                }
            }
        }
 public string SendToBriefcase(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails, bool doCheckOut)
 {
     string status = ConstantStrings.FALSE;
     string result = string.Empty;
     try
     {
         if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken())
         {
             Dictionary<string, Stream> collectionOfAttachments = new Dictionary<string, Stream>();
             Dictionary<string, string> collectionOfOriginalAttachments = new Dictionary<string, string>();
             string[] allAttachmentUrl = mailAttachmentDetails.FullUrl.Split(ConstantStrings.Semicolon[0]);
             ClientContext clientContext = null;
             string usersMySite = string.Empty;
             usersMySite = BriefcaseHelperFunction.GetPersonalURL(requestObject);
             if (!usersMySite.ToUpperInvariant().Contains(ServiceConstantStrings.OneDriveNotSetupUrl.ToUpperInvariant()))
             {
                 foreach (string attachmentUrl in allAttachmentUrl)
                 {
                     if (!string.IsNullOrWhiteSpace(attachmentUrl))
                     {
                         // Do not use 'using' to generate client context here since it will dispose the object before other functions get executed
                         clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken);
                         Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1]);
                         ClientResult<System.IO.Stream> clientResultStream = file.OpenBinaryStream();
                         ///// Load the Stream data for the file
                         clientContext.Load(file);
                         clientContext.ExecuteQuery();
                         Guid uniqueKey = Guid.NewGuid();
                         collectionOfAttachments.Add(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].Substring(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].LastIndexOf(Convert.ToChar(ConstantStrings.ForwardSlash, CultureInfo.InvariantCulture)) + 1) + ConstantStrings.DOLLAR + uniqueKey, clientResultStream.Value);
                         collectionOfOriginalAttachments.Add(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].Substring(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].LastIndexOf(Convert.ToChar(ConstantStrings.ForwardSlash, CultureInfo.InvariantCulture)) + 1) + ConstantStrings.DOLLAR + uniqueKey, attachmentUrl);
                         MailAttachmentDetails sendDocumentUrl = new MailAttachmentDetails();
                         sendDocumentUrl.FullUrl = attachmentUrl;
                         if (doCheckOut)
                         {
                             this.CheckOutDocument(requestObject, sendDocumentUrl);
                         }
                     }
                 }
                 status = BriefcaseHelperFunction.UploadtoBriefcase(requestObject, collectionOfAttachments, collectionOfOriginalAttachments, usersMySite, allAttachmentUrl, mailAttachmentDetails.IsOverwrite);
                 //// If error not occurred while sending documents to OneDrive
                 if (!status.Contains(ConstantStrings.Code) && !status.Contains(ConstantStrings.Value))
                 {
                     status = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, status);
                 }
             }
             else
             {
                 status = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.ErrorCodeOneDriveNotConfigured, usersMySite);
             }
             result = status;
         }
         else
         {
             result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, status);
         }
     }
     catch (Exception exception)
     {
         result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
     }
     return result;
 }
        public string[] CheckedOutDocumentByUser(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails)
        {
            string[] result = null;
            if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken())
            {
                string fileException;
                User checkedOutByUser = null;
                try
                {
                    List<string> checkedOutByUserTitle = new List<string>();
                    if (null != requestObject && null != mailAttachmentDetails)
                    {
                        // full URL, relative URL
                        string[] allAttachmentUrl = mailAttachmentDetails.FullUrl.Split(ConstantStrings.Semicolon[0]);
                        ClientContext clientContext;
                        foreach (string attachmentUrl in allAttachmentUrl)
                        {
                            try // To continue retrieve the document status for all documents even if one of the document is not present
                            {
                                if (!string.IsNullOrWhiteSpace(attachmentUrl))
                                {
                                    using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken))
                                    {
                                        string relativePath = attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1];
                                        string[] folderPath = relativePath.Split(Convert.ToChar(ConstantStrings.ForwardSlash, CultureInfo.InvariantCulture));
                                        bool checkExists = false;
                                        Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(relativePath.Substring(0, relativePath.Length - folderPath[folderPath.Length - 1].Length - 1));
                                        FileCollection files = folder.Files;
                                        clientContext.Load(folder);
                                        clientContext.Load(files);
                                        clientContext.ExecuteQuery();
                                        foreach (Microsoft.SharePoint.Client.File file in files)
                                        {
                                            if (file.Name.ToUpperInvariant() == folderPath[folderPath.Length - 1].ToUpperInvariant())
                                            {
                                                checkExists = true;
                                                break;
                                            }
                                        }

                                        if (checkExists)
                                        {
                                            Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1]);
                                            clientContext.Load(file);
                                            clientContext.ExecuteQuery();
                                            if (file.CheckOutType == CheckOutType.None)
                                            {
                                                checkedOutByUserTitle.Add(string.Empty);
                                            }
                                            else
                                            {
                                                clientContext.ExecuteQuery();
                                                checkedOutByUser = file.CheckedOutByUser;
                                                clientContext.Load(checkedOutByUser);
                                                clientContext.ExecuteQuery();
                                                checkedOutByUserTitle.Add(checkedOutByUser.Title);
                                            }
                                        }
                                        else
                                        {
                                            checkedOutByUserTitle.Add(TextConstants.FileNotAvailableMessage);
                                        }
                                    }
                                }
                            }
                            catch (Exception exception)
                            {
                                fileException = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                                checkedOutByUserTitle.Add(fileException);
                            }
                        }
                    }
                    result = checkedOutByUserTitle.ToArray();
                }
                catch (Exception exception)
                {
                    fileException = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                    result = new[] { fileException };
                }
            }
            else
            {
                result = new[] { TextConstants.MessageNoInputs };
            }
            return result;
        }
 public string CheckOutDocument(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails)
 {
     string returnFlag = ConstantStrings.FALSE;
     if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken())
     {
         string result = ConstantStrings.FALSE;
         ClientContext clientContext;
         try
         {
             using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(mailAttachmentDetails.FullUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken))
             {
                 Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(mailAttachmentDetails.FullUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].TrimEnd(ConstantStrings.Semicolon[0]));
                 clientContext.Load(file);
                 clientContext.ExecuteQuery();
                 if (file.CheckOutType == CheckOutType.None)
                 {
                     file.CheckOut();
                     result = string.Concat(ConstantStrings.TRUE, ConstantStrings.Comma, ConstantStrings.Space, file.Name);
                 }
                 else
                 {
                     result = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ServiceConstantStrings.AlreadyCheckOut);
                 }
                 clientContext.ExecuteQuery();
                 returnFlag = result;
             }
         }
         catch (Exception exception)
         {
             Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
             returnFlag = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message));
         }
     }
     else
     {
         returnFlag = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, TextConstants.InvalidParametersMessage);
     }
     return returnFlag;
 }