Friday, May 24, 2024
How to convert datatable to excel in ASP.NET C#
protected void ExportToExcel()
{
DataTable dt = new DataTable();
if (!String.IsNullOrEmpty(txtFromDate.Text))
{
FromDate = txtFromDate.Text;
}
if (!String.IsNullOrEmpty(txtToDate.Text))
{
ToDate = txtToDate.Text;
}
//if (!String.IsNullOrEmpty(txtDateOfJournery.Text))
//{
// ReuestDate = txtDateOfJournery.Text;
//}
//if (ddlStatus.SelectedIndex > 0)
//{
StatusId = Convert.ToInt32(ddlStatus.SelectedValue);
//}
dt = GuestHouseBAL.GuestHouseBALInstance.GetGHBookingExportToExelReport(FromDate, ToDate, StatusId);
if(dt.Rows.Count > 0)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GuestHouseReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView GridView1 = new GridView();
//To Export all pages
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
string reason = "";
// GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
//row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('No Record Found...');", true);
}
}
also add this if error occured
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Calling a function in javascript anchor tag
<a class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" style="cursor: pointer" onclick="showCaseProfile(\'' + value.FileNumber + '\');">' + value.FileNumber + '</a>
Logging in ASP.NET - Create Logs on ASP.NET
public static void LogInfoToTextFile(string message)
{
bool CreateLog = false;
if (ConfigurationManager.AppSettings["CreateLog"] != null)
{
CreateLog = Convert.ToBoolean(ConfigurationManager.AppSettings["CreateLog"]); //"CreateLog";
}
if (CreateLog)
{
string servicesPath = System.AppDomain.CurrentDomain.BaseDirectory + "/Log";
servicesPath += "/LogFile";
if (!Directory.Exists(servicesPath))
{
Directory.CreateDirectory(servicesPath);
}
var files = new DirectoryInfo(servicesPath).GetFiles("*.txt");
foreach (var file in files)
{
if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(10))
{
File.Delete(file.FullName);
}
}
string filepath = servicesPath + "/";
string fileName = DateTime.Now.Year + DateTime.Now.Month.ToString() + DateTime.Now.Day;
fileName = filepath + fileName + ".txt";
StreamWriter objwriter = new StreamWriter(fileName, true);
objwriter.Write(Environment.NewLine + "" + message);
objwriter.Close();
}
}
public static void LogInfoToTextFile_New(string message)
{
//Komal14486 : 10/11/2019 - Adding log to check the flow
bool CreateLog = true;
if (ConfigurationManager.AppSettings["CreateLog"] != null)
{
CreateLog = Convert.ToBoolean(ConfigurationManager.AppSettings["CreateLog"]); //"CreateLog";
}
if (CreateLog)
{
string servicesPath = System.AppDomain.CurrentDomain.BaseDirectory + "/Log_New";
servicesPath += "/LogFile";
if (!Directory.Exists(servicesPath))
{
Directory.CreateDirectory(servicesPath);
}
var files = new DirectoryInfo(servicesPath).GetFiles("*.txt");
foreach (var file in files)
{
if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(10))
{
File.Delete(file.FullName);
}
}
string filepath = servicesPath + "/";
string fileName = DateTime.Now.Year + DateTime.Now.Month.ToString() + DateTime.Now.Day;
fileName = filepath + fileName + ".txt";
using (StreamWriter objwriter = new StreamWriter(fileName, true))
{
objwriter.Write(Environment.NewLine + "" + message);
objwriter.Close();
};
}
}
========================================
Call it in Catch
catch (Exception ex)
{
PageUtils.LogInfoToTextFile(string.Format("While fetching data in the method LoadZoneList() in the page CMSReport.aspx.cs:{0} - {1} ", ex.Message, DateTime.Now));
//PageUtils.LogInfoToTextFile(ex.Message);
//ProcessException(ex);
}
==========================================
Using elmah
public void ProcessException(Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
var errorMessage = new StringBuilder();
errorMessage.Append(Environment.NewLine + "DateTime : " + DateTime.Now + Environment.NewLine);
//errorMessage.Append("User : " + userId + Environment.NewLine);
//errorMessage.Append("Class Name : " + className + Environment.NewLine);
//errorMessage.Append("Method Name : " + methodName + Environment.NewLine);
errorMessage.Append("Error Message : " + ex.Message + Environment.NewLine);
errorMessage.Append("Stack Trace : " + ex.StackTrace + Environment.NewLine);
errorMessage.Append("Inner Exception : " + ex.InnerException + Environment.NewLine);
Logger.Write(errorMessage.ToString());
SetErrorMesssage(ex.Message.ToString());
LoggingDTO loggingDTO = new LoggingDTO();
var objUserInfo = new UserInfo();
if (HttpContext.Current.Session[Constants.UserInformation] != null)
{
objUserInfo = (UserInfo)HttpContext.Current.Session[Constants.UserInformation];
loggingDTO.UserId = objUserInfo.UserId;
loggingDTO.RoleId = objUserInfo.RoleMasterId;
loggingDTO.OfficeId = objUserInfo.OfficeId;
loggingDTO.IpAddress = System.Web.HttpContext.Current.Request.UserHostAddress == null ? "" : System.Web.HttpContext.Current.Request.UserHostAddress.ToString();
}
loggingDTO.LoggingType = 2;
loggingDTO.ControlId = Convert.ToString(ex.Message);
loggingDTO.PageName = Convert.ToString(ex.StackTrace);
loggingDTO.ControlName = Convert.ToString(ex.InnerException);
loggingDTO.CreatedDate = DateTime.Now;
using (var client = ServiceClient<IMasterManager>.Create(ObjectConstants.MasterManager))
{
client.Instance.SaveLogging(loggingDTO);
}
//HttpContext.Current.Response.Redirect("/ErrorPage.aspx");
// Navigate to the error page
}
=====================================
catch (Exception ex)
{
ProcessException(ex);
}
Wednesday, May 22, 2024
String.Format in ASP.NET with {0}, {1}
string.Format("While fetching data in the method in the page CMSReport.aspx.cs:{0} - {1} ", ex.Message, DateTime.Now)
Jquery ajax - ASP.NET when exception occur in asp.net
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
and when method not found, than it will gone to error or any function not called by ajax call.
$.ajax({
type: "POST",
data: formData,
url: "/Forms/GetJobData",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
},
error: function (response) { // // Added this event to capture the failed requests.
alert("error!"); //
}
});
ref:- https://stackoverflow.com/questions/37187699/ajax-error-is-returned-as-success