Monday, August 16, 2010

SharePoint 2010 Provider Consumer Web Parts

In this tutorial I will show how to develop Provider and Consumer web parts and connect them through an Interface.
The result will be the ability to have two web parts on a SharePoint 2010 page and filter the contents of the consumer web part on the data from the provider web part. This is almost like a master - detail view.
You can view the same functionality by looking at the standard SharePoint web parts. Modify a web part --> select Connections and the "Provide data to..." or "Receive data from..."

and then...













Lets Get Started:
I will show the detailed steps to:
1 - Develop a Connection Interface
2 - Develop a simple provider web part.
3 - Develop a simple consumer web part.

1 - Develop a Connection Interface.

Open Visual Studio 2010 and create a new project. In the New Project dialog window, select Visual C# --> SharePoint 2010 --> Empty SharePoint Project.
Provide a descriptive name and click on OK.
Select to deploy the solution as a "Deploy as Farm Solution" and click on Finish.
Wait for the solution to be created in Visual Studio.


Now we will create the web part connection interface which is responsible for exchanging connection information between a provider and consumer web part.
In the Solution Explorer, right-click on your project and select "Add --> New item".
In the Add New Item dialog window, select Visual C# --> Code --> Interface.
Enter ITask in the Name textbox and click the Add button.
Open ITask.cs in code view and change the visibility of the interface to Public and add the following code inside the interface:
namespace WebPartConnectors
{
   public interface ITask
   {
      int Id { get; }
      string Name { get; }
   }
}

2 - Develop a simple provider web part:
In the Solution Explorer, right click on your project and select Add --> New Item…
Select Visual C# --> SharePoint 2010 Web Part.
Enter ProviderWebPart in the Name textbox and click Add.
Open ProviderWebPart.cs in code view and in the ProviderWebPart class declaration, implement ITask.
public class ProviderWebPart : Microsoft.SharePoint.WebPartPages.WebPart, ITask


Insert the following code after the ProviderWebPart class declaration.
This code block implements the ITask web part connection interface and adds a local variable to the web part.
DropDownList _objPicker = null;
int ITask.Id
 {
    get
    {
     return int.Parse(_objPicker.SelectedValue);
    }
 }
string ITask.Name
 {
   get
   {
     return _objPicker .SelectedItem.ToString();
   }
 }

Update the CreateChildControls method to contain the following code:

protected override void CreateChildControls()
{
  try
  {
    _objPicker= new DropDownList();
    using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
    using (SPWeb spWeb = spSite.OpenWeb())
    {
      SPList objList = spWeb.Lists["Tasks"];

      foreach (SPListItem objListItem in objList.Items)
      {
        _objPicker.Items.Add(new ListItem(objListItem.Title, objListItem.ID.ToString()));
      }    
     }
     _objPicker.AutoPostBack = true;
     this.Controls.Add(_objPicker);
  }
  catch (Exception ex)
  {  
    this.Controls.Clear();
    this.Controls.Add(new LiteralControl(ex.Message));
  }
}

Insert the following ConnectionProvider property below the CreateChildControls method. This provides the Connection Provider interface point for the ProviderWebPart: [ConnectionProvider("Task Name and ID")]
public ITask NameDoesNotMatter()
{
  return this;
}


Save your solution and build. Ensure that there are no build errors before you proceed.


3 - Develop a simple consumer web part.
In the Solution Explorer, right click on your project and select Add --> New Item…


Select Visual C# --> SharePoint 2010 Web Part.
Enter ConsumerWebPart in the Name textbox and click Add.


Insert the following code inside the ConsumerWebPart class declaration:
ITask _provider = null;
Label _lbl = null;

Update the CreateChildControls method to contain the following code:
protected override void CreateChildControls()
{
try
{
_lbl = new Label();
if (_provider != null)
{
if (_provider.Id > 0)
{
_lbl.Text = _provider.Name + " was selected.";
}
else
{
_lbl.Text = "Nothing was selected.";
}
}
else
{
_lbl.Text = "No Provider Web Part Connected.";
}
this.Controls.Add(_lbl);
}
catch (Exception ex)
{
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
}

Insert the following ConnectionConsumer property below the CreateChildControls method. This provides the Connection Consumer interface point for the ConsumerWebPart:[ConnectionConsumer("Name and ID")]
public void ThisNameDoesNotMatter(ITask providerInterface)
{
  _provider = providerInterface;
}

Save the solution, Build the solution and Deploy the solution.
Go to your target SharePoint 2010 site and refresh the site.
Edit a page and add the two new web parts.(ensure that you have some data in the SharePoint Tasks list)















View your two new web parts on the page:






















Edit the page again and select the ProviderWebPart and click on Edit Web Part.















Select the ProviderWebPart again, but this time select "Connections" --> "Send Task Name and ID To" --> ConsumerWebPart.



Now, if you select an item from the dropdown list control in the providerwebpart you will see the corresponding data change in the consumerwebpart.













This way you will be able to build master-detail views or web part filters based on selections of other web parts.

Enjoy !!

14 comments:

Anonymous said...
This comment has been removed by a blog administrator.
awfulguitarnoises said...

Some I've found in this sample is that CreateChildControls in the consumer was getting called before ThisNameDoesNotMatter, so the connection was never used. I added an overload for OnPreRender to check for the connection, and then it worked.

Ágúst og Kolbrún said...

Hi,
I am using Sharepoint Foundation and it throws an error when I try to have my webpart inherit from Microsoft.SharePoint.WebPartPages.WebPart - it defaults to UserControl.

With UserControl as base class I have not been able to get this to work. Perhaps there is something else wrong... "Connection" does not have any action under it after I have deployed the webpart.

Agust

Mostafa said...
This comment has been removed by a blog administrator.
Johan Olivier said...

Hi Everyone,
Thank you very much for the feedback and comments.
I updated the sample code and all is working fine now with ITask interface.
Regards,
Johan

Johan Olivier said...

Ágúst og Kolbrún, are you adding a Web Part to your SharePoint project or a Visual Web Part?
Please try the code by adding only a web part which does not include an user control instead of a visual web part.
Regards
Johan

Fernando J Borges said...

Adds the webparts when the option is disabled connection followed all the steps of your tutorial only thing I do different is that the tutorial does not use solutions Farm.

I await your response
thanks

Fernando João said...

Johan,
Excuse my English because I'm Brazilian.
Taking the above question, would also like to ask one more thing
I created a webpart for a preview of documents. (equal to the sharepoint already have, so you see only images)
observation.: create a webpart to display any type of document

I need a webpart that receives consumer data from my Document Library, as well as image webpart works connected with a Document Library;

So that I'm not getting access to the mining option conexion customized webpart

Do you have any idea what might be doing wrong. The question to be doing farm or not to change anything

Once again thank you
Fernando Borges
skype: fernando.joao.borges

Anonymous said...

Hi its very nice....
can you please update how to use datatable in interface in place of string and how to connect visual webparts in sharepoint 2010

Thanks in advance...

BillyK said...

Nice example many thanks :)

Anonymous said...

Thank You So much!
I would like to tell you one thing I jus blindly followed your steps and got strucked while build, after a long struggle i cam to know my mistake, I didnt declare interface as "public",one more thing u didnt mention abt Tasks list item which is predefined, where in we need to add item to this list.

Finally i got it.

Very very useful to ppl who are very new to SP 2010

Thanks a lot

Rishi Jagati said...

Hi,
can you suggest me how to connect two webparts pragmatically?

surabhisusheel said...

hi thanks for ur post can u post for OOB calendar and dropdownlist using connectable web parts.

Atiqsomroopk said...

CAn you please send dump of 7-573 certification

Post a Comment