SharePoint Dragons

Nikander & Margriet on SharePoint

Tag Archives: sharepoint 2010

Adding users and groups to SharePoint 2010 Lists via PowerShell Braindump

A braindump follows the train of thought of a person solving a problem. This process allows you to optimize through processes and reasoning patterns, and as such can be a useful and entertaining exercise. What follows is the braindump of adding users and groups to SharePoint 2010 Lists via PowerShell.

Let’s start by firing the SharePoint 2010 Management Shell and see what I can learn about SharePoint related PS commands.

I know that such commands contain “sp” in it, so I’ll do:

help *sp*.

Ah, that’s too much. I assume that I need to retrieve a list before I can add permissions, but in order to do that I’ll probably need to get hold of the correct site collection and site first. In that case, I’ll just go ahead and look for cmdlets that have get in it. I do:

help get-sp*

There they are, on the first page, Get-SPSite and Get-SPWeb. They look promising. Let’s see if I can get a site directly by using Get-SPWeb. But in order to do that, I first need to find out how to use it. I want to read the documentation, so I do:

help get-spweb -full

Hmm, if I take a look at the -Identity parameter, it seems to be enough to get hold of a specific site. Let’s try it.

get-spweb http://moon

Ok, got it. That wasn’t too bad. I notice that now i have an SPWeb object. Now, let’s see what I can do with a site, there should be a way to get a specific list. I do:

get-spweb http://moon | gm | more

Either the GetList or the GetListFromUrl method should help me to get a list. Let’s switch to MSDN at http://msdn.microsoft.com and look for:

spweb getlist

As it turns out, this method needs a server-relative URL for a list, for example, /sites/MySiteCollection/Lists/Announcements. That’s good enough for me. Once I have an SPList object, I’ll see what I can do with that. I’ll change the PS code a bit, so that I’ll have references to the various objects. I do:

$web = get-spweb http://moon
$list = $web.getlist(“/Lists/TheTestList”)

Let’s see that I really got it and try:

$list.Title

Fine, let’s find out about the list object then. I do:

$list | gm | more

Hmm, things are getting a little bit more complicated. Time to fire up Windows PowerShell ISE and work from there. That won’t do me any good unless I load the SharePoint PS snap in first. So, I do:

$snapIn = “Microsoft.SharePoint.PowerShell”

if ( get-pssnapin $snapIn -ea “silentlycontinue”)
{
  remove-pssnapin $snapIn
}

if ( get-pssnapin $snapIn -registered -ea “silentlycontinue”)
{
  add-pssnapin $snapIn
}

$web = get-spweb http://moon
$list = $web.getlist(“/Lists/TheTestList”)

The traditional PowerShell approach is getting too cumbersome by now. Instead of continuing going down this road, let’s find some C# code which does what I want and convert it to PowerShell.

$snapIn = “Microsoft.SharePoint.PowerShell”

Write-Host “Initializing SharePoint PowerShell Environment”
if ( get-pssnapin $snapIn -ea “silentlycontinue”)
{
  Write-Host “Remove SharePoint snap-in”
  remove-pssnapin $snapIn
}

if ( get-pssnapin $snapIn -registered -ea “silentlycontinue”)
{
  Write-Host “Add SharePoint snap-in”
  add-pssnapin $snapIn
}

Write-Host “Get web”
$web = get-spweb http://moon
Write-Host “Get list”
$list = $web.getlist(“/Lists/TheTestList”)

#Reset permissions
Write-Host “Reset to original security settings”
$list.BreakRoleInheritance($False)
$list.ResetRoleInheritance()
Write-Host “Break role inheritance”
$list.BreakRoleInheritance($True)

# Remove all current assignments.
Write-Host “Remove all Role assignments”
Write-Host “Count:” $list.RoleAssignments.Count
while ($list.RoleAssignments.Count -gt 0)
{
  Write-Host “Removing a specific assignment for” $list.RoleAssignments[0].Member.Name
  $list.RoleAssignments.Remove(0)
}
Write-Host “Count:” $list.RoleAssignments.Count

$userName = “lc\Administrator”
$user = $web.EnsureUser($userName)
Write-Host “user:” $user
$userRole = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
$builtInRole = $web.RoleDefinitions[“Read”]
Write-Host “Built in role” $builtInRole.Name

$userRole.RoleDefinitionBindings.Add($builtInRole)
$list.RoleAssignments.Add($userRole)

$groupName = “SharePoint Dragons Owners”
$group = $web.SiteGroups[$groupName]
Write-Host “Group:” $group
$groupRole = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
$groupRole.RoleDefinitionBindings.Add($builtInRole)
$list.RoleAssignments.Add($groupRole)

Write-Host “Finished”

Ah, there’s my proof of concept that I can later convert to Enterprise-level code. Now, let’s write that blog post.

Camlex.NET

Camlex.NET simplifies the creation of CAML queries: http://camlex.codeplex.com/ It’s not very popular yet, but it’s interesting. It seems to be offering an easier, more familiar way to construct CAML queries on the fly using lambda expressions and a fluent interface. Not sure how this compares to SPMetal, which requires you to generate classes beforehand before you’ll be able to use Linq to query object structures (which then get translated to CAML). At first glance SPMetal seems to be even easier, because it supports strong typing and concurrency conflict resolution. Tell us what you think?

A web part editor part containing a drop down list

This post contains the code required for making a SharePoint 2010 web part that uses an editor part that contains a drop down list.

Here’s the code for the web part editor part:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;

namespace SharePointProject3.WebPart1
{
    public class WebPart1EditorPart : EditorPart
    {
        // Reference to the web part that uses this editor part, the parent web part needs to implement the IWebEditable interface to support custom editing controls
        protected WebPart1 ParentWebPart { get; set; }
        protected DropDownList EditorChoices { get; set; }

        /// <summary>
        /// Does editor part init settings
        /// </summary>
        public WebPart1EditorPart()
        {
            Title = “Make a choice – good name here”;
        }

        /// <summary>
        /// Creates the dll
        /// </summary>
        protected override void CreateChildControls()
        {
            EditorChoices = new DropDownList();
            EditorChoices.Items.Add(new ListItem(“AAA”, “1”));
            EditorChoices.Items.Add(new ListItem(“BBB”, “2”));
            EditorChoices.Items.Add(new ListItem(“CCC”, “3”));
            Controls.Add(EditorChoices);

            base.CreateChildControls();
            ChildControlsCreated = true;
        }

        /// <summary>
        /// Reads current value from parent web part and show that in the ddl
        /// </summary>
        public override void SyncChanges()
        {
            EnsureChildControls();
            ParentWebPart = WebPartToEdit as WebPart1;

            if (ParentWebPart != null && WebPartManager.Personalization.Scope == PersonalizationScope.Shared)
            {
                ListItem item = EditorChoices.Items.FindByValue(ParentWebPart.MyEditorPartChoice);
                if (item != null) item.Selected = true;
            }
        }

        /// <summary>
        /// Applies change in editor part ddl to the parent web part
        /// </summary>
        /// <returns></returns>
        public override bool ApplyChanges()
        {
            try
            {
                EnsureChildControls();
                ParentWebPart = WebPartToEdit as WebPart1;

                if (ParentWebPart != null && WebPartManager.Personalization.Scope == PersonalizationScope.Shared)
                {
                    ParentWebPart.MyEditorPartChoice = EditorChoices.SelectedValue;
                }

                // The operation was succesful
                return true;
            }
            catch
            {
                // Because an error has occurred, the SyncChanges() method won’t be invoked.
                return false;
            }
        }
    }
}

Here’s the code for the web part itself:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace SharePointProject3.WebPart1
{
    [ToolboxItemAttribute(false)]
    public class WebPart1 : WebPart, IWebEditable
    {
        protected override void CreateChildControls()
        {
            var lbl = new Label();

            if (MyEditorPartChoice == null)
                lbl.Text = “Make a choice first”;
            else
                lbl.Text = “The value from the editor part choice: ” + MyEditorPartChoice;
           
            Controls.Add(lbl);
        }

        /// <summary>
        /// Contains the value of the choice in the editor part drop down list
        ///
        /// Set the Personalizable attribute to true,
        /// to allow for personalization of tabs by users.
        /// This causes  this property to be shown in the web part tool pane and lets SharePoint take care of the storage/retrieval of this property in the SharePoint content database.
        /// </summary>
        [Personalizable(true)]
        public string MyEditorPartChoice { get; set; }

        /// <summary>
        /// Creates custom editor parts here and assigns a unique id to each part
        /// </summary>
        /// <returns>All custom editor parts used by this web part</returns>
        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            var editors = new List<EditorPart>();           
            var editorPart = new WebPart1EditorPart();
            editorPart.ID = ID + “_editorPart”;
            editors.Add(editorPart);

            return new EditorPartCollection(editors);
        }

        /// <summary>
        /// Returns parent web part to editor part
        /// </summary>
        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }
    }
}