SharePoint: SafeControl Generator


Is your new web part not showing up in the SharePoint Web Part Gallery, New Web Parts page (NewDwp.aspx)?  It seems the number one problem for new (and experienced) SharePoint web part developers is getting the <SafeControl> element of the web.config file right. (especially for VB developers… see here). So here is a little console application that will read the namespace and class information from your assembly and give back a properly formatted <SafeControl> element.


Here is a typical SafeControl entry:

   1: <SafeControl 
   2:   Assembly="VBWebPart, Version=, Culture=neutral, PublicKeyToken=e7bc14c6318d16e3" 
   3:   Namespace="MaxTrain.Demo" 
   4:   TypeName="VBWebPart" 
   5:   Safe="True" />



2: Assembly: If the assembly is signed, then this is the four part name. This can be determined with the code below, or if you have deployed the assembly to the GAC, from the data displayed in the GAC (and a dozen other tools)

3: Namespace: For C# the namespace you supplied in your code:     namespace MyNamespace {}
                             For VB the name space in Project Properties plus the namespace you supplied in code

4: TypeName: Either the name of your class, or “*” for all classes in your assembly

5: Safe:  always True if you want the web part to work!


To create your own SafeControl element creator:

Create a new C# console application and name it something like SafeControlGenerator (no additional references needed). Copy and paste the following, build and test!



   C:\>  SafeControlGenerator.exe pathtoyourassembly


   C:\>  SafeControlGenerator.exe C:\Webparts\ClassLibrary1\bin\Debug\MyWebPart.dll


using System;
using System.Reflection;
namespace SafeControlGenerator
    class Program
        static void Main(string[] args)
            if (args.Length != 1)
                Console.WriteLine("Format:  SafeControlGenerator  pathToDll");
            string assemblyPath = args[0];
            Assembly a = Assembly.LoadFrom(assemblyPath);
            string fullname = a.FullName;
            if (fullname.Contains("PublicKeyToken=null")) 
                fullname = a.GetName().Name;
            foreach (Type t in a.GetExportedTypes())
                //Console.WriteLine(t.Namespace + " " + t.Name);
                Console.WriteLine("<SafeControl Assembly=\"{0}\" Namespace=\"{1}\" TypeName=\"{2}\" Safe=\"True\" />",
                                  fullname, t.Namespace, t.Name);



No comments:

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.