Code Snippet: Custom Business Data Web Part

Applies to: SharePoint Server 2010

The following code example shows how to create a custom Web Part that displays data from external systems by using the BDC runtime object model.

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.Runtime;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace Microsoft.SDK.SharePoint.BDCCustomWebpart
{
    public partial class CustomBDCWP : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void Render(HtmlTextWriter writer)
        {
            using (SPSite site = new SPSite(
                "Site URL"))
            {
                using (new SPServiceContextScope(
                    SPServiceContext.GetContext(site)))
                {
                    BdcService service =
                        SPFarm.Local.Services.GetValue<BdcService>(
                        String.Empty);
                    IMetadataCatalog catalog =
                        service.GetDatabaseBackedMetadataCatalog(
                        SPServiceContext.Current);

                    IEntity entity =
                        catalog.GetEntity("Entity Namespace", "Entity Name");
                    ILobSystemInstance LobSysteminstance =
                        entity.GetLobSystem().
                        GetLobSystemInstances()[0].Value;
                    IMethodInstance method =
                        entity.GetMethodInstance(
                        "FinderMethodInstanceName", MethodInstanceType.Finder);
                    IEntityInstanceEnumerator ieie =
                        entity.FindFiltered(
                        method.GetFilters(), LobSysteminstance);
                
                    writer.Write("<Table>");
                    while (ieie.MoveNext())
                    {
                        IEntityInstance customer = ieie.Current;
                        writer.Write("<tr><td>" + customer["Field 1 name"].ToString() + "</td><td>" + customer["Field 2 name"].ToString() + "</td></tr>");
                    }
                    writer.Write("</Table>");
                }
            }
        }
    }
}

See Also

Reference

BdcService

Services

GetDatabaseBackedMetadataCatalog(SPServiceContext)

IMetadataCatalog

GetEntity(String, String)

GetLobSystem()

GetLobSystemInstances()

ILobSystemInstance

IMethodInstance

IEntityInstanceEnumerator

GetMethodInstance(String, MethodInstanceType)

FindFiltered(IFilterCollection, ILobSystemInstance)

IEntityInstance