Saturday, July 10, 2010

Adding "Report viewer" webpart programmatically , sharepoint 2007

I know there are many people who are trying to find the solution to add "Report viewer webpart programmatically" to sharepoint 2007 pages. Ok, don't waste time anymore, I will show you how to do that.

STEPS:

1. Open page and manually add "Report Viewer webpart" [this is on "development" machine]
2. After adding webpart find small arrow on right side of web part and click on it to get drop down menu.










3. click on Export and it gives dialogue box to save /open. Save it some location [let's say on Desktop but safe bet is to add to your package folder so that when deployed u can write code to copy this to particular location on production (12 hive folder) then use that location in your code]
4. Now copy and paste the following code.

try

{
using (SPSite sourceSite = new SPSite(siteUrl))
{
using (SPWeb sourceWeb = sourceSite.OpenWeb())
{
sourceWeb.AllowUnsafeUpdates = true;
SPList publishList = sourceWeb.Lists["Pages"];   //THIS is the list name where your pages are stored. If you stored your pages in different list give that name.
int publishListItemCount = publishList.Items.Count;
for (int i = 1; i < publishListItemCount; i++)
{
SPListItem publishListItem = publishList.Items[i];

publishListItem.File.CheckOut();

SPLimitedWebPartManager WebPartMgr = sourceWeb.GetLimitedWebPartManager(siteUrl + "/Pages/" + publishListItem.File.Name, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\Report_Viewer.dwp");

//I saved to this location and my code copy webpart to this location in production when I run deployment package.

//This is needed when we import 'reportviewer' webpart.
//I copied follwoing code from internet...I really don't have any clue about this
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", WebPartMgr.Web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new System.IO.StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = WebPartMgr.Web;
}

string errors = String.Empty;
System.Xml.XmlReader xr = System.Xml.XmlReader.Create(new System.IO.StringReader(sr.ReadToEnd()));

System.Web.UI.WebControls.WebParts.WebPart webPart = WebPartMgr.ImportWebPart(xr, out errors);
string zoneId = "Header";
int zoneIndex = 0;
webPart.Title = publishListItem.Title;
WebPartMgr.AddWebPart(webPart, zoneId, zoneIndex);
sr.Dispose();

publishListItem.File.CheckIn("Added 'Report viewer' webpart");
publishListItem.File.Publish("Added 'Report viewer' webpart");
}

sourceWeb.AllowUnsafeUpdates = false;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}


You are done........open your pages and you see webparts are added to your pages !!!!

No comments:

Post a Comment