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

Deploying an ASP.NET HttpHandler to SharePoint 2010


 How to deploy an HttpHandler to SharePoint 2010 that uses code-behind.  The answer is that you don’t really use code-behind like you would in an ASP.NET application where the code and assembly are in the same folder.  With SharePoint, you need to deploy your code to the Global Assembly Cache (GAC).
You can create the code for an HttpHandler very easily in Visual Studio.  I am going to steal borrow some code from Ted Pattison’s walkthrough, “Creating a Custom HttpHandler in Windows SharePoint Services 3.0” on MSDN (includes a video as well).

using System;
using System.Web;
using Microsoft.SharePoint;

namespace ASHXHandlerDemo
{
    public class HelloHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }
 
        
        public void ProcessRequest(HttpContext context)
        {
            SPSite siteColl = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello HttpHandler from the site " +
                                   site.Title +
                                   " at " +
                                   site.Url);
        }
    }
}
The question is how to call that code?  When an HTTP request comes in, how do you map that request to this code? 
The easiest way is to create a .ASHX file and deploy it to the LAYOUTS directory in the SharePoint root (aka “14 hive”).  To do this, right-click your SharePoint project in Visual Studio 2010 and choose “Add SharePoint Layouts Mapped Folder”. 
image
In that newly created folder, add a new file with a .ASHX extension with the following contents.  The .ASHX file just points to the code in the GAC using the fully-qualified assembly name.

<%@ Assembly Name="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="ASHXHandlerDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=684a624f7b7a49ae" %>
<%@ WebHandler Language="C#"  Class="ASHXHandlerDemo.HelloHttpHandler" %>
 
The solution looks like this in Visual Studio 2010.
image
When you build and deploy your solution from Visual Studio, the code is compiled into an assembly (a .DLL) and registered in the Global Assembly Cache.  The output is:
image

Difference between Farm and Sandbox solutions in SharePoint

Farm Solutions:

Farm solutions, which are hosted in the IIS worker process (W3WP.exe), run code that can affect the whole farm. When you debug a SharePoint project whose Sandboxed Solution property is set to "farm solution," the system's IIS application pool recycles before SharePoint retracts or deploys the feature so as to release any files locked by the IIS worker process. Only the IIS application pool serving the SharePoint project's site URL is recycled.

Sandbox Solutions:


Sandboxed solutions, which are hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe), run code that can only affect the site collection of the solution. Because sandboxed solutions do not run in the IIS worker process, neither the IIS application pool nor the IIS server must restart. Visual Studio attaches the debugger to the SPUCWorkerProcess process that the SPUserCodeV4 service in SharePoint automatically triggers and controls. It is not necessary for the SPUCWorkerProcess process to recycle to load the latest version of the solution.

How to add WFE(Web Front Servers) in SharePoint 2010

Solution:


You need to join the new server to the farm, then go to Services on Server (in Central Administration) and enable Microsoft SharePoint Foundation Web Application Service. Then you'll see that in IIS your websites and application pools appeared

Managed Accounts in SharePoint 2010

Microsoft SharePoint Server 2010 provides a number of compelling improvements designed especially for the system administrator, of these, commonly overlooked, are Managed Accounts.  A Managed Account is effectively an Active Directory user account whose credentials are managed by and contained within SharePoint.  In addition to storing the credentials of the object, Microsoft SharePoint Server 2010 can also leverage Active Directory Domain Policies to  automatically reset passwords while meeting the requirements established by policy.
How credentials are stored…
Managed Account credentials are encrypted using a farm encryption key that is specified when you run PSConfig[ui].exe at farm creation based on the passphrase.  The passphrase is stored in a secure registry location so that it can only be accessed by the farm account and encrypted so that only the farm account has access (we won’t get into the encryption specifics here). The farm encryption key subsequently, is stored in the Configuration Database.   This scenario is what enables farm administrators to join machines to the farm without specifying the credentials as had to be done in previous versions of the product.
The last sentence of the paragraph above illustrates one of immediate benefits of using Managed Accounts, for example, suppose an administrator would like to create a new Web application using Windows PowerShell and/or SharePoint Central Administration – the administrator only needs to specify the Application Pool account (Windows PowerShell) or select the account in the SharePoint Central Administration user interface as opposed to both having to know the domain\username and associated password.
Example (Windows PowerShell)
$provider = New-SPAuthenticationProvider -ASPNETMembershipProvider "LdapMember" -ASPNETRoleProviderName "LdapRole"
$webApp = New-SPWebApplication -Name "Claims" -ApplicationPool "Claims Application Pool" -ApplicationPoolAccount "CONTOSO\administrator"
  -Url
http://claims.contoso.com -Port 80 -AuthenticationProvider $provider
Get Managed Accounts (SharePoint Central Administration)
  1. To view existing Managed Accounts using SharePoint Central Administration, select Security from the SharePoint Central Administration homepage.
  2. On the Security page select Configure managed accounts under General Security.
  3. The Managed Accounts page will list all Managed Accounts registered in SharePoint.
Register Managed Accounts (SharePoint Central Administration)
  1. To register new Managed Accounts using SharePoint Central Administration, select Security from the SharePoint Central Administration homepage.
  2. On the Security page select Configure managed accounts under General Security.
  3. On the Managed Accounts page select Register Managed Account.
  4. On the Register Managed Account page (see illustration below) specify the credentials and select the password change policies as desired.
CA

Get Managed Accounts (Windows PowerShell)
  1. To view existing Managed Accounts using Windows PowerShell, open the SharePoint 2010 Management Shell and enter Get-SPManagedAccount at the prompt.  For additional information on using the Get-SPManagedAccount CmdLet enter Get-Help Get-SPManagedAccount at the prompt.
ManagedAccount
Register Managed Accounts (Windows PowerShell)
  1. To register Managed Accounts using Windows PowerShell open the SharePoint 2010 Management Shell and use the Set-SPManagedAccount CmdLet (see below for syntax).
Syntax
New-SPManagedAccount [-Credential] <PSCredential> [-AssignmentCollection <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-WhatIf [<SwitchParameter>]]
Configure Managed Accounts (Windows PowerShell)
  1. To configure Managed Accounts using Windows PowerShell open the SharePoint 2010 Management Shell and use the Set-SPManagedAccount CmdLet (see below for syntax).
Syntax
Set-SPManagedAccount -Identity <SPManagedAccountPipeBind> [-AssignmentColle
ction <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-EmailNotif
ication <Int32>] [-PreExpireDays <Int32>] [-Schedule <String>] [-WhatIf [<S
witchParameter>]] [<CommonParameters>]
Set-SPManagedAccount -Identity <SPManagedAccountPipeBind> [-AssignmentColle
ction <SPAssignmentCollection>] [-AutoGeneratePassword <SwitchParameter>] [
-Confirm [<SwitchParameter>]] [-EmailNotification <Int32>] [-PreExpireDays
<Int32>] [-Schedule <String>] [-WhatIf [<SwitchParameter>]] [<CommonParamet
ers>]
Set-SPManagedAccount -Identity <SPManagedAccountPipeBind> -ConfirmPassword
<SecureString> -NewPassword <SecureString> [-AssignmentCollection <SPAssign
mentCollection>] [-Confirm [<SwitchParameter>]] [-EmailNotification <Int32>
] [-PreExpireDays <Int32>] [-Schedule <String>] [-SetNewPassword <SwitchPar
ameter>] [-WhatIf [<SwitchParameter>]] [<CommonParameters>]
Set-SPManagedAccount -Identity <SPManagedAccountPipeBind> -ExistingPassword
<SecureString> [-AssignmentCollection <SPAssignmentCollection>] [-Confirm
[<SwitchParameter>]] [-EmailNotification <Int32>] [-PreExpireDays <Int32>]
[-Schedule <String>] [-UseExistingPassword <SwitchParameter>] [-WhatIf [<Sw
itchParameter>]] [<CommonParameters>]
For additional information on using the Set-SPManagedAccount CmdLet enter Get-Help Set-SPManagedAccount at the prompt.

Difference between Application Server and Web Server 


Application Server:


 Application server maintains the application logic and serves the web pages in response to user request. That means application server can do both application logic maintanence and web page serving. 

Web Server: 


Web server just serves the web pages and it cannot enforce any application logic. Final conclusion is: Application server also contains the web server.

Difference between CLR,CTS and CLS in .Net


CLR....

The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of bytecode called the Common Intermediate Language (CIL, previously known as MSIL -- Microsoft Intermediate Language).
Developers using the CLR write code in a language such as C# or VB.Net. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.
Although some other implementations of the Common Language Infrastructure run on non-Windows operating systems, Microsoft's implementation runs only on Microsoft Windows operating systems.

The virtual machine aspect of the CLR allows programmers to ignore many details of the specific CPU that will execute the program. The CLR also provides other important services, including the following:

* Memory management
* Thread management
* Exception handling
* Garbage collection
* Security

CLS...

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the common type system; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these help you determine whether your managed code conforms to the CLS and to what extent a given tool supports the development of managed code that uses CLS features.

If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS. Components that adhere to the CLS rules and use only the features included in the CLS are said to be CLS-compliant components.

Most of the members defined by types in the .NET Framework class library are CLS-compliant. However, some types in the class library have one or more members that are not CLS-compliant. These members enable support for language features that are not in the CLS. The types and members that are not CLS-compliant are identified as such in the reference documentation, and in all cases a CLS-compliant alternative is available. For more information about the types in the .NET Framework class library, see the .NET Framework Reference.

The CLS was designed to be large enough to include the language constructs that are commonly needed by developers, yet small enough that most languages are able to support it. In addition, any language construct that makes it impossible to rapidly verify the type safety of code was excluded from the CLS so that all CLS-compliant languages can produce verifiable code if they choose to do so. For more information about verification of type safety, see JIT Compilation.

The following table summarizes the features that are in the CLS and indicates whether the feature applies to both developers and compilers (All) or only compilers. It is intended to be informative, but not comprehensive. For details, see the specification for the Common Language Infrastructure, Partition I, which is located in the Tool Developers Guide directory installed with the Microsoft .NET Framework SDK.

CTS.....

The Common Type System (CTS) is a standard that specifies how Type definitions and specific values of Types are represented in computer memory. It is intended to allow programs written in different programming languages to easily share information. As used in programming languages, a Type can be described as a definition of a set of values (for example, "all integers between 0 and 10"), and the allowable operations on those values (for example, addition and subtraction).

The specification for the CTS is contained in Ecma standard 335, "Common Language Infrastructure (CLI) Partitions I to VI." The CLI and the CTS were created by Microsoft, and the Microsoft .NET framework is an implementation of the standard.
 

Difference between Web Site and Web application in ASP.NET


• Development Wise Difference


Web Site
1. We can code one page in C# and one page in vb.net (Multiple programming languages allowed).
2. We cannot call (access) public functions from one page to other page.
3. Utility classes / functions must be placed in a special ASP.NET folder (the App_Code folder)
4. Web Sites do not have a .csproj/.vbproj file that manages the project (the folder that contains the site becomes the project root).
5. In the Web Site project, each file that you exclude is renamed with an exclude
keyword in the filename.
6. Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.


Web Application
1. Only one programming language allowed per project (Need to decide on programming language when starting project).
2. We can access public functions from one page to other page.
3. Utility classes / function can be placed anywhere in the applications folder structure.
4. Web Applications are treated like other .NET projects and are managed by a project file (.csproj or .vbproj) .
5. One nice feature of the Web Application project is it's much easier to exclude files from the project view.
6. Explicit namespaces are added to pages, controls, and classes by default.




• Deployment wise difference


Web Site
1. It has its code in a special App_Code directory and it's compiled into several DLLs (assemblies) at runtime.
2. No need to recompile the site before deployment.
3. We need to deploy both .aspx file and code behind file.
4. Small changes to the site do not require a full re-deployment. (We can upload the code file that was changed) 

Web Application
1. web application is precompiled into one single DLL.
2. Site has to be pre-compiled before deployment .
3. Deploy only .aspx page, but not associated code file (the pre-compiled dll will be uploaded) .
4. Even small changes require a full re-compile of the entire site(i.e. if the code for a single page changes the whole site must be compiled) (It requires careful planning to ensure new bugs aren't introduced to the production site when uploading bug fixes or other changes.)




sample format of .CSPROJ file in web application
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <ProjectView>ProjectFiles</ProjectView>
  </PropertyGroup>
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <StartPageUrl>CheckboxListTest.aspx</StartPageUrl>
          <StartAction>SpecificPage</StartAction>
          <AspNetDebugging>True</AspNetDebugging>
          <NativeDebugging>False</NativeDebugging>
          <SQLDebugging>False</SQLDebugging>
          <PublishCopyOption>RunFiles</PublishCopyOption>
          <PublishTargetLocation>
          </PublishTargetLocation>
          <PublishDeleteAllFiles>False</PublishDeleteAllFiles>
          <PublishCopyAppData>True</PublishCopyAppData>
          <ExternalProgram>
          </ExternalProgram>
          <StartExternalURL>
          </StartExternalURL>
 

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

Ad