Monday 11 August 2014

How to Post to Newsfeed / Sitefeed Programmatically in SharePoint 2013

Today I was trying to create a simple console application to post to a SharePoint 2013 sitefeed using server object model. Surprisingly there was no good article out there.
If it helps anyone, following is how I did it :

Add references

Microsoft.Office.Server.UserProfiles.dll
Microsoft.Office.Server.dll
System.Web.dll

Using Directives

using Microsoft.SharePoint;
using Microsoft.Office.Server.Social;
using Microsoft.Office.Server.UserProfiles;

Code

static void Main(string[] args)
        {
            const string siteUrl = "http://server/sites/sitename";
            const string user = "domain\\username";

            using (SPSite site = new SPSite(siteUrl))
            {
                SPUser userContext = site.RootWeb.SiteUsers[user];
                SPUserToken userToken = userContext.UserToken;

                SPServiceContext serviceContext = SPServiceContext.GetContext(site);

                using (new SPServiceContextScope(serviceContext))
                {

                    UserProfileManager profileManager = new UserProfileManager(serviceContext);

                    UserProfile userProfile = profileManager.GetUserProfile(userContext.LoginName);

                    SPSocialFeedManager feedManager = new SPSocialFeedManager(userProfile, serviceContext, userToken);

                    SPSocialPostCreationData post = new SPSocialPostCreationData();
                    post.ContentText = "Hi from server object model";

                    feedManager.CreatePost(site.Url+"/newsfeed.aspx", post);

                }
            }
        }

Troubleshooting


If you come across UserProfileApplicationNotAvailableEx, the chances are it is a permission issue. Use this article to solve it: Get User profile using Console App- Object reference error at Server context

If you encounter “User cannot be found” exception at site.RootWeb.SiteUsers[userName], try “i:0#.w|domain\\username” instead of “domain\\username

1 comment: