Friday, November 9, 2012

Connecting two webparts in SharePoint



This tutorial describes the step to access data by connecting two different Web Parts in a SharePoint Site. In order to do so, three things should be kept in mind:
  • Provider Web Part (that provides the data)
  • Connection Interface (that provides the connection between two Web Parts)
  • Consumer Web Part ( that accepts the data)
But before we go further, one should be aware of how to create and deploy a web part.

Following are the steps :

Creating a Connection Interface
In this step, we create an interface say ‘CommunicationInterface’.  
In this interface, we define a property ‘ parameter1’ for  providing data.  The no. of properties depends on the no. of parameter to be passed.



//Code Part

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace CommunicationInterface
{
    public interface ICommunicationInterface
    {
        string parameter1 { get; }

    }
}

Once this interface is created, compile it and add its DLL to the Global Assembly Cache (C:\Windows\Assembly) in your  system.





Creating a Provider Web Part
The second step is to create a Provider Web Part to pass the data to the interface.
Create a web part and name it say ‘WP_Provider’.  Add reference of the earlier created ‘CommunicationInterface’ DLL. 
Once the reference is added,  implement the ‘ICommunicationInterface’ to ‘WP_Provider’ class.
Then the connection provider property is added and the reference to the communication Interface is returned.
Implement the property defined in the interface.

//Code Part
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using CommunicationInterface;

namespace WP_Provider
{
   
   public class 
   WP_Provider: Microsoft.SharePoint.WebPartPages.WebPart,ICommunicationInterface
    
   {
        Label nm;
        TextBox tbname;
        Button btn=new Button();
       
        RadioButtonList rb = new RadioButtonList();

       
      // Provides connection provider property for the parameters
      [ConnectionProvider("Parameter1 Provider",
                    "Parameter1 Provider")]
        public ICommunicationInterface ConnectionInterface()
        {
         // this returns a reference to the communication interface
            return this;
        }

        protected string _parameter1 = "";


        // Property defined in Interface is implemented
        public string parameter1
        {
            get { return _parameter1; }
        }
       
       
        public WP_Provider()
        {
       
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();



            //Accessing a particular list items

            SPSite mysitecol = SPContext.Current.Site;
            SPWeb mysite = SPContext.Current.Web;
            SPList mylist = mysite.Lists["UpdateList"];
            SPListItemCollection itemcol = mylist.Items;
           
            foreach (SPListItem itm in itemcol)
            {
                string nm = itm["Company_Id"].ToString();
                rb.Items.Add(nm);

            }

            btn.Text = "Send";
            this.Controls.Add(rb);
            this.Controls.Add(btn);
            btn.Click += new EventHandler(btn_Click);
        }

   public  void btn_Click(object sender, EventArgs e)
        {
            // set connection provider property with required textbox info.
           // this._parameter1 = tbname.Text;
            this._parameter1 = rb.SelectedItem.Text;
        }

    }
}

After completing the code, compile and add the DLL in the Global Assembly Cache (C:\Windows\Assembly).
Create the corresponding ‘dwp’ file and add the SafeControl in the web.config of SharePoint Site.



Creating a Consumer Web Part
The third step is to create a Consumer  Web Part to pass the data to the interface.
Create a web part and name it say ‘WP_Consumer’.  Add reference of the earlier created ‘CommunicationInterface’ DLL. 
Then the connection Consumer property is added and the reference to the communication Interface is retrieved.
From this reference, the parameter that is passed from Provider Web Part is obtained.

//Code
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using CommunicationInterface;

namespace WP_Consumer
{
   
    public class WP_Consumer : Microsoft.SharePoint.WebPartPages.WebPart
    {
       //Label lblTitle;
       Label lblname=new Label();
      

    ///// the string info consumer from custom reciever   //
    ICommunicationInterface connectionInterface = null;

    // The consumer webpart  must define a method that
    // would accept the interface as an parameter
    // and must be decorated with ConnectionConsumer attribute     
    [ConnectionConsumer("Parameter1 Consumer",
                        "Parameter1 Consumer")]
    public void GetConnectionInterface(ICommunicationInterface
                                       _connectionInterface)
    {
        connectionInterface = _connectionInterface;
    }
    ///////////////////////////////////////////////////////// 

    public WP_Consumer()
    {
       
    }

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


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

            if (connectionInterface != null)
            {
                lblname.Text = connectionInterface.parameter1 +
                " is recieved!";
               

             }
            else
            {
                lblname.Text = "nothing is recieved!";
            }
           
        }

     
          
     }

       

  }
}

After completing the code, compile and add the DLL in the Global Assembly Cache. (C:\Windows\Assembly)
Create the corresponding ‘dwp’ file and add the SafeControl in the web.config of SharePoint Site.

Render methods in web parts in SharePoint

Today's blog post cover methods of rendering web parts. There are some methods which you can use to render content of a web part. The first method - override RenderContens  method. This method take HtmlTextWriter as argument. So, you can use it to write to the output any information. This code block illustrate how to do it:
protected override void RenderContents(HtmlTextWriter writer)
{
      writer.Write("Hello world");
}
This method simply put text "Hello world" to the output stream of the web part.
Another way to render web part content - override CreateChildControls:
protected override void CreateChildControls()
{
      var lblHello = new Label {Text = "Hello world"};
      Controls.Add(lblHello);
}
We'll get the same result as a previous one, but using CreateChildControls method. You can use the first method in a very simple scenarios, when there is no need to render complex layout with many controls. The second method fit situation when you must have several controls, but with rather simple logic.
But what if we have several controls, but we want insert this controls in a table or a div html tag? The third method help us - we can use both of RenderContents and CreateChildControls overloads. Standard implementation of RenderContents looks like this:
protected override void RenderContents(HtmlTextWriter writer)
{
    foreach(Control control in Controls)
    {
        control.RenderControl(writer);
    }
}
We can call control.RenderControl method in the required sequence and enclosed controls with addition html tags if required. Here is an example:
[ToolboxItemAttribute(false)]
public class HelloWorldWebPart3 : WebPart
{
    protected TextBox _txtName
    protected Button _btnSave;
 
    protected override void CreateChildControls()
    {
        _txtName = new TextBox();
        _btnSave = new Button {Text = "Save"};
        _btnSave.Click += btnSaveClick;
        Controls.Add(_btnSave);
        Controls.Add(_txtName);
    }
 
    private void btnSaveClick(object sender, EventArgs e)
    {
        //some code here
    }
 
    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Div);
        writer.Write("Please, enter your name:");
        _txtName.RenderControl(writer);
        writer.RenderBeginTag(HtmlTextWriterTag.Br);
            writer.RenderEndTag();
        _btnSave.RenderControl(writer);
        writer.RenderEndTag();
    }
}

Shared Services in SharePoint 2010

Shared Service Provider (SSP) in SharePoint 2007 has been replaced by Shared Services in SharePoint 2010. SSP in SharePoint 2007 was confusing and had its share of limitations which SharePoint 2010 seems to solve by introducing Shared Services.

Key differences between SSP and Shared Services
SSP in 2007Shared Services in 2010
MOSS onlyAvailable in WSS
Different services shared the same db         Services can have its own db
Internal to MOSSPublic APIs to create own Shared Services
Only one application of serviceMultiple instances of service allowed
Restricted to the farmCross farm support


SharePoint 2010 provides the following Shared Services ( not an exhaustive list )

Access Services : Allows viewing, editing, and interacting with Access databases in a browser.
Business Connectivity Service : Provides read/write access to external data from line-of-business (LOB) systems, Web services, databases, and other external systems. Also available in SharePoint Foundation.
Managed Metadata Service : Provides access to managed taxonomy hierarchies, keywords, social tags and Content Type publishing across site collections.
Secure Store Service : Provides capability to store data (e.g. credential set) securely and associate it to a specific identity or group of identities.
State Service : Provides temporary storage of user session data for Office SharePoint Server components.
Usage and Health data collection : This service collects farm wide usage and health data and provides the ability to view various usage and health reports.
Visio Graphics Service : Enables viewing and refreshing of published Visio diagrams in a web browser.
Web Analytics Service Application : Enable rich insights into web usage patterns by processing and analyzing web analytics data .
Word Conversion Service Application : Provides a framework for performing automated document conversions

SharePoint - Cannot convert a primitive value to the expected type 'Edm.Double'. See the inner exception for more details If y...

Ad