Sunday, December 22, 2013

SharePoint 2013 - Connectable Web parts

Overview
In SharePoint, a web part can be 'connected' to another web part to provide some information at run-time.  The Provider web part pushes out the contracted information and the Consumer web part is set up to receive and consume the shared information.

Components of Connectable webparts
1) Interface: This custom interface will define the data to be shared from the Provider to the Consumer web part.
2) Provider web part: Implements a data interface - this interface is a definition of the data that will be shared from the Provider web part to the Consumer web part.
Provide a ConnectionProvider method which will expose the interfacing data to the Consumer web part.
3) Consumer web part: ConnectionConsumer method which will receive the interfacing data
Consume the interfacing data and provide enriching details to the user.

Steps for creating connectable web parts

1) Create an Empty SharePoint Project named ConnectedWebparts in Visual Studio 2012.

2) Add a new C# Interface code class and name it IUser.

Code for IUser.cs
Code Snippet
  1. namespace ConnectedWebparts
  2. {
  3.     public interface IUser
  4.     {
  5.         string UserName { get; }
  6.     }
  7. }

3) Add a new web part named WPProvider in the project which will be the provider webpart. Make the changes as highlighted in the figure below.

Code for WPProvider.cs
Code Snippet
  1. namespace ConnectedWebparts.WPProvider
  2. {
  3.     [ToolboxItemAttribute(false)]
  4.     public class WPProvider : WebPart,IUser
  5.     {
  6.         //From the UI, we collect the user selections
  7.         Label lblUsername = null;
  8.         TextBox txtUsername = null;
  9.         Button btn = null;
  10.         protected override void CreateChildControls()
  11.         {
  12.             lblUsername = new Label();
  13.             txtUsername = new TextBox();
  14.             btn = new Button();
  15.             lblUsername.Text = "User name: ";
  16.             btn.Text = "Send User";
  17.             this.Controls.Add(lblUsername);
  18.             this.Controls.Add(txtUsername);
  19.             this.Controls.Add(btn);
  20.         }
  21.         public string UserName
  22.         {
  23.             get { return txtUsername.Text; }
  24.         }
  25.  
  26.         [ConnectionProvider("UserName")]
  27.         public IUser ConnectionProviderMethod()
  28.         {
  29.             // This method will expose the shared data to the Consumer.
  30.             return this;
  31.         }
  32.     }    
  33. }

4) Add a new web part named WPConsumer in the project which will be the provider webpart. Make the changes as highlighted in the figure below.

Code for WPConsumer.cs
Code Snippet
  1. namespace ConnectedWebparts.WPConsumer
  2. {
  3.     [ToolboxItemAttribute(false)]
  4.     public class WPConsumer : WebPart
  5.     {
  6.         Label lblUser = null;
  7.         IUser oIUser = null;
  8.         //Receive the data from the Provider web part here
  9.         [ConnectionConsumer("UserName")]
  10.         public void ConsumerMethod(IUser user)
  11.         {
  12.             oIUser = user;
  13.         }
  14.         protected override void CreateChildControls()
  15.         {
  16.             // Here we utilize the data received from the Provider
  17.             Label lblDisplayText = new Label();
  18.             if (oIUser != null)
  19.             {
  20.                 if (oIUser.UserName != "")
  21.                     lblDisplayText.Text = "Hello " + oIUser.UserName;
  22.                 else
  23.                     lblDisplayText.Text = "Hello Guest";
  24.             }
  25.             else
  26.                 lblDisplayText.Text = "No provider connected";
  27.             this.Controls.Add(lblDisplayText);
  28.         }
  29.     }
  30. }

5) After modifying the webpart as mentioned in the above steps, deploy the solution.

6) Add the Consumer webpart on the webpart page.


7) Add the Provider webpart on the webpart page.


8)  Edit the Provider webpart and connect it to the consumer.

9) Now the 2 webparts have been connected to each other using the interface. In the provider webpart, type a username in the textbox and click "Send User". You can see the name is displayed in the consumer webpart as highlighted in the figure below.


Sunday, December 15, 2013

SharePoint 2013 - Custom web part verbs

Web part verbs
The web part verbs are the menus items (like Minimize, Close etc) which appears when we click the Edit option in web parts as shown in the figure below. The SharePoint web part framework exposes one of the property called WebPartVerbCollection. This is very flexible which allows us to add our own items (custom web part verbs) to the web part collection.

Types of web part verbs
Verbs are objects of type WebPartVerb and can be of three different kinds:
1) Server-side Verbs that require a POST-back to carry out their job; they work on the server side.
2) Client-side Verbs that simply use JavaScript syntax to do their job; they work on the client side.
3) Client and server-side Verbs that first execute some client-side JavaScript, and then can execute some server-side code, unless the client-side code cancels request.

Creating a custom web part verb
1) Create a new classic webpart and add the following code in the CreateChildControls() event. Deploy the webpart.

2) Following content is displayed in the webpart. Note that only default verbs are included as highlight in the following figure.

3) Now lets add the custom verb. We have to override the read-only property Verbs provided by the base WebPart class. Modified the code in webpart file as highlighted below. We have added three verbs:
i) 'Server-side verb' which will only raise a server side post-back.
ii) 'Client-side verb' which will pop up a JavaScript alert.
iii) 'Client and Server-side verb' which will raise a JavaScript alert and then a server side post-back.

Following is the complete code for implementing verbs.
Code Snippet
  1. protected override void CreateChildControls()
  2.         {
  3.             this.Controls.Add(new LiteralControl("<h1>Custom WebPart Verbs Demo!</h1>"));
  4.         }
  5.  
  6.         public override WebPartVerbCollection Verbs
  7.         {
  8.             get
  9.             {
  10.                 // Create a Server side verb        
  11.                 WebPartVerb serverSideVerb = new WebPartVerb("serverSiteVerbId", handleServerSideVerb);
  12.                 serverSideVerb.Text = "Server-side verb";
  13.  
  14.                 // Create a Client side verb
  15.                 WebPartVerb clientSideVerb = new WebPartVerb("clientSideVerbId", "javascript:alert('Client-side Verb selected');");
  16.                 clientSideVerb.Text = "Client-side verb";
  17.                 WebPartVerb clientAndServerSideVerb = new WebPartVerb("clientAndServerSideVerbId", handleServerSideVerb, "javascript:alert('Client-side Verb selected');");
  18.  
  19.                 // Create a Client and Server side verb
  20.                 clientAndServerSideVerb.Text = "Client and Server-side verb";
  21.                 WebPartVerbCollection newVerbs = new WebPartVerbCollection(new WebPartVerb[] {serverSideVerb, clientSideVerb, clientAndServerSideVerb,});
  22.                 return (new WebPartVerbCollection(base.Verbs, newVerbs));
  23.             }
  24.         }
  25.  
  26.         protected void handleServerSideVerb(Object source, WebPartEventArgs args)
  27.         {
  28.             EnsureChildControls();
  29.         }

4) Deploy the web part and click on the webpart menu. You will notice that all three custom verbs are now displayed in the menu.

5) Clicking on the 'Server-side verb' link will only raise a server side post-back.

6) Clicking on the 'Client-side verb' link will pop up a JavaScript alert.

7) Clicking on the 'Client and Server-side verb' link will pop up a JavaScript alert and then raise a server side post-back.

Note
1) Usually, custom Verbs are defined in Intranet/Extranet solutions, to provide support for custom functionalities, such as refreshing content, opening custom pop-up windows, and so forth. 
2) In general, they are not used in CMS/Publishing solutions, because the context menu is usually disabled in these. 

References
1) Microsoft SharePoint 2013 Developer Reference, by Paolo Pialorsi - Book

Sunday, December 8, 2013

SharePoint 2013 - Handling page display modes in webpart

Overview
As you might already know that a SharePoint webpart page can be rendered in 3 different modes:-
1) Display mode: This is the page mode when the end user is browsing the site;
2) Design mode: This is the page mode when the user can design the page layout;
3) Edit mode: This is the page mode when the end user is configuring/customizing the page and/or its controls.

WebPartManager.DisplayMode Property
To identify the page display mode and render a Web Part accordingly, you need to query the DisplayMode property of the WebPartManager (SPWebPartManager in SharePoint).

Code Sample
Lets take a closer look by creating a simple webpart and analyzing the different display modes.

1) Create an empty SharePoint project and add a classic webpart named "WPDisplayModesDemo".

2) Write the following code in the CreateChildControls() event. Looking at the code you will observe that WebPartManager.DisplayMode Property is used to define functionality for different modes.
i) For Display mode the text will be "You are now viewing the webpart in Page Display Mode."
ii) For Design mode the text will be "You are now viewing the webpart in Page Design Mode."
iii) For Edit mode the text will be "You are now viewing the webpart in Page Edit Mode."

Following is the complete code for CreateChildControls() method.
Code Snippet
  1. protected override void CreateChildControls()
  2.         {
  3.             if (this.WebPartManager.DisplayMode == WebPartManager.BrowseDisplayMode)
  4.             {
  5.                 // Page Display mode
  6.                 this.Controls.Add(new LiteralControl(@"<div>You are now viewing the webpart in Page Display Mode.</div>"));
  7.             }
  8.             else if (this.WebPartManager.DisplayMode == WebPartManager.DesignDisplayMode)
  9.             {
  10.                 // Page Design mode
  11.                 this.Controls.Add(new LiteralControl(@"<div>You are now viewing the webpart in Page Design Mode.</div>"));
  12.             }
  13.             else if (this.WebPartManager.DisplayMode == WebPartManager.EditDisplayMode)
  14.             {
  15.                 // Page Edit mode
  16.                 this.Controls.Add(new LiteralControl(@"<div>You are now viewing the webpart in Page Edit Mode.</div>"));
  17.             }
  18.         }

3) Deploy the webpart. Open the target webpart page in Edit Mode and add the webpart.

4) The webpart page's initial mode will be Design mode, therefore the text displayed in the webpart will be "You are now viewing the webpart in Page Display Mode".

5) Click the webpart menu and choose Edit Web Part.

6) Now the webpart page's mode will be Edit mode, therefore the text displayed in the webpart will be "You are now viewing the webpart in Page Edit Mode."

7) Select "Stop Editing" button on the top-left corner of the page for rendering the page in Display Mode.

8)  Now the webpart page's mode will be Display mode, therefore the text displayed in the webpart will be "You are now viewing the webpart in Page Display Mode."

This is the basic implementation of WebPartManager.DisplayMode property for handling web part display modes. Hope this post is helpful to you!

Sunday, December 1, 2013

SharePoint 2013 - Creating Custom Editor Parts

Overview
In the previous post we discussed how we can create configurable webpart properties. We also noticed that the web part properties were ENUM and we could only enter static values as parameter like typing a list name or column name etc.
What if you type the list name incorrectly? Therefore, you would want to choose a list from a asp.net dropdown containing all the available lists and display the items for the selected list in a Gridview. This is were EditorParts come in handy! So lets get started...

Editor Parts
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.
ASP.NET 4.0 contains an abstract class called EditorPart, this class is used with the ASP.NET 4.0 WebPart class to create customized tool panes. By inheriting from this control you can customize the look and functionality of the tool pane and use standard ASP.NET constructs such as auto post backs, validations etc.

IWebEditable Interface
To provide a Web Part with a custom Editor Part, you need to override the implementation of the IWebEditable interface, which is implemented by the Web Part base class.


Steps to create an Editor Part
Following are the steps:-
1) Create a Visual web part as mentioned in the the post "Creating a Visual Webpart".

2) Go to the webpart file "MyVisualWP.ascx.cs" and implement the "IWebEditable" interface. Also, add a property named "ListName" as shown in the figure below.

3) Now add a new class named "WPEditor.cs" which inherits from the "EditorPart" class. Create a new Dropdownlist and populate the list with all the Lists in the site. Then add the dropdownlist to the controls collection as shown in the figure below.

4) EditorPart class has 2 important methods:
i) Apply Changes() : This method is used to save any changes to the currently-edited Web Part.
ii) SyncChanges()   : This method is used to load the current configuration from Web Part Properties.

5) Following is the complete code "WPEditor.cs" class file.
Code Snippet
  1. using Microsoft.SharePoint;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10.  
  11. namespace MyVisualWebpart.MyVisualWP
  12. {
  13.     public class WPEditor : EditorPart
  14.     {
  15.         private DropDownList ddlList;
  16.  
  17.         protected override void OnInit(EventArgs e)
  18.         {
  19.             base.OnInit(e);
  20.             ddlList = new DropDownList();
  21.             SPWeb oWeb = SPContext.Current.Web;
  22.             foreach (SPList oLists in oWeb.Lists)
  23.             {
  24.                 ddlList.Items.Add(oLists.Title);
  25.             }
  26.         }
  27.  
  28.         protected override void CreateChildControls()
  29.         {
  30.             base.CreateChildControls();
  31.             this.Controls.Add(new LiteralControl("My List Name<br/>"));
  32.             this.Controls.Add(ddlList);
  33.             this.Controls.Add(new LiteralControl("<br/>"));
  34.         }
  35.  
  36.         protected override void OnPreRender(EventArgs e)
  37.         {
  38.             base.OnPreRender(e);
  39.         }
  40.  
  41.         public override bool ApplyChanges()
  42.         {
  43.             MyVisualWP webPart = this.WebPartToEdit as MyVisualWP;
  44.             if (webPart != null)
  45.             {
  46.                 webPart.ListName = ddlList.SelectedValue;
  47.             }
  48.             return true;
  49.         }
  50.  
  51.         public override void SyncChanges()  
  52.         {
  53.             MyVisualWP webPart = this.WebPartToEdit as MyVisualWP;
  54.             if (webPart != null)
  55.             {
  56.                 ddlList.SelectedValue = webPart.ListName;
  57.             }
  58.         }
  59.     }
  60. }

6) Make the following changes in the user controls code behind file "MyVisualWPUserControl.ascx.cs" which nothing but passing the "ListName" property that we created in Step 2 as parameter to the Gridview.

7) Now, go back to the webpart file "MyVisualWP.cs" and override the "CreateEditorParts()" method which returns an EditorPartCollection. In this method we will add our custom EditorPart "WPEditor.cs" to the EditorPartCollection.

8) Following is the completed code for "MyVisualWP.ascx.cs" visual webpart class file.
Code Snippet
  1. using System;
  2. using System.ComponentModel;
  3. using System.Web.UI.WebControls.WebParts;
  4. using Microsoft.SharePoint;
  5. using System.Collections.Generic;
  6.  
  7. namespace MyVisualWebpart.MyVisualWP
  8. {
  9.     [ToolboxItemAttribute(false)]
  10.     public partial class MyVisualWP : WebPart, IWebEditable
  11.     {
  12.         public string ListName { get; set; }
  13.  
  14.         protected void Page_Load(object sender, EventArgs e)
  15.         {
  16.             if (this.ListName != null && this.ListName.Trim() != "")
  17.             {
  18.                 SPSite oSite = SPContext.Current.Site;
  19.                 using (SPWeb oWeb = oSite.OpenWeb())
  20.                 {
  21.                     SPList oList = oWeb.Lists[this.ListName];
  22.                     SPListItemCollection oColl = oList.GetItems();
  23.                     gvwProducts.DataSource = oColl.GetDataTable();
  24.                     gvwProducts.DataBind();
  25.                 }
  26.             }
  27.         }
  28.  
  29.         public override EditorPartCollection CreateEditorParts()
  30.         {
  31.             List<EditorPart> editorParts = new List<EditorPart>();
  32.             WPEditor oWPEditor = new WPEditor();
  33.             oWPEditor.ID = this.ID + "_sampleEditorPart";
  34.             oWPEditor.Title = "Personalize";
  35.             editorParts.Add(oWPEditor);
  36.             return new EditorPartCollection(base.CreateEditorParts(), editorParts);
  37.         }
  38.       
  39.         public MyVisualWP()
  40.         {
  41.         }
  42.  
  43.         protected override void OnInit(EventArgs e)
  44.         {
  45.             base.OnInit(e);
  46.             InitializeControl();
  47.         }        
  48.     }
  49. }

9) Deploy the solution and add the webpart to the page in edit mode. You can see that there is a dropdownlist in the webpart properties window with all the lists. Choose any of the list and click 'Apply' or 'Ok' button.


10) The Gridview will be populated with the items in the list that you selected in the dropdownlist. Similarly, you can choose any other list from the drop down to populate data.

So that was all about custom EditorParts in webparts in SharePoint 2013!