locked
Hide web part on MySite Profile RRS feed

  • Question

  • Hello,

    How hide web part with conditions depending on whose mysite profile is being viewed?

    Is it right solution? there is a problem, web part hides/unhides only after extra page refresh. Is there any "pretty" solution?

          SPWeb oWeb = SPContext.Current.Web;
    
          string curUser;
    
          if (HttpContext.Current.Request.Url.Query.ToString() != "")
          {
            curUser = HttpContext.Current.Request.Url.Query.Split('&')[0].Split('=')[1].Replace("%5C", "\\");
          }
          else
          {
            curUser = oWeb.CurrentUser.ToString();
            return;
          }
    
          bool isManag = false;
          if (isUserInGroup(oWeb.Groups["Managers"], curUser))
          {
            isManag = true;
          }
    
    Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr;
            mgr = oWeb.GetLimitedWebPartManager("Person.aspx", PersonalizationScope.Shared);
    
            foreach (WebPart myWebPart in mgr.WebParts)
            {
              if (myWebPart.Title == "MyWebPartName")
              {
                if (!isManag)
                {
                  myWebPart.Hidden = true;
                }
                else
                {
                  myWebPart.Hidden = false;
                }
    
                mgr.SaveChanges(myWebPart);
              }
            }
          
    
    
    

    Tuesday, April 12, 2011 4:00 AM

Answers

  • Not sure about links, but here are the steps.

    Add a module to your SharePoint VS 2010 project.  Get a copy of the person.aspx page (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\SiteTemplates\SPSMSITEHOST) so that it is provisioned.  Customize it as needed.

    When you do the steps above a new Feature is added. Name it MySiteHostPages (or whatever you like).

    Add a new feature receiver to MySiteHostPages feature.

    In the FeatureDeactivating event add code to delete (or rename) the OOB Person.aspx page; it sits in at the root of the rootweb.

    Build; package; deploy;

    Cycle the new Feature: Activate MySiteHostPages; Deactivate MySiteHostPages; Activate MySiteHostPages again

    Enjoy the new person.aspx page.

    Wednesday, April 13, 2011 3:28 PM

All replies

  • hi Raphael, 

    The code above should go good. But as you said u need to refresh the page to reflect those changes.

    You can also try hiding the webpart using javascript.

     

    Here is the code below. Keyword is the webpart title.

    You can run the RegisterClientScript on your page load.

    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "HideWebpart", script);
    
    where script is the Method call.

    //Function to hide the webpart
    function hideZones(keyWord) {
      var menu = ""
      var editString = "Add"
      editString = editString + ' a Web Part'
      var isEditMode = $("td:contains(editString):not('editString')"); // checks to see if in edit mode
      var listTitle = $("td:contains('" + keyWord + "')"); //make an array of the titles of the web parts
      $.each(listTitle, function (i, e) {
        var listZone = listTitle[i];
        var wpnum
        if (listTitle[i].title.length != 0) {
          if (listTitle[i].title.startsWith(keyWord)) {
            wpnum = "MSOZoneCell_WebPartWPQ" + listZone.id.substring(15);
            document.getElementById(wpnum).style.display = "none";
          }
    
        }
      });
    
    
    } 

     

     


    Sreeharsha Alagani|MCTS Sharepoint 2010
    Tuesday, April 12, 2011 5:01 AM
  • Hide the output from your custom webpart, instead of the web part itself.

    In the CreateChildControls() method check if the user has access, if not, bypass any execution logic. ie. don't add controls, etc.

    Also, SPGroup has a ContainsCurrentUser property that's really handy.

    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spgroup.containscurrentuser.aspx

    Just to make sure, is "Managers" a custom group you'd created? Or are you trying to find out if the current user is the profile owner's manager? If the goal is to check the effective policy, a different approach should be used.  You can reflect ProfilePropertyValue control's OnPreRender method to see how MS does it.

    The problem with a JS approach is that the webpart will still render on the page, hence anyone could "view source" the page to 'see' the output.


    Vitaly

    Tuesday, April 12, 2011 5:18 AM
  • Hi, Vitaly

    1) I trying to hide not mine custom web part, so I can not control it from inside itself.

    2) SPGroup.ContainsCurrentUser does not suitable for me because I need check if user whose page currently is being viewed in custom group "Managers". In other words it does not matter for me who browse page, but whose profile page it is.

    3) I know about that sad minus of JS, but now i do not see another solution.

    My current version of code is:

     

      protected override void Render(HtmlTextWriter writer)
      {
    
        SPWeb oWeb = SPContext.Current.Web;
    
        string curUser;
    
        if (HttpContext.Current.Request.Url.Query.ToString() != "")
        {
         curUser = HttpContext.Current.Request.Url.Query.Split('&')[0].Split('=')[1].Replace("%5C", "\\");
        }
        else
        {
         Page.ClientScript.RegisterStartupScript(Page.GetType(), "hidescript", "document.getElementById('MSOZoneCell_WebPartWPQ2').style.display='none';", true); 
         return;
        }
    
        bool isManag = isUserInGroup(oWeb.Groups["Managers"], curUser)
    
        try
        {
         if (!isManag)
         {
          Page.ClientScript.RegisterStartupScript(Page.GetType(), "hidescript", "document.getElementById('MSOZoneCell_WebPartWPQ2').style.display='none';", true);
         }
         else
         {
          return;
         }
        }
        catch (Exception ex)
        {
         writer.Write(ex);
        }
    
      }
    
    and there is another problem when anybody except site collection admin trying access page with this web part gets Error: Access Denied

    I think I should use Impersonation RunWithElevatedPrivileges


    Tuesday, April 12, 2011 10:31 AM
  • Yes Raphael, you should run with elevated privileages, Since the action of updating the Webpart manager needs higher level of privileages.

     


    Sreeharsha Alagani|MCTS Sharepoint 2010
    Tuesday, April 12, 2011 10:54 AM
  • Please use the CreateChildControls() method to add logic to. Using Render is a big no no. :)

    Consider creating a custom person.aspx to replace the OOB one. This can be done via a Feature.  Adding a custom security trimmed control to person.aspx should allow you to hide web parts.

    Here is a link to info on how to enhance the OOB SPSecurityTrimmedControl to hide content/controls based on group membership. You'd have to add your own logic of course.

    http://sarveshspn.blogspot.com/2010/05/enhance-spsecuritytrimmedcontrol-to.html

    Tuesday, April 12, 2011 2:02 PM
  • Please use the CreateChildControls() method to add logic to. Using Render is a big no no. :)

    Consider creating a custom person.aspx to replace the OOB one. This can be done via a Feature.  Adding a custom security trimmed control to person.aspx should allow you to hide web parts.

    Here is a link to info on how to enhance the OOB SPSecurityTrimmedControl to hide content/controls based on group membership. You'd have to add your own logic of course.

    http://sarveshspn.blogspot.com/2010/05/enhance-spsecuritytrimmedcontrol-to.html

    I like it! I think it more smart solution, I will give a try SPSecurityTrimmedControl. I'd googled for something like "custom Security trimming sharepoint" but did not see "enhancing SPSecurityTrimmedControl" it more flexible than i thought.

    I am new in programming for Sharepoint, I confident only in custom WebParts and Event Receivers, so could you give some links for "creating a custom person.aspx to replace the OOB one via a Feature"?

    Wednesday, April 13, 2011 5:56 AM
  • Not sure about links, but here are the steps.

    Add a module to your SharePoint VS 2010 project.  Get a copy of the person.aspx page (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\SiteTemplates\SPSMSITEHOST) so that it is provisioned.  Customize it as needed.

    When you do the steps above a new Feature is added. Name it MySiteHostPages (or whatever you like).

    Add a new feature receiver to MySiteHostPages feature.

    In the FeatureDeactivating event add code to delete (or rename) the OOB Person.aspx page; it sits in at the root of the rootweb.

    Build; package; deploy;

    Cycle the new Feature: Activate MySiteHostPages; Deactivate MySiteHostPages; Activate MySiteHostPages again

    Enjoy the new person.aspx page.

    Wednesday, April 13, 2011 3:28 PM
  • Hi Raphel

    I have the same business context as you mentioned. I want hide certain webparts in the mysite page on the first time when the mysite is provisioned. On clicking a link in the mysite, the page will trigger certain questions and the user has to answer them. on that list event handler the hidden webparts will be shown. Right now this solution works only when i logged in as an administrator. When i logged in as another user it is executing the code but not hidding or unhidding the webparts. Did the hidding part in the mysite provisioning feature.

     public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
                    SPSite spsite1 = properties.Feature.Parent as SPSite;

                    StreamWriter swLog;
                    if (!File.Exists("c:\\metadata.txt"))
                    {
                        swLog = new StreamWriter("c:\\metadata.txt");


                    }
                    else
                    {
                        swLog = File.AppendText("c:\\metadata.txt");

                    }
                    swLog.WriteLine("Site value :" + spsite1.ToString());
                    swLog.WriteLine( spsite1.RootWeb.Title);
                    swLog.WriteLine(spsite1.RootWeb.Name );

                    if (spsite1 != null)
                    {
                        SPWeb spWeb1 = spsite1.RootWeb;
                   
                  
                    spWeb1.AllowUnsafeUpdates = true;

                        mgr = spWeb1.GetLimitedWebPartManager("/my/default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                        ////swLog.WriteLine("mysite");

                        foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
                        {
                            //swLog.WriteLine(myWebPart.Title.ToString());

                            if (myWebPart.Title == "community")
                            {
                                myWebPart.Hidden = true; //don't show webpart

                            }
                            if (myWebPart.Title == "collegue")
                            {
                                myWebPart.Hidden = true; //don't show webpart

                            }
                            mgr.SaveChanges(myWebPart);
                        }
                        spWeb1.AllowUnsafeUpdates = false;
                    }
                  swLog.Close();
                 
                });

            }

    could you please let me know how you approched the problem

    Friday, June 22, 2012 5:22 AM