Friday, November 15, 2013

ListViewWebPart change ToolBarType

Changing the ToolBarType isn't allowed by the SharePoint API.

On a specific project i had to change the ToolBarType of a ListViewWebPart. My colleague Florent Vignaux helped me, and he released that function :


Code:
private void SetToolBarType(ListViewWebPart lv, string toolbarType)
 {
     SystemReflectionPropertyInfo ViewProp = lv.GetType().GetProperty("View", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
     SPView spView = ViewProp.GetValue(lv, null) as SPView;
 
     // This forces a refresh of the views internal xml or the node's child nodes are not populated
     string txt = spView.SchemaXml;
 
     SystemReflectionPropertyInfo NodeProp = spView.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
 
     // Again we force a refresh of the views
     txt = spView.Toolbar;
 
     XmlNode node = NodeProp.GetValue(spView, null) as XmlNode;
     XmlNode tBarNode = node.SelectSingleNode("Toolbar");
     if (tBarNode != null)
     {
         tBarNode.Attributes["Type"].Value = toolbarType;
         spView.Update();
     }
 }



The ToolbarType value can be : Standard, Freeform or None.

Change Masterpage on SPWeb

Code:
 using (SPSite site = new SPSite("http://siteUrl")) 
 { 
     using (SPWeb web = site.OpenWeb()) 
     { 
         string newMasterPage = "newMasterPage.master";
         string webAppRelativePath = site.ServerRelativeUrl.TrimEnd(new char[] { '/' }); 

         //Site master page 
         web.CustomMasterUrl = string.Format("{0}/_catalogs/masterpage/{1}", webAppRelativePath, newMasterPage); 

         //System master page 
         web.MasterUrl = string.Format("{0}/_catalogs/masterpage/{1}", webAppRelativePath, newMasterPage); 

         web.Update();    
     }
 }


Here we apply the new MasterPage to both site pages and system pages.

Tuesday, November 12, 2013

Add new role to SPgroup


Sometimes, you will need to programmatically add new roles and permissions to groups on your website.
Here is a sample of code I used : 


Code:
using (SPSite freshsite = new SPSite("http://siteUrl"))
{
    using (SPWeb freshweb = freshsite.OpenWeb())
    {
        SPGroup visitorsGroup = freshweb.SiteGroups["Group Name"];
        SPRoleAssignment visitorsRoleAssignment = new SPRoleAssignment(visitorsGroup);
        SPRoleDefinition readRoleDefinition = freshweb.RoleDefinitions["Read"];

        visitorsRoleAssignment.RoleDefinitionBindings.Add(readRoleDefinition);

        freshweb.RoleAssignments.Add(visitorsRoleAssignment);

        freshweb.Update();
     }
}

The default values of SPRoleDefinitions are : Limited Access, Design, Read, Contribute and Full Control.

Note that you may need to break role inheritance before adding the new SPRoleAssignment to your SPWeb


Code:
if (!freshweb.HasUniqueRoleAssignments)
{
    freshweb.BreakRoleInheritance(true);
}