/// <summary>
 /// Check if duplicate document exists 
 /// </summary>
 /// <param name="clientContext">SP client context</param>
 /// <param name="documentLibraryName">Name of the document library</param>
 /// <param name="folderName">Name of the folder</param>
 /// <param name="isMailUpload">Mail upload check</param>
 /// <param name="folderPath">The folder path.</param>
 /// <param name="contentCheck">Content check object</param>
 /// <param name="uploadFileName">Name of the file.</param>
 /// <returns>message as per duplicate exists or not</returns>
 internal static bool CheckDuplicateDocument(ClientContext clientContext, string documentLibraryName, bool isMailUpload, string folderPath, ContentCheckDetails contentCheck, string uploadFileName, bool allowContentCheck, ref string message)
 {
     DuplicateDocument duplicateDocument = ServiceUtility.DocumentExists(clientContext, contentCheck, documentLibraryName, folderPath, isMailUpload);
     if (duplicateDocument.DocumentExists)
     {
         string documentPath = string.Concat(ServiceConstantStrings.SiteURL, folderPath, ConstantStrings.ForwardSlash, uploadFileName);
         string duplicateMessage = (allowContentCheck && duplicateDocument.HasPotentialDuplicate) ? ConstantStrings.FilePotentialDuplicateMessage : ConstantStrings.FileAlreadyExistMessage;
         message = string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", string.Format(CultureInfo.InvariantCulture, duplicateMessage, uploadFileName, documentPath), ConstantStrings.SymbolAt, duplicateDocument.HasPotentialDuplicate.ToString());
     }
     return duplicateDocument.DocumentExists;
 }
        /// <summary>
        /// Checks if document exists.
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="documentLibraryName">Name of the document library.</param>
        /// <param name="folderPath">Path of the folder.</param>
        /// <returns>Returns true in case of Document presence</returns>
        public static DuplicateDocument DocumentExists(ClientContext clientContext, ContentCheckDetails contentCheck, string documentLibraryName, string folderPath, bool isMail)
        {
            DuplicateDocument duplicateDocument = new DuplicateDocument(false, false);
            if (null != clientContext && null != contentCheck && !string.IsNullOrEmpty(documentLibraryName) && !string.IsNullOrEmpty(folderPath))
            {
                string serverRelativePath = folderPath + ConstantStrings.ForwardSlash + contentCheck.FileName;
                ListItemCollection listItemCollection = null;
                string camlQuery = string.Format(CultureInfo.InvariantCulture, ConstantStrings.GetAllFilesInFolderQuery, serverRelativePath);
                listItemCollection = Lists.GetData(clientContext, documentLibraryName, camlQuery);
                duplicateDocument.DocumentExists = (null != listItemCollection && 0 < listItemCollection.Count) ? true : false;

                // Check file size, from, sent date as well.
                if (duplicateDocument.DocumentExists)
                {
                    // check for other conditions as well.
                    ListItem listItem = listItemCollection.FirstOrDefault();
                    DateTime sentDate, storedFileSentDate;
                    long fileSize = Convert.ToInt64(listItem.FieldValues[ConstantStrings.SearchEmailFileSize], CultureInfo.InvariantCulture);
                    if (isMail)
                    {
                        // check for subject, from and sent date
                        string subject = Convert.ToString(listItem.FieldValues[ConstantStrings.SearchEmailSubject], CultureInfo.InvariantCulture);
                        string from = Convert.ToString(listItem.FieldValues[ConstantStrings.SearchEmailFrom], CultureInfo.InvariantCulture);
                        bool isValidDateFormat;
                        isValidDateFormat = DateTime.TryParse(Convert.ToString(listItem.FieldValues[ConstantStrings.SearchEmailSentDate], CultureInfo.InvariantCulture), out storedFileSentDate);
                        isValidDateFormat &= DateTime.TryParse(contentCheck.SentDate, out sentDate);
                        if (isValidDateFormat)
                        {
                            TimeSpan diffrence = sentDate - storedFileSentDate;
                            uint tolleranceMin = Convert.ToUInt16(ConstantStrings.SentDateTolerance, CultureInfo.InvariantCulture);     // up to how much minutes difference between uploaded files is tolerable
                            duplicateDocument.HasPotentialDuplicate = ((fileSize == contentCheck.FileSize) && (subject.Trim() == contentCheck.Subject.Trim()) && (from.Trim() == contentCheck.FromField.Trim()) && (diffrence.Minutes < tolleranceMin));
                        }
                    }
                    else
                    {
                        duplicateDocument.HasPotentialDuplicate = (fileSize == contentCheck.FileSize);
                    }
                }
            }
            return duplicateDocument;
        }
 /// <summary>
 /// Uploads the file to SharePoint.
 /// </summary>
 /// <param name="request">Web request object</param>
 protected string UploadFileToSharePoint(HttpRequest request)
 {
     HttpFileCollection fileCollection = Request.Files;
     Regex regEx = new Regex("[*?|\\\t/:\"\"'<>#{}%~&]");
     string sharePointAppToken = Request.Form["SPAppToken"];
     string refreshToken = Request.Form["RefreshToken"];
     string clientUrl = Request.Form["ClientUrl"];
     string folderName = Request.Form["FolderName"];
     string documentLibraryName = Request.Form["DocumentLibraryName"];
     string originalName = string.Empty;
     bool allowContentCheck = Convert.ToBoolean(Request.Form["AllowContentCheck"], CultureInfo.InvariantCulture);
     bool continueUpload = true;
     Int16 isOverwrite = 3;
     IList<string> listResponse = new List<string>();
     string response = string.Empty;
     bool environment = Convert.ToBoolean(UIConstantStrings.IsDeployedOnAzure, CultureInfo.InvariantCulture);
     try
     {
         if (!environment || ((!string.IsNullOrWhiteSpace(sharePointAppToken) || !string.IsNullOrWhiteSpace(refreshToken)) && !string.IsNullOrWhiteSpace(clientUrl) && !string.IsNullOrWhiteSpace(folderName)))
         {
             for (int fileCounter = 0; fileCounter < fileCollection.Count; fileCounter++)
             {
                 if (!Int16.TryParse(Request.Form["Overwrite" + fileCounter], out isOverwrite))
                 {
                     isOverwrite = 3;
                 }
                 HttpPostedFile upload = fileCollection[fileCounter];
                 //// Added condition to check if upload.FileName returns the complete path or just the file name
                 string fileName = originalName = upload.FileName;
                 ContentCheckDetails contentCheck = new ContentCheckDetails(upload.FileName, upload.InputStream.Length);
                 string fileExtension = System.IO.Path.GetExtension(upload.FileName).Trim();
                 continueUpload = true;
                 if (-1 < fileName.IndexOf('\\'))
                 {
                     fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
                 }
                 else if (-1 < fileName.IndexOf('/'))
                 {
                     fileName = fileName.Substring(fileName.LastIndexOf('/') + 1);
                 }
                 if (null != upload.InputStream && 0 == upload.InputStream.Length)
                 {
                     listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", ConstantStrings.ErrorEmptyFile, ConstantStrings.DOLLAR, fileName));
                 }
                 else
                 {
                     if (regEx.IsMatch(fileName))
                     {
                         listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", UIConstantStrings.ErrorInvalidCharacter, ConstantStrings.DOLLAR, fileName));
                     }
                     else
                     {
                         using (ClientContext clientContext = ServiceUtility.GetClientContext(sharePointAppToken, new Uri(clientUrl), refreshToken, Request))
                         {
                             string folder = folderName.Substring(folderName.LastIndexOf(ConstantStrings.ForwardSlash, StringComparison.OrdinalIgnoreCase) + 1);
                             if (2 == isOverwrite)   //If User presses "Perform content check" option in overwrite Popup
                             {
                                 continueUpload = false;
                                 response = PerformContentCheck(folderName, listResponse, response, upload, clientContext);
                             }
                             else if (3 == isOverwrite)  //If user presses "Cancel upload" option in overwrite popup or file is being uploaded for the first time
                             {
                                 continueUpload = CheckDuplicateDocument(clientContext, folderName, documentLibraryName, listResponse, fileName, contentCheck, allowContentCheck);
                             }
                             else if (1 == isOverwrite)  //If User presses "Append date to file name and save" option in overwrite Popup
                             {
                                 string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileName);
                                 string timeStampSuffix = DateTime.Now.ToString(UIConstantStrings.TimeStampFormat, CultureInfo.InvariantCulture).Replace(":", "_");
                                 fileName = fileNameWithoutExt + "_" + timeStampSuffix + fileExtension;
                             }
                             if (continueUpload)
                             {
                                 listResponse = SetDocumentProperties(request, refreshToken, upload, fileExtension, originalName, listResponse, folderName, fileName, clientContext, folder, documentLibraryName);
                             }
                         }
                     }
                 }
             }
             foreach (var item in listResponse)
             {
                 response += string.Concat(item, ConstantStrings.DOLLAR, ConstantStrings.Pipe, ConstantStrings.DOLLAR);
             }
         }
         else
         {
             response = UIConstantStrings.MessageNoInputs;
         }
     }
     catch (Exception exception)
     {
         Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, UIConstantStrings.LogTableName);
         response = string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", exception.Message, ConstantStrings.DOLLAR, documentLibraryName);
     }
     return response;
 }
 /// <summary>
 /// checks for duplicate document to upload
 /// </summary>
 /// <param name="folderName">Path of the folder</param>
 /// <param name="documentLibraryName">Name of the document library</param>
 /// <param name="listResponse">List of responses</param>
 /// <param name="fileName">Name of the file.</param>
 /// <param name="contentCheck">Content check object</param>
 /// <param name="clientContext">SP client context</param>
 /// <param name="folder">Name of the folder</param>
 /// <returns>true if duplicate document found</returns>
 private static bool CheckDuplicateDocument(ClientContext clientContext, string folderName, string documentLibraryName, IList<string> listResponse, string fileName, ContentCheckDetails contentCheck, bool allowContentCheck)
 {
     bool continueUpload = true;
     DuplicateDocument duplicateDocument = ServiceUtility.DocumentExists(clientContext, contentCheck, documentLibraryName, folderName, false);
     if (duplicateDocument.DocumentExists)
     {
         continueUpload = false;
         string documentPath = string.Concat(UIConstantStrings.SiteURL, folderName, ConstantStrings.ForwardSlash, fileName);
         string duplicateMessage = (allowContentCheck && duplicateDocument.HasPotentialDuplicate) ? ConstantStrings.FilePotentialDuplicateMessage : ConstantStrings.FileAlreadyExistMessage;
         listResponse.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}{1}{1}{2}", string.Format(CultureInfo.InvariantCulture, duplicateMessage, fileName, documentPath), ConstantStrings.SymbolAt, Convert.ToString(duplicateDocument.HasPotentialDuplicate, CultureInfo.InvariantCulture)));
     }
     return continueUpload;
 }
        /// <summary>
        /// Reads the XMLDocument and determines whether the request is to upload entire mail/attachment/.eml file/.msg file and calls respective method.
        /// </summary>
        /// <param name="isOverwrite">Overwrite check</param>
        /// <param name="documentLibraryName">Name of the document library</param>
        /// <param name="folderName">Name of the folder</param>
        /// <param name="webResponse">HTTP web response to get the response stream</param>
        /// <param name="isMailUpload">Mail Upload Flag</param>
        /// <param name="requestObject">request object for web</param>
        /// <param name="client">Service Client Object</param>
        /// <param name="fileName">Name of the file</param>
        /// <param name="folderPath">upload folder path</param>
        /// <param name="message">Reference object for the message to be returned</param>
        /// <returns>Returns whether File Uploaded successfully or failed</returns>
        internal static string UploadFilesMail(bool isOverwrite, bool isContentCheckRequired, bool allowContentCheck, string documentLibraryName, HttpWebResponse webResponse, bool isMailUpload, RequestObject requestObject, Client client, string fileName, string folderPath, ref string message)
        {
            bool isMsg = true;
            MailMetaData mailMetaData = new MailMetaData();
            var bytes = (dynamic)null;
            string mailMessage = string.Empty;
            string originalName = string.Empty;
            string xmlPath = string.Empty;
            string result = ConstantStrings.UploadSucceeded;
            ContentCheckDetails contentCheck = null;
            try
            {
                XmlDocument xmlDocument = RetrieveXMLDocument(webResponse);
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
                nsmgr.AddNamespace("s", ConstantStrings.SoapEnvelopURI);
                nsmgr.AddNamespace("m", ConstantStrings.ExchangeServiceMessage);
                nsmgr.AddNamespace("t", ConstantStrings.ExchangeServiceTypes);
                string extension = System.IO.Path.GetExtension(fileName).Trim();
                string uploadFileName = UploadHelperFunctionsUtility.RemoveSpecialChar(fileName);
                if (xmlDocument.SelectSingleNode("/s:Envelope/s:Body/m:GetAttachmentResponse/m:ResponseMessages/m:GetAttachmentResponseMessage/m:Attachments/t:FileAttachment/t:Content", nsmgr) != null)
                {
                    isMsg = false;
                }
                if (string.IsNullOrEmpty(extension) && isMsg)
                {
                    uploadFileName = uploadFileName + ConstantStrings.EmailFileExtension;
                }
                using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(client.Url), requestObject.RefreshToken))
                {
                    if (isMailUpload)
                    {
                        bytes = GetEmailProperties(xmlDocument, ref mailMetaData);
                    }
                    else
                    {
                        bytes = UploadHelperFunctionsUtility.GetStream(xmlDocument, nsmgr, isMailUpload, extension, isMsg);
                    }
                    if (null != bytes)
                    {
                        using (MemoryStream memoryStream = new MemoryStream(bytes))
                        {
                            contentCheck = new ContentCheckDetails(uploadFileName, mailMetaData.mailSubject, memoryStream.Length, mailMetaData.mailSender, mailMetaData.sentDate);
                        }
                    }
                    if (!isOverwrite && !isContentCheckRequired && UploadHelperFunctionsUtility.CheckDuplicateDocument(clientContext, documentLibraryName, isMailUpload, folderPath, contentCheck, uploadFileName, allowContentCheck, ref message))
                    {
                        result = ConstantStrings.UploadFailed;
                    }
                    else if (isContentCheckRequired)
                    {
                        message = UploadHelperFunctionsUtility.PerformContentCheckUtility(isMailUpload, folderPath, isMsg, xmlDocument, nsmgr, extension, uploadFileName, clientContext);
                        result = ConstantStrings.UploadFailed;
                    }
                    else
                    {
                        if (isMailUpload)       //Upload entire Email
                        {
                            UploadMail(requestObject, client, folderPath, fileName, documentLibraryName, xmlDocument, ref message);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(extension) && isMsg)       //Upload .msg file
                            {
                                UploadAttachedMailExtBlank(requestObject, client, folderPath, fileName, documentLibraryName, xmlDocument, ref message);
                            }
                            else
                            {
                                if (string.Equals(extension, ConstantStrings.EmailFileExtension, StringComparison.OrdinalIgnoreCase))
                                {
                                    UploadEMLFile(documentLibraryName, requestObject, client, folderPath, fileName, ref message, xmlDocument, nsmgr, ref mailMetaData, ref bytes, extension);
                                }
                                else
                                {
                                    //get original name
                                    xmlPath = "/s:Envelope/s:Body/m:GetAttachmentResponse/m:ResponseMessages/m:GetAttachmentResponseMessage/m:Attachments/t:FileAttachment/t:Name";
                                    originalName = RetrieveNodeValue(xmlDocument, nsmgr, xmlPath, true);
                                    //get attachment content
                                    xmlPath = "/s:Envelope/s:Body/m:GetAttachmentResponse/m:ResponseMessages/m:GetAttachmentResponseMessage/m:Attachments/t:FileAttachment/t:Content";
                                    mailMessage = RetrieveNodeValue(xmlDocument, nsmgr, xmlPath, false);

                                    bytes = Convert.FromBase64String(mailMessage);
                                    using (MemoryStream memoryStream = new MemoryStream(bytes))
                                    {
                                        mailMetaData.mailImportance = string.Empty;
                                        mailMetaData.mailSubject = string.Empty;
                                        mailMetaData.originalName = originalName;
                                        if (!UploadToFolder(requestObject, client, folderPath, fileName, string.Empty, memoryStream, documentLibraryName, mailMetaData, ref message))
                                        {
                                            result = ConstantStrings.UploadFailed;
                                        }
                                    }
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(message))
                        {
                            result = ConstantStrings.UploadFailed;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                result = ConstantStrings.UploadFailed;
            }
            return result;
        }