public async Task <HttpResponseMessage> SetFileAttributes() { if (!Request.Content.IsFormData()) { return(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType)); // HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType); } string authorizationString = DecodeAuthorizationString(); SPHelper.SetSharePointCredentials(authorizationString); NameValueCollection formData = await Request.Content.ReadAsFormDataAsync(); if (formData.Keys.Count > 0) { SharePointDocument doc = new SharePointDocument(); doc.FileId = formData.Get("FileId").ToGuid(); doc.MasterId = formData.Get("MasterId"); doc.MasterNumber = formData.Get("MasterNumber"); doc.DocumentType = StringToLookupItem("DocumentType", formData.Get("DocumentType")); doc.MasterName = formData.Get("MasterName"); ListItem file = SPHelper.FindFile(doc.FileId); SPHelper.AddDocumentProperties(file, doc); } return(new HttpResponseMessage(HttpStatusCode.OK)); }
private void ProcessDocument(SharePointDocument document, string filePath) { TraceFactory.Logger.Debug("Found file: " + document.FileName); try { string fileName = Path.GetFileName(filePath); ScanFilePrefix filePrefix = ScanFilePrefix.Parse(fileName); // Create the log for this file DigitalSendJobOutputLogger log = new DigitalSendJobOutputLogger(fileName, filePrefix.ToString(), filePrefix.SessionId); log.FileSentDateTime = document.Created.LocalDateTime; log.FileLocation = $@"{_library.SiteUrl.Host}\{_library.Name}"; // Validate and analyze the file OutputProcessor processor = new OutputProcessor(filePath); ValidationResult result = null; Retry.WhileThrowing( () => result = processor.Validate(Configuration), 10, TimeSpan.FromSeconds(2), new List <Type>() { typeof(IOException) }); // If the validation failed, there is a small chance that the HPS file arrived // a little later than the PDF and didn't get downloaded at the same time. // Check the server to see if that's the case - if so, run the validation again if (!result.Succeeded && result.Message.Contains("metadata", StringComparison.OrdinalIgnoreCase)) { if (FindMetadataFile(document)) { result = processor.Validate(Configuration); } } DocumentProperties properties = processor.GetProperties(); log.FileSizeBytes = properties.FileSize; log.PageCount = properties.Pages; log.SetErrorMessage(result); // Clean up the file processor.ApplyRetention(Configuration, result.Succeeded); // Send the output log new DataLogger(GetLogServiceHost(filePrefix.SessionId)).Submit(log); } catch (IOException ex) { LogProcessFileError(filePath, ex); } catch (FormatException ex) { LogProcessFileError(filePath, ex); } }
public HttpResponseMessage GetByAlternateField() { string authorizationString = DecodeAuthorizationString(); SPHelper.SetSharePointCredentials(authorizationString); List <SharePointDocument> files = new List <SharePointDocument>(); if (!string.IsNullOrEmpty(Request.RequestUri.Query)) { List <KeyValuePair <string, string> > kvpList = Request.GetQueryNameValuePairs().ToList <KeyValuePair <string, string> >(); string alternateFieldName = "", alternateFieldValue = ""; foreach (KeyValuePair <string, string> kvp in kvpList) { string key = kvp.Key; string val = kvp.Value; switch (key) { case "AlternateFieldName": alternateFieldName = val; break; case "AlternateFieldValue": alternateFieldValue = val; break; default: break; } } if (!string.IsNullOrEmpty(alternateFieldName) && (!string.IsNullOrEmpty(alternateFieldValue))) { ListItemCollection list = SPHelper.GetDocuments(alternateFieldName, alternateFieldValue); if (list != null && list.AreItemsAvailable) { foreach (ListItem item in list) { SharePointDocument file = ListItemToSharePointDocument(item); files.Add(file); } } } } else { // No Query String Included return(new HttpResponseMessage(HttpStatusCode.OK)); } var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(JsonConvert.SerializeObject(files), Encoding.UTF8, "application/json"); return(response); }
public static void AddDocumentProperties(ListItem item, SharePointDocument doc) { ClientContext ctx = ConnectToSharePoint(); SetListItemText(item, "MasterId", doc.MasterId); SetListItemText(item, "MasterNumber", doc.MasterNumber); SetListItemText(item, "MasterName", doc.MasterName); SetListItemLookup(item, "DocumentType", doc.DocumentType); item.Update(); ctx.ExecuteQuery(); }
public static bool ValidateUploadFields(SharePointDocument doc) { bool rc = true; if (string.IsNullOrEmpty(doc.MasterId)) { rc = false; } if (string.IsNullOrEmpty(doc.MasterName)) { rc = false; } return(rc); }
public static SharePointDocument ListItemToCustomerDocument(ListItem item) { SharePointDocument file = new SharePointDocument(); file.FileId = (item["UniqueId"].ToString().ToGuid()); file.MasterId = FieldValueToString(item["MasterId"]); file.MasterNumber = FieldValueToString(item["MasterId"]); file.MasterName = FieldValueToString(item["MasterId"]); file.DocumentType = FieldLookupValueToLookupItem(item["DocumentType"]); file.FileName = item["FileLeafRef"].ToString(); file.FilePath = item["FileRef"].ToString(); return(file); }
private SharePointDocument ListItemToSharePointDocument(ListItem item) { SharePointDocument file = new SharePointDocument(); file.FileId = (item["UniqueId"].ToString().ToGuid()); file.MasterId = item["MasterId"] != null ? item["MasterId"].ToString() : ""; file.MasterNumber = item["MasterNumber"] != null ? item["MasterNumber"].ToString() : ""; file.DocumentType = FieldLookupValueToLookupItem(item["DocumentType"]); file.MasterName = item["MasterName"] != null ? item["MasterName"].ToString() : ""; file.FileName = item["FileLeafRef"].ToString(); file.FilePath = item["FileRef"].ToString(); return(file); }
private bool FindMetadataFile(SharePointDocument document) { string fileName = Path.GetFileNameWithoutExtension(document.FileName); SharePointDocumentQuery criteria = new SharePointDocumentQuery(); criteria.FileName = fileName; var retrieved = _library.Retrieve(criteria); if (retrieved.Any()) { foreach (SharePointDocument doc in retrieved) { _library.Download(doc, _tempPath); } _library.Delete(retrieved); return(true); } else { return(false); } }
public HttpResponseMessage GetByMasterNumber([FromUri] string id) { string authorizationString = DecodeAuthorizationString(); SPHelper.SetSharePointCredentials(authorizationString); List <SharePointDocument> files = new List <SharePointDocument>(); ListItemCollection list = SPHelper.GetDocumentsByNumber(id); if (list != null && list.AreItemsAvailable) { foreach (ListItem item in list) { SharePointDocument file = ListItemToSharePointDocument(item); files.Add(file); } } var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(JsonConvert.SerializeObject(files), Encoding.UTF8, "application/json"); return(response); }
public static ListItemCollection GetDocuments(string fieldName, string fieldValue) { CAMLQueryFilter filter = new CAMLQueryFilter(); if (!string.IsNullOrEmpty(fieldName)) { SPCAMLQueryBuilder.FieldType fieldType = SharePointDocument.GetFieldTypeByFieldName(fieldName); switch (fieldType) { case SPCAMLQueryBuilder.FieldType.Lookup: int intValue = int.MinValue; bool isInt = int.TryParse(fieldValue, out intValue); if (isInt) { filter = new CAMLQueryLookupFilter(fieldName, intValue, QueryType.Equal); } else { filter = new CAMLQueryLookupFilter(fieldName, fieldValue, QueryType.Equal); } break; default: filter = new CAMLQueryGenericFilter(fieldName, fieldType, fieldValue, QueryType.Equal); break; } } CAMLQueryBuilder builder = new CAMLQueryBuilder(filter); builder.DocumentFilter(FSObjType.Document, true); builder.AddViewFields(SharePointDocument.GetAllFieldNames()); builder.BuildQuery(); builder.OrderBy("Created", false); builder.BuildViewFields(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = builder.ToString(); ClientContext ctx = ConnectToSharePoint(); List spList = ctx.Web.Lists.GetByTitle("Documents"); ctx.Load(spList); ctx.ExecuteQuery(); if (spList != null && spList.ItemCount > 0) { ListItemCollection listItems = spList.GetItems(camlQuery); ctx.Load(listItems); ctx.ExecuteQuery(); // ctx.Dispose(); return(listItems); } else { return(null); } }
public async Task <HttpResponseMessage> UploadDocument() { string authorizationString = DecodeAuthorizationString(); SPHelper.SetSharePointCredentials(authorizationString); Guid fileId = Guid.Empty; if (!Request.Content.IsMimeMultipartContent()) { HttpResponseException ex = new HttpResponseException(HttpStatusCode.UnsupportedMediaType); throw ex; } SharePointDocument doc = new SharePointDocument(); string targetFolderName = ""; if (!string.IsNullOrEmpty(Request.RequestUri.Query)) { List <KeyValuePair <string, string> > list = Request.GetQueryNameValuePairs().ToList <KeyValuePair <string, string> >(); foreach (KeyValuePair <string, string> kvp in list) { string key = kvp.Key; string val = kvp.Value; switch (key) { case "MasterId": doc.MasterId = val; //(val == "!" ? "" : val); break; case "DocumentType": doc.DocumentType = StringToLookupItem("DocumentType", val); break; case "MasterNumber": doc.MasterNumber = val; break; case "MasterName": doc.MasterName = val; break; case "EntityName": targetFolderName = SetEntityName(val); break; default: break; } } } if (!ValidateUploadFields(doc)) { HttpResponseException ex = new HttpResponseException(HttpStatusCode.NotAcceptable); throw ex; } MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.Contents) { var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); byte[] buffer = await file.ReadAsByteArrayAsync(); int maxItems = APISetting.GetInt("MAX_ITEMS_PER_FOLDER"); if (maxItems == int.MinValue) { maxItems = 5000; } if (!string.IsNullOrEmpty(doc.MasterId)) { ListItem msaFolder = SPHelper.FindFolder(doc.MasterId); if (msaFolder == null) { ListItem rootFolder = SPHelper.GetRootFolderForUpload(targetFolderName, true); string rootFolderUrl = rootFolder["FileRef"].ToString(); int childFolders = SPHelper.GetChildFoldersCount(rootFolderUrl); if (childFolders < maxItems) { msaFolder = SPHelper.CreateFolder(rootFolder, rootFolderUrl, doc.MasterId); targetFolderName = doc.MasterId; } else { // CREATE NEXT PARENT FOLDER int currentIndex = rootFolderUrl.Substring(rootFolderUrl.LastIndexOf('_') + 1).ToInt(); string newRootFolderName = APISetting.GetString("CUSTOMER_FOLDER_PREFIX") + (++currentIndex).ToString(); SPHelper.CreateRootFolder(newRootFolderName); rootFolder = SPHelper.GetRootFolderForUpload(targetFolderName, true); rootFolderUrl = rootFolder["FileRef"].ToString(); msaFolder = SPHelper.CreateFolder(rootFolder, rootFolderUrl, doc.MasterId); targetFolderName = doc.MasterId; } } else { targetFolderName = doc.MasterId; } } File uploadedFile = SPHelper.UploadFile(fileName, targetFolderName, buffer); Common.SPHelper.AddRequiredDocumentProperties(uploadedFile, doc.MasterId, doc.MasterNumber, doc.MasterName, doc.DocumentType); fileId = new Guid(uploadedFile.ListItemAllFields["UniqueId"].ToString()); } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new KeyValuePair <string, string>("FileId", fileId.ToString())); return(response); }
public void UploadDocument(string relativeUrl, SharePointDocument doc) { //NOP }