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!  shades_smile






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("");
                    post.ContentItems = link;
                    // Save
                    SPSocialThread thread = mgr.CreatePost(null, post);



Return to Top ▲Return to Top ▲