Skip to content

Replace with evaluation function in PowerShell

I was looking for a way to convert a URL into a file name and back.  The problem is, of course, that URL contains characters that are not allowed in a file name such as forward slash (/), column (:), and question mark (?)

Of course, I found a whole bunch of solutions on the web, but I was not fully satisfied with any of them mostly because they were  hard to read and/or understand.

The solution that I created is short and sweet.  To convert the URL to a file name use:

get-SPSite http://mysharepoint/site

$name = [Regex]::Replace($site.Url, (\W), $toHex)

that replaces all non-alphanueric characters using the an anonymous evaluation function.

$toHex = {param($Match)(“%{0:x2}“) -f [int][char] $Match.Groups[1].Value}

the function uses -f (format) to convert each character with a % sign and the two-digit Hex value of the charachter.

ex:  http://place/my.%20weird-site-_name withspace/

becomes: http%3a%sf%2fplace%2fmy%2e%2520weird%2dsite%2d_name%20withspace%2f

The reverse function can be also used to decode URL parameters

$fromHex = {param($Match) [char][Convert]::ToInt32($Match.Groups[1].Value, 16)}

$url = [Regex]::Replace($name, ‘%(\w{2})’, $fromHex)

the regular expression “Replace” function finds the %xx combination in the string and replaces each one using the  anonymous function stored in $fromHex variable.  The evaluation function simply returns the ascii character of each Hexadecimal value.

Cool.  Isn’t it?

 

Advertisements

SharePoint solution stuck in the gullet

Every once in a while, while developing in Visual Studio 2010 and using the Deploy build, a solution will just get stuck.  One gets “Deployment Failed”  with informative messages such as “the language-natural solution package was not found…”  Say what??! 

Here is a little PowerShell snippets to help you expel the package. 

  • (get-SPSolution <package name>).Delete()

That’s it.  After running it you will be able to redeploy your solution.

If you don’t know which solution package is causing the problem just run get-spSolution and look at the list.  It is the package with a blank value in theDeployed column.

Adding Site Collection Administrators Programmatically

When creating new site collections in SharePoint you must select a Site Collection Administrator, and possibly add a secondary administrator.  For cases where you want to have more administrators, you can easily enough add more users manually.

Here is PowerShell function that adds a user to the owners group and also to Site Collection Administrators.  The function uses the get-SPClaim function from the previous post for Claims-based scenarios.  I include the function here as well for completeness.

$m = [Microsoft.SharePoint.Administration.Claims.SPClaimProviderManager]::Local
Add-PSSnapin Microsoft.SharePoint.PowerShell -ea silentlycontinue 
Function Get-SPClaim {
    param ([string]$user)
    $claim = New-SPClaimsPrincipal -identity $user -IdentityType "WindowsSamAccountName"
    return $m.EncodeClaim($claim)
}
Function Set-Owner() {
    param ([string]$login,
            $web)

    $owner = get-SPClaim($login)
    $sca = $web.EnsureUser($owner)
    $sca.IsSiteAdmin = $true
    $sca.update()
    $group = $web.AssociatedOwnerGroup
    $group.AddUser($sca)
    $group.Update()
}

One can reasonably assume that the property to control SCAs is part of the SPSite object, but then one would be wrong.  Despite the hard limit of the creation functionality, both Form and Function [sic], the inherit design is the reverse.  The property exists in SPUser and scoped to the root web (the property is named IsSiteAdmin.)  Needs some mental gymnastics, but it works…

Powershell commands with Claims Authentication

The new Claims Authentication model is very powerful and allows many more ways to authenticate into SharePoint web applications.

With every new power comes new complexity, and the one that comes with Claims Authentication will cause new and exciting ways for scripts, which were working just fine, to fail in the new environment.  Luckily, “There is a command for that” (should be PowerShell new mojo line..)

Specifically, commands that previouly (using good old NTLM) worked just fine when fed a user ID, now need a little TLC.  To help myself I created the following snippet:

$m = [Microsoft.SharePoint.Administration.Claims.SPClaimProviderManager]::Local
Add-PSSnapin Microsoft.SharePoint.PowerShell -ea silentlycontinue 
Function Get-SPClaim {
    param ([string]$user)
    $claim = New-SPClaimsPrincipal -identity $user -IdentityType "WindowsSamAccountName"
    return $m.EncodeClaim($claim)
}

The function above accepts a Windows user account name (like usa\annoying.user) creates a claim token for it using the New-SPClaimsPrincipal commandlet and returns the encoded claim (i:o#.w|usa\annoying.user, for example).

with the returned encoded claim you can now run a whole host of SharePoint PowerShell command that will not execute correctly otherwise.  Here is one for creating default groups after running New-SPSite (a new site collection created manually will do this automatically, but not the PowerShell command .  I’m sure there is a good explanation for this [not]..)

$spWeb = Get-SPWeb -identity $url
$owner = get-SPClaim("usa\Ive.gotthepower)
$admin = get-SPClaim("usa\me2")
$spWeb.CreateDefaultAssociatedGroups($owner,$admin, "Power Rangers”)
$spWeb.Update()

Reply to Comments in SharePoint 2010 Blogs

Overview (call it – The Gripe Zone)

SharePoint 2010 blogs are direct descendants of MOSS blogs.  That is not happy news for developers, as the blog features is awkwardly put together with no real API access and mysterious, undocumented inter-connections among its lists that are not very SharePoint-like.

These facts make SharePoint blogs notoriously hard to customize unless you would like to redo the whole site definition.  So, small JavaScript enhancements and other client-side are typically a good way to achieve your customizations.

The Challenge

In this installment we received a request to allow users to reply to other users’ comments.  After searching the Internet for a few hours a few good solutions surfaced.   A very good solution was the Comment Box [Web Part] for SharePoint by Alexander Bautz (to link to Alexandar’s blog entry click here). 

This is a general comment web part that you can through on any SharePoint site and get comments with replies implemented completely in JavaScript. Problem Solved!  well, not so fast.   This is a great general web part that even takes care of creating the backend list of comments.

We already have a comment list integrated into the blog site. We already had a few dozen comments that we did not want to lose, so using a new list will require additional migration work.  Even without migration, this Comment list is deeply linked with the Posts list with totals posted on the site and we wanted to keep using it.

The Solution

Comment Box for SharePoint is so well written that I had no problems digging into the JavaScript and modifying it to work for the specific needs of the blog site (alas, loosing its more general nature in the process.)    I also created a a solution (gasp.  what about Office 365?! – it’s optional..) to allow our users to quickly change their blogs to have comments with replies.  This is a convenient way to replace the existing Comment Box and comment list with the new web parts as well as make a minor change to the existing Comments list on the blog.

The event receiver does the following tasks:

    1. Validates and then adds a “Parent” column to the Comments list
    2. Modifies the Post page to hide “Comments” and “New Comment” web parts
    3. Adds a Content Editor Web-part (CEWP) with pre-defined HTML to show draw “threaded” comments.

The comment box script was modified to use the existing (but modified) Comments list.  the main change from the original javascript was to modify the PostId Parent of the list and include it in the “Insert” statement.  The PostId is grabbed from the URL by the initial javascript and then is used to tie the comment to the Post list. 

Finally, the button styles for posting and replying to the comments were matched to the blog button style with the help of css and two small images.

The final code can be found here (click here to download the code.)

If you are on the SharePoint version of this blog (www.PortalExpressions.com) you can see a live demo by posting a comment.