Sunday, November 17, 2013

SharePoint 2013 - Configurable Web Part Properties

In this post we will discuss about web part properties and how to create configurable web part properties.

WebPart Properties
All Web Parts share a set of common properties that allow you to specify attributes for the appearance, layout, and other information. To view web part properties, click on the web part menu and select Edit web part".

On the right hand side you can see the web part properties window opens. Here you can make the basic changes like adjusting height, width, Title, etc.


Configurable WebPart Properties
Apart from the default properties, you may want to add you own custom properties which can be even used as parameters for the webpart. Configurable Web Parts are used to present a user-friendly interface for Web Parts configuration. The following attributes makes it possible to add custom properties.

The WebBrowsableAttribute class
The WebBrowsableAttribute class instructs the Web Parts infrastructure that the property has to be made available in the Web Part’s configuration panel. 

The PersonalizableAttribute class
The PersonalizableAttribute declares that the property can be personalized and defines the scope of the personalization. There 2 types of scopes:
1) Scope of type User, which means that the property can be personalized on a per-user basis.
2) Scope of type Shared, which means that the property personalization will be shared between all users.

Configurable WebPart Attributes
Following attributes enables the display of the custom properties in web part properties window.
1) [WebBrowsable(true)] - This will hide or show the property on the tool pane.
2) [Personalizable(PersonalizationScope.Shared)] - How the WebPart is configured, which can be per-user (PersonalizationScope.User), or for everyone (PersonalizationScope.Shared). 
3) [WebDescription("Description of List")] - Description for the property.
4) [WebDisplayName("My List Name")] - Label for the property.
5) [Category("Personalized Items")] - This will group your property according to category. If not declared, “Miscellaneous” will be used as the default.
6) [DefaultValue("Default")] - The default value for the property.

Creating a Configurable Web Part Property
For a better understanding, lets modify the Visual web part we created in the previous post and add a configurable web part property. In the previous post we created a visual web part to show items in "Products" List. Now we will add a custom web part property to accept List name as a parameter and display the items for that specific list.


Following are the steps:

1) Create a 2 custom list named "Products" and "Customers" with columns and data of your choice. 


2) Create a new visual web part following the steps as mentioned in the previous post.
Code Snippet
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             if (this.ListName != null && this.ListName.Trim()!="")
  4.             {
  5.                 SPSite oSite = SPContext.Current.Site;
  6.                 using (SPWeb oWeb = oSite.OpenWeb())
  7.                 {                    
  8.                     SPList oList = oWeb.Lists["Products"];
  9.                     SPListItemCollection oColl = oList.GetItems();
  10.                     gvwProducts.DataSource = oColl.GetDataTable();
  11.                     gvwProducts.DataBind();
  12.                 }
  13.             }
  14.         }

3) Create a new property named ListName in the visual webpart class as follows and add the WebBrowsable attribute to it:
Code Snippet
  1. [WebBrowsable(true),
  2. Category("Personalize"),
  3. WebDisplayName("List Name"),
  4. WebDescription("Custom list name editable by user")]
  5. [Personalizable(PersonalizationScope.Shared)]
  6. public string ListName { get; set; }

3)  Modify the code inside the Page_Load method as follows. The ListName property will be passed as parameter for getting the data from the specified list and display in a grid-view.
Code Snippet
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             if (this.ListName != null && this.ListName.Trim()!="")
  4.             {
  5.                 SPSite oSite = SPContext.Current.Site;
  6.                 using (SPWeb oWeb = oSite.OpenWeb())
  7.                 {                    
  8.                     SPList oList = oWeb.Lists[this.ListName];
  9.                     SPListItemCollection oColl = oList.GetItems();
  10.                     gvwProducts.DataSource = oColl.GetDataTable();
  11.                     gvwProducts.DataBind();
  12.                 }
  13.             }
  14.         }

4) Deploy the solution and open the web part page in edit mode. Go to the web part properties and you can see the new custom property that we added. Enter the list name "Products" and click "Apply" button, you will see the items in the Products List are populated in the GridView.

5) Now change the List Name to "Customers" and click "Apply" button. 

6) You will see the items in the "Customers" list will be populated in the GridView.

Note:- The above code defined property that requires the end user to configure the Web Part manually, typing the target list name autonomously and  made use of the standard behaviour of SharePoint and the out-of-the-box CustomPropertyToolPart.

But this is not a user-friendly and error-free approach. The right solution would probably be to provide a drop-down list with all the lists available in the current website, thereby avoiding typo errors and the consequent time consuming debugging tasks.
To customize the Web Parts’ configuration user interface you can create custom classes called "Editor Parts" which are controls hosted in a specific WebPartZone called EditorZone.

We will take a closure look on to Editor Parts in the next post. 

Sunday, November 10, 2013

SharePoint 2013 - Creating a Visual Webpart

Overview
Visual webparts wraps asp.net user control inside a classic webpart, so that programmer could work on .ascx file as for any other web project instead to have to resort to programmatically create the controls via the CreateChildControl method.Visual webparts evolved in SharePoint 2010 and can be used for easily creating webparts with rich UI. But the performance is somewhat less compared to classic webparts, since there is an overhead of loading the user controls.

Creating a Visual Webpart
Following are the steps for creating a Visual Webpart.

1) Open Visual Studio 2012 and select "New Project->SharePoint Solutions". The following window will open displaying all SharePoint project templates. Select "SharePoint 2013 - Empty Project", give a suitable name and click "Finish".

2) Enter the suitable Site collection name for debugging purpose and click the "Finish" button..
Note: Sandboxed Solution option will be disabled since visual web parts can be created only in Farm Solution.

3) For adding the visual webpart, right click on the project and select Add->New Item.

4) The following window will appear. Select Visual Web Part and give a suitable name.

5)  When a visual web part is added 2 main components are added.
i) First one is the Web Part ("MyVisualWP" in our case) which contains all the files supporting the web part. It is basically a "User Control" which will be wrapped inside the Web part and rendered in the "CreateChildControl()" event.
ii) Second one is the "Features" component which deploys the web part to the site.
(Note: We will take a closer look into "Features" in the upcoming posts.)

6) In the "MyVisualWp.ascx" user control add an asp.net "Label" control as follows:

7) Select "Build-> Deploy Solution" to deploy the webpart to the site collection that we entered in the "SharePoint Customization Wizard" in the 2nd step.
(Note: For deploying the webpart solution to another site collection or sub-site we must use the STSADM command line tool or SharePoint Management Shell. We will discuss deployment in detail in the upcoming sessions.)

8) Now open the Web part page in "Edit mode" and click "Add a Web Part". The web part "MyVisualWebpart - MyVisualWP" is now available in the web part gallery under "Custom" group. Select the web part and click "Add".

9) Our web part has been created and displays the label that we added in the User Control.
10) Unlike other SharePoint versions, the .ascx file is not deployed to the Hive->Templates->Control Template folder. In SharePoint 2013, the "Deployment type" property for Visual webpart is set to "No Deployment" by default.

11) Now, lets try to display the following list items from a list named "Products" using a asp.net GridView in the user control.

12) Add a GridView control name "gvwProducts".

13) Write the following code in the Page_Load event for fetching list items and binding to the GridView.
Code Snippet
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             SPSite oSite = SPContext.Current.Site;
  4.             using (SPWeb oWeb = oSite.OpenWeb())
  5.             {
  6.                 SPList oList = oWeb.Lists["Products"];
  7.                 SPListItemCollection oColl = oList.GetItems();
  8.                 gvwProducts.DataSource = oColl.GetDataTable();
  9.                 gvwProducts.DataBind();
  10.             }
  11.         }

14) Deploy the solution refresh the existing web part page. You can see the list items have been fetched and display through GridView.
Note: You might see some additional columns generated which are default SharePoint columns in the List. To display just the required columns, you can use an "SPQuery" as follows

15) Modify code in the Page_Load event for fetching only the column that we want.
Code Snippet
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             SPSite oSite = SPContext.Current.Site;
  4.             using (SPWeb oWeb = oSite.OpenWeb())
  5.             {
  6.                 SPQuery oQuery = new SPQuery();
  7.                 oQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Description' /><FieldRef Name='Price' />";
  8.                 oQuery.ViewFieldsOnly = true;
  9.                 SPList oList = oWeb.Lists["Products"];
  10.                 SPListItemCollection oColl = oList.GetItems(oQuery);
  11.                 gvwProducts.DataSource = oColl.GetDataTable();
  12.                 gvwProducts.DataBind();
  13.             }
  14.         }

16) Now you can see that the GridView displays the items in the "Products" list with only the column that we choose to display.

Hope this post is helpful to you. Thanks!

Sunday, November 3, 2013

SharePoint 2013 - Creating a Classic Webpart

Overview
Classic webparts can be created by deriving from the WebPart class. You must write the code from scratch, in the CreateChildControls method, to create the layout design of the Web Part, which can be time consuming. One of the challenges that you face when designing a Web Part that has a complex user interface (UI) is the lack of drag-and-drop support.

Creating a Classic Webpart
Following are the steps for creating a Classic Webpart.

1) Open Visual Studio and select "New Project->Office/Sharepoint->SharePoint Solutions". The following window will open displaying all SharePoint project templates. Select "Empty SharePoint Project", give a suitable name and click "Finish".

2) The following window pops-up. Enter the suitable Site collection name for debugging purpose. You also have the option to select Farm Solution or Sandboxed Solution.  

3) Right click on Solution and select Add->New Item. 

4) Another window with SharePoint templates will open as shown in the below figure. Select "Web Part".

 5) When a webpart is added 2 main components are added. First one is the webpart "MyClassicWP" which contains all the files supporting the webpart. Second one is "Features" contains the features for deploying the webpart to the site.
(Note: We will take a closer look into features in the upcoming posts.)

6) Now we will some custom code to display a welcome text along with date and time. Add the following code in the CreateChildControls() method.
Code Snippet
  1. protected override void CreateChildControls()
  2.         {
  3.             SPWeb currentWeb = SPControl.GetContextWeb(HttpContext.Current);
  4.             String currentUserName = currentWeb.CurrentUser.Name;
  5.             this.Controls.Add(new LiteralControl(String.Format(
  6.             "<h1>Welcome {0}!</h1>", currentUserName)));
  7.             this.Controls.Add(new LiteralControl(String.Format(
  8.             "<div>Current DateTime: {0}</div>", DateTime.Now)));
  9.         }

7) Select "Build-> Deploy Solution" to deploy the webpart to the site collection that we entered in the "SharePoint Customization Wizard" in the 2nd step.
(Note: For deploying the webpart solution to another site collection or subsite we must use the STSADM command line tool or SharePoint Management Shell. We will discuss deployment in detail in the upcoming sessions.)

8) Now open the Webpart page in "Edit mode" and click "Add a Web Part". The webpart "MyClassicWP" is now available in the webpart gallery under "Custom" group. Select the webpart and click "Add".

9) Our webpart has been created and displays the Welcome message along with date and time.

This is just small example of creating a Classic Webpart. In the next post we will create a sample visual webpart.
This is just small example of creating a Classic Webpart. In the next post we will create a sample visual webpart.