Change Newsfeed setting of all User profiles in SharePoint 2010 – Part 2

With a savvy SharePoint guy’s help, finally I found the solution for new user profile.

He suggested me to use PowerShell script (on previous post) for all the existing users, and create a webpart adding to the person.aspx page, which will check/uncheck the Newsfeed setting for current user.

Step 1 – Add a new property for User Profile

In Central Admin, Go to Application Management -> Manage service applications -> Enterprise User Profile Service -> Manage User Properties

  • Click “New Property”
  • Enter property name as “NewsfeedFlag” and select “Boolean” for Type
  • Make sure that this property will not be allowed users to edit values
  • Confirm that this property will not show on page

Step 2 – Create a custom web part

using System;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server.ActivityFeed;
using System.Collections.Generic;
using System.IO;

namespace InitializeNewsfeedSetting.InitialNewsfeed
{
   public class InitialNewsfeed : System.Web.UI.WebControls.WebParts.WebPart, IWebEditable
   {
       protected override void CreateChildControls()
       {
          base.CreateChildControls();

          SPContext currContext = SPContext.Current;
          string name = currContext.Web.CurrentUser.LoginName;
          string siteURL = SPContext.Current.Site.Url;

          ConfigActivityFeed(siteURL, name);

       }


private void ConfigActivityFeed(string url, string name)
{

   UserProfileManager profileManager = null;
   try
   {
      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
         using (SPSite site = new SPSite(SPContext.Current.Site.ID))
         {
            SPServiceContext serverContext = SPServiceContext.GetContext(site);
            HttpContext context = HttpContext.Current;

            profileManager = new UserProfileManager(serverContext);

            UserProfile up = profileManager.GetUserProfile(name);
/* The code runs under the current context's application pool(MySite) identity account,
* but Shared Services-SSP(such as User Profile Service) typically run under another application pool
* with a different identity account.
*/
            HttpContext.Current = null;
            if (!(bool)up["NewsfeedFlag"].Value)
            {
               List apptList;
               List apptNewList = new List();
               ActivityManager am = new ActivityManager(up, serverContext);

               apptList = am.ActivityPreferences.GetActivityPreferencesPerType();

               foreach (ActivityPreferencePerType appt in apptList)
               {
                  if (appt.ActivityType.ActivityTypeName.Equals("SharingInterest"))
                  {
                       appt.IsSet = false;
                  }

                  apptNewList.Add(appt);
                }
/* Q: if not set HttpContext.Current = null
* When Commit the changes, throw exception:
* {"Updates are currently disallowed on GET requests. To allow updates on a GET, set the 'AllowUnsafeUpdates' property on SPWeb."}
* Tried to set AllowUnsafeUpdates = true, still not work
*/
              am.ActivityPreferences.SetActivityPreferencesPerType(apptNewList);
              am.ActivityPreferences.Commit();
              am.ActivityPreferences.Refresh();
              // Change NewsfeedFlag property value to true
              up["NewsfeedFlag"].Value = true;
              up.Commit();
         }

       //If not set back HttpContext, Exception page shows up
        HttpContext.Current = context;

      }
   });
}
catch (Exception ex)
{
}

}// end of function
}
}

NOTE: Set HttpContext.Current=null is the only way I can find to solve this problem. It's tricky, and I still don't understand why we have to do so.

Step 3 – Remove custom web part when deactivate feature

When we deploy this solution or activate feature, it will automatically add the custom web part to web part gallery (/_catalogs/wp). MS recommended that don’t add web part to page when feature activation.

However, when deactivate the feature, the web part will not be removed from gallery, and the page will shows error.

Therefore, we have to add custom code for FeatureDeactivating to remove custom web part from page and web part gallery.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
   // Retrieves a reference to the site collection in which we are deploying the solution
   using (SPSite site = properties.Feature.Parent as SPSite)
   {
      // Creates a reference to the root web site of the site collection
      using (SPWeb web = site.RootWeb)
      {
         //Remove the web part from person.aspx page
         SPLimitedWebPartManager manager = web.GetLimitedWebPartManager("person.aspx", PersonalizationScope.Shared);
         List<microsoft.sharepoint.webpartpages.webpart> webParts = new List<microsoft.sharepoint.webpartpages.webpart>();
         foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in manager.WebParts)
         {
            if (webPart.Title.Contains("Newsfeed"))
            {
               manager.DeleteWebPart(webPart);
               break;
            }
        }
        web.Update();
        manager.Dispose();

        SPList list = web.Lists["Web Part Gallery"];
        //Go through the items in reverse
        for (int i = list.ItemCount - 1; i >= 0; i--)
        {
           //Get Web Part Name
           string webpartName = list.Items[i].Name;
           webpartName = webpartName.Substring(0, webpartName.IndexOf("."));

           //Delete web parts that have been added
           if (webpartName.Contains("Newsfeed"))
           {
              list.Items[i].Delete();
              break;
           }
        }

      }
   }
}

I encountered a problem when I redeployed the solution to MySite. After trying to add the new web part to the site, I got the following error: “A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.”

This was caused by I changed WebPart name after creation and/or changed its namespace. It took me half a day to figure out what the problem is.

With Visual Studio 2010 in VS project:

  1. Select custom webpart
  2. Use right click > Properties
  3. In properties windows under SharePoint find Safe Control Entries
  4. Click ... button
  5. Verify settings (namespace)

Reference: 

(1) http://www.simple-talk.com/dotnet/.net-tools/using-features-and-solutions-to-deploy-your-sharepoint-customizations/

(2) http://greggalipeau.com/2009/03/21/cleaning-up-your-webpart-gallery/

Advertisements

One thought on “Change Newsfeed setting of all User profiles in SharePoint 2010 – Part 2

  1. Pingback: Change Newsfeed setting of all User profiles in SharePoint 2010 – Part 1 | lixuan0125

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s