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!

No comments:

Post a Comment