User Controls in Sharepoint Web Parts

March 5, 2009

Posted By: Chris Zwarts

Creating web parts is fairly easy in the Visual Studio environment, especially when using the templates. But there are times when creating a user control interface that writing simple code simply is far too difficult. It is, of course, possible. You can write the html code in there with C# commands, and create the ASP.NET controls inside these containers. For simple controls, where only some data is entered, this can be reasonable. But for web parts with a complicated user interface, this can be a very tedious process, in which any mistakes will make the whole part unusable.

    There are other situations where it would be very useful to use a custom web user control in the place of or with a web part. If the web user control is already made to be used in a classic ASP.NET page, moving it into Sharepoint would be far easier if you could just “wrap” the control into a Sharepoint web part.

    And this is fairly easy to accomplish.

    As for deployment, with the use of the template system for MSVS, the web user control is automatically deployed to the proper folder, making this a viable and secure solution.

    Here’s how it works.

Creating the Projects

The Web Part

    First, the obvious thing to do is to create a new solution that contains a Web Part Project, and to modify the web part as in my previous post so that it will compile properly. Then build it (but do not yet deploy!) and find the public key token, as outlined in my other post here.

The User Control

    A custom web user control is a simply a type of file, similar to a ASPX web page. This control, however, is actually a “piece” of a web page. It represents something similar to a hard-coded web part, that can be inserted into a master page. In this case, however, we will simply be wrapping it into the Sharepoint Web Part.

    The only problem is that Web User Controls can only be created in a web page project, not in the new Sharepoint Template projects.

    The solution to this problem is to create an empty Web Page by right clicking the solution and adding an ASP.NET Web Application. Remove the default.ASPX file from the solution, and create the new Web User Control by right clicking the project in the solution explorer and clicking the Add new Item item. Then, select the Web User Control, give it a name, and insert it.

    In the Solution Explorer, Add a reference to Microsoft.Sharepoint by going into the solution explorer, navigating to the user contol project, and right clicking references>Add Reference. Find Microsoft.Sharepoint in the list. it may be called Microsoft (r) sharepoint services.

    In the ASCX file, remove the reference to the code behind file that is in the top <% %> block. This will cause the web control to have no true ASP.NET code associated with it yet. Also, change the Inherits property to

Inherits=”[WebPartName].[UserControlName], [WebPartName], Version=[#.#.#.#], Culture=neutral, PublicKeyToken=###################” %>

You should have found the public key token earlier in the project, and here is where you put it. The Version should be at and incremented as required.

    Save the whole project, making sure that you know where it is for later reference.

Referencing the UserControl

The Web Part must be connected to the User Control by adding it to the proper folders in the 12 hive. This is easy to do by creating a folder hierarchy in the solution explorer. Add a folder tree in the Web Part Project as follows by right clicking each folder and adding another folder inside:Templates > ControlTemplates > [the name of your part]. Add the ASCX file reference to this folder by right clicking this folder, going to Add > Existing Item, and selecting the ASCX file that you created earlier. Make sure that you add it to the project as a link (in the drop down box.).

    Open the ASCX.CS and designer.cs files that are added as links with the ASCX file, and modify the namespace so it matches that of the Web Part. Add the statements

        using Microsoft.Sharepoint;
     using System.Web;

    to the ASCX.CS file if you plan on using any sharepoint environment variables.

    Now the user control can be modified as any other ASP.NET web app. Code can be added to the ASCX.CS File just like normal. Adding an SPweb variable to the Main class of the Web User Control allows you to access variables like SPweb.CurrentUser.Name from Sharepoint.

    Once you have the web user control looking the way you wish, it is time to add it to the compile code in the web part project. Make sure to build the solution to make sure there are no errors!

    After this file is added to this set of folders, upon compilation of the program you will find that the file has been added to the templates in the 12 hive of the sharepoint directory. However, the compiled program will not show anything. You have not yet wrapped it into the code for the web part itself!

    Add the following code where the commented TODO code is in the web part cs file.

 [usercontrolname] USControl =

([usercontrolname])Page.LoadControl(“~/_controltemplates/[Your Web Part Name]/[usercontrolname].ascx”);

    USControl.Web = SPContext.Current.Web;

    // Adds it to the controls collection of the Web Part



    This may have seemed like more work to some of the veterans of Sharepoint Development. References and extra code seem to take extra time to write and compile. But this is where writing the web part using the template really shines.

    To compile the web part, just right click the solution, and click deploy.

    That’s it! In the bin folder of the project, under the appropriate build, the .wsp featurepack is prebuilt and ready to deploy! By copying the entire release folder to another computer, the entire solution could easily be deployed onto another server farm.


Finding the Public Key Token

March 5, 2009

Posted By: Chris Zwarts

Microsoft uses a system of public keys in order to escape the problems of an earlier time, when any assemblies that had the same name, culture and version would interact badly or cause the assemblies to operate incorrectly. The solution was to give each strongly named assembly a public key, unique from all the other dlls. This public key is huge, 1024 bits in length, to ensure that there is minimal chance of duplicate keys. In order that this key be easily referenced (1024 bits is simply to long to work with), Microsoft uses an algorithm to generate a public key token from this key, which can be used in your programs. However, the algorithm is unclear. It is hard to manually generate a public key token. Luckily, Visual studio includes a command prompt tool called Sn.exe, which can be used to extract the public key either from the snk file in your project or from the dll after compilation

Using the Command Prompt

    This is the hard way to do things, but it offers you far more control over the finer elements of strong naming, if you need them. If all you need is the key token, skip this and go to the next heading “Using the Tools Menu”.

    Using the Command Prompt, you can access the public key token in one of 2 ways, depending upon whether or not the program has been built yet. Both of these methods require the Sn.exe tool. Open a visual studio command prompt from start>Program Files>Microsoft Visual Studio>Tools>Command Prompt. Navigate to your project folder, using the dir and cd commands like usual.

    Once you have found your project, you can extract the key. To extract it from the dll, navigate into the build, find the dll, and run >sn.exe -Tp “myassem.dll” (Obviously replacing myassem with the name of your assembly.). Notice the uppercase T in -Tp.

    To extract it from the snk file, navigate to it’s folder and run the following

command: >sn.exe -tp “mystrnm.snk” (Also replacing the name with your own.). Notice the lowercase t.

    Each of these commands will bring up the entire public key (wow it’s long, huh?) as well as, at the very bottom, the much-easier-to-handle public key token. It can be copied out and used as required.

Using the Tools Menu

     This method is far easier if you simply want to extract the token, nothing more. Open up the tools menu in visual studio, go to external tools and click add. In this box, enter the following lines:

Name:        Public Key Extractor

Command:   C:\Program Files\Microsoft Visual Studio #\SDK\v#.#\Bin\sn.exe.

Arguments: -Tp “$(TargetPath)”

(If you have more than one version in the SDK path, find the most recent one that has the SN.EXE file in it.)

Uncheck all the boxes, except for the use of the output window.

Now, going to the tool menu, you will find that there is a new command called Public Key Extractor. This tool will find the PKT for any built project.