Just Add Code

Archive for July, 2007

Creating SharePoint’s SafeControl Entries in PowerShell

Manually adding a new assembly for anWebPart to SharePoint can be a hassle. I always hate tracking down the various parts of the SafeControl line to add to the web.config. If you’ve ever done this manually before, you know that the most time consuming part is finding the public key token My preferred way had been to use ‘sn.exe -T someAssembly.txt’, but in .NET 2.0 sn.exe was no longer included with the default install. Once again, PowerShell gave me a simple solution:

1
2
3
$assembly = [System.Reflection.Assembly]::LoadFile("c:\temp\TestWebPartLibrary.dll") 
$name = $assembly.GetName() 
"<SafeControl Assembly=""{0}"" Namespace=""{1}"" TypeName=""*"" />" -f $assembly.FullName,$assembly.GetName().Name

The first line loads a dll into PowerShell and stores the resulting System.Reflection.Assembly in a variable. The next line stores the results of Assembly.GetName() into a local variable we can use later. The final line similar to String.Format in .NET. $assembly.FullName outputs the entire value for Assembly we need, including that pesky public key token!  For the Namespace attribute, I’m just using the name of the assembly. This isn’t necessarily true in all cases, but I usually have the dll and namespace sharing the same name.

When running these three lines I get the following familiar result:

<SafeControl Assembly="TestWebPartLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=82a1533dcdde9e6a" Namespace="TestWebPartLibrary" TypeName="*" />

Since we’re now able to create the line for a single .dll, lets wrap it up in a function so we can get a bit more mileage out of it.

function get-safecontrolline($assemblyLocation) 
{
   $assembly = [System.Reflection.Assembly]::LoadFile($assemblyLocation)
   $name = $assembly.GetName()
   "<SafeControl Assembly=""{0}"" Namespace=""{1}"" TypeName=""*"" />" -f $assembly.FullName,$assembly.GetName().Name 
}

Now we can call it and pass in the file as an argument. Now its a snap to generate the SafeControl entries for an entire directory!

C:Temp > dir *.dll|%{get-safecontrolline($_) } 
<SafeControl Assembly="TestWebPartLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=82a1533dcdde9e6a" Namespace="TestWebPartLibrary" TypeName="*" /> 
<SafeControl Assembly="AnotherLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=82a1533dcdde9e6a" Namespace="AnotherLibrary" TypeName="*" />        

C:Temp >
3 comments