My blog has moved!

My blog has moved to http://www.lamber.info. Click on the redirect button below to be redirected to the blog post.

Please update your bookmarks and use the new url for getting new updates.

Pages

Saturday, May 29, 2010

How do I create custom Editor Parts for my Visual Web Parts?

Hi all,

we saw how to build a simple address Web Part in my last post of my post series about Visual Web Part development. We saw how we are able to bind persistent custom properties to our web part instances by simply using attributes associated to our properties. These properties are then mapped automatically for us in the web part editor. This behavior may be enough for most of the cases, however, there are certain situations, where we want to have more control on the behavior of the web part editor. Examples are the addition of more complex controls and data validation. In this post we are going to explore the customization of Editor Parts for our Web Parts.

Walkthrough

At the beginning of this post we are going to explore what are the automatically rendered properties of the Web Part framework. These types are mapped automatically to control in our Editor Parts for us.

After this introduction, we are going to create an Editor Part by following these steps:

  • Step 1: Create a new class and inherit from Editor Part and add the abstract methods
  • Step 2: Add the controls to the Editor Part
  • Step 3: Synchronize the content of the controls in the Editor Part with the properties of your Web Part class
  • Step 4: Add a Editor Part reference to your Web Part

Which types are automatically mapped by the Web Part framework?

We know, that basic types are mapped automatically to controls in our Editor Parts for us. To check the different rendered controls, we have to create a new project called EditorPartExample.

  • create a Visual Web Part project EditorPartExample
  • Add in this project a new Visual Web Part EditorTestWebPart
  • add the following code into the EditorTestWebPart.cs file. (If you don’t know how to do it, follow this and this post).
namespace EditorPartExample.EditorTestWebPart
{
public enum EditorTestEnum
{
Value = 1,
Value = 2,
Value = 3
}

[ToolboxItemAttribute(false)]
public class EditorTestWebPart : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @~/_CONTROLTEMPLATES/EditorPartExample/EditorTestWebPart/EditorTestWebPartUserControl.ascx";

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public String PropertyAsString { get; set; }

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public int PropertyAsInteger { get; set; }

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public Boolean PropertyAsBoolean { get; set; }

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public EditorTestEnum PropertyAsEnum { get; set; }

protected override void CreateChildControls()
{
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
}
}
}

Only for illustrative purposes we are using different basic types and check how they look like in our Editor Part. Deploy your project and add the newly create Web Part to any page. Edit the page and you see these different mapping:

  • String: mapped as text editor
  • Integer (numeric values in general): mapped as text editor with a number validation (try to insert a String and press “Apply” if you don’t believe me)
  • Boolean: mapped as checkbox
  • Enum types: mapped in a dropdown list


image

Pretty neat stuff, however, we encounter some drawbacks when using only the automated approach:

  • you can’t include complex types (e.g., list of custom classes)
  • you don’t have much control on the validation of your controls. However, you can do this with basic types (check this post if you want to see how it may work).
  • you have to stick on the standard layout rules of the Editor Part (e.g., if you want to modify an integer property with a range of values included into a dropdown box that can’t be defined as an enum type)

Creating the first Editor Part

If we want to get more from the Editor Part, we have to customize it and create our own. Fortunately, this step is not so difficult as you might think. The Web Part framework does most of the job for us, we only need to create a new class and inherit from the EditorPart class of the Web Part framework. Then we have to add custom code and create our user interface from scratch. The steps needed to accomplish this task are:

  • Step 1: Create a new class and inherit from Editor Part and add the abstract methods
  • Step 2: Add the controls to the Editor Part
  • Step 3: Synchronize the content of the controls in the Editor Part with the properties of your Web Part class
  • Step 4: Add a Editor Part reference to your Web Part

To illustrate these steps, we are going to create a custom Editor Part that edits our property PropertyAsInteger in a custom way: we want a Dropdown list with the values ranging from 0 to 5. When the user edits the Web Part, he will see the Dropdown list and use it to modify the value of our Web Part property.

Step 1: Create a new class and inherit from Editor Part and add the abstract methods

First of all, we are going to create a new class called SampleEditor.cs and add it to our EditorTestWebPart container and setup the class to inherit from the EditorPart class of the Web Part framework. Please change the code of the SampleEditor.cs to the code you see in the next code snipped.

image

namespace EditorPartExample.EditorTestWebPart
{
public class SampleEditor : EditorPart
{
public override bool ApplyChanges()
{
throw new NotImplementedException();
}

public override void SynchChanges()
{
throw new NotImplementedException();
}
}
}

Step 2: Add the controls to the Editor Part

We only created a simple class. Now, we are going to extend it and put some controls. In our case we are going to add a DropDown list holding the values from 0 to 5. The code snipped that does it is shown below:

namespace EditorPartExample.EditorTestWebPart
{
public class SampleEditor : EditorPart
{
private DropDownList list;

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
list = new DropDownList();
}

protected override CreateChildControls()
{
base.CreateChildControls();
this.Controls.Add(list);
}

protected override void OnPrerender(EventArgs e)
{
base.OnPreRender(e);

list.DataSource = new int[] { 0, 1, 2, 3, 4, 5 };
list.DataBind();
}

public override bool ApplyChanges()
{
throw new NotImplementedException();
}

public override void SynchChanges()
{
throw new NotImplementedException();
}
}
}

What we did until now? We defined a Dropdown and initialized it in the OnInit method of the Web Part. In the CreateChildControls added the control to the Editor Part control list. At the end, we added an array of integers ranging from 0 to 5 to the datasource property of our dropdown list. There are still two methods that need to be implemented

Step 3: Synchronize the content of the controls in the Editor Part with the properties of your Web Part class

The content synchronization between Web Parts and Editor Parts is done by two methods:
  • The ApplyChanges method is called when the Editor Part applies the changes or presses ok. This is the right moment to save the properties back to our Web Part.
  • On the other hand, the SynchChanges method is used to synchronize the Web Part properties with our Editor Part.

In our example we are doing following. The code snippet that follows reflects these actions:

  • In the ApplyChanges method we are retrieving the Web Part instance that is currently edited and set the property that we want to change to the property defined in our Dropdown list. Afterwards, we tell to the Web Part framework that we passed correctly the values by returning true.
  • In the SynchChanges method we do it in the inverse order. We take the values from the Web Part that we want to edit and synchronize them with the controls in our Editor Part.
namespace EditorPartExample.EditorTestWebPart
{
public class SampleEditor : EditorPart
{
private DropDownList list;

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
list = new DropDownList();
}

protected override CreateChildControls()
{
base.CreateChildControls();
this.Controls.Add(list);
}

protected override void OnPrerender(EventArgs e)
{
base.OnPreRender(e);
list.DataSource = new int[] { 0, 1, 2, 3, 4, 5 };
list.DataBind();
}

public override bool ApplyChanges()
{
EditorTestWebPart webPart = this.WebPartToEdit as EditorTestWebPart;

if (webPart != null)
{
webPart.PropertyAsInteger = int.Parse(list.SelectedValue);
}

return false;
}

public override void SynchChanges()
{
EditorTestWebPart webPart = this.WebPartToEdit as EditorTestWebPart;

if (webPart != null)
{
list.SelectedValue = webPart.PropertyAsInteger.ToString();
}
}
}
}

Step 4: Add a Editor Part reference to your Web Part

We are almost finished. Our simple custom Editor Part is finished, but, the Web Part framework does not know that we want to bind this editor part to our Web Part. Therefore, we need to tell to the EditorTestWebPart, that we want to use this custom Editor Part when going in edit mode. In addition, we have to tell to the Web Part framework, that the property PropertyAsInteger should not be generated automatically in our editor. To do this we have to follow these steps:

  • Go to the EditorTestWebPart.cs
  • Override the method CreateEditorParts and add your Web Part to the EditorPart collection
  • Remove the WebBrowsable attribute from the PropertyAsInteger property
  • The final code in the Web Part EditorTestWebPart.cs will look like that:

namespace EditorPartExample.EditorTestWebPart
{
public enum EditorTestEnum
{
Value = 1,
Value = 2,
Value = 3
}

[ToolboxItemAttribute(false)]
public class EditorTestWebPart : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @~/_CONTROLTEMPLATES/EditorPartExample/EditorTestWebPart/EditorTestWebPartUserControl.ascx";

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public String PropertyAsString { get; set; }

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public int PropertyAsInteger { get; set; }

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public Boolean PropertyAsBoolean { get; set; }

[Personalizable(), WebBrowsable(), Category("Web Part Properties")>
public EditorTestEnum PropertyAsEnum { get; set; }

protected override void CreateChildControls()
{
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
}

public override EditorPartCollection CreateEditorParts()
{
List<EditorPart> editorParts = new List<EditorPart>();
SampleEditor sampleEditor = new SampleEditor();
sampleEditor.ID = this.ID + "_sampleEditorPart";
editorParts.Add(sampleEditor);

return new EditorPartCollection(base.CreatEditorPart, editorPart);
}
}
}
 

And we are done. Finally, you only need to deploy the solution to SharePoint and use your Web Part.

Summary

Now, that you saw how to create and combine a custom Editor Part with a Web Part, you can do whatever you want. However, there is still a big drawback with this technique. You have to create your Editor Part from scratch by hand. However, I will show you in a post that will follow in the next day, that with some simple modifications, we will be able to use the same approach of the Visual Web Parts with our Editor Parts. Are you interested how this might work? Then follow and bookmark my post series about Visual Web Part development. :)

 

Best regards,

Patrick Lamber

Friday, May 21, 2010

How do I create custom properties in Visual Web Parts?

Hi,

in this post of my Visual Web Part post series we are going to see how to setup custom properties in Visual Web Parts. As you probably know, the most interesting aspect of Visual Web Parts is the ability to configure them directly on a SharePoint page by changing properties during runtime. These properties are stored into the database and reused on each page load. This provides endless scenarios to build configurable pages.

We will follow the creation process of a simple Web Part storing addresses. This Web Part will provide custom properties that are modifiable by a SharePoint user. We will follow the steps that we already covered in detail here. The address Web Part will look like the Web Part in the next figure. We have a simple address consisting of a name, street, zip code and city. We want that these settings are configurable on each single page by our customers. image

This post is subdivided into three sections:

  • Preparing the project: we setup the Visual Web Part project and check the settings that we might want to change before deploying our Web Part
  • Personalize the Address Web Part: we see how we can add customizable properties, and how we connect them to our Visual Web Part
  • Some improvements: we make some small modifications to the Web Part that we created to improve the “look & feel” and “usability” of our Web Part
  • Points to consider: some notes to consider during Web Part development

Preparing the project

Let us jump in directly in the creation of the Visual Studio project with the Visual Web Part project template for SharePoint 2010.

  • create a new Visual Web Part project named “Examples.AddressWebPart” (if you don’t know how to do it, follow this link).
  • since the assembly name is called exactly the same, we don’t need to make further changes in the project property page
  • delete the Visual Web Part called “VisualWebPart1”
  • add a new “Visual Web Part” and call it “Address”
  • open the “Features” folder and double click on “Feature 1”. Change the feature name to “Addresses Feature” and description to “This feature activates the address-related Web Parts”. Ensure that the “Address” Web Part is listed in this feature on the right side. You see an example in the next picture:

image

  • we don’t make any changes to the package name, because it will be called like our project name. This is good for us.

Now, we are going to make small changes to our Web Part configuration files “Address.webpart” and “Elements.xml” in the “Address” container. We make these changes to complete our configuration process and to provide a better description to our Web Part on our SharePoint site.

  • Let us change the description shown in the Web Part catalog. Double click on the Address.webpart file in the Address container and change the description of the Web Part to “Displays a personalizable address on the screen”. The code will look similar to the next code snipped:
  1: <?xml version="1.0" encoding="utf-8"?>
  2: <webParts>
  3:   <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
  4:     <metaData>
  5:       <type name="Examples.AddressWebPart.Address.Address, $SharePoint.Project.AssemblyFullName$" />
  6:       <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
  7:     </metaData>
  8:     <data>
  9:       <properties>
 10:         <property name="Title" type="string">Address</property>
 11:         <property name="Description" type="string">Displays a personalizable address on the screen</property>
 12:       </properties>
 13:     </data>
 14:   </webPart>
 15: </webParts>



  • Finally, we change the category associated to our Web Part in the Web Part catalog. We will change the property value to “Utilities”.



  1: <?xml version="1.0" encoding="utf-8"?>
  2: <Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
  3:   <Module Name="Address" List="113" Url="_catalogs/wp">
  4:     <File Path="Address\Address.webpart" Url="Address.webpart" Type="GhostableInLibrary" >
  5:       <Property Name="Group" Value="Utilities" />
  6:     </File>
  7:   </Module>
  8: </Elements>


 



Personalize the Address Web Part



Development of Visual Web Parts is simple if you know the most important files to change:




  • “Address.cs”: the class inheriting from the Web Part base class and used to setup personalization settings. In addition, this class is loading the web user control needed for our Visual Web Part functionalities


  • “AddressUserControl.ascx”: this controls gives us the design time capabilities of Visual Studio 2010



The basic approach is:




  • configure the properties of the Web Part class to be persisted


  • combine the Web Part class with the web user control to control the rendering behavior



First, let us add the properties that we want to persist with the Web Part framework by adding some code in the “Address.cs” file. Follow the next code example.



  1: namespace Examples.AddressWebPart.Address
  2: {
  3:     [ToolboxItemAttribute(false)]
  4:     public class Address : WebPart
  5:     {
  6:         // Visual Studio might automatically update this path when you change the Visual Web Part project item.
  7:         private const string _ascxPath = @"~/_CONTROLTEMPLATES/Examples.AddressWebPart/Address/AddressUserControl.ascx";
  8: 
  9:         [Personalizable(), WebBrowsable]
 10:         public String Firstname { get; set; }
 11: 
 12:         [Personalizable(), WebBrowsable]
 13:         public String Lastname { get; set; }
 14: 
 15:         [Personalizable(), WebBrowsable]
 16:         public String Street { get; set; }
 17: 
 18:         [Personalizable(), WebBrowsable]
 19:         public int Zip { get; set; }
 20: 
 21:         [Personalizable(), WebBrowsable]
 22:         public String City { get; set; }
 23: 
 24:         protected override void CreateChildControls()
 25:         {
 26:             Control control = Page.LoadControl(_ascxPath);
 27:             Controls.Add(control);
 28:         }
 29:     }
 30: }


We added some basic type properties to the class. Important is to consider the attributes associated to our properties:




  • “Personalizable” tells the Web Part framework to store this property in the database


  • “WebBrowsable” tells the Web Part framework to display the property in the editor zone of your Web Part. If you don’t use this attribute, the property can be used for storage, but is not displayed in the editor zone to your end user.



You can store any type that is serializable with the Web Part framework (basic types and complex types). Hint: if you want to make your custom class serializable, put the “Serializable” attribute on the top of your class definition. These properties are only persisted when the Web Part is in “edit mode”. So, if you change some properties in the Web Part class above, they won’t be saved in the database.



Let us see what we did until now on our SharePoint site. Deploy the solution and add the Web Part to any page. When you press the “Edit Web Part” button, you will notice the five properties that we specified before added in the “miscellaneous” category of our editor part as textboxes. In addition, each textbox has a label with text containing the property name.



image image



Start inserting some values into the textboxes and press “OK” to confirm your choice. The Web Part framework stores the values into the database and associates them with the Web Part instance that you are editing. That means, after each page load, the properties in the Web Part class are populated with the settings that you defined in the editor part. However, until now nothing happens in our Web Part because we did not add some controls for rendering into our “AddressUserControl.ashx”. Before we start adding controls, we have to make a last change to our “AddressUserControl.ashx.cs” file. You see them in the next code snipped:



  1: namespace Examples.AddressWebPart.Address
  2: {
  3:     public partial class AddressUserControl : UserControl
  4:     {
  5:         public Address WebPart { get; set; }
  6:     }
  7: }


To end it, we have to make a small change in the “Address.cs” class and edit the “CreateChildControls” event:



  1: protected override void CreateChildControls()
  2: {
  3:    AddressUserControl control = Page.LoadControl(_ascxPath) as AddressUserControl;
  4:             
  5:    if (control != null)
  6:    {
  7:       control.WebPart = this;
  8:    }
  9: 
 10:    Controls.Add(control);
 11: }


With the code changes above we are telling our “AddressUserControl” to populate the property that we specified with the instance of our Web Part. In this way, we are able to access the Web Part properties specified in the “Address.cs” class.



Finally, we are able to add some controls to our “AddressUserControl.ascx” file that looks like that (please note that I used the designer to create this code):





  1: <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
  2: <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
  3: <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
  4: <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
  5: <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
  6: <%@ Import Namespace="Microsoft.SharePoint" %> 
  7: <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
  8: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddressUserControl.ascx.cs" Inherits="Examples.AddressWebPart.Address.AddressUserControl" %>
  9: <asp:Label ID="lblFirstname" runat="server" style="font-weight: 700" ></asp:Label>&nbsp;<asp:Label 
 10:     ID="lblLastname" runat="server" style="font-weight: 700" ></asp:Label>
 11: <br />
 12: <br />
 13: <asp:Label ID="lblStreet" runat="server" ></asp:Label>
 14: <br />
 15: <asp:Label ID="lblZip" runat="server" ></asp:Label>&nbsp;-&nbsp;<asp:Label ID="lblCity" runat="server" ></asp:Label>


The last step is to add in the “OnPrerender” event of the “AddressUserControls.ascx.cs” file. We are simply assigning to the text properties of the labels the corresponding Web Part properties that are persisted by the Web Part framework. The code looks like that:



  1: protected override void OnPreRender(EventArgs e)
  2: {
  3:    base.OnPreRender(e);
  4: 
  5:    if (this.WebPart != null)
  6:    {
  7:       this.lblFirstname.Text = this.WebPart.Firstname;
  8:       this.lblLastname.Text = this.WebPart.Lastname;
  9:       this.lblStreet.Text = this.WebPart.Street;
 10:       this.lblZip.Text = this.WebPart.Zip.ToString();
 11:       this.lblCity.Text = this.WebPart.City;
 12:    }
 13: }

Let us deploy the solution, add a Web Part to a page and modify it’s properties. The result may look like the next figure:

image





Some improvements



To end our Address development, we want to improve two aspects of our Web Part. First, we want to remove the label “Address” on the top of our Web Part when looking at our page. Something similar to the next figure:



 image



Second, we want to prohibit the end user, to minimize, hide or close the Web Part. In addition, we improve the editor zone by moving the properties from the “miscellaneous” section to a section that we are going to call “address settings”. Finally, we change the label associated to our city textbox to “city or town”.



image



This is done by changing some attributes and properties of our “Address.cs” class. The changes that we made are:




  1. set the “AllowMinimize” and “AllowHide” property to false to disable minimizing and hiding capabilities


  2. set the “ChromType” of the Web Part to hide the chrome around our Web Part during page load


  3. added to each property the attribute “Category("Address settings")” to move the property in the new category of our editor part


  4. added to the city property the attribute “WebDisplayName("City or Town")” to change the label associated to the textbox “city”



  1: namespace Examples.AddressWebPart.Address
  2: {
  3:     [ToolboxItemAttribute(false)]
  4:     public class Address : WebPart
  5:     {
  6:         public Address()
  7:         {
  8:             this.AllowMinimize = false;
  9:             this.AllowHide = false;
 10:             this.AllowClose = false;
 11:             this.ChromeType = PartChromeType.None;
 12:         }
 13: 
 14:         // Visual Studio might automatically update this path when you change the Visual Web Part project item.
 15:         private const string _ascxPath = @"~/_CONTROLTEMPLATES/Examples.AddressWebPart/Address/AddressUserControl.ascx";
 16: 
 17:         [Personalizable(), WebBrowsable, Category("Address settings")]
 18:         public String Firstname { get; set; }
 19: 
 20:         [Personalizable(), WebBrowsable, Category("Address settings")]
 21:         public String Lastname { get; set; }
 22: 
 23:         [Personalizable(), WebBrowsable, Category("Address settings")]
 24:         public String Street { get; set; }
 25: 
 26:         [Personalizable(), WebBrowsable, Category("Address settings")]
 27:         public int Zip { get; set; }
 28: 
 29:         [Personalizable(), WebBrowsable, WebDisplayName("City or Town"), Category("Address settings")]
 30:         public String City { get; set; }
 31: 
 32:         protected override void CreateChildControls()
 33:         {
 34:             AddressUserControl control = Page.LoadControl(_ascxPath) as AddressUserControl;
 35:             
 36:             if (control != null)
 37:             {
 38:                 control.WebPart = this;
 39:             }
 40: 
 41:             Controls.Add(control);
 42:         }
 43:     }
 44: }
 45: 


Points to consider



During Web Part development consider following points:




  • Never change assembly name, namespace or class name of a Web Part used by your customers. The customer will get an exception to this.


  • Never change property names that are personalized to change the description in the editor zone. Use the “WebDisplayName” instead


  • If you set a property in your Web Part class, this setting will not be stored in the database.


  • Base types are rendered automatically in your editor zone. If you want “complex” types, you need to extend the editor zone with custom code


  • Complex types must be serializable, or you will get exceptions on runtime



Summing up



In this post we created a simple address Web Part with customizable properties. We saw how to combine the Web Part class with our web user control and how to personalize some basic Web Part and Editor Part settings. If you want to get more information about Visual Web Part development, simply follow my post series.



Hope this helps,



patrick

Wednesday, May 19, 2010

How do I configure the basic project properties of my newly created Visual Web Part project?

Hi all,

in my last post about Visual Web Part development with Visual Studio 2010 I was talking about the creation of a simple Visual Web Part for SharePoint Foundation 2010. I will continue with the example that we made last time and emphasize the settings that you might want to setup in your project. In addition, I will give you some hints, how to avoid some common pitfalls during Web Part creation. Web Part development has become easier, however, there remain some important aspects to consider during development. If you are interested in an overview of all my posts about Visual Web Parts, then follow this link.

For the sake of simplicity, we are going to add a new Visual Web Part including only a “Hello World” text into our project (I will use the project we created last post, but you can also create one from scratch). Simply add a new Visual Web Part to your project. Your project should look similar to the next screen:

image 

The project structure and the most important folders that you might encounter are described below. The next sections describe more deeply the usage of these folders:

  • Properties: this section is used to make the most basic settings for your project such as namespace definitions, DLL name definition, DLL signing, debug properties and so on…
  • References: the DLLs that are used and referenced in your project
  • Package: the package folder defines all settings needed for a SharePoint solution. Here you are able to configure the most important settings, defining for example which features you will package for this solution.
  • Features: the features folder can contain one or more feature definitions that are associated to your package. Each feature definition can be used to encapsulate the items you might want to publish and activate on your SharePoint sites
  • Web Part Containers (e.g., HelloWorld, SimpleWebPart): this container summarizes the most important elements for your Visual Web Parts
  • key.snk: this is the key needed to sign your solution. Each DLL that is deployed in the Global Assembly Cache (GAC) must also be signed. Visual Studio does this automatically for you during project creation of SharePoint projects.

1) Properties

For most of you, the properties section of a Visual Studio project should not be something new. Depending on the project type you created, the section provides you more or less configuration properties. You can access this section by double clicking the “folder” “Properties” in your solution explorer. The result should be a window similar to the next one. The properties relevant to our Visual Web Part development are situated in the “Application”, “Resources”, and “SharePoint sections. This post will cover the “Application” and “SharePoint” section, the “Resource” section will be explained in the postings talking about Web Part localization.

image

Properties: Application

In this section you are able to change the assembly name, default namespace, assembly information and many more settings relevant to your assembly file. You should consider changing the assembly file and default namespace at the beginning of the development or at least before deploying the solution on a production environment. In addition, I recommend not to change any names related to the assembly, namespace or Web Part class name after deployment. Now, I will explain why you should not do it:

Note: As you probably know, SharePoint stores the full qualified path of your class (assembly name, namespace and class name) into it’s database and connects this entry with the page where you added the desired Web Part. Now imagine that you need to change any of the above names and you can imagine what will happen. SharePoint can’t find the Web Part that you recently added and returns an exception for your Web Part.

Let’s do a test to verify what exactly happens when we are doing something like that. We can do it by simply deploying our current project on our site and adding a Web Part to our pages (if you don’t know how to do it, I would recommend you to read my last post). Afterwards, we simply need to change the assembly name to something else (let us take for example the name “Examples.VisualWebPart”). It should look similar to next figure:

imageNow, we can deploy again the solution. Refresh the pages and SharePoint is not able to find your Web Parts anymore. If you used a Wiki Page, probably, the Web Part will not be displayed anymore. On the other hand, if you are using Web Part pages, you might encounter an error similar to the next one:

“Web Part Error: A Web Part or Web form Control on this Page cannot be displayed or imported. The type … could not be found or it is not registered as safe.”

image

Properties: SharePoint

In this section you can change some settings related to the SharePoint deployment. You can configure pre- and post-deployment command line settings. In addition you are able to choose different kind of deployment configurations for your project or create your own.

image

You only need to press the “New” button to create a new deployment configuration. You see in the next window that you have different possibilities to configure it. You can differentiate between the steps executed during deployment or even retraction. But to be honest, I think that the basic configurations provided in the figure above will be enough for most of your development scenarios. However, this remains a great way to customize your deployment process.

image

2) Package folder

The SharePoint project template supports you during development of so called SharePoint solutions. The “Package” folder is the main container of your solution that you can configure to your needs. The most important settings you might want to change are the name and the list of feature you want to include to your solution. You can even change the feature order with a button click. In the background, Visual Studio builds the necessary manifest files needed by your solution. In the advanced tab you can add additional assemblies that must be deployed with your solution on the server. Finally, you can even change manually the manifest of your solution in the manifest tab of this window.

image

3) Features folder

A feature is a collection of files that are deployed to your SharePoint project. You can add as many features you want in the features folder. If you click on a feature, you can define the usual settings such as the feature name and the contents that should be included into your feature. If you are adding a new feature to your project, you can define different items for your feature and add it to your solution by using the package folder. Finally, you are able to define the scope of your feature and even feature dependencies by using this window. Similar to the package folder, you can change also here the manifest file manually.

image

4) Web Part Container

Now, we are talking about the most important section of our post. The Visual Web Part containers that you see in the solution explorer image at the beginning of this post (in our cases the HelloWorld and SimpleWebPart containers) summarize all important files related to our Visual Web Part(s). We will check the different files by considering the “HelloWorld” Web Part container.

image

  • Elements.xml: this file contains the necessary feature settings needed for the Web Part deployment
  • HelloWorld.cs: this is the Web Part class inheriting from the System.UI.WebControls.WebPart. You will need it to create personalizable Web Part properties in future
  • HelloWorld.webpart: this is an additional file defining some Web Part default properties for SharePoint. When you add a Web Part to your page, these properties will be considered. Please note that these properties are used during first time instantiation. Afterwards, they can’t be overridden without manual intervention.
  • HelloWorldUserControl.ascx: this is the magic behind the Visual Web Part concept. The web user control that you will use to personalize your Web Part visually

Let us look behind behind the scenes to understand what Visual Web Parts really are. Let us open the “HelloWorld.cs” file to check this.

namespace VisualWebPartExample.HelloWorld
{
[ToolboxItemAttribute(false)]
public class HelloWorld : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item
private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartExamples/HelloWorld/HelloWorldUserControl.asxcx";

protected override void CreateChildControls()
{
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
}
}
}

This Web Part looks similar to our “old-school” Web Parts we created in the previous versions of SharePoint. You see that at the end the Visual Web Part concept is nothing else than a web user control (our “HelloWorldUserContro.ascx”) loaded dynamically in the “CreateChildControls” event of our Web Part. That means, that most of our development efforts base on the customization of both files, “HelloWorld.cs” and “HelloWorldUserControl.ascx”. We will see more about this in my next posts.

In the meantime, we are covering the last two files. The “Elements.xml” file looks like that:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
<Module Name="HelloWorld" List="113" Url="_catalogs/wp">
<File Path="HelloWorld\HelloWorld.webpart" Url="HelloWorld.webpart" Type="GhostableInLibrary" >
<Property Name="Group" Value="Custom" />
</File>
</Module>
</Elements>

Line 4 defines in which category our Web Part will be inserted in the Web Part catalog of our SharePoint site. You can see this in the next figure:


image

The last file is the file called “HelloWorld.webpart”. The code of this file looks similar to the next code section:

<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="VisualWebPartExamples.HelloWorld.HelloWorld, $SharePoint.Project.AssemblyFullName$" />
<importErrorMessage>$Resource:core,ImportMessage;</importErrorMessage>
</metaData
<data>
<properties>
<property name="Title" type="string">HelloWorld</property>
<property name="Description" type="string">My Visual WebPart</property>
</properties>
</data>
</webPart>
</webParts>

In the properties section you can change the properties of your Web Part such as the title or description that are visible in the “About the Web Part” section of the picture that we saw before. In addition, you are able to add additional property settings that are used during the addition of your Web Part in a SharePoint page. These settings are used as default settings for your personalizable properties. In the next posts we will see more about that.

Summary

In this post we saw the different project sections and their most important properties of a Visual Web Part project in Visual Studio 2010. With this knowledge, we can continue with our Visual Web Part journey and discover how to personalize them with this post series.



Best regards,

Patrick

Monday, May 17, 2010

How do I create my first Web Part with Visual Studio 2010 and SharePoint Foundation 2010?

Hi all,

in this post of my Visual Web Part post series I’m going to explain how to create your first Visual Web Part with Visual Studio 2010 and SharePoint Foundation 2010.

Walkthrough

We are going to create a new Visual Web Part project for SharePoint 2010. In this project we will add a small Visual Web Part containing only a label and a button. In addition, connect a button click event with this button and change with it the content of the label. Nothing special, but enough to discover the steps needed for simple Visual Web Part development on this new platform.

During this post we are following these steps:

  • Step 1: Setup the project
  • Step 2: Create and customize the Visual Web Part
  • Step 3: Deploy and test the Visual Web Part

Note: that you need the SharePoint Development Tools for SharePoint 2010 activated to do this tutorial.

So, let us start with it…

Step 1: Setup the project

In this step we are going to create a Visual Web Part project and connect it with a SharePoint server.

1. Create a new project in Visual Studio 2010 (SharePoint –> 2010 –> Visual Web Part), call it VisualWebPartExample and press ok

image

2. The SharePoint Customization Wizard opens. Specify the desired target site (in my case called http://jacklaptop) and select Deploy as a farm solution. Confirm your selection with finish image

3. Visual Studio creates for you a project customized for the SharePoint development. It adds automatically packaging and feature settings and an example Visual Web Part. Delete from the project VisualWebPart1.

To sum up, we created a new Visual Web Parts project which will be deployed as a farm solution. This solution is then activated automatically on the site collection that we specified at the beginning. Pretty cool.

Step 2: Create and customize the Visual Web Part

In this step we are going to add a new Visual Web Part to our project and customize it a little bit by adding a label with simple content

1) Press the right mouse button on your project and go to “Add –> new item”. Add a new Web Part called SimpleWebPart and confirm with add.

image

The solution explorer should look like in the next figure so far:

image

You can see in the solution explorer that there is a small container called SimpleWebPart. In this container you can find all necessary support files needed for the Visual Web Part development. A Visual Web Part is nothing else than a classic Web Part that automatically loads a web user control in it. The advantage of this approach is that you are able to use the design support with web user controls in Visual Studio. Now, we are going to finalize our Web Part development by customizing the most important file, the SimpleWebPartUserControl.ascx.

2) Open the file SimpleWebPartUserControl.ascx and go in design mode

3) Add a label and a button. This should look similar to next figure

image

4) By double clicking on the button, a button click event handler is associated to it. Please add in the previously generated method the code like in next code snippet:

namespace VisualWebPartExamples.SimpleWebPart
{
public partial class SimpleWebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Event triggered";
}
}
}

That’s all for now. We don’t need to add more functionality to this Web Part. Go to the next step to deploy the solution on your web application.

Step 3: Deploy and test the Visual Web Part

Our next step is to deploy this solution and to activate the feature on our web application. Guess what? Visual Studio 2010 is doing it for you automatically. Afterwards, we are going to test our Web Part on the web application.

1) Right mouse button on our project and press deploy

image

2) Visual Studio starts the building, solution packaging and feature activating for you. That is really great, because these steps were made manually some years ago.image

3) Open the web application that was specified at the beginning and add the newly added Web Part to any zone you like. Please note (I can’t say it often enough… Visual Studio did everything for you…). Do this by editing the page and going to the “insert” tab. Press the “Web Part” button and select from the “Custom” category the previously created Web Part.

image image image

  4) Last but not least, test the Web Part by pressing the Click me button

image

Summary

The example above is naturally nothing exciting. However, the most exciting thing is to see how simple the Web Part development has become with the support of Visual Studio 2010 and the SharePoint Development Tools. Great job to everyone who contributed to this fantastic feature.

Not enough? Ah, I forgot. If you want to debug the Web Part that you created before, you don’t need to attach the process manually anymore. With Visual Studio 2010 it is enough to press the debug button and you are ready for debugging.

That’s all for now. You can follow my post series of Visual Web Part development here, if you are interested in hearing more about this exciting new feature.

 

Best regards,

Patrick