Monday, June 20, 2005

SharePoint 2003: How to import a Web Part and mark it safe (without adding the assembly to the GAC)

You may have encountered the following error when trying to add a Web part to a page:

A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered on this site as safe.

There are two possible causes: either the Web part has not been strongly named/hasn't been added as such in the Web.config, or the Web part's DLL or one of its referenced DLLs were not placed in the bin directory.

Below are steps to make a Web part safe:

1. The assembly has to have a strong name. You need the strong name tool sn.exe. From the command line:

cd \Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin

sn.exe -k “YourProjectPath\ProjectNameKeyPair.snk”


2. In the AssemblyInfo.cs file, find

[assembly: AssemblyVersion("1.0.*")]

and change it to [assembly: AssemblyVersion("1.0.0.0")]

scroll to the end and replace the entry that reads

[assembly: AssemblyKeyFile("")]

with

[assembly: AssemblyKeyFile("..\\..\\ProjectNameKeyPair.snk")]

3. Compile your project. Now you need to get the public key token. To do so, run the sn.exe utility again:

sn.exe –T “YourProjectPath\obj\[Release or Debug]\AssemblyName.dll

4. In the .dwp file, replace the AssemblyName entry with:

AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=PublicKey

5. In the web.config file, you need to mark the Web Part as safe by adding the following under the SafeControls section:

<SafeControl Assembly="Copy_the_entry_from_the_dwp_file" Namespace=" Copy_the_entry_from_the_dwp_file" TypeName="*" Safe="True"/>

Remember that you need to repeat the above for every DLL referenced by the WebPart (directly or indirectly)

6. Copy the Web Part’s DLL (and dependencies) to the bin directory under the SharePoint directory. If there isn’t one, create it.

7. Add the .dwp file using the import function.

Resources:

1. Create a basic WebPart
2. MSDN SharePoint: making a WebPart safe
3. SharePoint Products and Technologies Resource Kit

No comments: