ActiveReports for .NET 3 Online Help Request technical support
Walkthrough: Custom Exporting with HTML
See Also
User Guide > Samples and Walkthroughs > Walkthroughs > Standard Edition Walkthroughs > Advanced > Web Walkthroughs (Standard Edition) > Custom Web Exporting Walkthroughs > Walkthrough: Custom Exporting with HTML

Glossary Item Box

ActiveReports provides custom components for several formats, including PDF, HTML, RTF, Excel, TIFF and plain text. Ultimate customizability is available by using any ASP.NET language.

This walkthrough illustrates how to create a simple Web application and set up custom exporting in HTML format.

This walkthrough is split up into the following activities:

To complete the walkthrough, you must have access to the Northwind database.
A copy is located at C:\Program Files\Data Dynamics\ActiveReports for .NET 3.0\Data\NWIND.MDB.

You must also have access to Internet Information Services either from your computer or from the server.

When you have completed this walkthrough, you will have a report that looks similar to the following.

Adding an ActiveReport to an ASP.NET Web application

To add an ActiveReport to your project using Visual Studio 2003

  1. Create a new ASP.NET Web application. 
  2. From the Project menu, select Add New Item
  3. Select ActiveReports 3.0 File and rename the file rptCustHTML.
  4. Click Open.

To add an ActiveReport to your project using Visual Studio 2005

  1. Create a new ASP.NET Web site. 
  2. From the Website menu, select Add New Item.
  3. Select ActiveReports 3.0 File and rename the file rptCustHTML.
  4. Click Add.
  5. Click Yes when a message box asks whether you would like to place the class in the 'App_Code' folder.
To see the design view of your report in Visual Studio 2005, right-click the report in the Solution Explorer and select View Designer.

Connecting the report to a data source

To connect the report to a data source

  1. Click on the gray report DataSource icon in the Detail section to open the report Datasource dialog.
  2. Click on Build.
  3. Select Microsoft Jet 4.0 OLE DB Provider and click Next.
  4. Click the ellipsis button to browse for the access path to the Northwind database. Click Open once you have selected the appropriate access path.
  5. Click OK to continue.
  6. In the Query field, type "Select * from customers order by country".
  7. Click OK to return to the report design surface.

Adding controls to the report to contain data

To add controls to the report

  1. Add a GroupHeader/Footer section to rptCustHTML by right-clicking on the design surface of the report and selecting Insert > Report Header/Footer.
  2. Make the following changes to the group header:
    • Change the Name property to ghCountries
    • Change the BackColor property to Silver
    • Change the DataField property to Country
  3. Add labels with the following properties to ghCountries:

    Name Text Location Formatting
    lblCustomerID Customer ID 0, 0 Bold
    lblCompanyName Company Name 0.88, 0 Bold
    lblContactName Contact Name 2.13, 0 Bold
    lblAddress Address 3.19, 0 Bold
    lblCity City 4.31, 0 Bold
    lblPhone Phone 5.44, 0 Bold

  4. Make the following changes to the detail section:
    • Change the BackColor property to WhiteSmoke
    • Change the CanShrink property to True
  5. In the Report Explorer, expand the Fields node, then the Bound node. Drag the following fields onto the detail section and set the properties of each textbox as indicated.

    Field Text Location
    CustomerID Customer ID 0, 0
    CompanyName Company Name 0.88, 0
    ContactName Contact Name 2.13, 0
    Address Address 3.19, 0
    City City 4.31, 0
    Phone Phone 5.44, 0

Adding the Html Export control to the Web Form

To add the Html Export control in Visual Studio 2003

  1. Click on the HtmlExport control in the appropriate toolbox to select it. (See Adding ActiveReports controls for help on adding it to the toolbox.)
  2. Drag the control onto the Web Form.
  3. The control appears in the tray beneath the WebForm.

To add the Html Export control in Visual Studio 2005

  1. From the View menu, select Component Designer to go to the design view of the aspx file.
  2. Click on the HtmlExport control in the appropriate toolbox to select it. (See Adding ActiveReports controls for help on adding it to the toolbox.)
  3. Drag the control onto the aspx design view.

Creating a public class for the HTML outputter

To create a public class

  1. In the Solution Explorer window, right-click on your project name and select Add > Add New Item.
  2. In the Templates window of the Add New Item dialog, select Class.
  3. Change the name of the file to "MyCustomHtmlOutputter" and click the Open button. (In Visual Studio 2005, click the Add button and then select Yes to place the class in the 'App_Code' folder.)
  4. This opens the code view of the class file where you can add the code needed to create the public class.

To write the code in Visual Basic

To write the code in C#

The following example shows what the complete code for the method looks like.

'Visual Basic
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports DataDynamics.ActiveReports
Imports DataDynamics.ActiveReports.Export.Html
Public Class MyCustomHtmlOutputter
  Implements IOutputHtml
  'The http context of the request.
  Private context As System.Web.HttpContext = Nothing
  'The directory the filename will be saved in--this will be used to ensure the filename 
  'is unique.
  Private dirToSave As System.IO.DirectoryInfo = Nothing
  Public mainPage As String = ""
  Public Sub New(ByVal context As System.Web.HttpContext)
    If context Is Nothing Then
       Throw New ArgumentNullException("context")
    End If
    Me.context = context
    Dim dirName As String = context.Server.MapPath("ReportOutput")
    Me.dirToSave = New DirectoryInfo(dirName)
  End Sub
  
  #Region "Implementation of IOutputHtml"
  Public Function OutputHtmlData(ByVal info As DataDynamics.ActiveReports.Export.Html _
    .HtmlOutputInfoArgs) As  String Implements IOutputHtml.OutputHtmlData
    Dim temp As String = ""
    Select Case info.OutputKind
        Case HtmlOutputKind.BookmarksHtml
        Case HtmlOutputKind.FramesetHtml
           temp = Me.GenUniqueFileNameWithExtension(".html")
           Dim fs As New FileStream(temp, FileMode.CreateNew)
           Me.WriteStreamToStream(info.OutputStream, fs)
           fs.Close()
           Return temp
        Case HtmlOutputKind.HtmlPage
        'We want to hold on to the name of the main page so we can redirect the 
    	'browser to it
    	   Me.mainPage = Me.GenUniqueFileNameWithExtension(".html")
    	   Dim fs As New FileStream(Me.mainPage, FileMode.CreateNew)
    	   Me.WriteStreamToStream(info.OutputStream, fs)
    	   fs.Close()
    	   Return Me.mainPage
    	 Case HtmlOutputKind.ImageJpg
    	 'should be a file with a .jpg extension:
    	   temp = Me.GenUniqueFileNameWithExtension(".jpg")
    	   Dim fs As New FileStream(temp, FileMode.CreateNew)
    	   fs = File.Create(temp)
    	   Me.WriteStreamToStream(info.OutputStream, fs)
    	   fs.Close()
    	   Return temp
    	 Case HtmlOutputKind.ImagePng
    	 'should be a file with a .png extension:
    	   temp = Me.GenUniqueFileNameWithExtension(".png")
    	   Dim fs As New FileStream(temp, FileMode.CreateNew)
    	   Me.WriteStreamToStream(info.OutputStream, fs)
    	   fs.Close()
    	   Return temp
    	 Case Else
    	 'This case shouldn't really happen, but we'll default to html.
    	   temp = Me.GenUniqueFileNameWithExtension(".html")
    	   Dim fs As New FileStream(temp, FileMode.CreateNew)
    	   Me.WriteStreamToStream(info.OutputStream, fs)
    	   fs.Close()
    	   Return temp
    End Select
  End Function
  
  Public Sub Finish() Implements IOutputHtml.Finish
  End Sub
  #End Region
  
  Private Sub WriteStreamToStream(ByVal sourceStream As Stream, ByVal targetStream As Stream)
  'What's the size of the source stream:
     Dim size As Integer = CType(sourceStream.Length, Integer)
     'Create a buffer that same size
     Dim buffer(size) As Byte
     'Move the source stream to the beginning
     sourceStream.Seek(0, SeekOrigin.Begin)
     'copy the whole sourceStream into our buffer
     sourceStream.Read(buffer, 0, size)
     'Write out buffer to the target stream
     targetStream.Write(buffer, 0, size)
  End Sub
  
  Private Function GenUniqueFileNameWithExtension(ByVal extensionWithDot As String) As String
     Dim r As New System.Random()
     Dim unique As Boolean = False
     Dim filePath As String = ""
     Dim iRandom As Integer = 0
     'Generate a random name until it's unique
     While Not unique
        iRandom = r.Next()
        'Buld the full filename
        Dim sb = New StringBuilder()
        sb.Append(Me.dirToSave.FullName)
        sb.Append(Path.DirectorySeparatorChar)
        sb.Append(iRandom.ToString())
        sb.Append(extensionWithDot)
        filePath = sb.ToString()
        If File.Exists(filePath) = False Then
            unique = True
        Else
            unique = False
        End If
     End While
     Return filePath
  End Function
End Class

//C#
using System;
using System.IO;
using System.Web;
using System.Text;
using DataDynamics.ActiveReports;
using DataDynamics.ActiveReports.Export.Html;

public class MyCustomHtmlOutputter:DataDynamics.ActiveReports.Export.Html.IOutputHtml
{
   //The http context of the request
   private System.Web.HttpContext context = null;
   //The directory the filename will be saved in--this will be used to ensure the 
   //filename is unique.
   private System.IO.DirectoryInfo dirToSave = null;
   public string mainPage = "";
   public MyCustomHtmlOutputter(System.Web.HttpContext context)
   {
      if(context == null)
      {		
        throw new ArgumentNullException("context");
    	this.context = context;
    	string dirName = context.Server.MapPath("ReportOutput");
    	this.dirToSave = new DirectoryInfo(dirName);
      }
    }
    
#region Implementation of IOutputHtml
public string OutputHtmlData(DataDynamics.ActiveReports.Export.Html.HtmlOutputInfoArgs info)
{
   string temp = "";
   switch(info.OutputKind)
   {
      case HtmlOutputKind.BookmarksHtml:
      case HtmlOutputKind.FramesetHtml:
      {
    	temp = this.GenUniqueFileNameWithExtension(".html");
    	FileStream fs = File.Create(temp);
    	this.WriteStreamToStream(info.OutputStream, fs);
    	fs.Close();
    	return temp;
      }
    		
      case HtmlOutputKind.HtmlPage:
      {
    	//We want to hold on to the name of the main page so we can
    	//redirect the browser to it
    	this.mainPage = this.GenUniqueFileNameWithExtension(".html");
    	FileStream fs = File.Create(this.mainPage);
    	this.WriteStreamToStream(info.OutputStream, fs);
    	fs.Close();
    	return this.mainPage;
      }
    		
      case HtmlOutputKind.ImageJpg:
      {
         // should be a file with a .jpg extension
         temp = this.GenUniqueFileNameWithExtension(".jpg");
    	FileStream fs = File.Create(temp);
    	this.WriteStreamToStream(info.OutputStream, fs);
    	fs.Close();
    	return temp;
      }
    		
      case HtmlOutputKind.ImagePng:
      {
    	//should be a file witha .png extension
    	temp = this.GenUniqueFileNameWithExtension(".png");
    	FileStream fs = File.Create(temp);
    	this.WriteStreamToStream(info.OutputStream, fs);
    	fs.Close();
    	return temp;
      }
    		
      default:
      {
    	//This case shouldn't really happen, but we'll default to html.
    	temp = this.GenUniqueFileNameWithExtension(".html");
    	FileStream fs = File.Create(temp);
    	this.WriteStreamToStream(info.OutputStream, fs);
    	fs.Close();
    	return temp;
      }
   }
}
    
public void Finish()
{
}
#endregion
    
private void WriteStreamToStream(Stream sourceStream, Stream targetStream)
{
   //Whats the size of the source stream
   int size = (int)sourceStream.Length;
       
   //Create a buffer that same size
   byte[] buffer = new byte[size];
       
   //Move the source stream to the begining
   sourceStream.Seek(0, SeekOrigin.Begin);
       
   //copy the whole sourceStream in to our buffer
   sourceStream.Read(buffer, 0, size);
       
   //Write out buffer to the target stream
   targetStream.Write(buffer, 0, size);
}
     
/// <summary>
/// Generates a unqiue file name with the specified extension.
/// </summary>
/// <param name="extensionWithDot">
/// The file extension begining with a dot such as ".jpg".
/// </param>
/// <returns></returns>
private string GenUniqueFileNameWithExtension(string extensionWithDot)
{
    System.Random r = new Random();
    bool unique = false;
    string filePath = "";
    int iRandom = 0;
    //Generate a random name until it's unique
    while(!unique)
    {
       iRandom = r.Next();
       //Buld the full filename
       System.Text.StringBuilder sb = new System.Text.StringBuilder();
       sb.Append(this.dirToSave.FullName);
       sb.Append(Path.DirectorySeparatorChar);
       sb.Append(iRandom.ToString());
       sb.Append(extensionWithDot);
       filePath = sb.ToString();
       unique = !File.Exists(filePath);
     }
     return filePath;
  }
}

Adding code to the Web Form to export to HTML

To write the code in Visual Basic

To write the code in Visual Basic or C#

The following example shows what the code for the method looks like.

'Visual Basic
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  _

    Dim rpt As New rptCustHTML()
    Try
       rpt.Run(False)
    Catch eRunReport As Exception
        'Failure running report, just report the error to the user
        Response.Clear()
        Response.Write("<h1>Error running report:</h1>")
        Response.Write(eRunReport.ToString())
        Return
    End Try
    
    'Buffer this page's output until the report output is ready.
    Response.Buffer = True
    
    'Clear any part of this page that might have already been buffered for output.
    Response.ClearContent()
    
    'Clear any headers that might have already been buffered (such as the content type 
    'for an HTML page)
    Response.ClearHeaders()
    
    'Tell the browser and the "network" that this resulting data of this page should be 
    'cached since this could be a dynamic report that changes upon each request.
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    
    'Tell the browser this is an Html document so it will use an appropriate viewer.
    Response.ContentType = "text/HTML"
    
    'Create the Html export object
    Dim HtmlExport1 As New DataDynamics.ActiveReports.Export.Html.HtmlExport()
    Dim outputter As New MyCustomHtmlOutputter(Me.Context)
    HtmlExport1.Export(rpt.Document, outputter, "")
    Response.Redirect("ReportOutput" + "/" + System.IO.Path.GetFileName _
       	(outputter.mainPage))
End Sub

//C#
private void Page_Load(object sender, System.EventArgs e)
{
   rptCustHTML rpt = new rptCustHTML();
   try
   {
      rpt.Run(false);
   }
   catch (Exception eRunReport)
   {
      //Failure running report, just report the error to the user
      Response.Clear();
      Response.Write("<h1>Error running report:</h1>");
      Response.Write(eRunReport.ToString());
      return;
   }
   //Buffer this page's output until the report output is ready.
   Response.Buffer = true;
	
   //Clear any part of this page that might have already been buffered for output.
   Response.ClearContent();

   //Clear any headers that might have already been buffered (such as the content 
   //type for an HTML page)
   Response.ClearHeaders();
    
   //Tell the browser and the "network" that this resulting data of this page should 
   //be cached since this could be a dynamic report that changes upon each request.
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
   //Tell the browser this is an Html document so it will use an appropriate viewer.
   Response.ContentType = "text/html";
    
   //Create the HTML export object
   DataDynamics.ActiveReports.Export.Html.HtmlExport html = new DataDynamics
       .ActiveReports.Export.Html.HtmlExport();
       
   //Export the report to HTML in this session's webcache
   MyCustomHtmlOutputter outputter = new MyCustomHtmlOutputter(this.Context);
   this.htmlExport1.Export(rpt.Document, outputter, "");
   Response.Redirect("ReportOutput" + "/" + System.IO.Path.GetFileName
       (outputter.mainPage));
}

Adding a folder to the project for report output

To add a folder to the project

  1. Open Windows Explorer and browse to the folder in which your project is contained.
  2. On the File menu, click New > Folder.
  3. Name the folder "ReportOutput".
  4. Make sure that you have write permissions for this folder.
To view the results in your Web browser, run the project.

See Also

©2009. All Rights Reserved.