Пример #1
0
        protected string GetAvailableTitle(string requestTitle, Folder parentFolderID, Func <string, Folder, bool> isExist)
        {
            if (!isExist(requestTitle, parentFolderID))
            {
                return(requestTitle);
            }

            var re    = new Regex(@"( \(((?<index>[0-9])+)\)(\.[^\.]*)?)$");
            var match = re.Match(requestTitle);

            if (!match.Success)
            {
                var insertIndex = requestTitle.Length;
                if (requestTitle.LastIndexOf(".", StringComparison.Ordinal) != -1)
                {
                    insertIndex = requestTitle.LastIndexOf(".", StringComparison.Ordinal);
                }
                requestTitle = requestTitle.Insert(insertIndex, " (1)");
            }

            while (isExist(requestTitle, parentFolderID))
            {
                requestTitle = re.Replace(requestTitle, MatchEvaluator);
            }
            return(requestTitle);
        }
Пример #2
0
 private Microsoft.SharePoint.Client.Folder OpenBaseFolder(Microsoft.SharePoint.Client.ClientContext Context)
 {
     // Open Base Folder
     Microsoft.SharePoint.Client.Folder SPBaseFolder = Context.Web.RootFolder;
     Context.Load(SPBaseFolder);
     Context.ExecuteQuery();
     return(SPBaseFolder);
 }
        public void Execute(string absoluteNativePath, SPFolder folder, Action <FileSystemOperation> operation)
        {
            var ctx = folder.Context;

            ctx.Load(folder, f => f.ServerRelativeUrl);
            ctx.ExecuteQuery();

            var nativeFileVisitor           = new List <FileSystemEntry>();
            Action <FileSystemInfo> visitor = f =>
                                              nativeFileVisitor.Add(new FileSystemEntry
            {
                SystemPath     = f.FullName,
                LastModifiedAt = f.LastWriteTimeUtc,
                NormalizedPath = f.FullName.Replace(absoluteNativePath + "\\", "").Replace("\\", "/"),
            });

            var             sharePointFilesVisitor = new List <FileSystemEntry>();
            Action <SPFile> sharePointFileVisitor  = f =>
            {
                var normalizedPath = f.ServerRelativeUrl.Replace(folder.ServerRelativeUrl + "/", "");
                if (normalizedPath.StartsWith("Forms"))
                {
                    return;
                }

                sharePointFilesVisitor.Add(new FileSystemEntry
                {
                    SystemPath     = f.ServerRelativeUrl,
                    LastModifiedAt = f.TimeLastModified,
                    NormalizedPath = normalizedPath
                });
            };

            new RecursiveNativeFolderVisitor(Logger).Execute(absoluteNativePath, visitor);
            new RecursiveSharePointFolderVisitor(Logger).Execute(folder, sharePointFileVisitor);

            var toDelete = sharePointFilesVisitor.Except(nativeFileVisitor);
            var toCopy   = nativeFileVisitor.Except(sharePointFilesVisitor);

            toDelete.ToList().ForEach(fsi =>
            {
                operation(new FileSystemOperation
                {
                    Kind    = OperationKind.Delete,
                    Operand = fsi
                });
            });

            toCopy.ToList().ForEach(fsi =>
            {
                operation(new FileSystemOperation
                {
                    Kind    = OperationKind.Copy,
                    Operand = fsi
                });
            });
        }
        public void Execute(string absoluteNativePath, SPFolder folder, Action<FileSystemOperation> operation)
        {
            var ctx = folder.Context;
            ctx.Load(folder, f => f.ServerRelativeUrl);
            ctx.ExecuteQuery();

            var nativeFileVisitor = new List<FileSystemEntry>();
            Action<FileSystemInfo> visitor = f =>
                nativeFileVisitor.Add(new FileSystemEntry
                {
                    SystemPath = f.FullName,
                    LastModifiedAt = f.LastWriteTimeUtc,
                    NormalizedPath = f.FullName.Replace(absoluteNativePath + "\\", "").Replace("\\", "/"),
                });

            var sharePointFilesVisitor = new List<FileSystemEntry>();
            Action<SPFile> sharePointFileVisitor = f =>
            {
                var normalizedPath = f.ServerRelativeUrl.Replace(folder.ServerRelativeUrl + "/", "");
                if (normalizedPath.StartsWith("Forms"))
                {
                    return;
                }

                sharePointFilesVisitor.Add(new FileSystemEntry
                {
                    SystemPath = f.ServerRelativeUrl,
                    LastModifiedAt = f.TimeLastModified,
                    NormalizedPath = normalizedPath
                });
            };

            new RecursiveNativeFolderVisitor(Logger).Execute(absoluteNativePath, visitor);
            new RecursiveSharePointFolderVisitor(Logger).Execute(folder, sharePointFileVisitor);

            var toDelete = sharePointFilesVisitor.Except(nativeFileVisitor);
            var toCopy = nativeFileVisitor.Except(sharePointFilesVisitor);

            toDelete.ToList().ForEach(fsi =>
            {
                operation(new FileSystemOperation
                {
                    Kind = OperationKind.Delete,
                    Operand = fsi
                });
            });

            toCopy.ToList().ForEach(fsi =>
            {
                operation(new FileSystemOperation
                {
                    Kind = OperationKind.Copy,
                    Operand = fsi
                });
            });
        }
Пример #5
0
        private Microsoft.SharePoint.Client.Folder OpenFolder(Microsoft.SharePoint.Client.ClientContext Context, Microsoft.SharePoint.Client.Folder BaseFolder, String Name)
        {
            Microsoft.SharePoint.Client.Folder SPRootFolder = null;

            try
            {
                // Ensure SPRootFolder Exists
                SPRootFolder = BaseFolder.Folders.GetByUrl(Name);
                Context.Load(SPRootFolder);
                Context.ExecuteQuery();
            }
            catch (Microsoft.SharePoint.Client.ServerException)
            {
                // CreateSPRoot Folder
                SPRootFolder = BaseFolder.Folders.Add(Name);
                Context.Load(SPRootFolder);
                Context.ExecuteQuery();
            }

            return(SPRootFolder);
        }
Пример #6
0
        protected String GetAvailableTitle(String requestTitle, Folder parentFolderID, Func<string, Folder, bool> isExist)
        {
            if (!isExist(requestTitle, parentFolderID)) return requestTitle;

            var re = new Regex(@"( \(((?<index>[0-9])+)\)(\.[^\.]*)?)$");
            var match = re.Match(requestTitle);

            if (!match.Success)
            {
                var insertIndex = requestTitle.Length;
                if (requestTitle.LastIndexOf(".", StringComparison.Ordinal) != -1)
                {
                    insertIndex = requestTitle.LastIndexOf(".", StringComparison.Ordinal);
                }
                requestTitle = requestTitle.Insert(insertIndex, " (1)");
            }

            while (isExist(requestTitle, parentFolderID))
            {
                requestTitle = re.Replace(requestTitle, MatchEvaluator);
            }
            return requestTitle;
        }
Пример #7
0
        private void Download()
        {
            byte[] buffer   = new byte[buffersize];
            int    sizeread = 0;

            while (true)
            {
                try
                {
                    this.Log.Add(plmOS.Logging.Log.Levels.DEB, "Starting to download from SharePoint: " + this.URL);

                    using (Microsoft.SharePoint.Client.ClientContext SPContext = new Microsoft.SharePoint.Client.ClientContext(this.SiteURL.AbsoluteUri))
                    {
                        SPContext.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(this.Username, this.Password);

                        // Open Base Folder
                        Microsoft.SharePoint.Client.Folder SPBaseFolder = this.OpenBaseFolder(SPContext);

                        // Open Supplier Folder
                        Microsoft.SharePoint.Client.Folder SPSupplierFolder = this.OpenFolder(SPContext, SPBaseFolder, this.SupplierID);

                        // Open Project Folder
                        Microsoft.SharePoint.Client.Folder SPProjectFolder = this.OpenFolder(SPContext, SPSupplierFolder, this.ProjectID);

                        // Open Root Folder
                        Microsoft.SharePoint.Client.Folder SPRootFolder = this.OpenFolder(SPContext, SPProjectFolder, "Database");

                        // Get Listing of Transaction files on SharePoint
                        SPContext.Load(SPRootFolder.Files);
                        SPContext.ExecuteQuery();

                        // Create list of comitted Transactions
                        List <Int64> committedtransactions = new List <Int64>();

                        foreach (Microsoft.SharePoint.Client.File transactionfile in SPRootFolder.Files)
                        {
                            Int64 transactiondate = -1;

                            if (Path.GetExtension(transactionfile.Name).ToLower() == ".comitted")
                            {
                                if (Int64.TryParse(Path.GetFileNameWithoutExtension(transactionfile.Name), out transactiondate))
                                {
                                    if (!committedtransactions.Contains(transactiondate))
                                    {
                                        committedtransactions.Add(transactiondate);
                                    }
                                }
                            }
                        }

                        // Create List of Transactions that need to be Downloaded
                        List <Microsoft.SharePoint.Client.File> tobedownlaoded = new List <Microsoft.SharePoint.Client.File>();

                        foreach (Microsoft.SharePoint.Client.File transactionfile in SPRootFolder.Files)
                        {
                            Int64 transactiondate = -1;

                            if (Path.GetExtension(transactionfile.Name).ToLower() == ".zip")
                            {
                                if (Int64.TryParse(Path.GetFileNameWithoutExtension(transactionfile.Name), out transactiondate))
                                {
                                    if (committedtransactions.Contains(transactiondate))
                                    {
                                        if (!this.Downloaded.Contains(transactiondate))
                                        {
                                            tobedownlaoded.Add(transactionfile);
                                        }
                                    }
                                }
                            }
                        }

                        if (tobedownlaoded.Count > 0)
                        {
                            this.ReadingTotal  = tobedownlaoded.Count;
                            this.ReadingNumber = 0;
                            this.Reading       = true;

                            foreach (Microsoft.SharePoint.Client.File transactionfile in tobedownlaoded)
                            {
                                Int64 transactiondate = -1;

                                if (Int64.TryParse(Path.GetFileNameWithoutExtension(transactionfile.Name), out transactiondate))
                                {
                                    if (!this.Downloaded.Contains(transactiondate))
                                    {
                                        // Check if Transaction Folder Exists in Local Cache
                                        Boolean downloadneeded = true;

                                        DirectoryInfo localtransactionfolder    = new DirectoryInfo(this.LocalRootFolder.FullName + "\\" + transactiondate.ToString());
                                        DirectoryInfo localtransactiontmpfolder = new DirectoryInfo(this.LocalRootFolder.FullName + "\\" + transactiondate.ToString() + ".download");
                                        FileInfo      committed = new FileInfo(localtransactionfolder.FullName + "\\committed");

                                        if (localtransactionfolder.Exists)
                                        {
                                            if (committed.Exists)
                                            {
                                                downloadneeded = false;
                                            }
                                        }
                                        else
                                        {
                                            localtransactionfolder.Create();
                                        }

                                        if (downloadneeded)
                                        {
                                            // Download Transaction File from SharePoint
                                            FileInfo localtransactionfile = new FileInfo(this.LocalRootFolder.FullName + "\\" + transactionfile.Name);
                                            Microsoft.SharePoint.Client.FileInformation transactionfileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(SPContext, transactionfile.ServerRelativeUrl);

                                            using (FileStream sw = System.IO.File.OpenWrite(localtransactionfile.FullName))
                                            {
                                                using (transactionfileInfo.Stream)
                                                {
                                                    while ((sizeread = transactionfileInfo.Stream.Read(buffer, 0, buffersize)) > 0)
                                                    {
                                                        sw.Write(buffer, 0, sizeread);
                                                    }
                                                }
                                            }

                                            // Extract files from ZIP File
                                            if (!localtransactiontmpfolder.Exists)
                                            {
                                                localtransactiontmpfolder.Create();
                                            }
                                            else
                                            {
                                                foreach (FileInfo file in localtransactiontmpfolder.GetFiles())
                                                {
                                                    file.Delete();
                                                }
                                            }

                                            ZipFile.ExtractToDirectory(localtransactionfile.FullName, localtransactiontmpfolder.FullName);

                                            // Move XML Files to Transaction Directory
                                            foreach (FileInfo tmpxmlfile in localtransactiontmpfolder.GetFiles("*.xml"))
                                            {
                                                FileInfo xmlfile = new FileInfo(localtransactionfolder.FullName + "\\" + tmpxmlfile.Name);

                                                if (xmlfile.Exists)
                                                {
                                                    xmlfile.Delete();
                                                    xmlfile.Refresh();
                                                }

                                                tmpxmlfile.MoveTo(xmlfile.FullName);
                                            }

                                            // Move Vault Files to Vault
                                            foreach (FileInfo tmpvaultfile in localtransactiontmpfolder.GetFiles("*.dat"))
                                            {
                                                FileInfo vaultfile = new FileInfo(this.LocalVaultFolder.FullName + "\\" + tmpvaultfile.Name);

                                                if (vaultfile.Exists)
                                                {
                                                    vaultfile.Delete();
                                                    vaultfile.Refresh();
                                                }

                                                tmpvaultfile.MoveTo(vaultfile.FullName);
                                            }

                                            // Delete Temp Folder
                                            localtransactiontmpfolder.Delete(true);

                                            // Delete ZIP File
                                            localtransactionfile.Delete();

                                            // Create Committ File
                                            committed.Create();

                                            this.Downloaded.Add(transactiondate);
                                        }
                                        else
                                        {
                                            this.Downloaded.Add(transactiondate);
                                        }
                                    }
                                }

                                this.ReadingNumber++;
                            }

                            this.Reading       = false;
                            this.ReadingTotal  = 0;
                            this.ReadingNumber = 0;
                        }

                        // Set Initialised to true once done one Sync
                        if (!this.Initialised)
                        {
                            // Set to Initialised
                            this.Initialised = true;

                            // Start Upload
                            this.UploadThread = new Thread(this.Upload);
                            this.UploadThread.IsBackground = true;
                            this.UploadThread.Start();
                        }
                    }
                }
                catch (Exception e)
                {
                    this.Log.Add(plmOS.Logging.Log.Levels.ERR, "SharePoint download failed: " + e.Message);
                    this.Log.Add(plmOS.Logging.Log.Levels.DEB, "SharePoint download failed: " + e.Message + Environment.NewLine + e.StackTrace);
                }

                // Delay to next check
                Thread.Sleep(this.SyncDelay * 1000);
            }
        }
Пример #8
0
        private void Upload()
        {
            while (true)
            {
                try
                {
                    this.WritingTotal  = this.UploadQueue.Count;
                    this.WritingNumber = 0;

                    while (this.UploadQueue.Count > 0)
                    {
                        this.Writing = true;
                        this.WritingNumber++;

                        this.Log.Add(plmOS.Logging.Log.Levels.DEB, "Starting to upload to SharePoint: " + this.URL);

                        Int64 transactiondate = -1;

                        if (this.UploadQueue.TryPeek(out transactiondate))
                        {
                            DirectoryInfo transactiondir = new DirectoryInfo(this.LocalRootFolder.FullName + "\\" + transactiondate.ToString());

                            FileInfo committed = new FileInfo(transactiondir.FullName + "\\committed");

                            if (committed.Exists)
                            {
                                using (Microsoft.SharePoint.Client.ClientContext SPContext = new Microsoft.SharePoint.Client.ClientContext(this.SiteURL.AbsoluteUri))
                                {
                                    SPContext.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(this.Username, this.Password);

                                    // Open Base Folder
                                    Microsoft.SharePoint.Client.Folder SPBaseFolder = this.OpenBaseFolder(SPContext);

                                    // Open Supplier Folder
                                    Microsoft.SharePoint.Client.Folder SPSupplierFolder = this.OpenFolder(SPContext, SPBaseFolder, this.SupplierID);

                                    // Open Project Folder
                                    Microsoft.SharePoint.Client.Folder SPProjectFolder = this.OpenFolder(SPContext, SPSupplierFolder, this.ProjectID);

                                    // Open Root Folder
                                    Microsoft.SharePoint.Client.Folder SPRootFolder = this.OpenFolder(SPContext, SPProjectFolder, "Database");

                                    // Check for Transaction File on SharePoint
                                    SPContext.Load(SPRootFolder.Files);
                                    SPContext.ExecuteQuery();

                                    Boolean committedexists = false;

                                    foreach (Microsoft.SharePoint.Client.File spfile in SPRootFolder.Files)
                                    {
                                        if (spfile.Name == transactiondate.ToString() + ".committed")
                                        {
                                            committedexists = true;
                                            break;
                                        }
                                    }

                                    if (!committedexists)
                                    {
                                        // Create Temp Folder
                                        DirectoryInfo tmptransactiondir = new DirectoryInfo(transactiondir.FullName + ".upload");

                                        if (tmptransactiondir.Exists)
                                        {
                                            foreach (FileInfo file in tmptransactiondir.GetFiles())
                                            {
                                                file.Delete();
                                            }
                                        }
                                        else
                                        {
                                            tmptransactiondir.Create();
                                        }

                                        // Copy XML Files and Vault Files to temp folder
                                        foreach (FileInfo xmlfile in transactiondir.GetFiles("*.xml"))
                                        {
                                            if (xmlfile.Name.EndsWith(".file.xml"))
                                            {
                                                // Copy Vault File
                                                FileInfo vaultfile = new FileInfo(this.LocalVaultFolder.FullName + "\\" + xmlfile.Name.Replace(".file.xml", ".dat"));
                                                vaultfile.CopyTo(tmptransactiondir.FullName + "\\" + vaultfile.Name);
                                            }

                                            xmlfile.CopyTo(tmptransactiondir.FullName + "\\" + xmlfile.Name);
                                        }

                                        // Create ZIP File
                                        FileInfo transactionzipfile = new FileInfo(transactiondir.FullName + ".zip");

                                        if (transactionzipfile.Exists)
                                        {
                                            transactionzipfile.Delete();
                                        }

                                        ZipFile.CreateFromDirectory(tmptransactiondir.FullName, transactionzipfile.FullName);

                                        // Upload ZIP File
                                        using (FileStream sr = System.IO.File.OpenRead(transactionzipfile.FullName))
                                        {
                                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPContext, SPRootFolder.ServerRelativeUrl + "/" + transactionzipfile.Name, sr, true);
                                        }

                                        // Upload Comitted File
                                        using (FileStream sr = System.IO.File.OpenRead(committed.FullName))
                                        {
                                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPContext, SPRootFolder.ServerRelativeUrl + "/" + Path.GetFileNameWithoutExtension(transactionzipfile.Name) + ".comitted", sr, true);
                                        }

                                        // Delete ZIP File
                                        transactionzipfile.Delete();

                                        // Delete Temp Folder
                                        tmptransactiondir.Delete(true);
                                    }

                                    // Completed - remove Transaction from Queue
                                    this.UploadQueue.TryDequeue(out transactiondate);
                                }
                            }
                        }

                        this.Writing = false;
                    }
                }
                catch (Exception e)
                {
                    this.Log.Add(plmOS.Logging.Log.Levels.ERR, "SharePoint upload failed: " + e.Message);
                    this.Writing = false;
                }

                // Sleep
                Thread.Sleep(500);
            }
        }
Пример #9
0
 public bool IsExist(string title, Microsoft.SharePoint.Client.Folder folder)
 {
     return(ProviderInfo.GetFolderFolders(folder.ServerRelativeUrl)
            .Any(item => item.Name.Equals(title, StringComparison.InvariantCultureIgnoreCase)));
 }
 public bool IsExist(string title, Microsoft.SharePoint.Client.Folder folder)
 {
     return(ProviderInfo.GetFolderFolders(folder.ServerRelativeUrl).FirstOrDefault(x => x.Name.Contains(title)) != null);
 }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // The following code gets the client context that represents the host web.
            var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

            // Because this is a provider-hosted app, SharePoint will pass in the host Url in the querystring.
            // Therefore, we'll retrieve it so that we can use it in GetClientContextWithContextToken method call
            var hostWeb = Page.Request["SPHostUrl"];

            // Then we'll build our context, exactly as implemented in the Visual Studio template for provider-hosted apps
            using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
            {
                // Now we will use some pretty standard CSOM operations to enumerate the
                // document libraries in the host web...
                Microsoft.SharePoint.Client.Web            hostedWeb = clientContext.Web;
                Microsoft.SharePoint.Client.ListCollection libs      = hostedWeb.Lists;
                clientContext.Load(hostedWeb);
                clientContext.Load(libs);
                clientContext.ExecuteQuery();
                var foundFiles = false;
                foreach (Microsoft.SharePoint.Client.List lib in libs)
                {
                    if (lib.BaseType == Microsoft.SharePoint.Client.BaseType.DocumentLibrary)
                    {
                        // ... and for each document library we'll enumerate all the Office files that
                        // may exist in the root folder of each library.
                        Microsoft.SharePoint.Client.Folder         folder = lib.RootFolder;
                        Microsoft.SharePoint.Client.FileCollection files  = folder.Files;
                        clientContext.Load(folder);
                        clientContext.Load(files);
                        clientContext.ExecuteQuery();
                        foreach (Microsoft.SharePoint.Client.File file in files)
                        {
                            if ((file.ServerRelativeUrl.ToLower().EndsWith(".docx")) ||
                                (file.ServerRelativeUrl.ToLower().EndsWith(".xlsx")) ||
                                (file.ServerRelativeUrl.ToLower().EndsWith(".pptx"))
                                )
                            {
                                // We know that we have at least one file, so we'll set the foundFiles variable to true
                                foundFiles = true;
                                // Then, for each Office file, we'll build a tile in the UI and set its style to an
                                // appropriate style that we have defined in point8020metro.css.
                                Panel fileItem = new Panel();
                                if (file.ServerRelativeUrl.ToLower().EndsWith(".docx"))
                                {
                                    fileItem.CssClass = "tile tileWord fl";
                                }
                                if (file.ServerRelativeUrl.ToLower().EndsWith(".xlsx"))
                                {
                                    fileItem.CssClass = "tile tileExcel fl";
                                }
                                if (file.ServerRelativeUrl.ToLower().EndsWith(".pptx"))
                                {
                                    fileItem.CssClass = "tile tilePowerPoint fl";
                                }
                                // Then we'll add text to the tile to represent the name of the file
                                fileItem.Controls.Add(new LiteralControl(file.Name));

                                // And now we'll add a custom-styled link for opening the file in 'View' mode
                                // in the Office Web Access Companion
                                HyperLink fileView = new HyperLink();
                                fileView.CssClass    = "tileBodyView";
                                fileView.Text        = "";
                                fileView.ToolTip     = "View in browser";
                                fileView.Target      = "_blank";
                                fileView.Width       = new Unit(125);
                                fileView.NavigateUrl = hostedWeb.Url + "/_layouts/15/WopiFrame.aspx?sourcedoc=" + file.ServerRelativeUrl + "&action=view&source=" + hostedWeb.Url + file.ServerRelativeUrl;

                                // And finally we'll add a custom-styled link for opening the file in 'Edit' mode
                                // in the Office Web Access Companion
                                HyperLink fileEdit = new HyperLink();
                                fileEdit.CssClass    = "tileBodyEdit";
                                fileEdit.Text        = "";
                                fileEdit.ToolTip     = "Edit in browser";
                                fileEdit.Target      = "_blank";
                                fileEdit.Width       = new Unit(125);
                                fileEdit.NavigateUrl = hostedWeb.Url + "/_layouts/15/WopiFrame.aspx?sourcedoc=" + file.ServerRelativeUrl + "&action=edit&source=" + hostedWeb.Url + file.ServerRelativeUrl;

                                fileItem.Controls.Add(new LiteralControl("<br/>"));
                                fileItem.Controls.Add(fileView);
                                fileItem.Controls.Add(new LiteralControl("<br/>"));
                                fileItem.Controls.Add(fileEdit);
                                FileList.Controls.Add(fileItem);
                            }
                        }
                    }
                }
                SiteTitle.Text = "Office Web Access: " + hostedWeb.Title;
                // If no videos have been found, build a red tile to inform the user
                if (!foundFiles)
                {
                    LiteralControl noItems = new LiteralControl("<div id='" + Guid.NewGuid()
                                                                + "' class='tile tileRed fl'>There are no Office files in the parent Web</div>");
                    FileList.Controls.Add(noItems);
                }
            }
        }
Пример #12
0
 /// <summary>
 /// Initializes the new instance of <see cref="SPClient.SPClientListItemConvertPipeBind"/> class.
 /// </summary>
 /// <param name="folder">the folder which converts to a list item.</param>
 public SPClientListItemConvertPipeBind(Microsoft.SharePoint.Client.Folder folder)
 {
     this.ClientObject = folder;
 }
        protected void CreateDocumentLink_Click(object sender, EventArgs e)
        {
            FileStream fs = null;

            try
            {
                // When the user has selected a library, they will be allowed to click the button
                // The first thing we'll do is get the target library and its root folder.
                targetLibrary = hostingWeb.Lists.GetByTitle(OutputLibrary.SelectedItem.Text);
                Microsoft.SharePoint.Client.Folder destintationFolder = targetLibrary.RootFolder;
                clientContext.Load(destintationFolder);
                clientContext.ExecuteQuery();

                // Then 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("~/SampleOOXML/LocalOOXMLDocument.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.
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run       run  = para.AppendChild(new Run());
                    run.AppendChild(new Text("Here's some text in a paragraph"));

                    // Create a table.
                    DocumentFormat.OpenXml.Wordprocessing.Table table
                        = new DocumentFormat.OpenXml.Wordprocessing.Table();

                    // Create some table border settings.
                    TableProperties borderProperties = new TableProperties(
                        new TableBorders(
                            new TopBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new BottomBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new LeftBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new RightBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.DashDotStroked),
                        Size = 12
                    },
                            new InsideHorizontalBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                            new InsideVerticalBorder
                    {
                        Val  = new EnumValue <BorderValues>(BorderValues.Single),
                        Size = 12
                    }));

                    // Add the table border settings to the table.
                    table.AppendChild <TableProperties>(borderProperties);

                    // Create a table row and add two cells with some text
                    var tr  = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
                    var tc1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    tc1.Append(new Paragraph(new Run(new Text("Here's some text in table cell #1"))));
                    var tc2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    tc2.Append(new Paragraph(new Run(new Text("Here's some text in table cell #2"))));
                    tr.Append(tc1);
                    tr.Append(tc2);

                    // Add the row to the table, and the table to the body of the document.
                    table.Append(tr);
                    body.Append(table);
                }

                // 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            = File.OpenRead(Server.MapPath("~/SampleOOXML/LocalOOXMLDocument.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       = hostingWeb.Url
                                      + destintationFolder.ServerRelativeUrl
                                      + "/SharePointOOXMLDocument.docx";
                ooxmlFile.Content = documentBytes;
                Microsoft.SharePoint.Client.File newFile = targetLibrary.RootFolder.Files.Add(ooxmlFile);
                clientContext.Load(newFile);
                clientContext.ExecuteQuery();

                // Let the user navigate to the document library where the file has been created
                string targetUrl = hostingWeb.Url + destintationFolder.ServerRelativeUrl;
                DocumentLink.Text        = "Document has been created in SharePoint! Click here to view the library";
                DocumentLink.Visible     = true;
                DocumentLink.NavigateUrl = targetUrl;
            }
            catch (Exception ex)
            {
                // Tell the user what went wrong
                DocumentLink.Text        = "An error has occurred: " + ex.Message;
                DocumentLink.Visible     = true;
                DocumentLink.NavigateUrl = "";
            }
            finally
            {
                // Clean up our filestream object
                fs.Close();
            }
        }
 /// <summary>
 /// Initializes the new instance of <see cref="SPClient.SPClientFolderParentPipeBind"/> class.
 /// </summary>
 /// <param name="folder">the folder which contains subfolders.</param>
 public SPClientFolderParentPipeBind(Microsoft.SharePoint.Client.Folder folder)
 {
     this.ClientObject = folder;
 }