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 184.108.40.206 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
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])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.
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.
Document By: Chris Zwarts
Creating web parts is very similar to creating a normal page script in many ways. The main difference is that every control must be placed programmatically, instead of in a nice fuzzy GUI. It is possible to use custom user controls in web parts, but unless the part is already in another page it is often easier and better to use it programmatically, because using a normal web part, the template in visual studio can perform automatic deployment of web parts, saving a lot of time and energy.
Using these templates is much better in a clean work environment, as this allows you to easily work on a machine that is also a MOSS server. The templates will automatically generate a featurepack, so transferring this feature onto an existing server will be a rather simple process.
The Templates to work with SharePoint code are produced and distributed free of charge by Microsoft. These templates are available on their download network, and are linked as follows.
On this page, there is a link to the 2005 version, which is in essence the same thing but made for visual studio 2005. The download within this link is for visual studio 2008.
Before downloading this program, there are some things you need to know. The computer that you are installing on must have both visual studio AND WSS or MOSS. Therefore, it must be a windows 2003 server as well.
Once you have downloaded the appropriate version, you must simply double click the setup file to install the templates. I would suggest closing VS while you do this. After the installation is complete, you will be able to use the extensions. Although the scope of this document refers only to the use of the Web Part template, the other templates and the included utility (A site definition generator) can be equally useful.
When installing, the program will give a default location of the SharePoint dll (in the 60 hive). If the installation is not in a standard location, ensure that the path is corrected.
Creating a web part is now as simple as creating any other type of premade project. Upon starting visual studio, you will find that under New Project there are now several new projects, including the one we are looking for: Web part, found under the SharePoint folder in either visual basic, C# or both, depending upon what you installed.
As soon as the boilerplate loads, you will see that, regardless of what you named the project, its main class (and several files) will still be called WebPart1. You must correct this immediately, before the first build and deployment, or it will require a fairly large amount of work to change it after (it would have to be retracted, removed, etc). Also, if a name is given that is the same as an existing feature, the deployment will fail and it will screw up the system in a way that is very hard to undo, so I would suggest having a program like SharePointInspector open to check for feature names before an attempted deployment.
Correcting the name of the class can be somewhat tricky; you must change the class name, the names of the files and of the folder, and the contents of the .webpart and xml files.
First, rename the class by right clicking it and going to Refactor>Rename. Then, Rename the folder in the solution explorer to the same thing, and also the name of each file in this folder (keep the proper extensions). Then, modify the contents of the XML file to show the new filenames.
The .webpart file contains the information to display in the SharePoint part gallery. Give the webpart a name (usually the same as what you named all the files) and give it a description.
Now that the formalities have been covered, you can work on the web part as you usually would. As you can see, the GUID is automatically generated, and if you need it in any subsequent files, simply copy and paste it. The part should already have a strong name from the snk file near the top of the explorer, and this file can be changed (before deployment to avoid errors) by going into the project properties and creating a new file under the signing heading. This should not be necessary, however.