SharePoint 2007 (MOSS/WSS) Custom BDC Web Part Example

Here is an example of a simple Custom Business Data Catalog (BDC) Web Part. I have used a BDC Metadata file which connects to Northwind database. It has reference of both Categories and Products table. But in this example I have only listed all Category ID and Category Name from Categories table. Here is the link to download the Metadata file.

In the Web Part Project add reference of microsoft.sharepoint.portal namespace. You can find the dll in this location - "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\microsoft.sharepoint.portal.dll". Here is the code for the Web Part:

using System;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

using Microsoft.Office.Server.ApplicationRegistry.Runtime;

using Microsoft.Office.Server.ApplicationRegistry.Infrastructure;

using Microsoft.Office.Server.ApplicationRegistry.MetadataModel;

namespace CustomBDCWP

{

[Guid("b42363a0-ef07-4247-81c3-cf567e617248")]

public class CustomBDCWP : System.Web.UI.WebControls.WebParts.WebPart

{

protected override void Render(HtmlTextWriter writer)

{

LobSystem nwSystem = ApplicationRegistry.GetLobSystems()["NorthwindLOBSystem"];

LobSystemInstance nwSystemInstance = nwSystem.GetLobSystemInstances()["NorthwindInstance"];

Entity categoryEntity = nwSystem.GetEntities()["dbo.Categories"];

FilterCollection fc = categoryEntity.GetFinderFilters();

IEntityInstanceEnumerator nwInstanceEnumerator = categoryEntity.FindFiltered(fc, nwSystemInstance);

writer.Write("<Table>");

while (nwInstanceEnumerator.MoveNext())

{

IEntityInstance category = nwInstanceEnumerator.Current;

writer.Write("<tr><td>" + category["CategoryID"].ToString() + "</td><td>" + category["CategoryName"].ToString() + "</td></tr>");

}

writer.Write("</Table>");

}

}

}

nw.xml