Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / IIS

Base class for skinned Web Parts and generator tool

4.33/5 (5 votes)
19 Jan 2009CDDL12 min read 2   101  
Base class for skinned Web Parts and a tool that will generate Web Part code based on previously made layout (ASCX)
Click for full size image

A new article

It was a year ago when I posted this article. We made a new release on codeplex with a VisualStudio Add-In that allows you even easier web parts generation. I also wrote a new article here on codeproject that explains how the web part should be used. You can read that article here.

Introduction

When I started working with Web Parts the first thing that I really missed was a possibility to work with Web Parts the way I worked with ASP.NET web pages and web user controls. In other words, I missed the ability to separate design/layout of Web Part from the "code behind" or business logic. Beside the fact that design is not separated from code behind I really didn't like the fact that I had to spend a lot of time writing everything manually.

Background

Some time ago I read a great article made by Michiel Van Otegem about skinned controls (http://www.code-magazine.com/article.aspx?quickid=0401051&page=1). Based on his idea and based on functionality of his SkinnedPart I made BaseSkinnedWebPart which is slightly improved Michiel's control. Beside that I created a console application that generates Web Parts based on already made skins (ASCX controls).
Another advantage of using the base class and swpgen is the fact you can create multiple skins (ASCX) controls and choose different look for your Web Parts at runtime.

Using BaseSkinnedWebPart and swpgen.exe (generator tool) developers can work with web parts almost the same way they work with web pages and web user controls. Base idea is as follows (more detailed explanation will follow below):
  1. Create an ASCX control without code behind (just ASCX file with ASP.NET controls and other HTML)
  2. Use swpgen.exe to generate class that inherits from BaseSkinnedWebPart and uses previously made ASCX control (skin)
  3. Add generated classes to a Web Parts project and add additional functionality the same way you would work with a regular web page.

A practical example

I’ll show here all the steps one should take in order to make a fully functional Web Part leveraging the functionalities of BaseSkinnedWebPart and using the swpgen generator tool.

Part 1 – Creating initial skins

In Part 1 I’ll cover the creation of initial skin. Here are the steps that one could perform:
  1. Create initial solution
    1. Open VisualStudio (I used version 2005 with SP1 in this example)
    2. Select File --> New --> Project from main menu
    3. Expand the “Other Project Types” node in “Project types:” section
    4. Click on “Visual Studio Solutions” node below “Other Project Types” node
    5. Click on “Blank Solution” node in “Templates” section (on right side)
      swpgen1_1.jpg
    6. Enter “Name” and “Location” for new solution and click OK
  2. Add a Web Application Project that will hold skins
    1. Right click on solution in “Solution Explorer”
    2. Choose “Add” ==> “New Project...”
    3. Click on “Visual C#” in “Project types:” section
    4. Select ASP.NET Web Application in “Templates” section (on right side)
    5. Enter “Name” and “Location” for your new Web Application project
      swpgen3.jpg
    6. Click OK button
  3. Remove unnecessary items
    1. Select Default.aspx and Web.config files
    2. Right click on selection and choose “Delete” menu item
    3. Confirm that you want to delete selected items
  4. Create initial skins folder structure
    NB: in this sample I planned to have to have two themes/skins for my web part. Depending on number of skins you want for your web parts you can make a slightly different configuration. You can also change this later if you want or if you need to add new skins.
    1. Right click on your Web Application project in Solution Explorer
    2. Choose “Add” ==> “New Folder”
    3. Name first folder “default”
    4. Repeat steps a. to c. to create another folder named “theme2”
  5. Add new “skins”
    1. Right click the “default” folder in your Web Application’s project
    2. Choose “Add” ? “New Item...”
    3. Select “Web User Control” in “Templates” section
    4. Enter name for your first skin; NB: I suggest you name skin the same way you will name your Web Part (just with extension ASCX instead of CS)
    5. Click “Add”
    6. Right click on “theme2” folder and repeat steps b. to e. (you can give the same name to skins in both folders)
  6. Remove code-behind files
    1. Expand both folder’s nodes
    2. Expand both ASCX control’s nodes
    3. Select “.ascx.cs” and “.ascx.designer.cs” files for first skin
      swpgen4.jpg
    4. Right click on selection and choose “Delete” menu item
    5. Confirm that you want to delete selected items permanently
    6. Repeat steps c. to e. for the second skin (in “theme2” folder)
  7. Design your skins
    1. Double click “SampleWebPart.ascx” in “default” folder
    2. Modify first line not to include any information about code-behind files. The line should looks like this at the end:
      C#
      <%@ Control %>
    3. Create layout of your skin by adding html and server controls; NB: you can use VisualStudio’s Designer to design the skin
      swpgen5.jpg swpgen6.jpg
    4. Repeat steps from a. to c. on ASCX control in “theme2” folder. NB: you can have completely different layout of controls in two skins but it is important that you have the same server controls in both skins (you can hide some server controls in one skin if you want but the controls must be present anyway).

Part 2 – Generating Web Part

In Part 2, I’ll cover the generation of Web Part class based on previously made skin. Here are the steps that one could perform:
  1. Download generator tool
    1. Go to the codeplex project where generator tools is hosted (http://www.codeplex.com/aspnetlibrary)
    2. Go to “Releases” section and locate the latest release of “ASPNETLibrary.SharePoint.WebParts” project
    3. Download the “Generator.zip” from the “Files” section at the bottom of the page; NB: at the time this article was written, the latest release was located at the following URL: http://www.codeplex.com/aspnetlibrary/Release/ProjectReleases.aspx?ReleaseId=10932
  2. Setup the tool
    1. Unpack downloaded archive to a folder on local disk; I unpacked it into “c:\Program Files\swpgen\” folder
    2. Add the tool’s folder to PATH environment variable
      1. Right click “My Computer” and select “Properties” menu item
      2. Go to advanced tab
      3. Click on “Environment Variables...”
      4. Locate “Path” variable in “System Variables” section
      5. Modify it by appending the semicolon character and path to the folder holding extracted archive; in my sample I added “;c:\Program Files\swpgen” to existing value of “Path” environment variable.
  3. Generate Web Part
    1. Open command prompt and navigate to “default” folder in your Web Application’s project
    2. You can optionally type and execute “swpgen” to see all the available options
      swpgen7.jpg
    3. Type next command to generate the Web Part:
      swpgen /source:SampleWebPart.ascx /namespace:MyCompany.MyProject.WebParts
NB: the command above will generate a Web Part class called SampleWebPart in namespace MyCompany.MyProject.WebParts.

Part 3 – Working on generated Web Part

In part 3, I’ll show how generated class should be used and customized. Here are the steps that one could perform:
  1. Create Web Parts project
    1. Go to your solution in VisualStudion
    2. Right click on solution and select “Add” ? “New Project...”
    3. Choose “Class Library” in “Templates” section
    4. Enter name for the project; I used “SampleWebParts” for the name in this sample
    5. Click OK
    6. Delete “Class1.cs” by right clicking it, selecting “Delete” menu item and confirming that you want to permanently delete it
    NB: You could also create a “Web Parts” project but I used a “Class Library” project in this sample as a more general solution.
  2. Add generated files to Web Parts project
    1. Go to the folder where you generated Web Part’s class. In my sample it was “C:\MyProjects\samples\SampleBaseSkinnedWebPart\SampleSkinns\default”
    2. Copy both generated files to folder holding Class Library project you created in step 1. In my sample, it is a “c:\MyProjects\samples\SampleBaseSkinnedWebPart\SampleWebParts” folder and generated files are:
      1. “SampleWebPart.cs” and
      2. “SampleWebPart.generated.cs”
    3. Go to VisualStudio and click on Class Library project (in my sample I clicked on SampleWebParts project)
    4. Select “Show All Files” option from Solution Explorer’s top menu as shown on next screen shoot
      swpgen8.jpg
    5. If you copied the files to the right folder then you will be able to see two generated files under the SampleWebParts project node. Select them, right click on selection and choose “Include in Project” menu item.
    6. Turn off the “Show All Files” option
    NB: instead of steps a. to f. you could right click on SampleWebParts project, choose “Add” ? “Existing Item...”, navigate to generated files, select them both and include in project.
  3. Add references to required assemblies
    1. In Solution Explorer, right-click the project, and then click Add Reference on the shortcut menu
    2. On the .NET tab of the Add Reference dialog box, select Windows SharePoint Services in the list of components, and then click OK
    3. Go to the codeplex project where generator tools is hosted (http://www.codeplex.com/aspnetlibrary)
    4. Go to “Releases” section and locate the latest release of “ASPNETLibrary.SharePoint.WebParts” project
    5. Download the “ASPNETLibrary.SharePoint.WebParts.zip” from the “Files” section at the bottom of the page; NB: at the time this article was written, the latest release was located at the following URL: http://www.codeplex.com/aspnetlibrary/Release/ProjectReleases.aspx?ReleaseId=10932
    6. Open Windows Explorer, navigate to folder where solution file is and create a folder called “ExternalReferences”. In my sample that is “c:\MyProjects\samples\SampleBaseSkinnedWebPart” folder
    7. Extract the downloaded archive to “ExternalReferences” folder
    8. Go to VisualStudio, right click on solution, choose “Add” ? “New Solution Folder” and set the name of solution folder to “ExternalReferences”
    9. Right click “ExternalReferences” solution folder and choose “Add” “Existing Item...”
    10. Navigate to “ExternalReferences” folder and choose “ASPNETLibrary.SharePoint.WebParts.dll”
    11. Right click the Web Parts project (in my sample it is SampleWebParts project) and choose “Add Reference...”
    12. Click on “Browse” tab, navigate to “ExternalReference” folder and choose “ASPNETLibrary.SharePoint.WebParts.dll”
    13. Right click the Web Parts project (in my sample it is SampleWebParts project) and choose “Add Reference...”
    14. From the “.NET” tab select “System.Web” assembly
  4. Add some code
    1. Open SampleWebPart.cs from SampleWebParts project
    2. Go to “Initialize” method and add next code:
      C#
      this._newQuestion.Click += 
          new EventHandler(NewQuestionClick);
      this._submit.Click += new EventHandler(SubmitClick);
      this._statusMessagePanel.Visible = false;
    3. Add next two event handlers to SampleWebPart class:
      C#
      void SubmitClick(object sender, EventArgs e)
      {
          this._statusMessagePanel.Visible = true;
          this._submitQuestionPanel.Visible = false;
          this._status.Text = 
              "Your question was successfully submited.";
      }
      
      void NewQuestionClick(object sender, EventArgs e)
      {
          this._submitQuestionPanel.Visible = true;
          this._statusMessagePanel.Visible = false;
      }
  5. Strongly sign the assembly
    1. Right click SampleWebParts project and choose “Properties”
    2. Go to Signing tab
    3. Select “Sign the assembly” option
    4. Open the drop down list and select “<new...>” item
    5. Put a name of key file. I put SampleWebParts
    6. Deselect “Protect my key file with a password” option and click OK

Part 4 – Creating setup scripts and setup project

In part 4, I’ll explain how setup scripts and setup project for deployment of Web Part should be made. Follow next steps in order to make the setup scripts:
  1. Create setup scripts
    1. Go to SampleWebParts project, right click on it, choose “Add” ? “New Folder” and name it “Configuration”
    2. Add three new files to the Configuration folder:
      1. SampleWebPart.dwp – a Text File
      2. manifest.xml – a XML File
      3. setup.cmd – a Text File
    3. Edit three files and set their content to be like the content of three files you can find in accompanied sample solution. NB: you will need to modify the value of “Assembly” tag in SampleWebPart.dwp and in manifest.xml for “SampleWebParts.dll “ (to set the right PublicKeyToken) and value of “url” parameter in setup.cmd (to URL of web site where you want to deploy Web Part)
    4. Select all three files, right click on selection, choose “Properties” and in “Build Action” drop down choose “Content”
  2. Create a setup project
    1. Right click on solution and choose “Add” ? “New Project...”
    2. Expand “Other Project Types” node in “Project Types:” section and select “Setup and Deployment” node
    3. Select “CAB Project” project type in “Templates:” section (right side)
    4. Type the name of the project and click OK (I entered SampleWebParts.Setup as name of the project)
    5. Right click on setup project you created in previous step and choose “Add” ? “Project Output”
    6. Select “SampleWebParts” in “Project:” drop down list
    7. Select “Primary output” and “Content Files” by holding down the “Ctrl” key and clicking on two items
    8. Click OK swpgen9.jpg
    9. Right click on setup project you created in previous step and choose “Add” ? ”File...”
    10. Navigate to “ExternalReferences” folder and select “ASPNETLibrary.SharePoint.WebParts.dll” file

Part 5 –Web Part deployment

In part 5, I’ll explain how the Web Part can be deployed to MOSS and how it should be configured to work properly. You can follow next steps:
  1. Deploy Web Part
    1. Copy “setup.cmd” file from “Configuration” folder (in my sample it is “C:\MyProjects\samples\SampleBaseSkinnedWebPart\SampleWebParts\Configuration\setup.cmd” file) into “Debug” folder of Setup project (in my sample it is “C:\MyProjects\samples\SampleBaseSkinnedWebPart\SampleWebParts.Setup\Debug” folder)
    2. Execute “setup.cmd” to deploy Web Part to MOSS NB: I would suggest you open a command prompt, navigate to “Debug” folder and execute setup.cmd from command prompt so that you can see if deployment went fine
  2. Setup MOSS web site
    1. Open InternetExplorer and go to your MOSS web site (the one where you deployed Web Part in previous step)
    2. Select “Site Actions” ? “Create”
    3. Choose “Document Library” under the “Libraries” section
    4. Set “Name” field to “Themes”
    5. Click “Create”
    6. In “Themes” document library click on small arrow next to “New” button and then on “New Folder”
    7. Type “default” for name of folder and click OK
    8. Repeat steps f. and g. and create a new folder called “theme2”
      swpgen10.jpg
  3. Upload skins
    1. Go to “default” folder
    2. Click on “Upload” button
    3. Click on “Browse” button, navigate to skin in default folder (in my sample it is “c:\MyProjects\samples\SampleBaseSkinnedWebPart\SampleSkinns\default\ SampleWebPart.ascx” file), click “Open” and then “OK” to upload the skin (ASCX file) into “default” folder in “Themes” document library
    4. Repeat steps a. to c. by choosing “theme2” folder instead of “default” in all steps
  4. Add Web Part to a page
    1. Go to a web page where you want to put your Web Part
    2. Select “Site Actions” ? “Edit Page”
    3. Click on “Add a Web Part” button in section where you want web part to be added
      swpgen11.jpg
    4. Find “Base Skinned Web Part Sample 1” under the “Miscellaneous” section
    5. Select it by clicking on check box and click “Add”
      swpgen12.jpg
    6. Open “edit” menu for added Web Part and then select “Modify Shared Web Part” option
      SampleBaseSkinnedWebPart
    7. Go to “Skinned Web Part Settings” section and see how you can choose different theme for your Web Part and different skin under the selected theme.
    8. After you choose the preferred skin, click “OK” and then “Exit Edit Mode”
    NB: you can try how the Web Part works if you click on “Submit” button in Web Part and then on “New Question” button; it will not do anything special except to show/hide different panels but it should be enough for demonstration.

Appendix A – Useful Links

Here are a few URLs that can be useful:

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)