Showing posts with label Crystal Reports. Show all posts
Showing posts with label Crystal Reports. Show all posts

Friday, November 23, 2018

Custom Printer and Paper Sizes Using C# and Crystal Report

Using Custom Printer and Paper Size With Crystal Report.

Often you may have faced situations where you are required to design a report (mostly bills, receipts, invoices etc) based on half or one 3rd of regular available paper sizes. It is fairly easy to define custom paper sizes based on requirement how ever a few points should be taken into consideration if your application is a client server (web) based application.

First let us see how to define a custom paper size.
Go to Start – settings – Printers to open Windows Printer Folder.
If you have not already installed a printer do it now.
Now go to File Menu and select Server Properties to open Print Server Properties


Now check Create a New Form.
Specify Paper Width and Height usually in Inches.
Provide a Name to your Form which a custom paper size . This will be listed in your print option dialog box.
Now Save the Form clicking on the save button.
Now your custom paper size is ready.
Choosing Printer & Paper Size :-
Before generating Crystal report you should select the printer and paper size programmatically if your application is hosted on a system which has more than one printer installed.
The following is code for the Printer & Paper initialization.










ReportDocument rptDoc = new ReportDocument();
rptDoc.Load(Server.MapPath("yourcrystalreport.rpt"));
CRT.ReportSource = rptDoc;
System.Drawing.Printing.PrintDocument doctoprint3 = new System.Drawing.Printing.PrintDocument();
doctoprint3.PrinterSettings.PrinterName = "yourprintername";
int i3 = 0;
for (i3 = 0; i3 <= doctoprint3.PrinterSettings.PaperSizes.Count - 1; i3++) { int rawKind3; if (doctoprint3.PrinterSettings.PaperSizes[i3].PaperName == "yourcustompapername") { rptDoc.PrintOptions.PaperSize = (CrystalDecisions.Shared.PaperSize)doctoprint3.PrinterSettings.PaperSizes[i3].RawKind; break; }//if }//for



VB.net 
cmd.CommandText = ("SELECT * FROM StockItem")
cmd.Connection = Con
con.Open()
DSRpt.Clear()
DA.SelectCommand = (cmd)
DA.Fill(DSRpt, cmd.CommandText)
DTRpt = DSRpt.Tables(0)
rptDoc = New ReportDocument
Dim rptPath As String = Application.StartupPath & "\CrystalReceipt.rpt"
rptDoc.Load(rptPath)
rptDoc.SetDataSource(DTRpt)
frmRptViewer.Text = "Print Sales Order"
Con.Close()
frmRptViewer.CrystalReportViewer1.ReportSource = rptDoc
Dim doctoprint As New System.Drawing.Printing.PrintDocument()
doctoprint.PrinterSettings.PrinterName = "EPSON LQ-300+ /II ESC/P 2" '"EPSON LQ-300+II ESC/P2" '(ex. "Epson SQ-1170 ESC/P 2")
For i = 0 To doctoprint.PrinterSettings.PaperSizes.Count - 1
   Dim rawKind As Integer
   If doctoprint.PrinterSettings.PaperSizes(i).PaperName = "A6 LR" Then
      rawKind = CInt(doctoprint.PrinterSettings.PaperSizes(i).GetType().GetField("kind", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).GetValue(doctoprint.PrinterSettings.PaperSizes(i)))
      rptDoc.PrintOptions.PaperSize = rawKind
      Exit For
   End If
Next
frmRptViewer.ShowDialog()
frmRptViewer.Dispose()
rptDoc = Nothing

Wednesday, November 21, 2018

Crystal Reports helper class

Sample Image - CrystalHelper.jpg

Introduction

Integrating Crystal Reports in a .NET application can be a real challenge. There are a number of things you need to know to successfully run reports from inside your application. The helper class described in this article offers a number of methods that can be useful when you want to integrate Crystal Reports in your .NET application. Integrating Crystal Reports will be a lot easier and faster when you use this helper class.
The helper class contains methods that will help you to:
  • Assign database connections or DataSet objects to a report
  • Print a report from code in a WinForms application
  • Export a report from code to disk in a WinForms application
  • Export a report to an ASP.NET form.
  • Download the report to an internet client from inside an ASP.NET application.
  • Tweak the way the Crystal Reports viewer presents itself in a Windows Forms application.
  • Assign values to the parameter fields.
The demo solution, which you can download, demonstrates a lot of the features of this class. You will need SQL Server 2000 with the Pubs and NorthWind database to use it.

Background

I started building this helper class a few years back, when I had to integrate Crystal Reports in an Windows GUI application. I had to solve the following problems:
  • Assign DataSet objects to a report.
  • Assign a database connection to a report.
  • Export the report to an Adobe PDF file.
  • Integrate the Crystal Reports viewer in the application.
The helper class was originally designed for use with .NET 1.1 applications. Visual Studio 2003 came with a trimmed down version of Crystal Reports 9, which was called Crystal for .NET. At this moment, Visual Studio 2005 comes with an updated version which is based on Crystal Reports 10.

Common actions handled by the CrystalHelper class

Assign a connection to a report

One of the problems most developers face when integrating Crystal Reports is getting it to work on another system. This problem is caused by the fact that Crystal requires a valid database connection. When you develop a report, this is usually a connection to your development database. But, when you deploy a report, you will need to assign the correct database connection to each table in your report. The following code shows how this can be done:
ConnectionInfo connection = new ConnectionInfo();

connection.DatabaseName = "DatebaseName";
connection.ServerName   = "ServerName";
connection.UserID       = "UserId";
connection.Password     = "Password";

// First we assign the connection to all tables in the main report
//
foreach (CrystalDecisions.CrystalReports.Engine.Table 
         table in _reportDocument.Database.Tables)
{
    // Cache the logon info block
    TableLogOnInfo logOnInfo = table.LogOnInfo;

    // Set the connection
    logOnInfo.ConnectionInfo = connection;

    // Apply the connection to the table!
    table.ApplyLogOnInfo(logOnInfo);
}
If you have one or more subreports, then it gets even more complex. You will need to perform the above action for each of the subreports. To do this, you will need to check all sections in the report, and then assign the connection info again to all tables in each subreport. For example:
foreach (CrystalDecisions.CrystalReports.Engine.Section 
         section in _reportDocument.ReportDefinition.Sections)
{
    // In each section we need to loop through all the reporting objects
    foreach (CrystalDecisions.CrystalReports.Engine.ReportObject 
             reportObject in section.ReportObjects)
    {
        if (reportObject.Kind == ReportObjectKind.SubreportObject)
        {
            SubreportObject subReport = (SubreportObject)reportObject;
            ReportDocument  subDocument = 
                            subReport.OpenSubreport(subReport.SubreportName);

            foreach (CrystalDecisions.CrystalReports.Engine.Table 
                     table in subDocument.Database.Tables)
            {
                // Cache the logon info block
                TableLogOnInfo logOnInfo = table.LogOnInfo;

                // Set the connection
                logOnInfo.ConnectionInfo = connection;

                // Apply the connection to the table!
                table.ApplyLogOnInfo(logOnInfo);
            }
        }
    }
}
The two code sections above are handled by the Open() method in the CrystalHelper class.

Assign a DataSet to a report

A similar problem occurs when you want to assign a DataSet to a report. The DataSet must be assigned not just to the report, but also to all subreports. The code to do this will look like this:
// Now assign the dataset to all tables in the main report
//
_reportDocument.SetDataSource(dsReportData);

// Now loop through all the sections
// and its objects to do the same for the subreports
//
foreach (CrystalDecisions.CrystalReports.Engine.Section section 
         in _reportDocument.ReportDefinition.Sections)
{
    // In each section we need to loop through all the reporting objects
    foreach (CrystalDecisions.CrystalReports.Engine.ReportObject 
             reportObject in section.ReportObjects)
    {
        if (reportObject.Kind == ReportObjectKind.SubreportObject)
        {
            SubreportObject subReport = (SubreportObject)reportObject;
            ReportDocument  subDocument = 
               subReport.OpenSubreport(subReport.SubreportName);

            subDocument.SetDataSource(dsReportData);
        }
    }
}
This code is also part of the Open() method in this CrystalHelper class.

Using the code to integrate a report

Print report

The first code sample shows how you can print a report when the report is an embedded resource and the data is stored in a DataSet:
private void PrintReport(SqlConnection connection)
{
    using (DataSet ds = new TestData())
    {
        SqlHelper.FillDataset(connection,
            CommandType.Text, "SELECT * FROM Customers", ds, new string [] {"Customers"});
    
        using (CrystalHelper helper = new CrystalHelper(new TestReport()))
        {
            helper.DataSource = ds;
            helper.Open();
            helper.Print();
            helper.Close();
        }
    }                                      
}
As you can see, in this example, the code to handle the report is very simple and straightforward. The Open()method will ensure the DataSet is assigned to all sections.
When you use embedded queries in your report, then you will need to assign the database connection instead of assigning a DataSet as in the example above. The code would then look like this:
private void PrintReport()
{ 
    using (LCrystalHelper helper = new LCrystalHelper(new TestReport()))
    {
        helper.DatabaseName = "DatabaseName";
        helper.ServerName   = "ServerName";
        helper.UserId       = "User";
        helper.Password     = "Password";
                    
        helper.Open();
        helper.Print();
        helper.Close();
    }                                      
}
Again, you see that using Crystal Reports with this helper class makes integrating reports very simple. In the example above, I used a fully qualified connection with a valid user ID and password. The version of Crystal Reports that is included with Visual Studio 2005 also supports integrated security. For that purpose, the CrystalHelper class also features a property IntegratedSecurity. This property defaults to false, but setting it to true will allow you to use integrated security, as show in this example:
private void PrintReport()
{ 
    using (LCrystalHelper helper = new LCrystalHelper(new TestReport()))
    {
        helper.DatabaseName = "DatabaseName";
        helper.ServerName   = "ServerName";
        helper.IntegratedSecurity = true;
                    
        helper.Open();
        helper.Print();
        helper.Close();
    }                                      
}
If the report is included in your solution as a content file, rather than an embedded resource, then you can replace this line:
using (CrystalHelper helper = new CrystalHelper(new TestReport()))
with this line:
using (CrystalHelper helper = new CrystalHelper(@"C:\ReportLocation\ReportFile.rpt"))

Export a report

Exporting a report can be done to the following Export formats:
  • Word (*.doc)
  • Excel (*.xls)
  • Rich text (*.rtf)
  • Portable Doc Format (*.pdf)
The helper class features four methods to perform an export. The first two simply export the file to a specified location. These two methods are useful for WinForms applications, or when you need to export files to a server in an ASP.NET environment. The first of these has a file name as an argument. The type of export is determined by checking the extension given to the file:
helper.Export(@"C:\ExportLocation\MyFile.pdf");
The second method also allows you to specify the Export format as an argument:
helper.Export(@"C:\ExportLocation\MyFile.pdf", CrystalExportFormat.PortableDocFormat);
When you use these methods in an ASP.NET application, you will probably want the files to be exported to the client. For this purpose, the helper class implements two methods which require you to pass the HttpResponseobject. The first of these methods will simply write the exported file to the response:
helper.Export(Response, CrystalExportFormat.PortableDocFormat);
This will result in the report being shown inside the client internet browser, provided the application that supports the export format is installed. The second method allows you to specify if the export has to be sent as an attachment, in which case you can specify the file name for the export. The user will be shown a dialog in which he/she can specify a download location.
helper.Export(Response, CrystalExportFormat.PortableDocFormat, 
              true, "AnExportedDocument.pdf");

Showing the report in the Crystal Reports viewer control

The last option to show a report is using the Crystal Reports viewer control. Assuming you have the control on your form (Windows or ASP.NET), you can do the following:
private void PrintReport(SqlConnection connection)
{
    using (DataSet ds = new TestData())
    {
        SqlHelper.FillDataset(connection, 
            CommandType.Text, "SELECT * FROM Customers", 
                              ds, new string [] {"Customers"});
    
        CrystalHelper helper = new CrystalHelper(@"C:\ReportLocation\ReportFile.rpt");
        helper.DataSource = ds;
        helper.Open();
        crystalReportViewer1.ReportSource = _crystalHelper.ReportSource;
    }                                      
}

Setting the values for report parameters

To set a value for a parameter, you would normally need to write about 6 lines of code. And, you will need to know when to do this. Normally, just before assigning the database connection. The helper class also assists you in setting values for the report parameter fields by providing the SetParameter method. The class will keep an internal list of all the parameters you wish to set, and will apply the values at the right time. The following example shows you how you can use this method:
using (CrystalHelper hlp = new CrystalHelper())
{
    _crystalHelper.SetParameter("CategoryId", "Beverages");

    _crystalHelper.ServerName   = "localhost";
    _crystalHelper.DatabaseName = "Pubs";
    _crystalHelper.UserId       = "UserId";
    _crystalHelper.Password     = "Password";

    _crystalHelper.ReportSource = new TestReport();

    _crystalHelper.Open();
    _crystalHelper.Export("C:\\Test.pdf", 
                          CrystalExportFormat.PortableDocFormat);
    _crystalHelper.Close();
}
The demo solution which you can download here also demonstrates this feature.

Tweaking the Crystal Reports viewer control

Change the name of a tab

When the report is shown, the viewer will always show a tab. This is a very useful feature when you have subreports or drill-down features in your report. The only thing is that the name of the tab is always "Main Report" or the name of your subreport. Changing the name of a tab is easily done by making the following call:
CrystalHelper.ReplaceReportName(crystalReportViewer1, 
             "MainReport", "My name for the report");
The first argument is the viewer control. The second is always the current name of the tab. The last argument is the new name for the tab. You need to be aware though, that changing the names of the tabs is a bit tricky. First of all, you are only sure that the first tab (MainReport) is always there. The other tabs are only shown when a user clicks to enter a subreport or drill-down section. You will need to respond to the events thrown by the viewer to make sure the names of the tabs are adjusted when a new tab is made visible.

Hide the tabs

If you want to hide the tabs, then you can simply use this call:
CrystalHelper.ViewerTabs(crystalReportViewer1, false);
This is of course reversible by calling the same method with true as the second argument.

Hide the statusbar

The report viewer also shows a status bar. This can be hidden by using the following call:
CrystalHelper.ViewerStatusBar(crystalReportViewer1, false);
This is of course reversible by calling the same method with true as the second argument.

Valuable resources

A lot of the information I needed to build this helper class was found on the Internet. I found the following resources to be very useful when you need to do something with Crystal Reports:
I strongly recommend anyone who wants to learn more about Crystal Reports to visit these links. I find most of the answers to questions related to Crystal Reports on one of the above locations.

Source : https://www.codeproject.com/Articles/15024/Crystal-Reports-helper-class

Friday, August 10, 2018

How to conditionally set the number of decimal places to display for a number, in Crystal Reports

Symptom

  • How to conditionally change the number of decimals?
       
  • In the Crystal Reports, a number field that returns decimal places is inserted into a report.
    When previewing the report, the decimal places in this number field contain unnecessary zeroes.
    How can you suppress the unnecessary zeroes in these fields and still leave up to two decimal places for fields that require them?
         
    For example:
       
    A number field is placed on a Crystal Report and is not formatted the way you want.
      
    The field displays: 
      
       1.25 
       2.50 
       8.00
      
    But you want the numeber to display like:
        
       1.25
       2.5
       8

Environment

  • SAP Crystal Reports 2008
  • SAP Crystal Reports 2011
  • SAP Crystal Reports 2013
  • SAP Crystal Reports 2016

Resolution

  • To conditionally suppress unnecessary zero values to the right of the decimal for numeric field in Crystal Reports:
        
    1. Right-click the number field and select: 'Format Field'
        
    2. In the 'Format Editor' dialog box, under the 'Number' tab,  click the 'Customize' button.
         
    3. In the 'Decimals' drop-down box, select the maximum number of decimal places to be displayed. 
          
      If you are not sure what the maximum number of decimals will be, click the maximum (1.0000000000).   
          
    4. In the 'Rounding' drop-down box, select the same number of decimal places chosen in the 'Decimal' drop-down box.
            
    5. Click the 'X+2' button to the right of the `Decimals` drop-down box and enter the following formula:
        
         WhilePrintingRecords;
         numberVar counter := 0;
         numberVar numericValue := <INSERT YOUR NUMERIC FIELD HERE>;
         While truncate(numericValue) < numericValue do
         (
             numericValue := numericValue * 10;
             counter := counter + 1
         );
         counter;
          
          
    6. Save this formula. Click 'OK' to close the 'Custom Style' dilaog box, and then click 'OK' to close the 'Format Editor' dialog box.
         
      Now, when you preview the report, unnecessary zeroes to the right of the decimal will not appear. 
          
      For examples:
            
      • 12.30 will display as: 12.3 
      • 12.38 will display as: 12.38 
      • 12.00 will display as: 12
source : https://apps.support.sap.com/sap/support/knowledge/public/en/1212821

Wednesday, May 16, 2018

Crystal Reports Comparison of Crystal and Basic Formula Syntax

Crystal Reports
Comparison of Crystal and Basic Formula Syntax
Overview
Crystal Reports version 8 and higher offers two different syntaxes for writingformulas: the Crystal syntax and the Basic syntax.This paper describes some of the differences between the two syntaxes andprovides general information on the control structures that are available for thesyntaxes

Wednesday, October 18, 2017

Create Dynamic Connection with Crystal Report using Asp.net and Oracle Stored Procedure

Dynamic crystal report connection string require
d for transfer application dev to test.Normally developer working in devlopment server and after complet the development it will deploy the application into TEST or Production Server .In this case crystal report have not worked if you are specially using oracle stored procedure .Here I explain you how to create function for dynamic connection with stored procedure.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
public static ReportDocument ConnectionInfo(ReportDocument rpt)
{
try
{
ReportDocument crSubreportDocument;
string[] strConnection = ConfigurationManager.ConnectionStrings(“ABC”)].ConnectionString.Split(new char[] { ‘;’ });
Database oCRDb = rpt.Database;
Tables oCRTables = oCRDb.Tables;
CrystalDecisions.CrystalReports.Engine.Table oCRTable = default(CrystalDecisions.CrystalReports.Engine.Table);
TableLogOnInfo oCRTableLogonInfo = default(CrystalDecisions.Shared.TableLogOnInfo);
ConnectionInfo oCRConnectionInfo = new CrystalDecisions.Shared.ConnectionInfo();
oCRConnectionInfo.ServerName = strConnection[0].Split(new char[] { ‘=’ }).GetValue(1).ToString();
oCRConnectionInfo.Password = strConnection[2].Split(new char[] { ‘=’ }).GetValue(1).ToString();
oCRConnectionInfo.UserID = strConnection[1].Split(new char[] { ‘=’ }).GetValue(1).ToString();
//Loop through all tables in the report and apply the
//connection information for each table.
for (int i = 0; i < oCRTables.Count; i++)
{
oCRTable = oCRTables[i];
oCRTableLogonInfo = oCRTable.LogOnInfo;
oCRTableLogonInfo.ConnectionInfo = oCRConnectionInfo;
oCRTable.ApplyLogOnInfo(oCRTableLogonInfo);
oCRTable.Location = “ABCUSER.” + oCRTable.Location;// this is a combination of Schema name and Stored procedure name
}
for (int i = 0; i < rpt.Subreports.Count; i++)
{
{
crSubreportDocument = rpt.OpenSubreport(rpt.Subreports[i].Name);
oCRDb = crSubreportDocument.Database;
oCRTables = oCRDb.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table aTable in oCRTables)
{
oCRTableLogonInfo = aTable.LogOnInfo;
oCRTableLogonInfo.ConnectionInfo = oCRConnectionInfo;
aTable.ApplyLogOnInfo(oCRTableLogonInfo);
oCRTable.Location = “DMS_SYS_PROC.” + oCRTable.Location;
}
}
}
}
catch (Exception ex)
{
if (ExceptionPolicy.HandleException(ex, “General”))
throw;
}
return rpt;
}
This will not work with oracle packages.
Source : https://dotnetfarrukhabbas.wordpress.com/2010/10/12/create-dynamic-connection-with-crystal-report-using-asp-net-and-oracle-stored-procedure/

Dynamic Crystal Report Connection String Using Asp.net

Dynamic crystal report connection string required for transfer application dev to test.Normally developer working in devlopment server and after complet the development it will deploy the application into TEST or Production Server .In this case crystal report have not worked if you are specially using oracle stored procedure .Here I explain you how to create function for dynamic connection with stored procedure.

using CrystalDecisions.CrystalReports.Engine; 
using CrystalDecisions.Shared; 


public ReportDocument ConnectionInfo(ReportDocument rpt)
   {
       ReportDocument crSubreportDocument;
       string[] strConnection = ConfigurationManager.ConnectionStrings[("AppConn")].ConnectionString.Split(new char[] { ';' });

       Database oCRDb = rpt.Database;

       Tables oCRTables = oCRDb.Tables;

       CrystalDecisions.CrystalReports.Engine.Table oCRTable = default(CrystalDecisions.CrystalReports.Engine.Table);

       TableLogOnInfo oCRTableLogonInfo = default(CrystalDecisions.Shared.TableLogOnInfo);

       ConnectionInfo oCRConnectionInfo = new CrystalDecisions.Shared.ConnectionInfo();

       oCRConnectionInfo.ServerName = strConnection[0].Split(new char[] { '=' }).GetValue(1).ToString();
       oCRConnectionInfo.Password = strConnection[2].Split(new char[] { '=' }).GetValue(1).ToString();
       oCRConnectionInfo.UserID = strConnection[1].Split(new char[] { '=' }).GetValue(1).ToString();

       for (int i = 0; i < oCRTables.Count; i++)
       {
           oCRTable = oCRTables[i];
           oCRTableLogonInfo = oCRTable.LogOnInfo;
           oCRTableLogonInfo.ConnectionInfo = oCRConnectionInfo;
           oCRTable.ApplyLogOnInfo(oCRTableLogonInfo);
           if (oCRTable.TestConnectivity())
               //' If there is a "." in the location then remove the
               // ' beginning of the fully qualified location.
               //' Example "dbo.northwind.customers" would become
               //' "customers".
               oCRTable.Location = oCRTable.Location.Substring(oCRTable.Location.LastIndexOf(".") + 1);


       }

       for (int i = 0; i < rpt.Subreports.Count; i++)
       {

           {
               //  crSubreportObject = (SubreportObject);
               crSubreportDocument = rpt.OpenSubreport(rpt.Subreports[i].Name);
               oCRDb = crSubreportDocument.Database;
               oCRTables = oCRDb.Tables;
               foreach (CrystalDecisions.CrystalReports.Engine.Table aTable in oCRTables)
               {
                   oCRTableLogonInfo = aTable.LogOnInfo;
                   oCRTableLogonInfo.ConnectionInfo = oCRConnectionInfo;
                   aTable.ApplyLogOnInfo(oCRTableLogonInfo);
                   if (aTable.TestConnectivity())
                       //' If there is a "." in the location then remove the
                       // ' beginning of the fully qualified location.
                       //' Example "dbo.northwind.customers" would become
                       //' "customers".
                      aTable.Location = aTable.Location.Substring(aTable.Location.LastIndexOf(".") + 1);

               }
           }
       }
       //  }

       rpt.Refresh();
       return rpt;
   }


This will not work with oracle packages.

source : https://dotnetfarrukhabbas.blogspot.com/2010/10/create-dynamic-connection-with-crystal.html

Monday, September 30, 2013

Crystal Report - Load Report Failed on ASP.Net Page deployed in IIS 7 - Windows Server 2008 x64

Load Report Failed 
Yesterday i got this error, when i'm trying to load my crystal report in production machine. This one is a generic error, it means that, you maybe wondering where this error come from, even i'm wondering too ^^.
Before, in my development machine, everything is fine, i can see the report. 
When i tried to deploy it in my production machine, suddenly this error show up.

This is what i do to solve this problem :
1. Go to IIS -> Application Pools
2. Right click on DefaultAppPool (or application pools that your site using) --> Choose advanced Settings...
If you are thinking How To : Check Application Pools that a site is using from IIS 7, please click the link
3. Choose identity
4.Choose Network Services
5.Choose Ok and then Ok again

You are ready to go ^^

Off  course there some things that you need to check first, like :
1. Gave full rights for “C:\WINDOWS\Temp” folder depending on IIS user
2. Redistributable crystal version has installed
Reference : Sendy Santoso (http://geekydeveloper.blogspot.com/)

source : http://geekydeveloper.blogspot.com/2011/05/crystal-report-load-report-failed-on.html