0

I have the following scenario:

1) Document has to be uploaded in SharePoint 2013 Document Library.

2) Uploaded document then hits the web service(PostMan in my case), the service then returns a few keywords/tags.

3) These tags have to be updated in a column in SharePoint Document Library.

I need help with Creating Event Receivers using a Farm Solution.

The following is the code to retrieve all the tags/keywords from the web service:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;

    namespace TestWebService1
    {
        class Program
        {
        private const string URL = "http://10.56.74.7:9090/cms-m2ts/rest/DocumentTagService/uploadFile";

    static void Main(string[] args)
    {
        // Create a http request to the server endpoint
        HttpWebRequest requestToServerEndpoint = (HttpWebRequest)WebRequest.Create(URL);

        string boundaryString = "----TestWebService";
        string fileUrl = @"E:\XYZ.WebServiceTest\RFP Management Services.pdf";
        string strTagCount = "5";

        //To get the values from command line arguments
        if (args.Count() == 2)
        {
            fileUrl = args[0];
            strTagCount = args[1];
        }
        else
        {
            Console.WriteLine("No agrguments found !!\nTaking the Default values \n");
        }

        // Set the http request header \
        requestToServerEndpoint.Method = WebRequestMethods.Http.Post;
        requestToServerEndpoint.ContentType = "multipart/form-data; boundary=" + boundaryString;
        requestToServerEndpoint.KeepAlive = true;
        requestToServerEndpoint.Credentials = System.Net.CredentialCache.DefaultCredentials;

        // Use a MemoryStream to form the post data request,
        // so that we can get the content-length attribute.
        MemoryStream postDataStream = new MemoryStream();
        StreamWriter postDataWriter = new StreamWriter(postDataStream);

        // Include value from the myFileDescription text area in the post data
        postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
        postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
        "tagCount",
        strTagCount);

        // Include the file in the post data
        postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
        postDataWriter.Write("Content-Disposition: form-data;"
        + "name=\"{0}\";"
        + "filename=\"{1}\""
        + "\r\nContent-Type: {2}\r\n\r\n",
        "uploadFile",
        Path.GetFileName(fileUrl),
        getFileType(Path.GetExtension(fileUrl)));
        postDataWriter.Flush();

        // Read the file
        FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            postDataStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
        postDataWriter.Flush();

        // Set the http request body content length
        requestToServerEndpoint.ContentLength = postDataStream.Length;

        // Dump the post data from the memory stream to the request stream
        using (Stream s = requestToServerEndpoint.GetRequestStream())
        {
            postDataStream.WriteTo(s);
        }
        postDataStream.Close();

        // Grab the response from the server. WebException will be thrown
        // when a HTTP OK status is not returned

        WebResponse response = requestToServerEndpoint.GetResponse();
        StreamReader responseReader = new StreamReader(response.GetResponseStream());
        string replyFromServer = responseReader.ReadToEnd();

        ArrayList list = new ArrayList();

        list.AddRange(replyFromServer.Split(new char[] { ',' }).ToList());

        for (int i = 2; i < list.Count; i = i + 3)
        {
            var text = list[i].ToString().Replace("{", "").Replace("}", "").Split(new char[] { ':' })[1].Replace(@"""", "");
        }

        //System.Web.Script.Serialization.JavaScriptSerializer se = new System.Web.Script.Serialization.JavaScriptSerializer();

        //var data = se.Serialize(replyFromServer);

        //var valueSet = se.Deserialize<DocumentProperties>(data);

        //Console.WriteLine(valueSet.word);
        //Console.ReadLine();
        //Today 2 END
    }

    private static string getFileType(string str)
    {
        string type = "";
        switch (str)
        {
            case ".pdf":
                type = "application/pdf";
                break;
            case ".doc":
            case ".docx":
                type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                break;
            default:
                type = "Invalid";
                break;
        }
        return type;
    }
}

public class DocumentProperties
{
    public string word { get; set; }
}

}

I have created an Event Receiver, I further need code on how to sync my above code to the Event Receiver code.

The following is my code for Event Receiver that got generated :

    public class EventReceiver1 : SPItemEventReceiver
    {
    public override void ItemAdding(SPItemEventProperties properties)
    {
        base.ItemAdding(properties);            
    }

    /// <summary>
    /// An item is being updated.
    /// </summary>
    public override void ItemUpdating(SPItemEventProperties properties)
    {
        base.ItemUpdating(properties);
    }

    /// <summary>
    /// An item was added.
    /// </summary>
    public override void ItemAdded(SPItemEventProperties properties)
    {
        base.ItemAdded(properties);

        using (SPWeb web = properties.OpenWeb())
        {
            try
            {
                SPListItem currentItem = properties.ListItem;
                currentItem["UpdatedBy"] = "Event Receiver";
                currentItem.Update();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    /// <summary>
    /// An item was updated.
    /// </summary>
    public override void ItemUpdated(SPItemEventProperties properties)
    {
        base.ItemUpdated(properties);
    }
}

This is the first time I am working on Event Receivers.

Please help me with appropriate code on how this entire thing could work well. Each time when the document is uploaded that code has to run and the tags retrieved from the service have to be placed in SharePoint Document Library column.

Kindly help..Thanks. :)

0

We can create a method in the Event Receiver to call web service and get the return data, then call the method in the ItemAdded method.

Here is an example(It also work for SharePoint 2013) for your reference:

SharePoint 2010: Calling WCF Services from Event Receivers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.