how to email crystal report in pdf form - c#

I am new here and this is my first post, if there is any mistake pardon me and do let me know I'l correct it.
My question is I need to email crystal report to a particular recipient's email address which will also be included in crystal report, and that crystal report needs to be in PDF format, is this possible, if yes then can you please elaborate the procedure how to do it.
Thanks.

string pdfFile = "c:\\CrytalReport.pdf";
protected void Button1_Click(object sender, EventArgs e)
{
try
{
ExportOptions CrExportOptions;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = pdfFile;
CrExportOptions = ReportDocument .ExportOptions;//Report document object has to be given here
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
ReportDocument .Export();
sendmail();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
private void sendmail()
{
try
{
MailMessage Msg = new MailMessage();
Msg.To = "to Address";
Msg.From = "From Address";
Msg.Subject = "Crystal Report Attachment ";
Msg.Body = "Crystal Report Attachment ";
Msg.Attachments.Add(new MailAttachment(pdfFile));
// System.Web.Mail.SmtpMail.Send(Msg);
SmtpMail.SmtpServer = "you mail domain";
//SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
SmtpMail.Send(Msg);
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
Don't forget add these DLL's
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;
/// <summary>
/// Summary description for CrystalReport
/// </summary>
'public class CrystalReport
{
private void SetDBLogOnInfo(ConnectionInfo connectionInfo, ReportDocument objectReportDocument, TableLogOnInfo tableLogonInfo)
{
Tables Tbl = objectReportDocument.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table TmpTbl in Tbl)
{
tableLogonInfo = TmpTbl.LogOnInfo;
tableLogonInfo.ConnectionInfo = connectionInfo;
TmpTbl.ApplyLogOnInfo(tableLogonInfo);
}
}
public ReportDocument CrystalLogon(String pReportPath, ConnectionInfo objConnInfo, ref TableLogOnInfo tableLogonInfo)
{
ReportDocument objReportDoc = new ReportDocument();
objReportDoc.Load(pReportPath);
SetDBLogOnInfo(objConnInfo, objReportDoc, tableLogonInfo);
return objReportDoc;
}
public string[] GetCampaignConn()
{
//string server, database, userid, password;
string strConn = System.Configuration.ConfigurationSettings.AppSettings["Connection String"];
string[] strArray = strConn.Split(';');
string[] strOutput = new string[4];
for (int i = 0; i < strArray.Length; i++)
{
string[] strObject = strArray[i].Split('=');
if (strObject[0] == "Data Source")
{
strOutput[0] = strObject[1];
}
else if (strObject[0] == "Initial Catalog")
{
strOutput[1] = strObject[1];
}
else if (strObject[0] == "User ID")
{
strOutput[2] = strObject[1];
}
else if (strObject[0] == "Password")
{
strOutput[3] = strObject[1];
}
}
return strOutput;
}
}`
use above method you will problem will resolved

private void SetReportDataSource(string sCarrierID)
{
try
{
CrystalReport objCrystalReport = new CrystalReport();
//ReportDocument objReportDoc = new ReportDocument();
ConnectionInfo objConnInfo = new ConnectionInfo();
//string strConn = System.Configuration.ConfigurationSettings.AppSettings[Campaign];
string[] strArray = objCrystalReport.GetCampaignConn();
CrystalDecisions.Shared.TableLogOnInfo logOnInfo = new CrystalDecisions.Shared.TableLogOnInfo();
objConnInfo.DatabaseName = strArray[1].ToString();
objConnInfo.UserID = strArray[2].ToString();
objConnInfo.Password = strArray[3].ToString();
objConnInfo.ServerName = strArray[0].ToString();
String ReportPath = (Server.MapPath("Report") + #"\rptInvoice.rpt");
//String ReportPath = Server.MapPath("~//Report//VendorRegistration.rpt");
//objReportDoc = objCrystalReport.CrystalLogon(ReportPath, objConnInfo, ref logOnInfo);
//// for displaying Crystal report
//crVendorRegistration.ReportSource = objReportDoc;
//crVendorRegistration.ParameterFieldInfo[0].CurrentValues.Clear();
ParameterDiscreteValue pdvalue = new ParameterDiscreteValue();
pdvalue.Value = Convert.ToInt32(sCarrierID);
//crVendorRegistration.ParameterFieldInfo[0].CurrentValues.Add(pdvalue);
//crVendorRegistration.DataBind();
//// for Exporitng in PDF
ReportDocument repDoc = objCrystalReport.CrystalLogon(ReportPath, objConnInfo, ref logOnInfo);
repDoc.ParameterFields[0].CurrentValues.Add(pdvalue);
// Stop buffering the response
HttpContext.Current.Response.Buffer = false;
// Clear the response content and headers
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
// Export the Report to Response stream in PDF format and file name Customers
//repDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, HttpContext.Current.Response, true, "Truck Invoice " + sCarrierID + "");
//repDoc.GenerateReport
String ReportGenerated = (Server.MapPath("GenerateReport") + #"\rptInvoice" + sCarrierID + ".pdf");
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
ExportOptions CrExportOptions = new ExportOptions();
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = ReportGenerated;
CrExportOptions = repDoc.ExportOptions;
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
repDoc.Export(CrExportOptions);
//pdvalue = new ParameterDiscreteValue();
//pdvalue.Value = QC_By;
//crSalesRpt.ParameterFieldInfo[1].CurrentValues.Add(pdvalue);
//objReportDoc.VerifyDatabase();
//objReportDoc.Refresh();
}
catch (Exception ex)
{
//bool rethrow = ExceptionPolicy.HandleException(ex, "");
//if (rethrow)
// throw;
//Redirecting to error message page
//Server.Transfer(ConstantClass.StrErrorPageURL);
}
}
by above you create pdf using crystal report by using mail concept u will sending mail thats it

Related

reader stopping after first result c#

Ok, so i have written code to make a PDF file using Itextsharp and variables from a select statement. and updates into a database. the reader has to return multiple results with the query that i have made. for some reason it stops after the first result.
can anyone tell me what i need to change to make it iterate through each row that has been returned and update it to the database within in the while loop.
here is my code.
public Form1()
{
InitializeComponent();
}
private void CreateBtn_Click(object sender, EventArgs e)
{
try
{
make_pdf();
MessageBox.Show("completed");
}
catch (Exception exe )
{
MessageBox.Show("failed");
}
}
public void vaiabless()
{
}
public static void make_pdf()
{
string Contact = "";
string emailAddress = "";
string Tel = "";
string InvoiceDate = "";
string address = "";
string Reference = "";
string AccountNo = "";
string Debit = "";
string Credit = "";
string refnum = "";
string transtype = "";
string breaker = "|";
string connetionString = null;
MySqlConnection cnn;
connetionString = "*************";
cnn = new MySqlConnection(connetionString);
try
{
cnn.Open();
// MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
try
{
MySqlDataReader reader = null;
string selectCmd = "SELECT accounting.code,users.curr_email , users.physicaddr ,accounting.date , accounting.refnum , accounting.transtype, users.telephone , accounting.debit , accounting.acc_pdf, accounting.credit, accounting.reference, users.contact, accounting.transnum FROM accounting INNER JOIN users ON accounting.code = users.code WHERE(accounting.transtype = 1)";
MySqlCommand createcommand = new MySqlCommand(selectCmd, cnn);
reader = createcommand.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
//get account number
AccountNo = reader["code"].ToString();
//get emailaddress
emailAddress = reader["curr_email"].ToString();
transtype = reader["transtype"].ToString();
//get Contact Name
Contact = reader["contact"].ToString();
//get telephone number
Tel = reader["telephone"].ToString();
//Get Date
InvoiceDate = reader["date"].ToString();
//Get reference
Reference = reader["reference"].ToString();
//Get Address
address = reader["physicaddr"].ToString();
//Get Debit
Debit = reader["debit"].ToString();
//Get Credit
Credit = reader["credit"].ToString();
//Get Refnum
refnum = reader["refnum"].ToString();
MemoryStream ms = new MemoryStream();
byte[] bits = new byte[0];
// Make The PDF File
Document NewDoc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
PdfWriter pdfwri = PdfWriter.GetInstance(NewDoc,ms);
NewDoc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("intsa-header.jpg");
img.ScaleAbsolute(596f, 100f);
//Account List
List AccountNolist = new List(List.UNORDERED);
AccountNolist.SetListSymbol("");
AccountNolist.IndentationLeft = 300f;
AccountNolist.Add(new ListItem("AccountNo " + AccountNo));
// AddressList
List AddressList = new List(List.UNORDERED);
AddressList.SetListSymbol("");
AddressList.IndentationLeft = 300f;
AddressList.Add(new ListItem("Address: " + address));
#region Emailaddresslist
//EmailAddressList
List emailAddresslist = new List(List.UNORDERED);
emailAddresslist.SetListSymbol("");
emailAddresslist.IndentationLeft = 300f;
emailAddresslist.Add(new ListItem("Email address: " + emailAddress));
#endregion
//ContactList
List Contactlist = new List(List.UNORDERED);
Contactlist.SetListSymbol("");
Contactlist.IndentationLeft = 300f;
Contactlist.Add(new ListItem("Contact: " + Contact));
//TelephoneList
List Telephonelist = new List(List.UNORDERED);
Telephonelist.SetListSymbol("");
Telephonelist.IndentationLeft = 300f;
Telephonelist.Add(new ListItem("Tel: " + Tel));
// Make a Table
#region pdftable
//PdfPTable General_Table = new PdfPTable(1);
//General_Table.SpacingBefore = 50f;
//General_Table.SpacingAfter = 50f;
//PdfPCell Caption = new PdfPCell(new Phrase("Description"));
//PdfPCell Body = new PdfPCell(new Phrase(" " + refnum + " "+ Reference + " Total Due: " + Debit ));
//Body.HorizontalAlignment = Element.ALIGN_RIGHT;
//Caption.Colspan = 0;
//Caption.HorizontalAlignment = 1;
//General_Table.AddCell(Caption);
//General_Table.AddCell(Body);
PdfPTable mytable = new PdfPTable(3);
mytable.SpacingBefore = 40f;
Paragraph accountpar = new Paragraph("Description");
accountpar.IndentationLeft = 200f;
accountpar.SpacingBefore = 30f;
accountpar.SpacingAfter = 10f;
Paragraph Referencepar = new Paragraph( Reference);
Referencepar.IndentationLeft = 200f;
Referencepar.SpacingBefore = 30f;
Referencepar.SpacingAfter = 10f;
Paragraph Totalpar = new Paragraph("Total Due:" + "R" + Debit);
Totalpar.IndentationLeft = 200f;
Totalpar.SpacingBefore = 30f;
Totalpar.SpacingAfter = 10f;
Paragraph Refnumpar = new Paragraph("Reference Num: "+refnum);
Refnumpar.IndentationLeft = 150f;
Refnumpar.SpacingBefore = 10f;
Refnumpar.SpacingAfter = 30f;
mytable.AddCell(Refnumpar);
mytable.AddCell(Referencepar);
mytable.AddCell(Totalpar);
#endregion
//add Image to pdf
NewDoc.Add(img);
//add accountNo to pdf
NewDoc.Add(AccountNolist);
//add Contact to pdf
NewDoc.Add(Contactlist);
//add emailaddress to pdf
NewDoc.Add(emailAddresslist);
//add Telephone Number to pdf
NewDoc.Add(Telephonelist);
//add address to pdf
NewDoc.Add(AddressList);
//NewDoc.Add(accountpar);
//NewDoc.Add(Supscriptionpar);
NewDoc.Add(mytable);
//save Pdf
NewDoc.Close();
bits = ms.ToArray();
string updateCmd = "UPDATE users.accounting SET acc_pdf = #acc_pdf WHERE refnum =" + refnum;
MySqlConnection cnnx;
connetionString = "****************";
cnnx = new MySqlConnection(connetionString);
MySqlCommand Updatecommand = new MySqlCommand(updateCmd, cnnx);
Updatecommand.Parameters.AddWithValue("#acc_pdf", bits);
cnnx.Open();
Updatecommand.ExecuteNonQuery();
cnnx.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Try to change the order of your statements like given on msdn's example for the MySqlDataReader:
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
Also check what #Cameron Tinker asked:
Does the query return more than one result if you run it on the
database directly?
And to avoid resource leaks, don't forget to close the reader with reader.Close(); and also the connections. (or better use the using keyword)

Getting multiple results from one select query

So I am stuck with my code and have thoroughly tried looking for an answer.
I have 1 select statement that brings about 52806 results.
I put the result of the query I run in variables and then put it into a PDF file i make. After the first result it doesn't work. I want to make it so that it puts the results in my pdf file and then goes to the next result.
if anyone can help me id appreciate it a lot.
Here is my code. Sorry for the bad practice in advance.
private void CreateBtn_Click(object sender, EventArgs e)
{
try
{
make_pdf();
}
catch (Exception exe )
{
MessageBox.Show("failed");
}
}
public static void make_pdf()
{
string Contact = "";
string emailAddress = "";
string Tel = "";
string InvoiceDate = "";
string address = "";
string Reference = "";
string AccountNo = "";
string Debit = "";
string Credit = "";
string refnum = "";
string connetionString = null;
MySqlConnection cnn;
connetionString = "server=********;user id=web_support;database=users;password=!w3b_supp0rt~;persistsecurityinfo=True";
cnn = new MySqlConnection(connetionString);
try
{
cnn.Open();
// MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
try
{
MySqlDataReader reader = null;
string selectCmd = "SELECT accounting.code,users.curr_email , users.physicaddr ,accounting.date , accounting.refnum , users.telephone , accounting.debit , accounting.acc_pdf, accounting.credit, accounting.reference, users.contact, accounting.transnum FROM accounting INNER JOIN users ON accounting.code = users.code WHERE(accounting.transtype = 1)";
MySqlCommand command = new MySqlCommand(selectCmd, cnn);
reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
//get account number
AccountNo = reader["code"].ToString();
//get emailaddress
emailAddress = reader["curr_email"].ToString();
//get Contact Name
Contact = reader["contact"].ToString();
//get telephone number
Tel = reader["telephone"].ToString();
//Get Date
InvoiceDate = reader["date"].ToString();
//Get reference
Reference = reader["reference"].ToString();
//Get Address
address = reader["physicaddr"].ToString();
//Get Debit
Debit = reader["debit"].ToString();
//Get Credit
Credit = reader["credit"].ToString();
//Get Refnum
refnum = reader["refnum"].ToString();
// MessageBox.Show(address+" "+Reference+" "+InvoiceDate+" "+emailAddress+" "+AccountNo+" "+Contact);
// Make The PDF File
Document NewDoc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
PdfWriter pdfwri = PdfWriter.GetInstance(NewDoc, new FileStream("text.pdf", FileMode.Create));
NewDoc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("intsa_header_small.jpg");
// Paragraph par = new Paragraph("Everything is working");
//Account List
List AccountNolist = new List(List.UNORDERED);
AccountNolist.SetListSymbol("");
AccountNolist.IndentationLeft = 300f;
AccountNolist.Add(new ListItem("AccountNo " + AccountNo));
// AddressList
List AddressList = new List(List.UNORDERED);
AddressList.SetListSymbol("");
AddressList.IndentationLeft = 300f;
AddressList.Add(new ListItem("Address: " + address));
#region Emailaddresslist
//EmailAddressList
List emailAddresslist = new List(List.UNORDERED);
emailAddresslist.SetListSymbol("");
emailAddresslist.IndentationLeft = 300f;
emailAddresslist.Add(new ListItem("Email address: " + emailAddress));
#endregion
//ContactList
List Contactlist = new List(List.UNORDERED);
Contactlist.SetListSymbol("");
Contactlist.IndentationLeft = 300f;
Contactlist.Add(new ListItem("Contact: " + Contact));
//TelephoneList
List Telephonelist = new List(List.UNORDERED);
Telephonelist.SetListSymbol("");
Telephonelist.IndentationLeft = 300f;
Telephonelist.Add(new ListItem("Tel: " + Tel));
// Make a Table
PdfPTable General_Table = new PdfPTable(1);
General_Table.SpacingBefore = 50f;
General_Table.SpacingAfter = 50f;
PdfPCell Caption = new PdfPCell(new Phrase("Description"));
PdfPCell Body = new PdfPCell(new Phrase(" " + refnum + " " + Reference + " Debit: " + Debit + " Credit: " + Credit));
Body.HorizontalAlignment = Element.ALIGN_RIGHT;
Caption.Colspan = 0;
Caption.HorizontalAlignment = 1;
General_Table.AddCell(Caption);
General_Table.AddCell(Body);
// NewDoc.Add(par);
//add Image to pdf
NewDoc.Add(img);
//add accountNo to pdf
NewDoc.Add(AccountNolist);
//add Contact to pdf
NewDoc.Add(Contactlist);
//add emailaddress to pdf
NewDoc.Add(emailAddresslist);
//add Telephone Number to pdf
NewDoc.Add(Telephonelist);
//add address to pdf
NewDoc.Add(AddressList);
NewDoc.Add(General_Table);
//save Pdf
NewDoc.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The problem is you are creating the PDF file in the while loop, I don't think you want 52k PDF files, so you should create the PDF file first, then loop through all of the results and paste them into the file.
EDIT: I would suggest adding line to insert/update PDF to database after
NewDoc.Close();
Then deleting the local file (text.pdf) before running loop again.

CsvHelper how to filter a column and return only distinct values

I am using CsvHelper in C#. I want to filter my ORIGTITLE column for distinct values and store those in the Dictionary collection. So in my Dictionary collection I should have the values below. How can I accomplish this ?
[Abbrechen,Ab] [Abgleichen,translate1] [Abgrenzung,Something]
[Tree,Baum]
My .csv file looks like this:
ORIGTITLE;REPLACETITLE;ORIGTOOLTIP
Abbrechen;Ab;Abbrechen
Abbrechen;Abort;abgelaufen
Abgleich;translate1;
Abgrenzung;Something;Abgrenzung zum Konto
Tree;Baum;Baum
Tree;Leaf;Baum
Here is my C# code so far:
class DataRecord
{
public string ORIGTITLE { get; set; }
public string REPLACETITLE { get; set; }
public string ORIGTOOLTIP { get; set; }
}
public void CsvReader()
{
using (StreamReader streamReader = new StreamReader(#"C:\Users\Devid\Desktop\Newtest.txt"))
{
CsvReader reader = new CsvReader(streamReader);
reader.Configuration.Encoding = Encoding.UTF8;
reader.Configuration.Delimiter = ";";
List<DataRecord> records = reader.GetRecords<DataRecord>().ToList();
//records has to be a distinct list
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (DataRecord record in records)
{
dict.Add(record.ORIGTITLE, record.REPLACETITLE);
//i get a error because the key is not distinctq
}
}
}
You can use my CSV reader which puts results into a datatable. You can then use Linq to get distinct values.
You can get a dictionary with code like this
CSVReader reader = new CSVReader();
DataTable dt = reader.ReadCSVFile("filename", true).Tables[0];
Dictionary<int, List<DataRow>> dict = dt.AsEnumerable()
.GroupBy(x => x.Field<int>(0), y => y)
.ToDictionary(x => x.Key, y => y.ToList());
here is the class for a form application
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Xml;
using System.Xml.Xsl;
namespace CSVImporter
{
public partial class CSVImporter : Form
{
//const string xmlfilename = #"C:\Users\fenwky\XmlDoc.xml";
const string xmlfilename = #"C:\temp\test.xml";
DataSet ds = null;
public CSVImporter()
{
InitializeComponent();
// Create a Open File Dialog Object.
openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialog1.ShowDialog();
string fileName = openFileDialog1.FileName;
//doc.InsertBefore(xDeclare, root);
// Create a CSV Reader object.
CSVReader reader = new CSVReader();
ds = reader.ReadCSVFile(fileName, true);
dataGridView1.DataSource = ds.Tables["Table1"];
}
private void WXML_Click(object sender, EventArgs e)
{
WriteXML();
}
public void WriteXML()
{
StringWriter stringWriter = new StringWriter();
ds.WriteXml(new XmlTextWriter(stringWriter), XmlWriteMode.WriteSchema);
string xmlStr = stringWriter.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.InsertBefore(xDeclare, doc.FirstChild);
// Create a procesing instruction.
//XmlProcessingInstruction newPI;
//String PItext = "<abc:stylesheet xmlns:abc=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">";
//String PItext = "type='text/xsl' href='book.xsl'";
string PItext = "html xsl:version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"";
XmlText newPI = doc.CreateTextNode(PItext);
//newPI = docCreateProcessingInstruction("html", PItext);
//newPI = doc.CreateComment(CreateDocumentType("html", PItext, "", "");
doc.InsertAfter(newPI, doc.FirstChild);
doc.Save(xmlfilename);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(xmlfilename);
string directoryPath = Path.GetDirectoryName(xmlfilename);
myXslTrans.Transform(xmlfilename, directoryPath + "result.html");
webBrowser1.Navigate(directoryPath + "result.html");
}
}
public class CSVReader
{
public DataSet ReadCSVFile(string fullPath, bool headerRow)
{
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();
try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}
}
Check if the key exists before you add it:
if (!dict.ContainsKey(record.ORIGTITLE))
{
dict.Add(record.ORIGTITLE, record.REPLACETITLE);
}
This will not perform very well for big datasets. Consider using LINQ to get distinct values instead.
You can use LINQ to group the records by ORIGTITLE property, and then project to a dictionary taking ORIGTITLE as dictionary key and the first REPLACETITLE in each group as dictionary value :
List<DataRecord> records = reader.GetRecords<DataRecord>().ToList();
var dict = records.GroupBy(r => r.ORIGTITLE)
.ToDictionary(k => k.Key, v => v.First(). REPLACETITLE );

send mail with attachement in c# using outlook

I m getting error when i m trying to send email to different Recipients with their respective attachment. i m using looping to change the Recipients and attachment but getting error. pls help to resolve this issue
my code is
private void BtnEmail_Click(object sender, EventArgs e)
{
try
{
string[] fileEntries = System.IO.Directory.GetFiles(txtPdfFiles.Text, "*.pdf");
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
if (RtxtBox.Text == "")
{
MessageBox.Show("Please set Mail body text");
GrpMailBody.Visible = true;
}
else
{
oMsg.HTMLBody = RtxtBox.Text;
}
if (RtxtSubject.Text == "")
{
MessageBox.Show("Please Enter Mail Subject");
GrpMailBody.Visible = true;
}
else
{
oMsg.Subject = RtxtSubject.Text;
}
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
for (int i = 0; i <= grvExcelData.RowCount; i++)
{
string EmaildID = grvExcelData.Rows[i].Cells[3].Value.ToString();
string sFileName = grvExcelData.Rows[i].Cells[5].Value.ToString()+".pdf";
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(EmaildID);
foreach (string fileName in fileEntries)
{
string fileN = "";
string xfileName;
xfileName=System.IO.Path.GetFileName(fileName);
if (xfileName == sFileName)
{
Outlook.Attachment oAttach = oMsg.Attachments.Add(#fileName, iAttachType, iPosition, sDisplayName); //getting error in this line
}
else
{
}
}
oRecip.Resolve();
oMsg.Send();
oRecip = null;
//oRecips = null;
oMsg = null;
oApp = null;
}
Add this--
Add reference Microsoft.Office.Interop.Outlook
using Outlook = Microsoft.Office.Interop.Outlook;
public void sendEMailThroughOUTLOOK()
{
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = "Hello!!";
//Add an attachment.
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
//now attached the file
Outlook.Attachment oAttach = oMsg.Attachments.Add(#"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);
//Subject line
oMsg.Subject = "Your Subject will go here.";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("EmailAddress");
oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}//end of try block
catch (Exception ex)
{
}//end of catch
}//end of Email Method
Try to add Outlook Inspector as described here:
https://groups.google.com/forum/#!msg/microsoft.public.outlook.program_vba/lLJwbwwl-XU/gRuQYRpJtxEJ
using Outlook = Microsoft.Office.Interop.Outlook;
try
{
string[] fileEntries = System.IO.Directory.GetFiles(txtPdfFiles.Text, "*.pdf");
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMsg.GetInspector;
// ...
}

Pdf file is not updating in asp.net application

In my asp.net application we generating pdf using ITextSharp.dll
Now my problem is every time same pdf is opening(not refreshing) unless until clear my browser history it is same. I am using chrome browser.
Here is my code
private void fillForm() {
try {
string Phone = "", Physical = "";
string formFile = Server.MapPath("~\\Inspection.pdf");
string newFile = Server.MapPath("~\\InspectionPrint.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = stamper.AcroFields;
PdfContentByte d = new PdfContentByte(stamper.Writer);
//getting values from DB
SqlCommand comd = new SqlCommand("usp_PrintInspection", QMSConn);
QMSConn.Open();
comd.CommandType = CommandType.StoredProcedure;
comd.Parameters.Add("#QuoteNumber", SqlDbType.VarChar);
comd.Parameters["#QuoteNumber"].Value = Session["CurrQuoteNumber"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlAdapter.SelectCommand = comd;
sqlAdapter.Fill(ds, "Table");
if (ds.Tables[0].Rows.Count > 0) {
// set form fields
string Name = ds.Tables[0].Rows[0]["NAME"].ToString();
string Address1 = ds.Tables[0].Rows[0]["Address1"].ToString();
string CompanyID = ds.Tables[0].Rows[0]["CompanyID"].ToString();
string PolicyNumber = ds.Tables[0].Rows[0]["PolicyNumber"].ToString();
fields.SetField("Name", Name);
fields.SetField("Address1", Address1);
fields.SetField("CompanyID ", CompanyID);
fields.SetField("PolicyNumber", PolicyNumber);
stamper.FormFlattening = false;
stamper.Close();
string file = "InspectionPrint";
string Url = "../" + file + ".pdf";
String js = #"WindowPopup('" + Url + "');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Key", js, true);
}
else {
showalert("No Record Available For This Quote");
}
}
catch(exception ex) {
}
}
as you are saying it is working in the Localhost but not in the production server, most likely it seems to me as an URL/Path issue.
1. after observing your code, you are creating one more string Url variable without using the existing String formFile variable.
as you should provide the valid path you need to use the formFile instead of Url as you have created formFile using Server.MapPath()
Try This:
/*string Url = "../" + file + ".pdf";*/ //comment or remove
String js = #"WindowPopup('" + formFile + "');";//use formFile instead of Url

Categories