/// <summary> /// /// </summary> /// <returns></returns> public DuplicateDocument DocumentExists(string clientUrl, ContentCheckDetails contentCheck, string documentLibraryName, string folderName, bool isMail) { ClientContext clientContext = spoAuthorization.GetClientContext(clientUrl); DuplicateDocument duplicateDocument = documentRepository.DocumentExists(clientContext, contentCheck, documentLibraryName, folderName, isMail); if (duplicateDocument.DocumentExists) { return duplicateDocument; } return null; }
/// <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="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> public GenericResponseVM CheckDuplicateDocument(ClientContext clientContext, string documentLibraryName, bool isMailUpload, string folderPath, ContentCheckDetails contentCheck, string uploadFileName, bool allowContentCheck, ref string message) { GenericResponseVM genericResponse = null; DuplicateDocument duplicateDocument = documentRepository.DocumentExists(clientContext, contentCheck, documentLibraryName, folderPath, isMailUpload); if (duplicateDocument.DocumentExists) { string documentPath = string.Concat(generalSettings.SiteURL, folderPath, ServiceConstants.FORWARD_SLASH, uploadFileName); string duplicateMessage = (allowContentCheck && duplicateDocument.HasPotentialDuplicate) ? errorSettings.FilePotentialDuplicateMessage : errorSettings.FileAlreadyExistMessage; duplicateMessage = $"{duplicateMessage}|{duplicateDocument.HasPotentialDuplicate}"; genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.DuplicateDocument.ToString(), Value = string.Format(CultureInfo.InvariantCulture, duplicateMessage, uploadFileName, documentPath) }; return genericResponse; } return genericResponse; }
/// <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); }
public GenericResponseVM CheckDuplicateDocument(string clientUrl, string folderName, string documentLibraryName, string fileName, ContentCheckDetails contentCheck, bool allowContentCheck) { GenericResponseVM genericResponse = null; DuplicateDocument duplicateDocument = uploadHelperFunctions.DocumentExists(clientUrl, contentCheck, documentLibraryName, folderName, false); if (duplicateDocument != null && duplicateDocument.DocumentExists) { string documentPath = string.Concat(generalSettings.SiteURL, folderName, ServiceConstants.FORWARD_SLASH, fileName); string duplicateMessage = (allowContentCheck && duplicateDocument.HasPotentialDuplicate) ? errorSettings.FilePotentialDuplicateMessage : errorSettings.FileAlreadyExistMessage; duplicateMessage = $"{duplicateMessage}|{duplicateDocument.HasPotentialDuplicate}"; genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.DuplicateDocument.ToString(), Value = string.Format(CultureInfo.InvariantCulture, duplicateMessage, fileName, documentPath) }; } return(genericResponse); }
/// <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); }
public IActionResult UploadFiles() { try { IFormFileCollection fileCollection = Request.Form.Files; Regex regEx = new Regex("[*?|\\\t/:\"\"'<>#{}%~&]"); string clientUrl = Request.Form["clientUrl"]; string folderUrl = Request.Form["folderUrl"]; string folderName = folderUrl.Substring(folderUrl.LastIndexOf(ServiceConstants.FORWARD_SLASH, StringComparison.OrdinalIgnoreCase) + 1); string documentLibraryName = Request.Form["documentLibraryName"]; MatterExtraProperties documentExtraProperites = null; if (!string.IsNullOrWhiteSpace(Request.Form["DocumentExtraProperties"])) { documentExtraProperites = JsonConvert.DeserializeObject <MatterExtraProperties>(Request.Form["DocumentExtraProperties"].ToString()); } bool isDeployedOnAzure = Convert.ToBoolean(generalSettings.IsTenantDeployment, CultureInfo.InvariantCulture); string originalName = string.Empty; bool allowContentCheck = Convert.ToBoolean(Request.Form["AllowContentCheck"], CultureInfo.InvariantCulture); Int16 isOverwrite = 3; //Input validation #region Error Checking GenericResponseVM genericResponse = null; IList <object> listResponse = new List <object>(); bool continueUpload = true; if (isDeployedOnAzure == false && string.IsNullOrWhiteSpace(clientUrl) && string.IsNullOrWhiteSpace(folderUrl)) { genericResponse = new GenericResponseVM() { Value = errorSettings.MessageNoInputs, Code = HttpStatusCode.BadRequest.ToString(), IsError = true }; return(matterCenterServiceFunctions.ServiceResponse(genericResponse, (int)HttpStatusCode.OK)); } #endregion //Get all the files which are uploaded by the user for (int fileCounter = 0; fileCounter < fileCollection.Count; fileCounter++) { IFormFile uploadedFile = fileCollection[fileCounter]; if (!Int16.TryParse(Request.Form["Overwrite" + fileCounter], out isOverwrite)) { isOverwrite = 3; } continueUpload = true; ContentDispositionHeaderValue fileMetadata = ContentDispositionHeaderValue.Parse(uploadedFile.ContentDisposition); string fileName = originalName = fileMetadata.FileName.Trim('"'); fileName = System.IO.Path.GetFileName(fileName); ContentCheckDetails contentCheckDetails = new ContentCheckDetails(fileName, uploadedFile.Length); string fileExtension = System.IO.Path.GetExtension(fileName).Trim(); if (-1 < fileName.IndexOf('\\')) { fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1); } else if (-1 < fileName.IndexOf('/')) { fileName = fileName.Substring(fileName.LastIndexOf('/') + 1); } if (null != uploadedFile.OpenReadStream() && 0 == uploadedFile.OpenReadStream().Length) { listResponse.Add(new GenericResponseVM() { Code = fileName, Value = errorSettings.ErrorEmptyFile, IsError = true }); } else if (regEx.IsMatch(fileName)) { listResponse.Add(new GenericResponseVM() { Code = fileName, Value = errorSettings.ErrorInvalidCharacter, IsError = true }); } else { string folder = folderUrl.Substring(folderUrl.LastIndexOf(ServiceConstants.FORWARD_SLASH, StringComparison.OrdinalIgnoreCase) + 1); //If User presses "Perform content check" option in overwrite Popup if (2 == isOverwrite) { genericResponse = documentProvision.PerformContentCheck(clientUrl, folderUrl, uploadedFile, fileName); } //If user presses "Cancel upload" option in overwrite popup or file is being uploaded for the first time else if (3 == isOverwrite) { genericResponse = documentProvision.CheckDuplicateDocument(clientUrl, folderUrl, documentLibraryName, fileName, contentCheckDetails, allowContentCheck); } //If User presses "Append date to file name and save" option in overwrite Popup else if (1 == isOverwrite) { string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(fileName); string timeStampSuffix = DateTime.Now.ToString(documentSettings.TimeStampFormat, CultureInfo.InvariantCulture).Replace(":", "_"); fileName = fileNameWithoutExt + "_" + timeStampSuffix + fileExtension; } if (genericResponse == null) { genericResponse = documentProvision.UploadFiles(uploadedFile, fileExtension, originalName, folderUrl, fileName, clientUrl, folder, documentLibraryName, documentExtraProperites); } if (genericResponse == null) { string documentIconUrl = string.Empty; fileExtension = fileExtension.Replace(".", ""); if (fileExtension.ToLower() != "pdf") { documentIconUrl = $"{generalSettings.SiteURL}/_layouts/15/images/ic{fileExtension}.gif"; } else { documentIconUrl = $"{generalSettings.SiteURL}/_layouts/15/images/ic{fileExtension}.png"; } //Create a json object with file upload success var successFile = new { IsError = false, Code = HttpStatusCode.OK.ToString(), Value = UploadEnums.UploadSuccess.ToString(), FileName = fileName, DropFolder = folderName, DocumentIconUrl = documentIconUrl }; listResponse.Add(successFile); } else { //Create a json object with file upload failure var errorFile = new { IsError = true, Code = genericResponse.Code.ToString(), Value = genericResponse.Value.ToString(), FileName = fileName, DropFolder = folderName }; listResponse.Add(errorFile); } } } //Return the response with proper http status code and proper response object return(matterCenterServiceFunctions.ServiceResponse(listResponse, (int)HttpStatusCode.OK)); } catch (Exception ex) { customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable); throw; } }
/// <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 GenericResponseVM UploadFilesMail(bool isOverwrite, bool isContentCheckRequired, bool allowContentCheck, string documentLibraryName, HttpWebResponse webResponse, bool isMailUpload, 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; GenericResponseVM genericResponse = null; ContentCheckDetails contentCheck = null; try { XmlDocument xmlDocument = RetrieveXMLDocument(webResponse); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable); nsmgr.AddNamespace("s", ServiceConstants.SOAP_ENVELOP_URI); nsmgr.AddNamespace("m", ServiceConstants.EXCHANGE_SERVICE_MESSAGE); nsmgr.AddNamespace("t", ServiceConstants.EXCHANGE_SERVICE_TYPES); 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 + ServiceConstants.EMAIL_FILE_EXTENSION; } using (ClientContext clientContext = spoAuthorization.GetClientContext(client.Url)) { 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); } } genericResponse = uploadHelperFunctionsUtility.CheckDuplicateDocument(clientContext, documentLibraryName, isMailUpload, folderPath, contentCheck, uploadFileName, allowContentCheck, ref message); if (!isOverwrite && !isContentCheckRequired && (genericResponse!=null && genericResponse.IsError==true)) { return genericResponse; } else if (isContentCheckRequired) { genericResponse = uploadHelperFunctionsUtility.PerformContentCheckUtility(isMailUpload, folderPath, isMsg, xmlDocument, nsmgr, extension, uploadFileName, clientContext); return genericResponse; } else { genericResponse = null; if (isMailUpload) //Upload entire Email { UploadMail(client, folderPath, fileName, documentLibraryName, xmlDocument, ref message); } else { if (string.IsNullOrEmpty(extension) && isMsg) //Upload .msg file { UploadAttachedMailExtBlank(client, folderPath, fileName, documentLibraryName, xmlDocument, ref message); } else { if (string.Equals(extension, ServiceConstants.EMAIL_FILE_EXTENSION, StringComparison.OrdinalIgnoreCase)) { UploadEMLFile(documentLibraryName, 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(client, folderPath, fileName, string.Empty, memoryStream, documentLibraryName, mailMetaData, ref message)) { //result = ServiceConstants.UPLOAD_FAILED; genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.UploadToFolder.ToString(), Value = message }; return genericResponse; } } } } } if (!string.IsNullOrEmpty(message)) { //result = ServiceConstants.UPLOAD_FAILED; genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.UploadFailure.ToString(), Value = message }; return genericResponse; } } } } catch (Exception exception) { //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.UploadFailure.ToString(), Value = "" }; } return genericResponse; }
/// <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="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> public GenericResponseVM CheckDuplicateDocument(ClientContext clientContext, string documentLibraryName, bool isMailUpload, string folderPath, ContentCheckDetails contentCheck, string uploadFileName, bool allowContentCheck, ref string message) { GenericResponseVM genericResponse = null; DuplicateDocument duplicateDocument = documentRepository.DocumentExists(clientContext, contentCheck, documentLibraryName, folderPath, isMailUpload); if (duplicateDocument.DocumentExists) { string documentPath = string.Concat(generalSettings.SiteURL, folderPath, ServiceConstants.FORWARD_SLASH, uploadFileName); string duplicateMessage = (allowContentCheck && duplicateDocument.HasPotentialDuplicate) ? errorSettings.FilePotentialDuplicateMessage : errorSettings.FileAlreadyExistMessage; duplicateMessage = $"{duplicateMessage}|{duplicateDocument.HasPotentialDuplicate}"; genericResponse = new GenericResponseVM() { IsError = true, Code = UploadEnums.DuplicateDocument.ToString(), Value = string.Format(CultureInfo.InvariantCulture, duplicateMessage, uploadFileName, documentPath) }; return(genericResponse); } return(genericResponse); }
/// <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); }
/// <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); }