/// <summary> /// Upload a file to the specific library/folder /// </summary> /// <param name="onlineLibrary"></param> /// <param name="onlineLibraryFolder"></param> /// <param name="onlineFileName"></param> /// <returns></returns> public static string UploadFile(this List onlineLibrary, string onlineLibraryFolder, string onlineFileName) { var relativeUrl = string.Empty; var fileName = System.IO.Path.GetFileName(onlineFileName); try { var webUri = new Uri(onlineLibrary.Context.Url); var currentFolder = GetOrCreateFolder(onlineLibrary, onlineLibrary.RootFolder, onlineLibraryFolder); var logFileItem = GetFileInFolder(onlineLibrary, currentFolder, fileName); if (logFileItem == null) { onlineLibrary.Context.Load(currentFolder, pf => pf.Name, pf => pf.Files, pf => pf.ServerRelativeUrl, pf => pf.TimeCreated); onlineLibrary.Context.ExecuteQuery(); using (var stream = new System.IO.FileStream(onlineFileName, System.IO.FileMode.Open)) { var creationInfo = new Microsoft.SharePoint.Client.FileCreationInformation(); creationInfo.Overwrite = true; creationInfo.ContentStream = stream; creationInfo.Url = fileName; var uploadStatus = currentFolder.Files.Add(creationInfo); onlineLibrary.Context.Load(uploadStatus, ups => ups.ServerRelativeUrl); onlineLibrary.Context.ExecuteQuery(); relativeUrl = uploadStatus.ServerRelativeUrl; } } else { onlineLibrary.Context.Load(logFileItem.File, ups => ups.ServerRelativeUrl); onlineLibrary.Context.ExecuteQuery(); relativeUrl = logFileItem.File.ServerRelativeUrl; } var assertedUri = new Uri(webUri, relativeUrl); relativeUrl = assertedUri.AbsoluteUri; } catch (Exception ex) { System.Diagnostics.Trace.TraceError("Failed to upload file {0} MSG:{1}", onlineFileName, ex.Message); } return(relativeUrl); }
/// <summary> /// Execute the command uploading the file to the root of the document library /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); try { LogVerbose("Entering Library Upload Cmdlet"); var ctx = this.ClientContext; var w = ctx.Web; var l = ctx.Web.Lists.GetByTitle(ListTitle); ctx.Load(w); ctx.Load(l, listEntity => listEntity.RootFolder.ServerRelativeUrl); ClientContext.ExecuteQueryRetry(); var serverRelativeUrl = string.Format("{0}/{1}", this.ClientContext.Url, l.RootFolder.ServerRelativeUrl); LogVerbose(string.Format("Context has been established for {0}", serverRelativeUrl)); var fileName = Path.GetFileName(this.FileName); using (var stream = new System.IO.FileStream(this.FileName, FileMode.Open)) { var creationInfo = new Microsoft.SharePoint.Client.FileCreationInformation(); creationInfo.Overwrite = true; creationInfo.ContentStream = stream; creationInfo.Url = fileName; var uploadStatus = l.RootFolder.Files.Add(creationInfo); ctx.Load(uploadStatus); ctx.ExecuteQuery(); } } catch (Exception ex) { LogError(ex, "Failed in SetFileUpload File:{0}", this.FileName); } }
/// <summary> /// Ajoute un Document dans sharepoint /// </summary> /// <param name="relativePath"></param> /// <param name="fileName"></param> /// <param name="fileContent"></param> /// <param name="metadatas"></param> /// <param name="completed"></param> public void CreateFile(string relativePath, string fileName, byte[] fileContent, Dictionary<string, object> metadatas, Action<Exception> completed) { Logger.Log(LogSeverity.Information, GetType().FullName, MethodBase.GetCurrentMethod().Name); ResetContext(); if (ContextClientSharePoint != null) { // Chargement de la liste ContextClientSharePoint.Load(SharepointList); ContextClientSharePoint.Load(SharepointList.RootFolder); ContextClientSharePoint.Load(SharepointList.RootFolder.Files); // Chargement des contentTypes ContentTypeCollection contentTypes = ContextClientSharePoint.Web.AvailableContentTypes; ContextClientSharePoint.Load(contentTypes); ContextClientSharePoint.ExecuteQueryAsync( (o, e) => { var ctid = from ct in contentTypes where ct.Name == "Proteca Document" select ct.Id; FileCreationInformation file = new Microsoft.SharePoint.Client.FileCreationInformation(); file.Content = fileContent; file.Overwrite = true; file.Url = relativePath + "/" + fileName; Microsoft.SharePoint.Client.File newFile = SharepointList.RootFolder.Files.Add(file); ContextClientSharePoint.Load(newFile); ListItem item = newFile.ListItemAllFields; ContextClientSharePoint.Load(item); foreach (var metadata in metadatas) { item[metadata.Key] = metadata.Value; } item["ContentTypeId"] = ctid; item.Update(); ContextClientSharePoint.ExecuteQueryAsync( (oo, ee) => { _syncCtxt.Post(unused => completed(null), null); }, (oo, ee) => { Logger.Log(LogSeverity.Error, this.GetType().FullName, ee.Exception); _syncCtxt.Post(unused => completed(ee.Exception), null); }); }, (o, e) => { Logger.Log(LogSeverity.Error, this.GetType().FullName, e.Exception); _syncCtxt.Post(unused => completed(e.Exception), null); } ); } else { var ex = new Exception(Resource.TypeDocument_SharepointContextError); Logger.Log(LogSeverity.Warning, this.GetType().FullName, ex); completed(ex); } }
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument) { var message = await argument; if (message.Attachments != null && message.Attachments.Any()) { var attachment = message.Attachments.First(); var attachmentUrl = message.Attachments[0].ContentUrl; var content = message.Attachments[0].Content; using (HttpClient httpClient = new HttpClient()) { try { var responseMessage = await httpClient.GetAsync(attachment.ContentUrl); var contentLenghtBytes = responseMessage.Content.Headers.ContentLength; var attachmentdata = await httpClient.GetByteArrayAsync(attachmentUrl); string siteUrl = Convert.ToString(ConfigurationManager.AppSettings["SiteUrl"]); string login = Convert.ToString(ConfigurationManager.AppSettings["ApplicationUserName"]); string password = Convert.ToString(ConfigurationManager.AppSettings["Password"]); string listName = Convert.ToString(ConfigurationManager.AppSettings["DocumentLib"]); var securePassword = new SecureString(); foreach (var c in password) { securePassword.AppendChar(c); } var credentials = new SP.SharePointOnlineCredentials(login, securePassword); SP.ClientContext clientContext = new SP.ClientContext(siteUrl); clientContext.Credentials = credentials; SP.List documentsList = clientContext.Web.Lists.GetByTitle(listName); var fileCreationInformation = new SP.FileCreationInformation(); //Assign to content byte[] i.e. documentStream fileCreationInformation.ContentStream = new MemoryStream(attachmentdata); //Allow owerwrite of document fileCreationInformation.Overwrite = true; //Upload URL fileCreationInformation.Url = siteUrl + "/" + listName + "/" + attachment.Name; SP.File uploadFile = documentsList.RootFolder.Files.Add( fileCreationInformation); uploadFile.ListItemAllFields.Update(); clientContext.ExecuteQuery(); SP.ListItem item = uploadFile.ListItemAllFields; string filenameWithoutExtension = Path.GetFileNameWithoutExtension(attachment.Name); item["Title"] = filenameWithoutExtension; item.Update(); clientContext.Load(item); clientContext.ExecuteQuery(); //of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received await context.PostAsync($"Thanks for submitting the attachement."); } catch (Exception ex) { } } } else { await context.PostAsync("Hi there! I'm a bot created to show you how I can receive message attachments, but no attachment was sent to me. Please, try again sending a new message including an attachment."); } context.Wait(this.MessageReceivedAsync); }
protected void Page_Load(object sender, EventArgs e) { // Read the data that has been posted connectedSiteUrl = Request.Form["connectedSiteUrl"]; accessToken = Request.Form["accessToken"]; refreshToken = Request.Form["refreshToken"]; // Note that the following form fields were set dynamically by JavaScript // to represent the data from the document to be translated and the target language string documentContent = string.Empty; string targetLanguage = string.Empty; documentContent = Request.Form["documentContent"]; targetLanguage = Request.Form["documentLanguage"]; try { using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(connectedSiteUrl, accessToken)) { // Use standard CSOM and OOXML approaches for creating a file Web thisWeb = context.Web; List docLib = thisWeb.Lists.GetByTitle("Documents"); Folder rootFolder = docLib.RootFolder; context.Load(thisWeb); context.Load(docLib); context.Load(rootFolder); context.ExecuteQuery(); FileStream fs = null; try { // We'll build a Word Document by using OOXML // Note that we'll first create it in a folder in this Web app. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(Server.MapPath("~/TempOOXML/SourceDocument.docx"), WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); // Create a paragraph based on the text that was posted // in Request.Form["documentContent"] Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(documentContent)); } // At this stage, the local file has been created in the folder of this Web project // so we'll now read it and create a new file in SharePoint, based on this local file. byte[] documentBytes; fs = System.IO.File.OpenRead(Server.MapPath("~/TempOOXML/SourceDocument.docx")); documentBytes = new byte[fs.Length]; fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length)); // At this stage, the file contents of the OOXML document has been read into the byte array // so we can use that as the content of a new file in SharePoint. Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile = new Microsoft.SharePoint.Client.FileCreationInformation(); ooxmlFile.Overwrite = true; ooxmlFile.Url = thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx"; ooxmlFile.Content = documentBytes; Microsoft.SharePoint.Client.File newFile = rootFolder.Files.Add(ooxmlFile); context.Load(newFile); context.ExecuteQuery(); success = true; } catch (Exception ex) { // Tell the user what went wrong. These variables will be used // to report the error to the user in the TextTranslator.aspx page. success = false; exception = ex; } finally { // Clean up our filestream object fs.Close(); } // Do the actual translation work. Note that we use a synchronous translation // approach here, but you could also use the TranslationJob object to // perform an asynchronous translation. if (success) { try { SyncTranslator job = new SyncTranslator(context, targetLanguage); job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; job.Translate( thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx", thisWeb.Url + rootFolder.ServerRelativeUrl + "/" + targetLanguage + "_Document.docx"); context.ExecuteQuery(); targetLibrary = thisWeb.Url + rootFolder.ServerRelativeUrl; } catch (Exception ex) { // Tell the user what went wrong. These variables will be used // to report the error to the user in the TextTranslator.aspx page. success = false; exception = ex; } } } } catch (Exception ex) { // Tell the user what went wrong. These variables will be used // to report the error to the user in the TextTranslator.aspx page. success = false; exception = ex; } }
/// <summary> /// Upload a file from disk to the specific <paramref name="onlineFolder"/> /// </summary> /// <param name="onlineLibrary"></param> /// <param name="onlineFolder"></param> /// <param name="fileNameWithPath"></param> /// <param name="clobber">(OPTIONAL) if true then overwrite the existing file</param> /// <exception cref="System.IO.FileNotFoundException">File not found if fullfilename does not exist</exception> /// <returns></returns> public static string UploadFile(this List onlineLibrary, Folder onlineFolder, string fileNameWithPath, bool clobber = false) { var relativeUrl = string.Empty; var fileName = System.IO.Path.GetFileName(fileNameWithPath); if (!System.IO.File.Exists(fileNameWithPath)) { throw new System.IO.FileNotFoundException(string.Format("File {0} does not exists on disk", fileNameWithPath)); } if (!onlineFolder.IsPropertyAvailable(fctx => fctx.ServerRelativeUrl)) { try { // setup processing of folder in the parent folder onlineFolder.Context.Load(onlineFolder, pf => pf.ServerRelativeUrl); onlineFolder.Context.ExecuteQueryRetry(); } catch (Exception ex) { System.Diagnostics.Trace.TraceError("Failed to ensure folder server relative url property MSG:{0}", ex.Message); } } var logFileItem = GetFileInFolder(onlineLibrary, onlineFolder, fileName); if (logFileItem == null || (clobber && logFileItem != null)) { onlineLibrary.Context.Load(onlineFolder, pf => pf.Name, pf => pf.Files, pf => pf.ServerRelativeUrl, pf => pf.TimeCreated); onlineLibrary.Context.ExecuteQueryRetry(); using (var stream = new System.IO.FileStream(fileNameWithPath, System.IO.FileMode.Open)) { var creationInfo = new Microsoft.SharePoint.Client.FileCreationInformation { Overwrite = clobber, ContentStream = stream, Url = fileName }; var uploadStatus = onlineFolder.Files.Add(creationInfo); onlineLibrary.Context.Load(uploadStatus, ups => ups.ServerRelativeUrl); onlineLibrary.Context.ExecuteQueryRetry(); relativeUrl = uploadStatus.ServerRelativeUrl; } } else { onlineLibrary.Context.Load(logFileItem.File, ups => ups.ServerRelativeUrl); onlineLibrary.Context.ExecuteQueryRetry(); relativeUrl = logFileItem.File.ServerRelativeUrl; } var webUri = new Uri(onlineFolder.Context.Url); var assertedUri = new Uri(webUri, relativeUrl); relativeUrl = assertedUri.AbsoluteUri; return(relativeUrl); }
/// <summary> /// Upload the specific file to the destination folder /// </summary> /// <param name="checkIn"></param> /// <param name="destinationFolder"></param> /// <param name="fileNameWithPath"></param> /// <returns></returns> private bool UploadFileToSharePointFolder(Microsoft.SharePoint.Client.Folder destinationFolder, string directoryPath) { // Retrieve the files in the directory var filesInDirectPath = System.IO.Directory.GetFiles(directoryPath, "*", System.IO.SearchOption.TopDirectoryOnly); if (filesInDirectPath.Count() > 0) { // Upload the file LogVerbose("Uploading directory {0} files", directoryPath); // For each file in the source folder being evaluated, call the UploadFile function to upload the file to the appropriate location foreach (var fileNameWithPath in filesInDirectPath) { try { var fileExists = false; var fileTags = string.Empty; var fileInfo = new System.IO.FileInfo(fileNameWithPath); // Notify the operator that the file is being uploaed to a specific location LogVerbose("Uploading file {0} to {1}", fileInfo.Name, destinationFolder.Name); try { var fileInFolder = destinationFolder.GetFile(fileInfo.Name); if (fileInFolder != null) { fileExists = true; LogVerbose("File {0} exists in the destination folder. Skip uploading file.....", fileInfo.Name); } } catch (Exception ex) { LogError(ex, "Failed check file {0} existance test.", fileInfo.Name); } if (!fileExists) { try { if (this.MetadataList.Any(md => md.FullPath == fileInfo.FullName)) { var distinctTags = this.MetadataList.Where(md => md.FullPath == fileInfo.FullName).Select(s => s.Tag).Distinct(); fileTags = string.Join(@";", distinctTags); } } catch (Exception ex) { LogDebugging("Failed to pull metadata from CSV file {0}", ex.Message); } using (var stream = new System.IO.FileStream(fileNameWithPath, System.IO.FileMode.Open)) { var creationInfo = new Microsoft.SharePoint.Client.FileCreationInformation(); creationInfo.Overwrite = true; creationInfo.ContentStream = stream; creationInfo.Url = fileInfo.Name; var uploadStatus = destinationFolder.Files.Add(creationInfo); if (!uploadStatus.IsPropertyAvailable("ListItemAllFields")) { this.ClientContext.Load(uploadStatus, w => w.ListItemAllFields); this.ClientContext.ExecuteQuery(); } if (!string.IsNullOrEmpty(fileTags)) { uploadStatus.ListItemAllFields["_Source"] = fileTags; } uploadStatus.ListItemAllFields[ConstantsListFields.Field_Modified] = fileInfo.LastWriteTime; uploadStatus.ListItemAllFields.SystemUpdate(); if (this.CheckIn) { this.ClientContext.Load(uploadStatus); this.ClientContext.ExecuteQuery(); if (uploadStatus.CheckOutType != Microsoft.SharePoint.Client.CheckOutType.None) { uploadStatus.CheckIn("Checked in by Administrator", Microsoft.SharePoint.Client.CheckinType.MajorCheckIn); } } this.ClientContext.Load(uploadStatus); this.ClientContext.ExecuteQuery(); } } } catch (Exception ex) { LogError(ex, "Failed in UploadFileToSharePointFolder destination {0} and file {1}", destinationFolder, fileNameWithPath); } } return(true); // Has Files } return(false); // No Files in Directory }
/// <summary> /// 文件上传 /// </summary> /// <param name="SiteUri">网站站点</param> /// <param name="UserName">用户名</param> /// <param name="PassWord">密码</param> /// <param name="Domain">域名</param> /// <param name="documentListName">文档名称</param> /// <param name="GZID">文档的ID号</param> /// <param name="documentListURL">文档的路径</param> public void UploadDocument(string SiteUri, string UserName, string PassWord, string Domain, string documentListName, int GZID, string documentListURL) { try { this.Dispatcher.BeginInvoke(new Action(() => { using (ol.ClientContext clientContext = new ol.ClientContext(SiteUri)) { clientContext.Credentials = new NetworkCredential(UserName, PassWord, Domain); ol.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName); clientContext.Load(documentsList); #region 载文件信息初始化(datagrid) this.DatagridInit(listDocuments); #endregion //后台工作者,实时更新ui控件值 BackgroundWorker worker = new BackgroundWorker(); //更新事件 worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); //更新完毕 worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); //BackgroundWorker.WorkerReportsProgress 获取或设置一个值,该值指示 BackgroundWorker 能否报告进度更新。 worker.WorkerReportsProgress = true; //后台工作者 worker.DoWork += (obj, e) => { fileParts.Clear(); ////根据文件总长度设置块的大小 if (((lonSize / 1024) / 500) < 200) //如果总文件数小于200个 { BURRFERLEN = 512000; } else { BURRFERLEN = 1024000; } #region 循环上传文件 for (int i = 0; i < listDocuments.Count; i++) { //每次上传一个文件更新一次 ((BackgroundWorker)obj).ReportProgress(i); var fileCreationInformation = new ol.FileCreationInformation(); //判断 文件的大小 #region 执行分块文件上传方法 if (listDocuments[i].BytFilebyte.Length >= PartLongh) { //分好块,得到sum块 int filepartCount = (int)Math.Ceiling((double)listDocuments[i].BytFilebyte.Length / BURRFERLEN); filePartAllCount += filepartCount; byte[] filePart = new byte[BURRFERLEN]; //byte[] partEnd; for (int k = 1; k <= filepartCount; k++) { //将文件块的名称添加到准备给后台传的参数里 fileParts.Add("TEMP" + (k - 1).ToString() + "_." + listDocuments[i].StrMingCheng); //最后一段 if (k == filepartCount) { filePart = new byte[listDocuments[i].BytFilebyte.Length - BURRFERLEN * (filepartCount - 1)]; Array.Copy(listDocuments[i].BytFilebyte, BURRFERLEN * (k - 1), filePart, 0, filePart.Length); } else if (k == 1) { Array.Copy(listDocuments[i].BytFilebyte, BURRFERLEN * (k - 1), filePart, 0, BURRFERLEN); } else { Array.Copy(listDocuments[i].BytFilebyte, BURRFERLEN * (k - 1), filePart, 0, BURRFERLEN); } #region `fileCreationInformation设置 //文件流 fileCreationInformation.Content = filePart; //允许文档覆盖 fileCreationInformation.Overwrite = true; //文件名称 fileCreationInformation.Url = SiteUri + documentListURL + GZID + "/" + "TEMP" + (k - 1).ToString() + "_." + listDocuments[i].StrMingCheng; #endregion //加载并更新列表 clientContext.Load(documentsList); clientContext.ExecuteQuery(); //生成加载文件 ol.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation); //加载并更新文件 clientContext.Load(uploadFile); clientContext.ExecuteQuery(); } } #endregion #region 执行小文件直接上传方法 else //小于3M直接提交 { //指定内容 byte[]数组,这里是 documentStream fileCreationInformation.Content = listDocuments[i].BytFilebyte; //允许文档覆盖 fileCreationInformation.Overwrite = true; //文件名称 fileCreationInformation.Url = SiteUri + documentListURL + GZID + "/" + "txddd" + "_" + TimeNow + "_" + listDocuments[i].StrMingCheng; //加载并更新列表 clientContext.Load(documentsList); clientContext.ExecuteQuery(); //生成加载文件 ol.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation); //加载并更新文件 clientContext.Load(uploadFile); clientContext.ExecuteQuery(); } #endregion } #endregion //通过判断上传文件中是否有大于1M的文件,决定是否启用大文件合并方法 #region 完成后处理情况 if (fileParts.Count > 0) { Thread thread附件合并 = new Thread(SumFile); //根据文件大小判断 阻塞时间 int s = fileParts.Count / PartLongh; Thread.Sleep(s * 1000); thread附件合并.Start(); } else //没有大文件 { //调用完成设置信息 并同时调用 设置isFirst方法 SetInfo(); } #endregion }; //后台工作者开始工作(开始执行DoWork) worker.RunWorkerAsync(); } })); } catch (Exception ex) { MethodLb.CreateLog(this.GetType().FullName, "UploadDocument", ex.ToString(), SiteUri, UserName, PassWord, Domain, documentListName, GZID, documentListURL); } finally { } }
public void Upload() { try { using (context = new MSC.ClientContext(sharePointSite)) { SecureString s = new SecureString(); //s. MSC.SharePointOnlineCredentials cred = new MSC.SharePointOnlineCredentials(ConfigurationManager.AppSettings["UsrName"], getPassword(ConfigurationManager.AppSettings["PassWord"])); context.Credentials = cred; var list = context.Web.Lists.GetByTitle(documentLibraryName); context.Load(list); var root = list.RootFolder; context.Load(root); context.ExecuteQuery(); // ADDITION string SourceDocPath = ConfigurationManager.AppSettings["SourceDocsPath"]; DirectoryInfo dInfo = new DirectoryInfo(SourceDocPath); FileInfo[] ListofFiles = dInfo.GetFiles(); List <linkIdentifier> listofLinks = new List <linkIdentifier>(); XmlDocument doc = new XmlDocument(); doc.Load("Links.xml"); XmlNodeList listXml = doc.GetElementsByTagName("link"); foreach (XmlNode n1 in listXml) { linkIdentifier id = new linkIdentifier(); id.rowIndex = Convert.ToInt32(n1["rowIndex"].InnerText); id.colIndex = Convert.ToInt32(n1["colIndex"].InnerText); id.SheetName = n1["SheetName"].InnerText; listofLinks.Add(id); } foreach (FileInfo fileInstance in ListofFiles) { bool IsgoodLink = false; string path = fileInstance.FullName; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = excel.Workbooks.Open(path); //***********************LINK CHECK***************************************** //Read the first cell foreach (linkIdentifier identifier in listofLinks) { Worksheet excelSheet = wb.Sheets[identifier.SheetName]; string test = excelSheet.Cells[identifier.rowIndex, identifier.colIndex].Formula; test = test.Split(',')[0].TrimEnd("\"".ToCharArray()); String[] pathList = test.Split('/'); try { if (test.Contains(".aspx")) { //LinkCheck(test); IsgoodLink = CheckLink(pathList, cred); } else { IsgoodLink = CheckLink(pathList, cred); } } catch (MSC.ServerException e) { if (e.ServerErrorTypeName == "System.IO.FileNotFoundException") { IsgoodLink = false; } wb.Close(); IsgoodLink = false; } if (IsgoodLink == false) { Console.WriteLine("File {0} is having deadlinks.", fileInstance.Name); wb.Close(); return; } } wb.Close(); //***********************LINK CHECK***************************************** string tempdir = fileInstance.Name; tempdir = tempdir.Substring("2019.craft ".Length); tempdir = tempdir.Trim(' '); tempdir = tempdir.Remove((tempdir.Length - ".xlsm".Length)); String ParentDirectoryName = tempdir.Split('-')[0]; ParentDirectoryName = ParentDirectoryName.Trim(); string ChildDirectoryName = tempdir.Split('-')[1]; ChildDirectoryName = ChildDirectoryName.Trim(); try { MSC.ListItemCreationInformation information = new MSC.ListItemCreationInformation(); string targetFolder = ConfigurationManager.AppSettings["RootFolder"]; if (ConfigurationManager.AppSettings["Testing"] == "1") { targetFolder = ConfigurationManager.AppSettings["RootFolderTest"]; } ; information.FolderUrl = list.RootFolder.ServerRelativeUrl + targetFolder + ParentDirectoryName; MSC.Folder parentFolder = list.RootFolder.Folders.Add(information.FolderUrl); context.Load(parentFolder); context.ExecuteQuery(); information.FolderUrl = information.FolderUrl + "/" + ChildDirectoryName; MSC.Folder childDirectory = list.RootFolder.Folders.Add(information.FolderUrl); context.Load(childDirectory); context.ExecuteQuery(); if (IsgoodLink) { string filePath = fileInstance.FullName; FileStream documentStream = System.IO.File.OpenRead(filePath); byte[] info = new byte[documentStream.Length]; documentStream.Read(info, 0, (int)documentStream.Length); string fileURL = information.FolderUrl + "/" + fileInstance.Name; MSC.FileCreationInformation fileCreationInformation = new MSC.FileCreationInformation(); fileCreationInformation.Overwrite = true; fileCreationInformation.Content = info; fileCreationInformation.Url = fileURL; try { Microsoft.SharePoint.Client.File f = context.Web.GetFileByServerRelativeUrl(fileURL); context.Load(f); context.ExecuteQuery(); f.CheckOut(); } catch (Microsoft.SharePoint.Client.ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { Console.WriteLine("File is not found for Checkout"); } } Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(fileCreationInformation); uploadFile.CheckIn("Improvement Plan", MSC.CheckinType.MajorCheckIn); context.Load(uploadFile, w => w.MajorVersion, w => w.MinorVersion); context.ExecuteQuery(); Console.WriteLine("Document {0} is uploaded and checked in into SharePoint", fileURL); } } catch (Exception e) { Console.WriteLine(e.Message); } } } } catch (Exception ex) { new EventLog().WriteEntry(ex.Message, EventLogEntryType.Error); return; } }
protected void Page_Load(object sender, EventArgs e) { // Read the data that has been posted connectedSiteUrl = Request.Form["connectedSiteUrl"]; accessToken = Request.Form["accessToken"]; refreshToken = Request.Form["refreshToken"]; // Note that the following form fields were set dynamically by JavaScript // to represent the data from the document to be translated and the target language string documentContent = string.Empty; string targetLanguage = string.Empty; documentContent = Request.Form["documentContent"]; targetLanguage = Request.Form["documentLanguage"]; try { using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(connectedSiteUrl, accessToken)) { // Use standard CSOM and OOXML approaches for creating a file Web thisWeb = context.Web; List docLib = thisWeb.Lists.GetByTitle("Documents"); Folder rootFolder = docLib.RootFolder; context.Load(thisWeb); context.Load(docLib); context.Load(rootFolder); context.ExecuteQuery(); FileStream fs = null; try { // We'll build a Word Document by using OOXML // Note that we'll first create it in a folder in this Web app. using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(Server.MapPath("~/TempOOXML/SourceDocument.docx"), WordprocessingDocumentType.Document)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure. mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); // Create a paragraph based on the text that was posted // in Request.Form["documentContent"] Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text(documentContent)); } // At this stage, the local file has been created in the folder of this Web project // so we'll now read it and create a new file in SharePoint, based on this local file. byte[] documentBytes; fs = System.IO.File.OpenRead(Server.MapPath("~/TempOOXML/SourceDocument.docx")); documentBytes = new byte[fs.Length]; fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length)); // At this stage, the file contents of the OOXML document has been read into the byte array // so we can use that as the content of a new file in SharePoint. Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile = new Microsoft.SharePoint.Client.FileCreationInformation(); ooxmlFile.Overwrite = true; ooxmlFile.Url = thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx"; ooxmlFile.Content = documentBytes; Microsoft.SharePoint.Client.File newFile = rootFolder.Files.Add(ooxmlFile); context.Load(newFile); context.ExecuteQuery(); success = true; } catch (Exception ex) { // Tell the user what went wrong. These variables will be used // to report the error to the user in the TextTranslator.aspx page. success = false; exception = ex; } finally { // Clean up our filestream object fs.Close(); } // Do the actual translation work. Note that we use a synchronous translation // approach here, but you could also use the TranslationJob object to // perform an asynchronous translation. if (success) { try { SyncTranslator job = new SyncTranslator(context, targetLanguage); job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite; job.Translate( thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx", thisWeb.Url + rootFolder.ServerRelativeUrl + "/" + targetLanguage + "_Document.docx"); context.ExecuteQuery(); targetLibrary = thisWeb.Url + rootFolder.ServerRelativeUrl; } catch (Exception ex) { // Tell the user what went wrong. These variables will be used // to report the error to the user in the TextTranslator.aspx page. success = false; exception = ex; } } } } catch (Exception ex) { // Tell the user what went wrong. These variables will be used // to report the error to the user in the TextTranslator.aspx page. success = false; exception = ex; } }