Export Crystal Report to PDF and send in Email as Attachment using Windows Service


In this article I''m going to explain how to Export Crystal Report to PDF and send in Email as Attachment using Windows Service.Windows services are applications that will run in the background and then perform various task. This application does not have user interface. Windows Service are controlled by using service control manager. If you want to start and stop the service then go to Control Panel ---> Administrative Tools ---> Services. Right click the service and then select Start or stop.


In this article I''m going to explain how to Export Crystal Report to PDF and send in Email as Attachment using Windows Service.Windows services are applications that will run in the background and then perform various task.
This application does not have user interface. Windows Service are controlled by using service control manager. If you want to start and stop the service then go to Control Panel ---> Administrative Tools ---> Services. Right click the service and then select Start or stop..



Step 1:
Select File-->New -->click Project and then project window will display.


Step 2:
Expand "Visual C#" tab and select Windows Service and then give proper name for your service.

Step 3:
Expand "Visual C#" tab and select Windows Service and then give proper name for your service.

Step 4:
Right click on the form and then click Add Installer and then project Installer added to your project.


Step 5:
Select ServiceInstaller1 go to properties and then set DisplayName, ServiceName and finally set StartType equal to Automatic or manual.
step 6:

select ServiceProcessInstaller1 and set Account property as LocalSystem.
Step 7:
Add ScheduledService form Within this form we need to add two crystalreport file.

Step 8:
Build the application and then get exe of this application from bin directory.

By using following steps you can install and uninstall the windows service easily. By using InstallUtil.exe we can install or uninstall
windows service easily.

1)On the Windows Start menu, choose Visual Studio (2008,2010,2003, 2005) , Visual Studio Tools, Visual Studio Command Prompt.

2)Access the directory in which your project's compiled executable file is located.

3)Run InstallUtil.exe from the command prompt with your project's output as a parameter. For example
installutil WindowsService1.exe

4)To uninstall the Windows Service use below statement
installutil /u WindowsService1.exe

Herewith I have given full code kindly check it. Create two Crystal reports and one notepad file in D & C directory and then try this example.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
using System.Data.SqlClient;
using System.Net.Mail;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;

namespace WindowsService1
{

public partial class ScheduledService : ServiceBase
{
Boolean bolfa = false;
Boolean bolfa22 = false;
Boolean bolfa2 = false;
DateTime timeOnInit = DateTime.Now;
DataSet ds = new DataSet();
Timer timer = new Timer();
public ScheduledService()
{
InitializeComponent();
}
//This method is used to raise event during start of service
protected override void OnStart(string[] args)
{
//add this line to text file during start of service
TraceService("start service");
myservice();
//handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

//This statement is used to set interval to 1 minute (= 60,000 milliseconds)
//36000000 36000000
timer.Interval = 36000000;
//timer.Interval = 60000;

//enabling the timer
timer.Enabled = true;
}
//This method is used to stop the service
protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService("Another entry at " + DateTime.Now);
myservice();
}
private DataTable BindReports()
{
try
{
string conString = @"Data Source=192.168.1.168;Initial Catalog=databasename;Persist Security Info=True;User ID=userid;Password=password";
DataTable dtReport = new DataTable();
SqlConnection con = new SqlConnection(conString);
SqlCommand cmdSetupGetdata = new SqlCommand("[Attendance_NoEntryStoredprocedure]", con);
cmdSetupGetdata.CommandType = CommandType.StoredProcedure;
cmdSetupGetdata.CommandTimeout = 600;
cmdSetupGetdata.Parameters.AddWithValue("@BR", "ALL");
SqlDataAdapter mySqlDataAdapter1 = new SqlDataAdapter();
mySqlDataAdapter1.SelectCommand = cmdSetupGetdata;
con.Open();
mySqlDataAdapter1.Fill(dtReport);
con.Close();
return dtReport;
}
catch (Exception ex)
{
throw ex;
}

}
private DataTable BindReports2()
{
try
{

string conString = @"Data Source=192.168.1.168;Initial Catalog=databasename;Persist Security Info=True;User ID=userid;Password=password";
DataTable dtReport = new DataTable();
SqlConnection con = new SqlConnection(conString);
SqlCommand cmdSetupGetdata = new SqlCommand("ReimburmentReportStoredprocedure", con);
cmdSetupGetdata.CommandType = CommandType.StoredProcedure;
cmdSetupGetdata.CommandTimeout = 600;
SqlDataAdapter mySqlDataAdapter1 = new SqlDataAdapter();
mySqlDataAdapter1.SelectCommand = cmdSetupGetdata;
con.Open();
mySqlDataAdapter1.Fill(dtReport);
con.Close();




return dtReport;
}
catch (Exception ex)
{
throw ex;
}
}
private void myservice()
{


bolfa2 = true;
ReportDocument cryRpt;

cryRpt = new ReportDocument();
cryRpt.Load(@"D:\DailyAbsentListReportfile.rpt");

ParameterFieldDefinitions crParameterFieldDefinitions;
ParameterFieldDefinition crParameterFieldDefinition;
ParameterValues crParameterValues = new ParameterValues();
ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

crParameterDiscreteValue.Value = "ALL";
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
crParameterFieldDefinition = crParameterFieldDefinitions["Branch"];
crParameterValues = crParameterFieldDefinition.CurrentValues;

crParameterValues.Clear();
crParameterValues.Add(crParameterDiscreteValue);
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);




crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
DataTable dtReports = BindReports();
cryRpt.SetDataSource(dtReports);
crystalReportViewer1.ReportSource = dtReports;
crystalReportViewer1.Refresh();
ExportOptions rptExportOption;
DiskFileDestinationOptions rptFileDestOption = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions rptFormatOption = new PdfRtfWordFormatOptions();

string reportFileName = @"D:\DailyAbsentListPDFFile.pdf";

rptFileDestOption.DiskFileName = reportFileName;
rptExportOption = cryRpt.ExportOptions;
{
rptExportOption.ExportDestinationType = ExportDestinationType.DiskFile;
//if we want to generate the report as PDF, change the ExportFormatType as "ExportFormatType.PortableDocFormat"
//if we want to generate the report as Excel, change the ExportFormatType as "ExportFormatType.Excel"
rptExportOption.ExportFormatType = ExportFormatType.PortableDocFormat;
rptExportOption.ExportDestinationOptions = rptFileDestOption;
rptExportOption.ExportFormatOptions = rptFormatOption;
}


try
{
cryRpt.Export();
}
catch (Exception ex)
{


}

ReportDocument cryRptReimburement;

cryRptReimburement = new ReportDocument();
cryRptReimburement.Load(@"D:\DailyReimbursementDetailsReportFile.rpt");





crystalReportViewer2.ReportSource = cryRptReimburement;
crystalReportViewer2.Refresh();
DataTable dtReportsReimburement = BindReports2();
cryRptReimburement.SetDataSource(dtReportsReimburement);
crystalReportViewer2.ReportSource = dtReportsReimburement;
crystalReportViewer2.Refresh();
ExportOptions rptExportOption2;
DiskFileDestinationOptions rptFileDestOption2 = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions rptFormatOption2 = new PdfRtfWordFormatOptions();

string reportFileName2 = @"D:\Reimburment.pdf";

rptFileDestOption2.DiskFileName = reportFileName2;
rptExportOption2 = cryRptReimburement.ExportOptions;
{
rptExportOption2.ExportDestinationType = ExportDestinationType.DiskFile;
//if we want to generate the report as PDF, change the ExportFormatType as "ExportFormatType.PortableDocFormat"
//if we want to generate the report as Excel, change the ExportFormatType as "ExportFormatType.Excel"
rptExportOption2.ExportFormatType = ExportFormatType.PortableDocFormat;
rptExportOption2.ExportDestinationOptions = rptFileDestOption2;
rptExportOption2.ExportFormatOptions = rptFormatOption2;
}
try
{
cryRptReimburement.Export();
}
catch (Exception ex)
{


}



SmtpClient client = new SmtpClient(); // setting email smtp client to send email from
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = false;
client.Host = "smtp.gmail.com"; //google mail smtp host
client.Port = 587; //Google mail port
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("fromMailid@gmail.com", "password"); //your email and password
client.UseDefaultCredentials = false;
client.Credentials = credentials;
//foreach (DataRow dr in ds.Tables[0].Rows)
//{
MailMessage mm3 = new MailMessage("frommailid@.com", "renganathan@gmail.com"); //fields in the database

// Add attachment
string attachmentPath = @"D:\DailyAbsentList.pdf";
mm3.Attachments.Add(new Attachment(attachmentPath));
string attachmentPath2 = @"D:\Reimburment.pdf";
mm3.Attachments.Add(new Attachment(attachmentPath2));

mm3.Subject = "Sending Auto Mail From windows Service"; //Email Subject to send out
mm3.Body = "Herewith I have attached PDF file " + Environment.NewLine + "Regards" + Environment.NewLine + "Rengan";
mm3.IsBodyHtml = true;
client.Send(mm3);
mm3.Dispose();




}

private void TraceService(string content)
{

//set up a filestream
FileStream fs = new FileStream(@"C:\test.txt", FileMode.OpenOrCreate, FileAccess.Write);

//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);

//add the text
sw.WriteLine(content);
//add the text to the underlying filestream

sw.Flush();
//close the writer
sw.Close();


}
}
}


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: