How to customize ASP.Net chart - asp.net

Am creating ASP.NET Report for my Application.
i want the X-AXIS of my graph to display Timeperiod in this format:eg
1990-2000,2000-2010,2010-2020 etc.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection DBconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString());
SqlCommand sqlCmd = new SqlCommand("select YEAR(ValidityFrom) as SpecYear,COUNT(DocumentTypeID) as Total From Document WHERE ValidityFrom is not null AND DocumentTypeID = 1 Group by YEAR(ValidityFrom)", DBconnection);
SqlDataReader reader;
try
{
DBconnection.Open();
reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
SumID.Series["summery-id"].Points.AddXY(reader["SpecYear"], reader["Total"]);
}
reader.Close();
}
catch (SqlException err)
{
for (int i = 0; i < err.Errors.Count; i++)
{
lblErrorMessage.Text = ("Message: " + err.Errors[i].Message + "\n" +
"LineNumber: " + err.Errors[i].LineNumber + "\n" +
"Error-Code: " + err.ErrorCode.ToString() + "\n" +
"Or Connection To server Fail");
}
}
catch (NullReferenceException err)
{
lblErrorMessage.Text = ("Error:" + err.Message + "\n" +
"Source :" + err.Source +
"Method:" + err.TargetSite);
}
catch (Exception err)
{
lblErrorMessage.Text = "Error Reading Data " + err.Message;
}
finally
{
DBconnection.Close();
}

Related

Unable to send mail from asp.net (framework version 4) application hosted on IIS running on windows 2008R2?

My application is hosted on IIS running on windows 2008R2.Code to send mail is mentioned below.
public bool SendMail(string to, string cc, string subject, string body)
{
bool abc = false;
System.Net.Mail.SmtpClient smtpClient = null;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
bool IsSSLfailed = false;
bool allPortsFailed = false;
bool SSLEnabled = false;
bool CertificateByPassed = false;
smtpClient = new System.Net.Mail.SmtpClient();
again: try
{
// SmtpClient smtpserver = new SmtpClient("smtp.gmail.com", 25);
string from = ConfigurationSettings.AppSettings.Get("UserName");
string Password = ConfigurationSettings.AppSettings.Get("Password");
message.From = new MailAddress(from);
message.To.Add(to);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
message.Subject = WebUtility.HtmlEncode(subject);
message.SubjectEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
message.Body = WebUtility.HtmlDecode(body);
message.BodyEncoding = Encoding.UTF8;
smtpClient.Timeout = 10000;
message.SubjectEncoding = Encoding.UTF8;
if (IsSSLfailed)
{
if (smtpClient.Port == 587)
{
smtpClient.Port = 465;
}
else if (smtpClient.Port == 465)
{
smtpClient.Port = 25;
}
else if (smtpClient.Port == 25)
{
smtpClient.Port = 2525;
allPortsFailed = true;
}
}
else
{
smtpClient.Port = 587;
}
smtpClient.EnableSsl = SSLEnabled;
if (!CertificateByPassed)
{
BypassCertificateError();
}
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(from, Password);
smtpClient.Credentials = nc;
smtpClient.Send(message);
abc = true;
}
catch (System.Net.Mail.SmtpFailedRecipientException ex)
{
IsSSLfailed = true;
logger.ErrorFormat("Error occured in SendMail() method,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString()+ " smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " Detailed error:{0}{1}", Environment.NewLine, ex.Message.ToString());
logger.ErrorFormat("Inner Exception", Environment.NewLine, ex.InnerException != null ? ex.InnerException.Message.ToString() : string.Empty);
if (!allPortsFailed)
{
goto again;
}
else if (!SSLEnabled)
{
SSLEnabled = true;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
else if (!CertificateByPassed)
{
CertificateByPassed = true;
SSLEnabled = false;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
this.upForm.Update();
throw ex;
}
catch (System.Net.Mail.SmtpException ex)
{
IsSSLfailed = true;
logger.ErrorFormat("SendMail SmtpException,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString() + " smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " StatusCode:" + ex.StatusCode.ToString() + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.Message.ToString());
logger.ErrorFormat("SendMail Inner ExceptionSmtpException StatusCode:" + ex.StatusCode.ToString() + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.InnerException != null ? ex.InnerException.Message.ToString() : string.Empty);
if (!allPortsFailed)
{
goto again;
}
else if (!SSLEnabled)
{
SSLEnabled = true;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
else if (!CertificateByPassed)
{
CertificateByPassed = true;
SSLEnabled = false;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
this.upForm.Update();
throw ex;
}
catch (Exception ex)
{
IsSSLfailed = true;
logger.ErrorFormat("SendMail error sending mail,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString() +" smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " " + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.Message.ToString());
logger.ErrorFormat("SendMail error sending mail,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString() + " smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " " + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.InnerException != null ? ex.InnerException.Message.ToString() : string.Empty);
if (!allPortsFailed)
{
goto again;
}
else if (!SSLEnabled)
{
SSLEnabled = true;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
else if (!CertificateByPassed)
{
CertificateByPassed = true;
SSLEnabled = false;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
this.upForm.Update();
throw ex;
}
return abc;
}
public static void BypassCertificateError()
{
try
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(
Object sender1,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
catch (Exception ex)
{
throw ex;
}
}
As you can see from the code,i've checked all ports that are used to send mail.
This same code works on application hosted on windows 7/8 but doesn't work on windows 2008R2.
Below is the error message i get
SendMail SmtpException,CertificateBypassed:False SSLEnabled: False
smtpClient.DeliveryMethod:Network smtpClient.EnableSsl:False
smtpClient.Host:SMTP.GMAIL.COM smtpClient.Port:587
smtpClient.UseDefaultCredentials:False StatusCode:GeneralFailure
Nothing in innerexception.This same message is repeated for all ports.I am sending this mail via gmail.I've tested with MS Outlook on the server with same gmail account,and it was working properly so i guess firewall ristriction are not applicable in my case.I've also enabled "Access for less secure app" in gmail settings.
McAfee was blocking mail attemps.Never doubted it as i could send the mail from outlook but couldn't do it from my code.Just included w3wp.exe to exclusion in mass mailing

How to use and improve wakhtmltopdf performance?

I have my aspx pages , and some logic is written in code behind to bind the data of aspx pages.Now using wkhtmltopdf i am sending these files to convert into pdf files.Its work very well when the data is smaller in size however when the data comes in larger side for that page the wkhtmltopdf stops working and doesnt create any pdf file.
Can you suggest any way to overcome this problem. What i tried was limiting the data.. for example i have repeater control on my page if that controls binds 350 record i am only taking 20 records , but also if size of those 20 records are large it happens the same
the also next option i tried is my giving the parameter inside
Process myProcess = Process.Start(startInfo);
myProcess.WaitForExit(few seconds);
but it still doesnt work
Please suggest
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
This is the answer => what happen is when u start process , and wait for exit () both creates a deadlock somtimes which hammers the performance .. by adding readtoend() method before waitforexit() clears the deadlock and then continues further processing ...
this solves my problem.
The reason i am showing complete solution is that , wkhtmltopdf is very good for creating dynamic pdf files , but this is free tool as well and hence very limited documentation for this ..
private void ProcessHtmlToPdf(List<ExportToPdfCategories> lstExportToPdfCategories)
{
try
{
string pdfExportPath = string.Empty;
string PDFdeletePath = string.Empty;
string deletePath = string.Empty;
string PdfSavePath = string.Empty;
if (lstExportToPdfCategories != null)
{
foreach (var item in lstExportToPdfCategories)
{
path = "";
pdfExportPath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
PDFdeletePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString();
PdfSavePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
htmlpath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
deletePath = Server.MapPath(PDFdeletePath);
string ClearDirectory = Server.MapPath(PdfSavePath);
if (Directory.Exists(deletePath))
{
//Directory.Delete(ClearDirectory, true);
//Directory.Delete(deletePath, true);
}
if (!Directory.Exists(Server.MapPath(pdfExportPath)))
{
Directory.CreateDirectory(Server.MapPath(pdfExportPath));
}
string name =
pdfExportPath = pdfExportPath + "/" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-" + item.HeaderCategory + "_" + (drpYear.SelectedValue != "0" ? Convert.ToString(drpYear.SelectedValue) : System.DateTime.Now.Year.ToString()) + ".pdf";
objpath = Server.MapPath(pdfExportPath);
//this will create html mockup
//item.WebsiteUrl = CreateTemportHtmlFile(item.HeaderCategory, PdfSavePath, item.WebsiteUrl);
if (path == "")
{
path = CreateTemportHtmlFile(PdfSavePath, item.HeaderCategory);
}
HtmlToPdf(item.WebsiteUrl, objpath, path);
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-actusdocs.zip");
Response.ContentType = "application/zip";
objZip.Save(Response.OutputStream);
Response.End();
}
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("ProcessHtmlToPdf method : ", ex.Message + ex.StackTrace, objExpDetails);
}
}
//Method overloading
//this is for testing html pages(not in used during main running)
private string CreateTemportHtmlFile(string categoryName, string htmlMockupSavingPath, string websiteURL)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
htmlMockupSavingPath = Server.MapPath(htmlMockupSavingPath) + "\\" + categoryName + ".html";
StreamWriter sw;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(websiteURL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(htmlMockupSavingPath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(htmlMockupSavingPath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlMockupSavingPath;
}
private string CreateTemportHtmlFile(string PdfSavePath, string categoryName)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
PdfSavePath = Server.MapPath(PdfSavePath) + "\\BindHeader.html";
htmlpath = htmlpath.Substring(1);
htmlpath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + htmlpath + "/BindHeader.html";
string exportedYear = (drpYear.SelectedValue == "0" ? System.DateTime.Now.Year.ToString() : drpYear.SelectedValue);
StreamWriter sw;
if (categoryName == "MidYearAppraisal" || categoryName == "EndYearAppraisal")
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeaderforAppraisal.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
else
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeader.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(PdfSavePath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(PdfSavePath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlpath;
}
private void HtmlToPdf(string website, string destinationFile, string path)
{
try
{
string hrmlPath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + "/user/UserPdfReports/FooterPdfReports.html";
ProcessStartInfo startInfo = new ProcessStartInfo();
string switches = "";
switches += "--header-html " + path + " --footer-html " + hrmlPath;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
startInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
startInfo.Arguments = switches + " " + website + " " + destinationFile;
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("HtmlToPdf : ", ex.Message + ex.StackTrace, objExpDetails);
}
}

Java servlet - export to an excell using string buffer

I am new to JAVA. I am trying to export Excel through servlet from resultset.
When i am trying to store data in String buffer the it is not actually saving it.
Testfirst.java
String assingee_name = req.getParameter("firstName");
String track_name = req.getParameter("track");
String sla_id = req.getParameter("sla");
StringBuffer sb = new StringBuffer();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Databasethree");
stmt = con.createStatement();
//pw.println("'" +assingee_name + "'");
length = track_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where track =" + "'" + track_name + "'");
}
length = sla_id.length();
if (length > 0) {
//rs = stmt.executeQuery("SELECT* FROM casedetails where case_age >"+"'" +sla_id + "'");
rs = stmt.executeQuery("SELECT* FROM cdoscase where Incident_Submit_Fiscal_Year=" + "'" + sla_id + "'");
}
length = assingee_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where Assingee_name =" + "'" + assingee_name + "'");
}
pw.println("<html><body>");
pw.println("<H1> CDOS Case Management Version 1.1 </H1>");
pw.println("<Head><style>table,th,td{border:1px solid black;}</style></head>");
pw.println("<table>");
ResultSetMetaData rm = rs.getMetaData();
int clm = rm.getColumnCount();
StringBuffer sb1 = new StringBuffer();
String sb2 = new String();
for (int j = 1; j <= clm; j++) {
sb2 = rm.getColumnName(j);
pw.println("<th>");
pw.println(sb2);
pw.println("</th>");
}
ArrayList Rows = new ArrayList();
ArrayList row = new ArrayList();
Object a = new Object();
int jj = 0; // to find out the number rows
while (rs.next()) {
jj = jj + 1;
pw.println("<tr>");
for (int i = 1; i <= clm; i++) {
//data1[i]=rs.getString(i);
pw.println("<td>");
//pw.println(rs.getObject(i).toString());
pw.println(rs.getString(i));
pw.println("</td>");
sb2.append(rs.getString(i);
//row.add(rs.getString(i));
//sb2=sb2+rs.getObject(i).toString();
}
pw.println("</tr>");
} sb1.append("fd");
//Rows.add(row);
pw.println("Total Records found" + sb1);
pw.println("</table>");
//sb2=sb2+rs.getObject(clm).toString();
//sb1.append(sb2);
//sb1.append(sb2);
a = rs.getString(4).toString();
pw.println("this is data " + a);
pw.println("<p>");
pw.println("<td>Do you want to download report </td>");
req.setAttribute("data", Rows);
pw.println("<input type=\"submit\" name =\"submit1\" value=\"Export To Excel\">");
pw.println("</form>");
} catch (SQLException e) {
pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
pw.println(e.getException());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
pw.close();
}
}
}
Any help on this is highly appreciated.
Thanks,
SR

Exception Occurs While Opening a Downloaded Excel Sheet(.xls) In Asp.Net

I download an Excel Sheet by using the following code.
The above code is starting code of my logic.After downloaded, I open the Excel Sheet.It shows an Warning like this
Because of this warning,when Im trying to upload the same page to Mysql DataBase using Asp.Net.It shows an Exception like "Page is not in correct Format".
This Is My Entire Logic For Downloading an Excel Sheet
protected void download_Click(object sender, EventArgs e)
{
ExportToExcel(SqlDataSource1, "StudentMarks");
}
public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
//Add Response header
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/ms-excel";
//GET Data From Database
MySqlConnection cn = new MySqlConnection(dataSrc.ConnectionString);
// string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
MySqlCommand cmd9 = new MySqlCommand("select subject from class_subject where standard='" + DropDownList1.SelectedItem.Value + "';", cn);
// cn.Open();
//DataSet ds9=new DataSet();
MySqlDataAdapter da9 = new MySqlDataAdapter(cmd9);
// da9.Fill(ds9);
DataTable dt = new DataTable();
da9.Fill(dt);
StringBuilder sb9 = new StringBuilder();
for (int count = 0; count < dt.Rows.Count; count++)
{
// string headerRowText = GridView4.HeaderRow.Cells[i].Text;
sb9.Append("'");
sb9.Append(dt.Rows[count][0].ToString());
sb9.Append("'");
if (count < dt.Rows.Count - 1)
//if (count < count3 - 1)
{
sb9.Append(",");
}
}
Label2.Text = sb9.ToString();
//MySqlCommand fyearcmd = new MySqlCommand("select fyear from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and completed_status='running';", cn);
//MySqlDataReader fyeardr = fyearcmd.ExecuteReader();
string query = "select Admission_Num,Name,'Standard','Fyear','Type_of_exam'," + sb9.ToString() + " from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and fyear='" + DropDownList4.SelectedItem.Value + "';";
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandTimeout = 999999;
cmd.CommandType = CommandType.Text;
try
{
cn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
//Session["fieldcount"] = dr.FieldCount.ToString();
//Label1.Text = dr.FieldCount.ToString();
//Add Header
int count3 = 4;
for (int count = 0; count < dr.FieldCount; count++)
//for (int count = 0; count < count3; count++)
{
if (dr.GetName(count) != null)
sb.Append(dr.GetName(count));
if (count < dr.FieldCount - 1)
//if (count < count3 - 1)
{
sb.Append("\t");
}
}
Response.Write(sb.ToString() + "\n");
Response.Flush();
//Append Data
while (dr.Read())
{
sb = new StringBuilder();
//for (int col = 0; col < dr.FieldCount - 1; col++)
for (int col = 0; col <= count3; col++)
{
if (col < (count3 - 2))
{
if (!dr.IsDBNull(col))
sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append("\t");
}
if (col == (count3 - 2))
{
if (!dr.IsDBNull(col))
sb.Append(DropDownList1.SelectedItem.Text);
sb.Append("\t");
}
if (col == (count3 - 1))
{
if (!dr.IsDBNull(col))
{
//sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(DropDownList4.SelectedItem.Text);
}
sb.Append("\t");
}
if (col == count3)
{
if (!dr.IsDBNull(col))
{
//sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(DropDownList3.SelectedItem.Text);
}
sb.Append("\t");
}
}
//if (!dr.IsDBNull(dr.FieldCount - 1))
// sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
Response.Write(sb.ToString() + "\n");
Response.Flush();
}
dr.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cmd.Connection.Close();
cn.Close();
}
Response.End();
}
So Please give me the suggestion how to download the Excel Sheet with out showing errors while opening.
You you are generating a csv file, not a excel file. Try to change you header:
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
Normally excel is default for opening csv files.

Devexpress MessageBox is closing automatically

I have a Devexpress form which is having Progress bar and MessageBox.
When i click search button on my form,the progress bar displays percentage and then grid will be bind with records.
and when it returns no records, message box will appear after progress bar like "No Records Found"
but after showing No records found,it is closing automatically with out clicking OK or CANCEL button on messagebox
Code for Progress Bar
namespace DMS
{
public partial class ProgressBar : WaitForm
{
public ProgressBar()
{
InitializeComponent();
}
#region Overrides
public override void SetCaption(string caption)
{
base.SetCaption(caption);
this.progressPanel1.Caption = caption;
}
public override void SetDescription(string description)
{
base.SetDescription(description);
this.progressPanel1.Description = description;
}
public override void ProcessCommand(Enum cmd, object arg)
{
base.ProcessCommand(cmd, arg);
}
#endregion
private void progressBarControl1_EditValueChanged(object sender, EventArgs e)
{
try
{
int i = int.Parse(Math.Floor(double.Parse(this.progressBarControl1.EditValue.ToString())).ToString());
if (i.ToString().EndsWith("0"))
{
//satya
//i += 5;
i += 0;
}
this.Opacity = 100;
SetCaption("Please Wait...");
SetDescription(i.ToString() + "% Completed...");
Application.DoEvents();
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString() + " " + ex.Source.ToString());
}
}
}
}
Code for Showing Message Box
private void btnshow_Click(object sender, EventArgs e)
{
try
{
if (dtstartdate.DateTime.Date > dtEnddate.DateTime.Date)
{
XtraMessageBox.Show("Start date should be less than End date", Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
dtstartdate.Focus();
return;
}
string CommandText = "select * from DMS_View_Payments where v_Paymentdate between '" + General.DateToDatabase(this.dtstartdate.DateTime.ToShortDateString())
+ "' and '" + General.DateToDatabase(this.dtEnddate.DateTime.ToShortDateString()) + "'";
if (ccbeForClient.EditValue.ToString() != string.Empty)
{
CommandText += " and v_clientid in (" + this.ccbeForClient.EditValue.ToString() + ")";
}
else if (Logs.UserLimitedClients != "0")
{
CommandText += " and v_clientid in (" + Logs.UserLimitedClients + ")";
}
if (ccbeForBatch.Text.Trim() != "" && ccbeForBatch.Text.Trim() != "--")
{
string selected_client_list = "";
if (ccbeForBatch.Text.Trim() != "" && ccbeForBatch.Text.Trim() != "--")
{
//selected_client_list = ccbe_client_list.Text.Replace(" ", "").Replace(",", "','");
string source = ccbeForBatch.Text;
string[] split = source.Split(',');
string changed = "";
for (int i = 0; i < split.Length; i++)
{
changed += "," + split[i].Trim();
}
//string output = changed.Trim(',').Replace(",", "','");
selected_client_list = changed.Trim(',').Replace(",", "','");
}
else
{
selected_client_list = "";
}
CommandText += " and v_Batch in ('" + selected_client_list + "') ";
}
if (ccbeForBranch.EditValue.ToString() != string.Empty)
{
CommandText += " and v_BRANCH_ID in (" + ccbeForBranch.EditValue.ToString() + ")";
}
if (ccbeForCollector.EditValue.ToString() != string.Empty)
{
CommandText += " and V_CollectorId in (" + ccbeForCollector.EditValue.ToString() + ")";
}
else if (DevXCharts.EmpIdsForHierarchey != "")
{
CommandText += " and V_CollectorId in (" + DevXCharts.EmpIdsForHierarchey.ToString() + ")";
}
if (ccbeForAccountType.Text.Trim() != "" && ccbeForAccountType.Text.Trim() != "--")
{
string selected_client_list = "";
if (ccbeForAccountType.Text.Trim() != "" && ccbeForAccountType.Text.Trim() != "--")
{
//selected_client_list = ccbe_client_list.Text.Replace(" ", "").Replace(",", "','");
string source = ccbeForAccountType.Text;
string[] split = source.Split(',');
string changed = "";
for (int i = 0; i < split.Length; i++)
{
changed += "," + split[i].Trim();
}
//string output = changed.Trim(',').Replace(",", "','");
selected_client_list = changed.Trim(',').Replace(",", "','");
}
else
{
selected_client_list = "";
}
CommandText += " and v_AccountType in ('" + selected_client_list + "') ";
}
if (radioPayment.SelectedIndex == 0)
{
CommandText += " and v_Confirmed='Y'";
}
else if (radioPayment.SelectedIndex == 1)
{
CommandText += " and v_Confirmed='N'";
}
if (radioCases.SelectedIndex == 0)
{
CommandText += " and v_flagabort='0'";
}
else if (radioCases.SelectedIndex == 1)
{
CommandText += " and v_flagabort='1'";
}
CommandText += " order by v_debtorname";
Application.DoEvents();
if (objPB != null)
{
objPB.Close();
objPB = null;
}
objPB = new ProgressBar();
objPB.StartPosition = FormStartPosition.CenterScreen;
objPB.progressBarControl1.EditValue = 20;
objPB.TopMost = true;
objPB.ShowInTaskbar = false;
Application.DoEvents();
objPB.Show();
Application.DoEvents();
SqlDataAdapter sql_for_debtors = new SqlDataAdapter(CommandText, DBConString.ConnectionString());
DataSet ds_for_rhb = new DataSet();
sql_for_debtors.SelectCommand.CommandTimeout = 0;
sql_for_debtors.Fill(ds_for_rhb, "DMS_View_Payments");
sql_for_debtors.Dispose();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 40;
Application.DoEvents();
if (ds_for_rhb.Tables["DMS_View_Payments"].Rows.Count > 0)
{
XrtPaymentsDevx obj_report = new XrtPaymentsDevx();
obj_report.xrlReportHeader.Text = "Payments From " + this.dtstartdate.DateTime.ToString("dd/MM/yyyy") + " To " + this.dtEnddate.DateTime.ToString("dd/MM/yyyy");
string SelectionCriteria = "";
if (this.ccbeForClient.Text != "" && this.ccbeForClient.Text != "--")
{
SelectionCriteria += " Client: " + this.ccbeForClient.Text + " , ";
}
if (this.ccbeForBatch.Text != "" && this.ccbeForBatch.Text != "--")
{
SelectionCriteria += " Batch: " + this.ccbeForBatch.Text + " , ";
}
if (this.ccbeForBranch.Text != "" && this.ccbeForBranch.Text != "--")
{
SelectionCriteria += " Branch: " + this.ccbeForBranch.Text + " , ";
}
if (this.ccbeForCollector.Text != "" && this.ccbeForCollector.Text != "--")
{
SelectionCriteria += " Collector: " + this.ccbeForCollector.Text + " , ";
}
if (this.ccbeForAccountType.Text != "" && this.ccbeForAccountType.Text != "--")
{
SelectionCriteria += " AccType: " + this.ccbeForAccountType.Text + " , ";
}
if (radioPayment.SelectedIndex == 0)
{
SelectionCriteria += " Payment Confirmed='Y'" + " , ";
}
else if (radioPayment.SelectedIndex == 1)
{
SelectionCriteria += " Payment Confirmed='N'" + " , ";
}
else if (radioPayment.SelectedIndex == 2)
{
SelectionCriteria += " Payment Confirmed='Y' And 'N'" + " , ";
}
if (radioCases.SelectedIndex == 1)
{
SelectionCriteria += " Abort Cases" + " , ";
}
else if (radioCases.SelectedIndex == 0)
{
SelectionCriteria += " Active Cases" + " , ";
}
else if (radioCases.SelectedIndex == 2)
{
SelectionCriteria += " Both Active And Abort Cases" + " , ";
}
obj_report.xrlSelectionCriteria.Text = SelectionCriteria;
obj_report.DataSource = ds_for_rhb;
obj_report.DataMember = "DMS_View_Payments";
Application.DoEvents();
objPB.progressBarControl1.EditValue = 60;
Application.DoEvents();
obj_report.CreateDataBindings();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 80;
Application.DoEvents();
//obj_report.bind_data();
obj_report.ShowPreview();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 90;
Application.DoEvents();
Application.DoEvents();
objPB.progressBarControl1.EditValue = 100;
Application.DoEvents();
objPB.Close();
Application.DoEvents();
}
else
{
XtraMessageBox.Show("No Records(s) Found", Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
objPB.progressBarControl1.EditValue = 100;
//objPB.progressBarControl1.EditValue = 100;
Application.DoEvents();
objPB.Close();
//Application.DoEvents();
//objPB.progressBarControl1.EditValue = 100;
//Application.DoEvents();
//objPB.Close();
//XtraMessageBox.Show("No Records(s) Found", Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString() + " " + ex.Source.ToString(), Program.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The reason of the issue is incorrect usage of WaitForm instance.
You should'not show/hide the WaitForm directly rather then use the SplashScreenManager API to show/hide and interact with WaitForm.
Here i'll try to get you correct approach:
At first, the code for running search operation with WaitForm showing should looks like this:
void OnRunSearchOperation_ButtonClick(object sender, EventArgs e) {
bool success = false;
SplashScreenManager.ShowForm(this, typeof(ProgressWaitForm), false, false);
try {
// here you can run some long time operations
success = SearchOperation();
}
finally { SplashScreenManager.CloseForm(); }
if(!success) {
XtraMessageBox.Show(this, "No entries found");
}
}
bool SearchOperation() {
// THIS IS SEARCH OPERATION IMITATION
const int count = 70000000;
int stepThreshold = count / 100;
decimal dec = 1.41M;
for(int i = 0; i < count; i++) {
dec /= 2;
if((i % stepThreshold) == 0)
SplashScreenManager.Default.SendCommand(WaitFormCommand.PerformStep, null);
}
return false; // result
}
Here are the WaitFormCommand and 'ProgressWaitForm' implementation:
public enum WaitFormCommand {
PerformStep
}
public partial class ProgressWaitForm : WaitForm {
public ProgressWaitForm() {
InitializeComponent();
}
#region Overrides
public override void ProcessCommand(Enum cmd, object arg) {
base.ProcessCommand(cmd, arg);
WaitFormCommand wfCmd = (WaitFormCommand)cmd;
if(wfCmd == WaitFormCommand.PerformStep)
progressBarControl1.PerformStep();
}
#endregion
}

Resources