Embed a Document in a post in SharePoint Server 2013 using .Net csom

Steps
  • Open Visual Studio in your system
  • Select Console Applciation template and give as name .
  • Add a Microsoft.Cleint Assembly refrence file in right side refrence tab in visual studio.
  • Replace Program.cs with the source code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.SharePoint.Client;  
  7. using Microsoft.SharePoint.Client.Social;  
  8.   
  9. namespace EmbedDocumentInPost  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             // Replace the following placeholder values with the actual values.  
  16.             const string serverUrl = "http://gauti.sharepoint.com/sp";  
  17.             const string documentUrl = "http://gauti.sharepoint.com//Shared%20Documents/fileName.docx";  
  18.   
  19.             try  
  20.             {  
  21.   
  22.                 // Get the context and the SocialFeedManager instance.  
  23.                 ClientContext clientContext = new ClientContext(serverUrl);  
  24.                 SocialFeedManager feedManager = new SocialFeedManager(clientContext);  
  25.   
  26.                 // Get the document attachment from the server.  
  27.                 ClientResult<SocialAttachment> attachment = feedManager.GetPreview(documentUrl);  
  28.                 clientContext.ExecuteQuery();  
  29.   
  30.                 // Define properties for the post and add the attachment.  
  31.                 SocialPostCreationData postCreationData = new SocialPostCreationData();  
  32.                 postCreationData.ContentText = "Post with a document.";  
  33.                 postCreationData.Attachment = attachment.Value;  
  34.   
  35.                 // Publish the post. This is a root post to the user's feed, so specify  
  36.                 // null for the targetId parameter.  
  37.                 feedManager.CreatePost(null, postCreationData);  
  38.                 clientContext.ExecuteQuery();  
  39.                 Console.Write("The post was published.");  
  40.                 Console.ReadLine();  
  41.             }  
  42.             catch (Exception ex)  
  43.             {  
  44.                 Console.Write("Error publishing the post: " + ex.Message);  
  45.                 Console.ReadLine();  
  46.             }  
  47.         }  
  48.     }  
  49. }