Welcome to MSDN Blogs Sign in | Join | Help

Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Summary: Learn a technique for printing reports programmatically using the Reporting Services XML Web service and C#.

Microsoft SQL Server 2000 Reporting Services is Microsoft's latest entry into the Business Intellegence marketplace and it joins a host of other BI products for SQL Server 2000. Reporting Services is a new, server-based reporting platform that you can use to create and manage tabular, matrix, graphical, and free-form reports that contain data from relational and multidimensional data sources. The reports that you create can be viewed and managed over a Web-based connection. As a developer, you have several programming opportunities available to you through the Reporting Services API. One of the most appealing aspects of Reporting Services is the open and flexible Web service API (also known as the SOAP API) which enables you to integrate existing features and capabilities of Reporting Services into your own custom reporting and management tools for Web sites and Windows applications. The SOAP API consists of close to one-hundred different XML Web service methods that you can use to integrate anything from report management to report rendering and execution into your custom applications. In this article, I will focus on one programming technique in particular: programmatically rendering a report and then sending that report directly to a local or network printer using C# and the Reporting Services Web service.

Before reading on, you can view the source code at the end of this article. The source code assumes you are creating a simple console application to test your print functionality and your ability to successfully call the Reporting Services Web service.

Creating a Reference to the Web service

The first thing you need to do is add a Web reference to the Reporting Services Web service in your development project that points to your report server. This can be done by right-clicking on your project in Visual Studio and choosing Add Web reference... . You should add a reference to a local report server (localhost) at "http://localhost/reportserver/reportservice.asmx". If you have a remote report server, simply change the URL of the Web reference. The end point for any Reporting Services Web service is "http://servername/reportserver/reportservice.asmx". For you Web service enthusiasts, you can access the end point through your browser with the ?wsdl directive to see the Web Service Description Language (WSDL) for the Reporting Services Web service (http://servername/reportserver/reportservice.asmx?wsdl).

The Render Method

Once you have added the appropriate Web reference, you will have all of the Web methods at your disposal. The Web methods are methods of the ReportingService class of the Web service proxy. To access the Web methods, you need to instantiate a ReportingService object and set credentials. A sample of this looks like the following:

// Create proxy object and authenticate        
Console.WriteLine("Authenticating to the Web service...");
rs = new ReportingService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;

Once you have created a proxy object for the Web service, you can access the methods as you would any normal C# class. The method that we are most interested in for the purpose of this article is the ReportingService.Render method. This is the primary method for rendering reports that have been published to the report server. The syntax for the Render method is as follows:

public Byte[] Render(
string Report,
string Format,
string HistoryID,
string DeviceInfo,
[Namespace].ParameterValue[] Parameters,
[Namespace].DataSourceCredentials[] Credentials,
string ShowHideToggle,
out string Encoding,
out string MimeType,
out [Namespace].ParameterValue[] ParametersUsed,
out [Namespace].Warning[] Warnings
out string[] StreamIds);
Member of [Namespace].ReportingService

For more details about the various method arguments, see Reporting Services Books Online.

In code, you need to render to the Image output format designated by the Format argument. The value of this parameter is a string, simply "IMAGE". To get Enhanced Meta File (EMF) output, the kind of output you will need for printing, you also need to specify device information for the call to Render. That device information should be passed as an XML string for the DeviceInfo argument and should look like "<DeviceInfo><OutputFormat>EMF</OutputFormat></DeviceInfo>". The Render method returns the report as a base 64-encoded byte array. This array of bytes can be used to perform a number of functions including saving the output to a file on the hard drive, or more importantly, sending the bytes as a stream to a printer.

The sample code at the end of this article renders one of the report samples that ships with Reporting Services: the Company Sales sample report. Once you have effectively used the Render method to render a report, you can begin to think about how to print that report programmatically.

Printing the Report Programmatically

There are a few key challenges here in order to be able to print a report successfully using C# and Reporting Services. One challenge is figuring out how to print in the .NET Framework using C#. In the sample code included with this article, I use the classes of the System.Drawing.Printing namespace in order to send EMF output to a printer. The source code can show you how it all comes together. From a Reporting Services standpoint, the key challenge is determining how many pages there are in the report. The SOAP API for Reporting Services lacks the ability to evaluate a report's number of printed pages through any exposed report properties. So the trick is to determine how many pages there are through some other means. Fortunately, the SOAP API does return an array of stream IDs whenever Render is called. What are these stream IDs you ask? Well, when EMF output is selected, the Render method returns the results of the rendered report as a byte array, but it only sends back the first page. Subsequent pages are associated with the report as streams with accompanying stream IDs. By counting the number of StreamIDs in the resultant string array, you can determine how many pages are in the report. The following code should give you the number of pages:

// The total number of pages of the report is 1 + the streamIDs
int m_numberOfPages = streamIDs.Length + 1;

Once you know how many pages you are dealing with you can call the Render method for each page in the report and send that page to the printer. You can render specific pages using device information. The device information for this is StartPage. In the sample code, the device information for each subsequent call to render (that is each call after the original one) looks like "<DeviceInfo><OutputFormat>EMF</OutputFormat><StartPage>current page </StartPage></DeviceInfo>". After each page is rendered, you load the page (set of rendered bytes) into an array of pages, a multi-dimensional array of bytes, and process that array. For each byte array, you generate a memory stream and load an image of that memory stream into the print document. From there you can print each page. Printing using this technique is not for beginners, so you may want to study the source code and consult your .NET Framework Developers Guide for more information.

One more thing to remember is that you will need to replace the printer name placeholder in the source code with a valid printer name for your system:

static void Main(string[] args)
{
   PrintExample pe = new PrintExample();
   pe.PrintReport(@"PrinterName");
}

Okay so get your hands dirty with some code, that is really the whole point of this article anyway! Seriously, I hope this provided you with some insight into printing reports programmatically using C# and Reporting Services. The Web service and its methods expose a rich set of operations that enable you to draw on the complete functionality of the report server and allow you to create custom tools for any part of the report life cycle, from management to execution. I highly encourage you to not only get involved in programming with XML Web services, but to experiment with tools that harness the power of the Reporting Services Web service and start integrating reporting into your current development projects.

Source Code (app.cs)

/*=====================================================================

  File:      app.cs
  
  Summary:  A simple console application that demonstrates one way to
            print Reporting Services reports to a printer.

------------------------------------------------------------------------

 This code is provided "AS IS" with no warranties. Do not use this code
 in your production environment. This sample is not endorsed by Microsoft
 and does not represent production quality code.

======================================================================== */
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Web.Services.Protocols;
using PrintReport.reportserver;
using System.Runtime.InteropServices; // For Marshal.Copy
namespace PrintReport
{
    /// <summary>
    /// A simple console application that demonstrates one way to
    /// print Reporting Services reports to a printer.
    /// </summary>
    class app
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
         static void Main(string[] args)
         {
            PrintExample pe = new PrintExample();
            // The name of the printer should be added here;
            // this could be a local or network printer.
            pe.PrintReport(@"PrinterName");
         }
    }
   class PrintExample
   {
      ReportingService rs;
      private byte[][] m_renderedReport;
      private Graphics.EnumerateMetafileProc m_delegate = null;
      private MemoryStream m_currentPageStream;
      private Metafile m_metafile = null;
      int m_numberOfPages;
      private int m_currentPrintingPage;
      private int m_lastPrintingPage;
                  
      public PrintExample()
      {
         // Create proxy object and authenticate
         Console.WriteLine("Authenticating to the Web service...");
         rs = new ReportingService();
         rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
      }
      public byte[][] RenderReport(string reportPath)
      {
         // Private variables for rendering
         string deviceInfo = null;
         string format = "IMAGE";
         Byte[] firstPage = null;
         string encoding;
         string mimeType;
         Warning[] warnings = null;
         ParameterValue[] reportHistoryParameters = null;
         string[] streamIDs = null;
         Byte[][] pages = null;
                                             
         // Build device info based on the start page
         deviceInfo = 
            String.Format(@"<DeviceInfo><OutputFormat>{0}</OutputFormat></DeviceInfo>", "emf");
            
         //Exectute the report and get page count.
         try
         {
            // Renders the first page of the report and returns streamIDs for 
            // subsequent pages
            firstPage = rs.Render(
               reportPath, 
               format, 
               null, 
               deviceInfo,
               null,
               null,
               null,
               out encoding,
               out mimeType,
               out reportHistoryParameters, 
               out warnings, 
               out streamIDs);
            // The total number of pages of the report is 1 + the streamIDs         
            m_numberOfPages = streamIDs.Length + 1;
            pages = new Byte[m_numberOfPages][];
            
            // The first page was already rendered
            pages[0] = firstPage;
            
            for (int pageIndex = 1; pageIndex < m_numberOfPages; pageIndex++)
            {
               // Build device info based on start page
               deviceInfo = 
                  String.Format(@"<DeviceInfo><OutputFormat>{0}</OutputFormat><StartPage>{1}</StartPage></DeviceInfo>", 
                    "emf", pageIndex+1);
               pages[pageIndex] = rs.Render(
                  reportPath, 
                  format, 
                  null, 
                  deviceInfo,
                  null,
                  null,
                  null,
                  out encoding,
                  out mimeType,
                  out reportHistoryParameters, 
                  out warnings, 
                  out streamIDs);
            }
         }
         catch (SoapException ex)
         {
            Console.WriteLine(ex.Detail.InnerXml);
         }
         catch (Exception ex)
         {
            Console.WriteLine(ex.Message); 
         }
         finally
         {
            Console.WriteLine("Number of pages: {0}", pages.Length);
         }
         return pages;
      }
      
      public bool PrintReport(string printerName)
      {
         this.RenderedReport = this.RenderReport("/SampleReports/Company Sales");
         try
         {  
            // Wait for the report to completely render.
            if(m_numberOfPages < 1)
               return false;
            PrinterSettings printerSettings = new PrinterSettings();
            printerSettings.MaximumPage = m_numberOfPages;
            printerSettings.MinimumPage = 1;
            printerSettings.PrintRange = PrintRange.SomePages;
            printerSettings.FromPage = 1;
            printerSettings.ToPage   = m_numberOfPages;
            printerSettings.PrinterName = printerName;
            PrintDocument pd = new PrintDocument();
            m_currentPrintingPage = 1;
            m_lastPrintingPage = m_numberOfPages;
            pd.PrinterSettings = printerSettings;
            // Print report
            Console.WriteLine("Printing report...");
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            pd.Print();
         }
         catch(Exception ex) 
         {
            Console.WriteLine(ex.Message);
         }
         finally
         {
            // Clean up goes here.
         }
         return true;
      }
      private void pd_PrintPage(object sender, PrintPageEventArgs ev)
      {
         ev.HasMorePages = false;
         if (m_currentPrintingPage <= m_lastPrintingPage && MoveToPage(m_currentPrintingPage))
         {
            // Draw the page
            ReportDrawPage(ev.Graphics);
            // If the next page is less than or equal to the last page, 
            // print another page.
            if (++m_currentPrintingPage <= m_lastPrintingPage)
               ev.HasMorePages = true;
         }
      }
      
      // Method to draw the current emf memory stream 
      private void ReportDrawPage(Graphics g)
      {
         if(null == m_currentPageStream || 0 == m_currentPageStream.Length || null ==m_metafile)
            return;
         lock(this)
         {
            // Set the metafile delegate.
            int width = m_metafile.Width;
            int height= m_metafile.Height;
            m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback);
            // Draw in the rectangle
            Point destPoint = new Point(0, 0);
            g.EnumerateMetafile(m_metafile,destPoint , m_delegate);
            // Clean up
            m_delegate = null;
         }
      }
      private bool MoveToPage(Int32 page)
      {
         // Check to make sure that the current page exists in
         // the array list
         if(null == this.RenderedReport[m_currentPrintingPage-1])
            return false;
         // Set current page stream equal to the rendered page
         m_currentPageStream = new MemoryStream(this.RenderedReport[m_currentPrintingPage-1]);
         // Set its postion to start.
         m_currentPageStream.Position = 0;
         // Initialize the metafile
         if(null != m_metafile)
         {
            m_metafile.Dispose();
            m_metafile = null;
         }
         // Load the metafile image for this page
         m_metafile =  new Metafile((Stream)m_currentPageStream);
         return true;
      }
      private bool MetafileCallback(
         EmfPlusRecordType recordType,
         int flags,
         int dataSize,
         IntPtr data,
         PlayRecordCallback callbackData)
      {  
         byte[] dataArray = null;
         // Dance around unmanaged code.
         if (data != IntPtr.Zero)
         {
            // Copy the unmanaged record to a managed byte buffer 
            // that can be used by PlayRecord.
            dataArray = new byte[dataSize];
            Marshal.Copy(data, dataArray, 0, dataSize);
         }
         // play the record.      
         m_metafile.PlayRecord(recordType, flags, dataSize, dataArray);
            
         return true;
      }
      public byte[][] RenderedReport
      {
         get 
         {
            return m_renderedReport;
         }
         set
         {
            m_renderedReport = value;
         }
      }
   }
}
Published Wednesday, February 11, 2004 12:23 PM by bryanke
Filed under:

Comments

# Printing Reports in Reporting Services

Wednesday, February 11, 2004 5:15 PM by Bryan's WebLog

# Items of interest

Thursday, February 12, 2004 1:28 PM by Random Thoughts of Jorriss

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Thursday, February 12, 2004 11:51 AM by chadb
good stuff! keep up the good work...

# Printing Reports in Reporting Services

Friday, February 13, 2004 7:42 PM by Bryan's WebLog

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Tuesday, March 23, 2004 9:29 PM by Sameer
Hi,
Thanks for this article...

But it is not working, When I call, "pd.Print".
I am getting following exception.. "A null context handle was passed from the client to the host during a remote procedure call"

The only change is I am printing from Web application and not through console application...

Can you pls help ?

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Thursday, April 01, 2004 2:56 PM by Keith Walton
Thinks for the article, it was very helpful.

In order to get this code to print my report page the correct size, I had to make the following minor change:

<code>
// Draw in the rectangle
Point[] points = new Point[3];
Point destPoint = new Point(0, 0);
Point destPoint1 = new Point(width, 0);
Point destPoint2 = new Point(0, height);

points[0]=destPoint;
points[1]=destPoint1;
points[2]=destPoint2;

g.EnumerateMetafile(m_metafile,points, m_delegate);
</code>

I think you were heading in this direction, since you had already declared the width and height variables.

Thanks,
Keith Walton
NHXS

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, April 02, 2004 7:05 AM by LesioS
Works fine.... Almost :(
Your code is working, but when I'd like to print report as landscape I've some problems. I've informed deviceinfo that paper size is 11.25in*8.25in (A4 in landscape) and Render generates report in landscape (in fact it renders it to 6 pages when 2 would be enough). Printer prints it on portait pages inspite of setting printerSettings.DefaultPageSettings.Landscape = true;

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, April 02, 2004 8:34 AM by Bryan Keller
Okay, so this is my multiple help post. Here we go:

Sameer,

Did you set impersonate=true in your ASP.NET client app Web.config? Where does your client app live?

Keith,

Thanks for the heads up. I will do some additional testing and post your fix if it all checks out. Thanks again.

Lesio,
Did you see Keith's post? Did you set up your printer settings as well as the render size and width. If you are familiar with the actual devmode structure for the Win32 API that is the underlying API for PrintDocument, you will notice that you should not set width and height, rather simply orientation. Does your orientation match the render width/height and does your report size that you defined in the RDL also match A4?

Okay, let me know.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, April 02, 2004 8:59 AM by Jen Rubin
Do you have a similar example for VB.NET, or can you direct me to a source that does?
Thank you.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Monday, April 05, 2004 1:45 AM by LesioS
Yes, I saw it... I've to add explicite size of page in deviceInfo definition, cause without it I was receiving page size as portarait in ReportDrawPage function & Keith's ammandement with Points in fact didn't work. When I added all this things & set printer default orientation into landscape then report is printing properly.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Monday, April 05, 2004 11:46 AM by Aniruddha
I tested your code its working fine with Format type "IMAGE". Any idea how to make this run for other formats like CSV,XML,PDF?
Any help in this regard is greatly appreciated.
Pl. contact me at c-ashinde@state.pa.us

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Thursday, April 08, 2004 2:16 PM by Keith Walton
I had to make a few more modifications to get this code to print my report the correct size. I am creating reports that populate preprinted forms, so the position of fields is very important.

After some trial and error, I discovered that both the report designer print functionality and this code were by default printing my report relative to the printable area of the page. For example, my printer cannot print beyond .25 inches on the right and left edges. If I place a text box .25 inches from the left edge of my report (which has margins is set to zero) the text box will display approximately .5 inches from the edge. Also, the whole report is being scaled down to print within the printable area. If I place several lines on a report that are exactly one inch apart, when printed they will be less than one inch apart.

To correct this, I first had to instruct the printer to print relative to the edge of the paper instead of the edge of the printable area.

(vb.net code)
pd.OriginAtMargins = True
pd.DefaultPageSettings.Margins = New Printing.Margins(0, 0, 0, 0)

Then, to correct for the report being scaled down I had to implement this kluge in ReportDrawPage:

Dim destPoint1 As Point = New Point(0, 0)
Dim destPoint2 As Point = New Point(859, 0)
Dim destPoint3 As Point = New Point(0, 1118)

These values indicate 1/100 of an inch, so I have to render the image to the page as though it is larger than it really is.

These changes print my portrait reports very precisely, but there has to be a better way to do this.

Any ideas?

Thanks

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Thursday, April 15, 2004 1:33 AM by Zam
Hi,

I'm fairly new to these stuff... How do I set the report parameters in this example?

Thanks

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, April 23, 2004 9:39 AM by Amy

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Monday, April 26, 2004 8:07 AM by GB
it works fine!
How to get orientation from rdl definition?

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Monday, April 26, 2004 8:25 AM by Bryan Keller
You will have to read the PageHeight and PageWidth elements of the report defintion to determine orientation.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Wednesday, April 28, 2004 3:41 AM by GB
Fine.
Here is the source I'm using (not too clean, anyway it works!)

public bool isLandscape(string reportName)
{
string rdl;
string sheight = "", swidth = "";
byte[] reportDefinition = null;
double Height;
double Width;
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

reportDefinition = rs.GetReportDefinition(reportName);
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
rdl = enc.GetString(reportDefinition);
doc.LoadXml(rdl);
XmlNodeList elemList = doc.GetElementsByTagName ("PageHeight");

int i;
for (i = 0 ; i<elemList[0].InnerXml.Length; i++)
{
if ((elemList[0].InnerXml[i] >= '0' && elemList[0].InnerXml[i] <= '9')|| elemList[0].InnerXml[i] <= '.' )
{
//= elemList[0].InnerXml[i];
}
else { break; }
}
sheight= elemList[0].InnerXml.Substring(0,i);
Height = Convert.ToDouble (sheight);

elemList = doc.GetElementsByTagName ("PageWidth");
for (i = 0 ; i<elemList[0].InnerXml.Length;i++)
{
if ((elemList[0].InnerXml[i] >= '0' && elemList[0].InnerXml[i] <= '9')|| elemList[0].InnerXml[i] <= '.' )
{
} else { break; }
}
swidth= elemList[0].InnerXml.Substring(0,i);
swidth= swidth.Replace (".",",");
Width = Convert.ToDouble (swidth);

if (Height < Width)
{
return true;
}
else
{
return false;
}
}

# SQL Server Reporting Services Printing? What's the go!

Monday, May 24, 2004 9:25 PM by Justin King's Rant::Blog

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Tuesday, June 01, 2004 11:28 AM by RBisch
As asked before, how can you stream a PDF type to the printer ?

Thanks.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Thursday, June 10, 2004 3:26 AM by Alexandru Mihai
It works great. I'm using it from ASP.NET. One problem: I would like not to go to a default printer that I already know, but at the press of a print button to spawn the Internet Explorer print dialog...
Is this possible?
Thanks

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, June 11, 2004 8:51 AM by RBisch
Note: Anything relating to size is referencing the size of an .emf (image type) file.

The ability to do this is great! However, I was concerned about the size of the .emf in the sample report used in the code above, a whopping 1,621 KB. This is significant if you want to stream across a network, considering the report was only 1 page and has potential to get very large. The sample report used background images which is why I think it was so big. I created a simple 1 page report and it was 31 KB (.emf) which relieved me.

However, I am concerned with the variations in size between these 2 reports, both being 1 page long, but drastically different in size.
Do I need to keep my reports simple, or just avoid using a repeating background image ? I have no in-depth knowledge about .emf and what determines thier size, but I need to use them as it is an excellent windows format for printing.

Best Regards.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Monday, June 14, 2004 3:22 AM by Vik
I'm printing using a method similar to the above using an EMF image, I display the report in a printpreview control and it looks fine however when printing to the printer the report is cropped to about 75%. All works fine if i use reporting services installed locally instead of on the win2k server.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, June 18, 2004 8:50 AM by A better Option, Print From a Pdf File
We have been working with the posted example, and we think is much easier render to a Guid named File and Print it in background using the adobe ActiveX.
I put here the two necesary forms, it isn´t finished however i think is a really easier way.

#Region "Summary"
''' ============================================================================
''' AUTOR : alias
''' FECHA DE CREACION : 5 Nov 2004
''' PROPOSITO :
''' NOTAS :
''' NOMBRE DEL FICHERO : $Workfile: $
''' VSS ARCHIVE : $Archive: $
''' VERSION : $Revision: $
'''
''' (c) 2004 DTI GRUPO FCC
''' ===========================================================================
''' $History: $
'''
'''
''' ============================================================================

#Region "QA Status"
#Region "Review History"
''' ============================================================================
''' CODE STATUS : REVIEWED {NOT REVIEWED | REVIEWED}
'''
''' ============================================================================
''' REVIEW HISTORY
''' ---------------------------------------------------------------------------
''' DATE | NAME | COMMENTS
''' ---------------------------------------------------------------------------
''' 4 Aug 2002 jsmith Conformed to coding standards
'''
''' ============================================================================
#End Region

#Region "Known Issues and Limitations"
''' ============================================================================
''' DATE : 4 Aug 2002
''' NAME : bsmith
''' METHOD NAME : Foo()
''' DESCRIPTION : Looping is quite inefficient. Should be revisited and
''' improved.
'''
'''----------------------------------------------------------------------------
''' DATE : 5 Aug 2002
''' NAME : patcoleman
''' METHOD NAME : Goo()
''' DESCRIPTION : Refer to DefectList.Doc under section "Goo() Defects".
'''
''' ============================================================================
#End Region
#End Region

#End Region

#Region ".NET Base Class Namespace Imports"

Imports System.IO
Imports ResportingServiceViewer.ReportServer

#End Region

Public Class ReportManager
Inherits System.Windows.Forms.Form

#Region " Código generado por el Diseñador de Windows Forms "

Public Sub New()
MyBase.New()

'El Diseñador de Windows Forms requiere esta llamada.
InitializeComponent()

'Agregar cualquier inicialización después de la llamada a InitializeComponent()

End Sub

'Form reemplaza a Dispose para limpiar la lista de componentes.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Requerido por el Diseñador de Windows Forms
Private components As System.ComponentModel.IContainer

'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
'Puede modificarse utilizando el Diseñador de Windows Forms.
'No lo modifique con el editor de código.
Friend WithEvents cmbFormato As System.Windows.Forms.ComboBox
Friend WithEvents sfdArchivoGuardado As System.Windows.Forms.SaveFileDialog
Friend WithEvents cmbReports As System.Windows.Forms.ComboBox
Friend WithEvents btnExportar As System.Windows.Forms.Button
Friend WithEvents btnImprimir As System.Windows.Forms.Button
Friend WithEvents btnVerWeb As System.Windows.Forms.Button
Friend WithEvents btnVerPdf As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.cmbFormato = New System.Windows.Forms.ComboBox
Me.btnExportar = New System.Windows.Forms.Button
Me.btnImprimir = New System.Windows.Forms.Button
Me.btnVerWeb = New System.Windows.Forms.Button
Me.sfdArchivoGuardado = New System.Windows.Forms.SaveFileDialog
Me.cmbReports = New System.Windows.Forms.ComboBox
Me.btnVerPdf = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'cmbFormato
'
Me.cmbFormato.Items.AddRange(New Object() {"PDF", "EXCEL", "IMAGE", "MHTML"})
Me.cmbFormato.Location = New System.Drawing.Point(8, 8)
Me.cmbFormato.Name = "cmbFormato"
Me.cmbFormato.Size = New System.Drawing.Size(64, 21)
Me.cmbFormato.TabIndex = 25
Me.cmbFormato.Text = "PDF"
'
'btnExportar
'
Me.btnExportar.Location = New System.Drawing.Point(8, 32)
Me.btnExportar.Name = "btnExportar"
Me.btnExportar.Size = New System.Drawing.Size(72, 23)
Me.btnExportar.TabIndex = 26
Me.btnExportar.Text = "Exportar"
'
'btnImprimir
'
Me.btnImprimir.Location = New System.Drawing.Point(8, 64)
Me.btnImprimir.Name = "btnImprimir"
Me.btnImprimir.Size = New System.Drawing.Size(72, 23)
Me.btnImprimir.TabIndex = 27
Me.btnImprimir.Text = "Imprimir"
'
'btnVerWeb
'
Me.btnVerWeb.Location = New System.Drawing.Point(88, 32)
Me.btnVerWeb.Name = "btnVerWeb"
Me.btnVerWeb.Size = New System.Drawing.Size(144, 23)
Me.btnVerWeb.TabIndex = 22
Me.btnVerWeb.Text = "Ver Parametrizable"
'
'cmbReports
'
Me.cmbReports.Items.AddRange(New Object() {"rptBriProducts", "rptBriRegions", "rptBriEmpleadosParametros", "rptBriTerritoriosParametros"})
Me.cmbReports.Location = New System.Drawing.Point(88, 8)
Me.cmbReports.Name = "cmbReports"
Me.cmbReports.Size = New System.Drawing.Size(144, 21)
Me.cmbReports.TabIndex = 28
Me.cmbReports.Text = "Selecione Un Report"
'
'btnVerPdf
'
Me.btnVerPdf.Location = New System.Drawing.Point(88, 64)
Me.btnVerPdf.Name = "btnVerPdf"
Me.btnVerPdf.Size = New System.Drawing.Size(144, 23)
Me.btnVerPdf.TabIndex = 29
Me.btnVerPdf.Text = "Ver Como Pdf"
'
'ReportManager
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(248, 102)
Me.Controls.Add(Me.btnVerPdf)
Me.Controls.Add(Me.cmbReports)
Me.Controls.Add(Me.btnImprimir)
Me.Controls.Add(Me.btnExportar)
Me.Controls.Add(Me.cmbFormato)
Me.Controls.Add(Me.btnVerWeb)
Me.Name = "ReportManager"
Me.Text = "Report Manager"
Me.ResumeLayout(False)

End Sub

#End Region

#Region "Variables Miembro, Constantes y Enumeraciones de la Clase"

#Region "Constantes Privadas"
Private Const _PDF As String = "PDF file (*.pdf)|*.pdf"
Private Const _IMAGE As String = "Tiff file (*.tif)|*.tif"
Private Const _MHTML As String = "Web Page, single file (*.mhtml)|*.mhtml"
Private Const _EXCEL As String = "Microsoft Excel Workbook (*.xls)|*.xls"
#End Region

#Region "Variables Privadas"

Private rs As ReportServer.ReportingService

#End Region

#End Region

#Region "Propiedades Internal/Protected/Public"

Private _NombreReport As String
Property NombreReport() As String
Get
Return _NombreReport
End Get
Set(ByVal Value As String)
_NombreReport = Value
End Set
End Property

#End Region

#Region "Metodos Internal/Protected/Private/Public"

#Region "Metodos Privados"

Private Sub ExportaReport(ByVal NombreArchivo As String)

rs = New ReportingService
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.Url = "http://localhost/ReportServer/ReportService.asmx"

Dim historyID As String = Nothing
Dim credentials As DataSourceCredentials() = Nothing

Dim forRendering As Boolean = False

Dim parametros As ReportParameter() = Nothing
Dim reportHistoryParameters As ParameterValue() = Nothing

Try
parametros = rs.GetReportParameters(PathFichero(), historyID, forRendering, reportHistoryParameters, credentials)

Dim ParametersValue(parametros.GetLength(0) - 1) As ParameterValue
Dim i As Integer = 0
Dim parameter As ReportParameter

For Each parameter In parametros
Dim pp As PideParametros
pp = New PideParametros(parameter)
pp.ShowDialog(Me)
ParametersValue(i) = New ParameterValue
ParametersValue(i).Name = pp.ParaValue.Name
ParametersValue(i).Value = pp.ParaValue.Value
i = i + 1
Next parameter

Dim deviceInfo As String = Nothing
Dim format As String = cmbFormato.Text
Dim showHide As String = Nothing

Dim results() As [Byte]
Dim encoding As String
Dim mimeType As String
Dim warnings As Warning() = Nothing
Dim streamIDs As String() = Nothing


Try
results = rs.Render(PathFichero, format, historyID, deviceInfo, ParametersValue, credentials, showHide, encoding, mimeType, ParametersValue, warnings, streamIDs)

Dim stream As FileStream = File.OpenWrite(NombreArchivo)
stream.Write(results, 0, results.Length)
stream.Close()

Catch exception As Exception
MsgBox("Error: " & exception.ToString())
End Try

Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try

End Sub

Private Function GetFiltro() As String
Select Case cmbFormato.Text
Case "MHTML"
Return _MHTML
Case "PDF"
Return _PDF
Case "IMAGE"
Return _IMAGE
Case "EXCEL"
Return _EXCEL
Case Else
Return ""
End Select
End Function

Private Function PathFichero() As String
Return "/BriReports/" & _NombreReport
End Function

#End Region

#Region "Metodos Públicos"


#End Region

#Region "Metodos que Escuchan Eventos"

Private Sub cmbReports_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbReports.SelectedIndexChanged
Me._NombreReport = Me.cmbReports.SelectedItem
End Sub

Private Sub btnVer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVerWeb.Click
Dim rv As ReportViewerWeb

rv = New ReportViewerWeb(_NombreReport)
rv.Show()

End Sub

Private Sub btnExportar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportar.Click

Me.sfdArchivoGuardado = New SaveFileDialog
Me.sfdArchivoGuardado.Filter = Me.GetFiltro()
Me.sfdArchivoGuardado.FileName = _NombreReport

Dim dr As DialogResult = Me.sfdArchivoGuardado.ShowDialog()

If dr = DialogResult.OK Then
ExportaReport(Me.sfdArchivoGuardado.FileName)
End If

End Sub

Private Sub btnPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVerPdf.Click, btnImprimir.Click
Dim NombrePdf As String

ExportaReport("C:\ExportedReport.pdf")
Dim pv As New ReportViewerPdf("C:\ExportedReport.pdf")

Select Case CType(sender, Button).Name
Case "btnVerPdf"
pv.Show()
Case "btnImprimir"
pv.Imprimir()
End Select

End Sub

#End Region

#End Region

End Class


#Region "Summary"
''' ============================================================================
''' AUTOR : alias
''' FECHA DE CREACION : 5 Nov 2004
''' PROPOSITO :
''' NOTAS :
''' NOMBRE DEL FICHERO : $Workfile: $
''' VSS ARCHIVE : $Archive: $
''' VERSION : $Revision: $
'''
''' (c) 2004 DTI GRUPO FCC
''' ===========================================================================
''' $History: $
'''
'''
''' ============================================================================

#Region "QA Status"
#Region "Review History"
''' ============================================================================
''' CODE STATUS : REVIEWED {NOT REVIEWED | REVIEWED}
'''
''' ============================================================================
''' REVIEW HISTORY
''' ---------------------------------------------------------------------------
''' DATE | NAME | COMMENTS
''' ---------------------------------------------------------------------------
''' 4 Aug 2002 jsmith Conformed to coding standards
'''
''' ============================================================================
#End Region

#Region "Known Issues and Limitations"
''' ============================================================================
''' DATE : 4 Aug 2002
''' NAME : bsmith
''' METHOD NAME : Foo()
''' DESCRIPTION : Looping is quite inefficient. Should be revisited and
''' improved.
'''
'''----------------------------------------------------------------------------
''' DATE : 5 Aug 2002
''' NAME : patcoleman
''' METHOD NAME : Goo()
''' DESCRIPTION : Refer to DefectList.Doc under section "Goo() Defects".
'''
''' ============================================================================
#End Region
#End Region

#End Region
#Region ".NET Base Class Namespace Imports"

Imports ResportingServiceViewer.ReportServer

#End Region

Public Class PideParametros
Inherits System.Windows.Forms.Form

#Region " Código generado por el Diseñador de Windows Forms "

'Form reemplaza a Dispose para limpiar la lista de componentes.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Requerido por el Diseñador de Windows Forms
Private components As System.ComponentModel.IContainer

'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
'Puede modificarse utilizando el Diseñador de Windows Forms.
'No lo modifique con el editor de código.
Private WithEvents lbTexto As System.Windows.Forms.Label
Private WithEvents dtpDate As System.Windows.Forms.DateTimePicker
Private WithEvents cmbBoolean As System.Windows.Forms.ComboBox
Private WithEvents txtString As System.Windows.Forms.TextBox
Private WithEvents txtInteger As System.Windows.Forms.TextBox
Private WithEvents txtFloat As System.Windows.Forms.TextBox
Private WithEvents pnInteger As System.Windows.Forms.Panel
Private WithEvents pnFloat As System.Windows.Forms.Panel
Private WithEvents pnFecha As System.Windows.Forms.Panel
Private WithEvents pnString As System.Windows.Forms.Panel
Private WithEvents pnBoolean As System.Windows.Forms.Panel
Private WithEvents btnAceptar As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.lbTexto = New System.Windows.Forms.Label
Me.dtpDate = New System.Windows.Forms.DateTimePicker
Me.cmbBoolean = New System.Windows.Forms.ComboBox
Me.txtString = New System.Windows.Forms.TextBox
Me.txtInteger = New System.Windows.Forms.TextBox
Me.txtFloat = New System.Windows.Forms.TextBox
Me.pnInteger = New System.Windows.Forms.Panel
Me.pnFloat = New System.Windows.Forms.Panel
Me.pnFecha = New System.Windows.Forms.Panel
Me.pnString = New System.Windows.Forms.Panel
Me.pnBoolean = New System.Windows.Forms.Panel
Me.btnAceptar = New System.Windows.Forms.Button
Me.pnInteger.SuspendLayout()
Me.pnFloat.SuspendLayout()
Me.pnFecha.SuspendLayout()
Me.pnString.SuspendLayout()
Me.pnBoolean.SuspendLayout()
Me.SuspendLayout()
'
'lbTexto
'
Me.lbTexto.Location = New System.Drawing.Point(8, 8)
Me.lbTexto.Name = "lbTexto"
Me.lbTexto.Size = New System.Drawing.Size(216, 32)
Me.lbTexto.TabIndex = 0
'
'dtpDate
'
Me.dtpDate.Format = System.Windows.Forms.DateTimePickerFormat.Short
Me.dtpDate.Location = New System.Drawing.Point(8, 8)
Me.dtpDate.Name = "dtpDate"
Me.dtpDate.Size = New System.Drawing.Size(104, 20)
Me.dtpDate.TabIndex = 1
'
'cmbBoolean
'
Me.cmbBoolean.Items.AddRange(New Object() {"Cierto", "Falso"})
Me.cmbBoolean.Location = New System.Drawing.Point(8, 8)
Me.cmbBoolean.Name = "cmbBoolean"
Me.cmbBoolean.Size = New System.Drawing.Size(104, 21)
Me.cmbBoolean.TabIndex = 2
Me.cmbBoolean.Text = "Cierto"
'
'txtString
'
Me.txtString.Location = New System.Drawing.Point(8, 8)
Me.txtString.Name = "txtString"
Me.txtString.TabIndex = 3
Me.txtString.Text = ""
'
'txtInteger
'
Me.txtInteger.Location = New System.Drawing.Point(8, 8)
Me.txtInteger.Name = "txtInteger"
Me.txtInteger.TabIndex = 4
Me.txtInteger.Text = "0"
Me.txtInteger.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
'
'txtFloat
'
Me.txtFloat.Location = New System.Drawing.Point(8, 8)
Me.txtFloat.Name = "txtFloat"
Me.txtFloat.TabIndex = 5
Me.txtFloat.Text = "0,0"
Me.txtFloat.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
'
'pnInteger
'
Me.pnInteger.Controls.Add(Me.txtInteger)
Me.pnInteger.Location = New System.Drawing.Point(0, 40)
Me.pnInteger.Name = "pnInteger"
Me.pnInteger.Size = New System.Drawing.Size(120, 40)
Me.pnInteger.TabIndex = 6
'
'pnFloat
'
Me.pnFloat.Controls.Add(Me.txtFloat)
Me.pnFloat.Location = New System.Drawing.Point(0, 40)
Me.pnFloat.Name = "pnFloat"
Me.pnFloat.Size = New System.Drawing.Size(120, 40)
Me.pnFloat.TabIndex = 7
'
'pnFecha
'
Me.pnFecha.Controls.Add(Me.dtpDate)
Me.pnFecha.Location = New System.Drawing.Point(0, 40)
Me.pnFecha.Name = "pnFecha"
Me.pnFecha.Size = New System.Drawing.Size(120, 40)
Me.pnFecha.TabIndex = 8
'
'pnString
'
Me.pnString.Controls.Add(Me.txtString)
Me.pnString.Location = New System.Drawing.Point(0, 40)
Me.pnString.Name = "pnString"
Me.pnString.Size = New System.Drawing.Size(120, 40)
Me.pnString.TabIndex = 9
'
'pnBoolean
'
Me.pnBoolean.Controls.Add(Me.cmbBoolean)
Me.pnBoolean.Location = New System.Drawing.Point(0, 40)
Me.pnBoolean.Name = "pnBoolean"
Me.pnBoolean.Size = New System.Drawing.Size(120, 40)
Me.pnBoolean.TabIndex = 10
'
'btnAceptar
'
Me.btnAceptar.Location = New System.Drawing.Point(136, 48)
Me.btnAceptar.Name = "btnAceptar"
Me.btnAceptar.Size = New System.Drawing.Size(75, 24)
Me.btnAceptar.TabIndex = 11
Me.btnAceptar.Text = "Aceptar"
'
'PideParametros
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(224, 102)
Me.Controls.Add(Me.btnAceptar)
Me.Controls.Add(Me.pnBoolean)
Me.Controls.Add(Me.pnString)
Me.Controls.Add(Me.pnInteger)
Me.Controls.Add(Me.lbTexto)
Me.Controls.Add(Me.pnFloat)
Me.Controls.Add(Me.pnFecha)
Me.Name = "PideParametros"
Me.Text = "PideParametros"
Me.pnInteger.ResumeLayout(False)
Me.pnFloat.ResumeLayout(False)
Me.pnFecha.ResumeLayout(False)
Me.pnString.ResumeLayout(False)
Me.pnBoolean.ResumeLayout(False)
Me.ResumeLayout(False)

End Sub

#End Region

#Region "Variables Miembro, Constantes y Enumeraciones de la Clase"

Private NOPromptMessage As String = "Introducir valor para "

Private Parametro As ReportServer.ReportParameter

#End Region

#Region "Constructores/Destructores/Finalizadores"

Public Sub New(ByVal Parameter As ReportServer.ReportParameter)
MyBase.New()
InitializeComponent()

Parametro = Parameter

If Parametro.PromptUser Then
Me.Text = Parametro.Prompt
Me.lbTexto.Text = Parametro.Prompt
Else
Me.Text = NOPromptMessage & Parametro.Name
Me.lbTexto.Text = NOPromptMessage & Parametro.Name
End If
Me.pnString.Visible = False
Me.pnInteger.Visible = False
Me.pnBoolean.Visible = False
Me.pnFecha.Visible = False
Me.pnFloat.Visible = False

Select Case Parametro.Type
Case ParameterTypeEnum.Boolean
Me.pnBoolean.Visible = True
Case ParameterTypeEnum.DateTime
Me.pnFecha.Visible = True
Case ParameterTypeEnum.Float
Me.pnFloat.Visible = True
Case ParameterTypeEnum.Integer
Me.pnInteger.Visible = True
Case ParameterTypeEnum.String
Me.pnString.Visible = True
End Select


End Sub
#End Region

#Region "Propiedades Internal/Protected/Public"

Private _ParaValue As ReportServer.ParameterValue
Property ParaValue() As ReportServer.ParameterValue
Get
Return _ParaValue
End Get
Set(ByVal Value As ReportServer.ParameterValue)
_ParaValue = Value
End Set
End Property

#End Region

#Region "Metodos Internal/Protected/Private/Public"

Private Sub btnAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAceptar.Click
_ParaValue = New ParameterValue
_ParaValue.Name = Parametro.Name
Select Case Parametro.Type
Case ParameterTypeEnum.Boolean
_ParaValue.Value = Me.cmbBoolean.Text
Case ParameterTypeEnum.DateTime
_ParaValue.Value = Me.dtpDate.Value.ToString()
Case ParameterTypeEnum.Float
_ParaValue.Value = Me.txtFloat.Text
Case ParameterTypeEnum.Integer
_ParaValue.Value = Me.txtInteger.Text
Case ParameterTypeEnum.String
_ParaValue.Value = Me.txtString.Text
End Select
Me.Close()
End Sub

#End Region

End Class


Public Class ReportViewerPdf
Inherits System.Windows.Forms.Form

#Region " Código generado por el Diseñador de Windows Forms "

'Form reemplaza a Dispose para limpiar la lista de componentes.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Requerido por el Diseñador de Windows Forms
Private components As System.ComponentModel.IContainer

'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
'Puede modificarse utilizando el Diseñador de Windows Forms.
'No lo modifique con el editor de código.
Friend WithEvents pdf As AxPdfLib.AxPdf
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(ReportViewerPdf))
Me.pdf = New AxPdfLib.AxPdf
CType(Me.pdf, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'pdf
'
Me.pdf.Dock = System.Windows.Forms.DockStyle.Fill
Me.pdf.Enabled = True
Me.pdf.Location = New System.Drawing.Point(0, 0)
Me.pdf.Name = "pdf"
Me.pdf.OcxState = CType(resources.GetObject("pdf.OcxState"), System.Windows.Forms.AxHost.State)
Me.pdf.Size = New System.Drawing.Size(448, 446)
Me.pdf.TabIndex = 0
'
'ReportViewerPdf
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(448, 446)
Me.Controls.Add(Me.pdf)
Me.Name = "ReportViewerPdf"
Me.Text = "BRI - Visualizador de Informes"
CType(Me.pdf, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

End Sub

#End Region

Private _ReportSrc As String
Public Sub New(ByVal ReportSrc As String)
MyBase.New()
InitializeComponent()

_ReportSrc = ReportSrc
pdf.src = _ReportSrc
End Sub

Public Sub Imprimir()
pdf.printAllFit(True)
End Sub

End Class



Public Class ReportViewerWeb
Inherits System.Windows.Forms.Form

#Region " Código generado por el Diseñador de Windows Forms "

'Form reemplaza a Dispose para limpiar la lista de componentes.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Requerido por el Diseñador de Windows Forms
Private components As System.ComponentModel.IContainer

'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
'Puede modificarse utilizando el Diseñador de Windows Forms.
'No lo modifique con el editor de código.
Friend WithEvents wbReport As AxSHDocVw.AxWebBrowser
Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(ReportViewerWeb))
Me.wbReport = New AxSHDocVw.AxWebBrowser
Me.MainMenu1 = New System.Windows.Forms.MainMenu
Me.MenuItem1 = New System.Windows.Forms.MenuItem
Me.MenuItem2 = New System.Windows.Forms.MenuItem
Me.MenuItem3 = New System.Windows.Forms.MenuItem
CType(Me.wbReport, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'wbReport
'
Me.wbReport.Dock = System.Windows.Forms.DockStyle.Fill
Me.wbReport.Enabled = True
Me.wbReport.Location = New System.Drawing.Point(0, 0)
Me.wbReport.OcxState = CType(resources.GetObject("wbReport.OcxState"), System.Windows.Forms.AxHost.State)
Me.wbReport.Size = New System.Drawing.Size(464, 441)
Me.wbReport.TabIndex = 0
'
'MainMenu1
'
Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1})
'
'MenuItem1
'
Me.MenuItem1.Index = 0
Me.MenuItem1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem2, Me.MenuItem3})
Me.MenuItem1.Text = "Archivo"
'
'MenuItem2
'
Me.MenuItem2.Index = 0
Me.MenuItem2.Text = "Imprimir"
'
'MenuItem3
'
Me.MenuItem3.Index = 1
Me.MenuItem3.Text = "Salir"
'
'ReportViewerWeb
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(464, 441)
Me.Controls.Add(Me.wbReport)
Me.Menu = Me.MainMenu1
Me.Name = "ReportViewerWeb"
Me.Text = "BRI - Visualizador de Informes"
CType(Me.wbReport, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

End Sub

#End Region

Private _NombreReport As String
Private Url As String

Public Sub New(ByVal NombreReport As String)
MyBase.New()
InitializeComponent()

Me._NombreReport = NombreReport
End Sub

Private Sub NavegaReport()

Url = GetHost() & GetProyectName() & _NombreReport & GetCommandRender()

Dim Missing As System.Reflection.Missing = System.Reflection.Missing.Value
Me.wbReport.Navigate(Url, Missing, Missing, Missing, Missing)

End Sub

Private Function GetHost() As String
Return "http://localhost/ReportServer?"
End Function

Private Function GetProyectName() As String
Return "/BriReports/"
End Function

Private Function GetCommandRender() As String
Return "&rs:Command=Render"
End Function

Private Sub ReportViewer_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
NavegaReport()
End Sub

End Class


Cheers And Beers
RicardoCasquete@hotmail.com

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, June 18, 2004 8:57 AM by Bryan Keller
Great example and thanks for posting this code! Cheers and beers to you my friend.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Tuesday, June 22, 2004 7:59 AM by AK
Getting Error "Access is Denied" when using with ASP.NET (C#)

StackTrace "at System.Windows.Forms.PrintControllerWithStatusDialog.OnStartPrint(PrintDocument document, PrintEventArgs e)\r\n at System.Drawing.Printing.PrintController.Print(PrintDocument document)\r\n at System.Drawing.Printing.PrintDocument.Print()\r\n at ABC.XYZ.Reports.PrintReport.Print(String printerName, String reportPath) in c:\\inetpub\\wwwroot\\ABC\\XYZ\\misreports\\printreport.cs:line 137" string

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Tuesday, June 22, 2004 9:02 AM by AK
For "Access is Denied" error is fixed by
<identity impersonate="true" />

-AK

# my weblog &raquo; Printing in Reporting Services

Tuesday, June 29, 2004 6:40 PM by TrackBack
my weblog &raquo; Printing in Reporting Services

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Wednesday, July 07, 2004 5:21 AM by Jeff
where do you put <identity impersonate = "true"

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Wednesday, July 07, 2004 11:08 AM by Bryan Keller
In the Web.config file of the client application.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Friday, July 16, 2004 12:46 AM by Graham
Hi All,

I have a one pager that just sneaks ove to two pages. The original margins all round are 0.25 in and the original page size in design time is 8.5in x 11.95in (A4). I made the length 11.95in so that it would print to the complete length of the page, cause at 11.00in it stops printing about 5cm before the bottom of the page. This works nicely when I export to PDF then print from there.

Now, we have the need to print directly to the default client printer. This is when I stumbled onto this code. The code works nicely, except that it cuts off the report about 2.5cm from the bottom whereas it should be printing about 1cm from the bottom.

I have tries both Keith's posts but still doing the same thing.

Has anyone got any idea why it is doing this.

Thanks in advance.
Graham

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Wednesday, August 04, 2004 11:48 AM by sharon
Hi! It was very helpful, thanks. However a problem appears when I try to run the code. It gives a rsAccessDenied and says that my permissions are not sufficient and stuff like that. What could it be?

Thanks in advance!
Sharon.

# re: Printing Reports Programmatically Using C# and SQL Server 2000 Reporting Services

Thursday, August 05, 2004 3:13 AM by Ganesh
I am getting an error while calling the pd.print method. the error is as follows:
Tried to access printer 'HP2200' with invalid settings.System.Drawing.Printing.I
nvalidPrinterException: Tried to access printer 'HP2200' with invalid settings.
at System.Drawing.Printing.PrinterSettings.GetHdevmodeInternal()
at System.Drawing.Printing.PrinterSettings.GetHdevmode(PageSettings pageSetti
ngs)
at System.Drawing.Printing.PrintController.OnStartPrint(PrintDocument documen
t, PrintEventArgs e)
at System.Windows.Forms.PrintControllerWithStatusDialog.OnStartPrint(PrintDoc
ument document, PrintEventArgs e)
at System.Drawing.Printing.PrintController.Print(PrintDocument document)
at System.Drawing.Printing.PrintDocument.Print()
at PrintingSample.PrintingEx.PrintReport(String printerName) in d:\reportings
ervices\printingsample\class1.cs:line 139

Can anyone help!!!!
Regards,
Ganesh

# Service Pack 2 brings client-side printing

Saturday, January 01, 2005 3:34 PM by Prologika

# Service Pack 2 brings client-side printing

Saturday, January 01, 2005 3:38 PM by Prologika

# SQL Reporting Preview Window

Wednesday, January 26, 2005 11:05 PM by Jon(e)sie.Net Blog

# Items of interest

Sunday, April 23, 2006 4:38 PM by Jorriss.Net
I love the MSDN blog feed.&amp;nbsp; Frank Prengel writes about a study between .Net and Websphere where...

# Ultracet.

Friday, July 18, 2008 10:41 PM by Ultracet.

Lexapro-ultracet-interactions. Ultracet.

# Voyforums work at home moms.

Friday, July 25, 2008 12:34 PM by Wahm com the online magazine for work at home moms.

Work at home moms. Site build it work at home moms wahm. Wahm com the online magazine for work at home moms. Work at home ideas for moms wahmoms net. Message boards for work at home moms.

# Using mapped printers on Report Server | keyongtech

Sunday, January 18, 2009 12:34 PM by Using mapped printers on Report Server | keyongtech
Anonymous comments are disabled
 
Page view tracker