Post to Newsfeed on behalf of another user (Server Object Model)
The below code will post to Newsfeed for any user account you specify. Activity appears the same as if the user manually posted. This could be helpful for populating Newsfeed from external activity, custom event receivers, workflow, and other developer sources. Enjoy!

Screenshot

Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
using Microsoft.Office.Server.Social; using Microsoft.Office.Server.UserProfiles; using Microsoft.SharePoint; using System; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // Config string siteUrl = "http://mysite"; string login = "i:0#.w|domain\\user"; using (SPSite site = new SPSite(siteUrl)) { // Context SPUser user = site.RootWeb.SiteUsers[login]; SPUserToken token = user.UserToken; SPServiceContext ctx = SPServiceContext.GetContext(site); using (new SPServiceContextScope(ctx)) { // Init UserProfileManager upm = new UserProfileManager(ctx); UserProfile prof = upm.GetUserProfile(user.LoginName); SPSocialFeedManager mgr = new SPSocialFeedManager(prof, ctx, token); SPSocialPostCreationData post = new SPSocialPostCreationData(); // Text post.ContentText = "hello world, look at {0}!"; post.UpdateStatusText = true; // Link SPSocialDataItem [] link = new SPSocialDataItem [1]; link[0] = new SPSocialDataItem(); link[0].ItemType = SPSocialDataItemType.Link; link[0].Text = "My Cool Link"; link[0].Uri = new Uri("http://www.google.com"); post.ContentItems = link; // Save SPSocialThread thread = mgr.CreatePost(null, post); } } } } } |