Problem in Application_Error in Global.asax - asp.net

my problem is User.Identity.Name or Request.Url.AbsoluteUri in exception handling is empty when exception email to me.
this is Application_Code:
void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/errors/default.aspx");
}
and this is default.aspx code:
protected void Page_Load(object sender, EventArgs e)
{
if (Server.GetLastError() == null)
return;
Exception ex = Server.GetLastError().GetBaseException();
if (ex == null)
return;
string message = string.Format("User: ", User.Identity.Name);
message += Environment.NewLine;
message += string.Format("AbsoluteUri: ", Request.Url.AbsoluteUri);
message += Environment.NewLine;
message += string.Format("Form: ", Request.Form.ToString());
message += Environment.NewLine;
message += string.Format("QueryString: ", Request.QueryString.ToString());
message += Environment.NewLine;
but i receive email like this (this is header without full exception content):
User:
AbsoluteUri:
Form:
QueryString:
Browser Capabilities:
Type = IE8
Name = IE
Version = 8.0
Platform = WinXP
Is Crawler = False
Supports Cookies = True
Supports JavaScript = 1.2
why username and request url is emty?
this problem is exist when i replace transfer with redirect or i don't use both.
tanx

You do not have set the string.Format in the correct way
Try this.
string.Format("AbsoluteUri: {0}", Request.Url.AbsoluteUri);
How ever I suggest to use StringBuilder for this code.

Related

IsPostBack doesn't work in ASP.NET

I want that when the page is first loaded , the string str is initialized with the text "I am here". And when the page is updated by clicking on the button (btn_click) the value is the same that was initialized. But it does not work. In the console I reads:
First time I load the page: "I ​​am here"
1.When I click on the button: "empty"
2.And I think we should keep this value: "I am here". Please help.
public partial class Default : System.Web.UI.Page
{
string str = "empty";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
str = "I am here";
Debug.Write("VALUE: " + str + "\r\n");
}
else
{
Debug.Write("VALUE: " + str + "\r\n");
}
}
protected void btn_Click(object sender, EventArgs e)
{
//do something...
}
}
Each individual request to the server creates a new instance of the page... both the very first request (IsPostBack==false) and all subsequent requests (IsPostBack==true).
This means that your str variable is initialised with "empty" every time you request the page, but only ever set to "I am here" on the first load (i.e. the IsPostBack==false). You need to store it somehow so that when the post-back occurs you still have it.
There are several ways, including using the Session object, but I would suggest using the ViewState like this...
string str = "empty";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
str = "I am here";
ViewState["str"] = str;
Debug.Write("VALUE: " + str + "\r\n");
}
else
{
str = (string)ViewState["str"];
Debug.Write("VALUE: " + str + "\r\n");
}
}

is Application_Error declaration in global.asax file common for all logged in user?

in my application i am using Application_Error to logged the application user.
but in my code on error i am registering error in error log system and redirecting user on error page.
now if there are multiple users then will it affect to all logged in user ?
also i am saving values in Application["ErrorDetails"]
will this cause problem to all users ?
below is code
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
StringBuilder sb = new StringBuilder();
sb.Append("Error Caught in Application_Error event" + Environment.NewLine);
sb.Append("Error Message:" + objErr.Message.ToString() + Environment.NewLine);
sb.Append("Stack Trace:" + objErr.StackTrace.ToString() + Environment.NewLine);
sb.Append(Environment.NewLine);
log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Global));
logger.Error(sb.ToString());
Exception ex = Server.GetLastError();
if (ex is ThreadAbortException)
{
Server.ClearError();
return;
}
Server.ClearError();
Application["ErrorDetails"] = sb.ToString();
// redirect to the error page
HttpCookie SMTPCookies = new HttpCookie("ErrorDetails");
Response.Cookies["ErrorDetails"]["ErrorUrl"] = Request.Url.ToString();
Response.Cookies["ErrorDetails"]["Message"] = objErr.Message.ToString();
Response.Cookies["ErrorDetails"]["StackTrace"] = objErr.StackTrace.ToString();
Response.Cookies["ErrorDetails"].Expires = DateTime.Now.AddSeconds(60);
Response.Redirect("~/pages/ErrorPage.aspx");
}
Correct, storing a variable in the Application object is not thread safe. If 2 users quickly have an error, the Application["ErrorDetails"] variable may have changed by the time the 1st user loads your "ErrorPage.aspx".

response write inside global asax

this example dosent work for me ,I tried Response.write but I am getting nothing.
here is the sample
(is it also possiable come up a pop up window tell the error detail")
protected void Application_Error(object sender, EventArgs e)
{
// At this point we have information about the error
HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError ();
string errorInfo =
"<br>Offending URL: " + ctx.Request.Url.ToString () +
"<br>Source: " + exception.Source +
"<br>Message: " + exception.Message +
"<br>Stack trace: " + exception.StackTrace;
ctx.Response.Write (errorInfo);
ctx.Server.ClearError ();
}
Method signature of an event that is fired when an unhandled exception is encountered within the application in Global.asax is:
void Application_Error(object sender, EventArgs e)
{
// your code...
}

implementation of customized application_end method in asp.net

I want to have a method which gets executed when session expires or user logs out or user closes the web application. How can i catch these events in asp.net and execute a method ?
I'm building a web app in vs 2008/asp.net/c#.
Please help me.
Thanks in anticipation
use Global.asax file
Refer the link to use Global.asax file http://www.dotnetcurry.com/ShowArticle.aspx?ID=126
Right click on The solution and the Add new item the Add Global.asax in the solution Then after
which have the following Event
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
//Utils.LoadExtensions();
}
void Application_End(object sender, EventArgs e)
{
ClsCollege ObjClsColledge = new ClsCollege();
ObjClsColledge.TruncateAllUserDetails(Session["UserSessionId"].ToString());
ObjClsColledge.TruncateAllUserDetailsPrefrance(Session["UserSessionId"].ToString());
}
void Application_Error(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
Exception ex = context.Server.GetLastError();
if (ex == null || !(ex is HttpException) || (ex as HttpException).GetHttpCode() == 404)
{
return;
}
StringBuilder sb = new StringBuilder();
try
{
sb.AppendLine("Url : " + context.Request.Url);
sb.AppendLine("Raw Url : " + context.Request.RawUrl);
while (ex != null)
{
sb.AppendLine("Message : " + ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("TargetSite : " + ex.TargetSite);
ex = ex.InnerException;
}
}
catch (Exception ex2)
{
sb.AppendLine("Error logging error : " + ex2.Message);
}
if (BlogSettings.Instance.EnableErrorLogging)
{
Utils.Log(sb.ToString());
}
context.Items["LastErrorDetails"] = sb.ToString();
context.Response.StatusCode = 500;
//// Custom errors section defined in the Web.config, will rewrite (not redirect)
//// this 500 error request to error.aspx.
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
ClsCollege ObjClsColledge = new ClsCollege();
ObjClsColledge.TruncateAllUserDetails(Session["UserSessionId"].ToString());
ObjClsColledge.TruncateAllUserDetailsPrefrance(Session["UserSessionId"].ToString());
}
</script>
The Event Session_start(),Session_End() and Application_End() you will able to track the
Event.

SmtpClient.SendAsync bug in ASP.NET 2.0

I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.
To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.
Note that you should set Page.Async = true to use SendAsync.
If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.
TIA.
Note that you should set Page.Async = true to use SendAsync.
Please explain the rationale behind this. Misunderstanding what Page.Async does may be the cause of your problems.
Sorry, I was unable to get an example working that reproduced the problem.
See http://msdn.microsoft.com/en-us/magazine/cc163725.aspx (WICKED CODE: Asynchronous Pages in ASP.NET 2.0)
EDIT: Looking at your code example, I can see that you're not using RegisterAsyncTask() and the PageAsyncTask class. I think you must do this when executing asynchronous tasks on a Page where #Async is set to true. The example from MSDN Magazine looks like this:
protected void Page_Load(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
null
);
RegisterAsyncTask(task);
}
Inside BeginAsyncOperation, then, should you send a mail asynchronously.
RegisterAsyncTask could not be used.
Look at the BeginEventHandler delegate:
public delegate IAsyncResult BeginEventHandler(
Object sender,
EventArgs e,
AsyncCallback cb,
Object extraData
)
It should return an IAsyncResult.
Now look at the SmtpClient.SendAsync function :
public void SendAsync(
MailMessage message,
Object userToken
)
There is no return value.
Anyway this is working fine, as long as SmtpClient.SendAsync does not throw an exception.
Here is mine. Give it a try.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Using an incorrect SMTP server
SmtpClient client = new SmtpClient(#"smtp.nowhere.private");
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
MailAddress from = new MailAddress("someone#somewhere.com",
"SOMEONE" + (char)0xD8 + " SOMEWHERE",
System.Text.Encoding.UTF8);
// Set destinations for the e-mail message.
MailAddress to = new MailAddress("someone#somewhere.com");
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Set the method that is called back when the send operation ends.
client.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, the userToken is a string constant.
string userState = "test message1";
try
{
client.SendAsync(message, userState);
}
catch (System.Net.Mail.SmtpException ex)
{
Response.Write(string.Format("Send Error [{0}].", ex.InnerException.Message));
}
finally
{
}
}
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
Response.Write(string.Format("[{0}] Send canceled.", token));
}
if (e.Error != null)
{
Response.Write(string.Format("[{0}] {1}", token, e.Error.ToString()));
}
else
{
Response.Write("Message sent.");
}
}
}

Resources