Friday, February 22, 2019

Create document and upload list item attachment (SharePoint 2010, 2013, 2016)

Hello everyone, this time I will talk about creating Event Reciever and actions that will occur with the element of the list, we are talking about reading the properties of the list item, creating the Word document, filling it with these properties of the current list element and attaching it to an attachment to this element of the list while creating. Such a task came to mind non-monotonously, it was set by user asked it on the forum, I thought that in future project it was possible, and I myself wanted to broaden my horizons in this topic.
In this project, to create a document and its content, I will use DocumentFormat.OpenXml and a description of this library I will use the blog Create a word document with OpenXml and C# (by Ludovic Perrichon).

So begin!!!

1. Create is a Custom list (name "ListProject") then modify list view and show column "Created", "Created by", "Modified", "Modified by".



2.List is ready, then open Visual studio and click "New project" choose project depending on your version SharePoint On-Premises "SharePoint -(2010, 2013, 2016) Empty Project" project name "ItemUploadAttachments".



3. Set URL and Select a Farm Solution.



4. Click right-click on the project name and click "Add" then "New item" and choose "Event Reciever" is name "UploadAttachments".



5. And will see Event Reciever Settings then choose event source "Custom List" and click handle events only "An item was added". Click Finish.



6. Open is added in project Event Reciever "UploadAttachments" and you will see "Elements.xml" open and edit file, set to comment or remove row "<Receivers ListTemplateId="101">" and add "<Receivers ListUrl="Lists/ListProject">", then save file.



7. Open DocumentFormat.OpenXml and insert last version to nuget package "Install-Package DocumentFormat.OpenXml -Version 2.9.0".







8. We continue to work with Event Reciever open file "UploadAttachments.cs" and will see code "public override void ItemAdded(SPItemEventProperties properties) {}" this will be our event, which is activated when creating a list item. Add the code of this void "ItemAdded".
using (SPWeb web = properties.OpenWeb()) {
  try {
      //GetListCurrentItem
        SPListItem currentItem = properties.ListItem;
        string Title = currentItem["Title"].ToString();
        string Author = currentItem["Author"].ToString();
        DateTime Created = DateTime.Parse(currentItem["Created"].ToString());
        string Modified = currentItem["Editor"].ToString();
        DateTime EndTime = DateTime.Parse(currentItem["Modified"].ToString());
        string filepath = @"C:\Temp\" + Title + ".docx";
        //Create file
        CreateWordprocessingDocument(filepath, Title, Author, Created, Modified, EndTime);
        //Upload file
        FileStream stream = new FileStream(filepath, FileMode.Open);
        byte[] byteArray = new byte[stream.Length];
        stream.Read(byteArray, 0, Convert.ToInt32(stream.Length));
        stream.Close();
        currentItem.Attachments.Add(Title + ".docx", byteArray);
        currentItem.Update();
      }
       catch (Exception ex)
       {
        throw ex;
       }
}
9. Further, beyond the limits of this method, we create a public static void "CreateWordprocessingDocument"
public static void CreateWordprocessingDocument(string filepath, string Title, string Author, DateTime Created, string Modified, DateTime EndTime)
        {
        using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                if (Author != "")
                    run.AppendChild(new Text("Author: " + Author));
                {
                    if (Created != null)
                    {
                        Paragraph p = new Paragraph();
                        Run r = new Run();
                        RunProperties rp2 = new RunProperties();
                        rp2.Italic = new Italic();
                        rp2.Bold = new Bold();
                        r.Append(rp2);
                        Text t = new Text("Date created: " + Created) { Space = SpaceProcessingModeValues.Preserve };
                        r.Append(t);
                        p.Append(r);
                        body.Append(p);
                    }
                    if (Modified != "")
                    {
                        Paragraph p = new Paragraph();
                        Run r = new Run();
                        Text t = new Text("Editor: " + Modified);
                        r.Append(t);
                        p.Append(r);
                        body.Append(p);
                    }
                    if (EndTime != null)
                    {
                        Paragraph p = new Paragraph();
                        Run r = new Run();
                        RunProperties rp2 = new RunProperties();
                        rp2.Bold = new Bold();
                        r.Append(rp2);
                        Text t = new Text("Date Modified: " + EndTime);
                        r.Append(t);
                        p.Append(r);
                        body.Append(p);
                    }
                }
            }
        }
10. Check our project is not error, Build solution and Deploy solution. Open our list "ListProject" then "New item" and check in attachment to this item.








Happy Coding!

Wednesday, February 13, 2019

Create folder in SharePoint list (SharePoint 2010, 2013, 2016)

So, we continue to work with basic operations, today is another piece of code in which we are using CSOM create a folder in the program list. And as usual by tradition I use Visual studio.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using Microsoft.SharePoint.Client;

using (var clientContext = new ClientContext("http://sp/sites/test"))
            {
                string folderName = "test";
                var list = clientContext.Web.Lists.GetByTitle("ListBase");
                list.EnableFolderCreation = true;

                clientContext.Load(list);
                clientContext.Load(list.RootFolder);
                clientContext.Load(list.RootFolder.Folders);
                clientContext.ExecuteQuery();

                var folderCollection = list.RootFolder.Folders;

                foreach (var folder in folderCollection)
                {
                    if (folder.Name == folderName)
                    {
                        clientContext.Load(folder.Files);
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        var itemCreateInfo = new ListItemCreationInformation
                        {
                            UnderlyingObjectType = FileSystemObjectType.Folder,
                            LeafName = folderName
                        };
                        var newItem = list.AddItem(itemCreateInfo);
                        newItem["Title"] = folderName;
                        newItem.Update();
                        clientContext.ExecuteQuery();
                        break;
                    }
                }
            }
Happy Coding!

Copying folder library to another library (SharePoint 2010, 2013, 2016)

In this article, I continue to lay out the basic operations for working with .NET MS SharePoint server On-Premises one of which is copying a folder from an attachment inside from one library to another, as always I run the code from the Console application from Visual studio.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using Microsoft.SharePoint;

using (SPSite SPsite = new SPSite("http://sp/sites/test"))
            {
                using (SPWeb SPWeb = SPsite.OpenWeb())
                {
                    SPDocumentLibrary srcLib = (SPDocumentLibrary)SPWeb.Lists["Documents"];
                    SPDocumentLibrary destLib = (SPDocumentLibrary)SPWeb.Lists["OldDocuments"];
                    foreach (SPListItem sourceItem in srcLib.Folders)
                    {
                        SPFolder sourceFolder = sourceItem.Folder;
                        string targetPath = destLib.RootFolder.ServerRelativeUrl + "/" + sourceFolder.Name;
                        SPFolder targetFolder = SPWeb.GetFolder(targetPath);
                        SPListItem targetItem = targetFolder.Item;
                        sourceItem.Folder.CopyTo(targetPath);
                    }
               }
           }
Happy Coding!