sugestions on global error handler to get dump of diagnostic data - asp.net

there are loads of resources that show how to use global.ascx global error event handler to capture un-managed errors in the web application but i am yet to find a good sample of code to include in this method that will report on major topics like error message, an output of stack trace, page that generated the error, the user-name/ role that generated the error... and the such.
has anyone used, have, or come across a nice code spinet for this purpose?
thanks in advance.

Your best best it to do nothing. ASP.NET Health Monitoring will write an event to the event log containing most of the data you could need.
If that's not enough information for you, then you should look into wrapping certain of your exceptions in an outer exception which includes the additional data. For instance:
string fileSpec = " ... ";
try
{
using (var stream = new FileStream(fileSpec))
{
// Something
}
}
catch (IOException ex)
{
throw new Exception(String.Format("Error processing {0}", fileSpec), ex);
}

Here's what we're using though we may now want to switch to Health Monitoring seeing the other answers to this question.
public static void LogErrorWithStackTrace(String message, Exception exception,
EventLogEntryType entryType)
{
var context = HttpContext.Current;
var session = context.Session;
var request = context.Request;
var errorMessage =
String.Format(
#"Message: {0}
Error in: {1}
Referer: {2}
Agent: {3}
IP: {4}
Request type: {5}",
message, request.Url, request.UrlReferrer,
request.UserAgent, request.UserHostAddress, request.RequestType);
errorMessage += "\rQuery string variables:";
errorMessage = request.QueryString.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current +
"\r " + key + " = " +
request.QueryString[
key]);
errorMessage += "\rForm variables:";
errorMessage = request.Form.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current + "\r " + key +
" = " +
request.Form[key]);
errorMessage += "\rCookies:";
errorMessage = request.Cookies.Keys.Cast<string>().Aggregate(errorMessage,
(current, key) =>
current + "\r " + key +
" = " +
request.Cookies[key]);
if (session != null)
{
errorMessage += "\rISession:";
var sess = (ISession) session["session"];
errorMessage += sess.ToString();
errorMessage += "\rSession:";
errorMessage = session.Keys.Cast<string>().Aggregate(errorMessage,
(current, sessionKey) =>
current +
"\r " + sessionKey + ": " +
session[sessionKey]);
}
errorMessage += "\rStack Trace:";
errorMessage += exception.StackTrace;
WriteEntry(errorMessage, entryType);
if (!QuietTypes.Contains(exception.GetType()))
SendExceptionEmail(errorMessage);
}

This is some VB code we use, it provides enougth info for us to diagnose most problems. Only downside with emailing errors like this is when there is a major failure you can end up with thousands of messages in your mailbox :(
Dim e As Exception
If System.Web.HttpContext.Current.Request.IsLocal Then Exit Sub
e = System.Web.HttpContext.Current.Server.GetLastError
If e IsNot Nothing Then
If TypeOf e Is HttpException Then
Dim he As HttpException = DirectCast(e, HttpException)
If he.GetHttpCode=404 Then
System.Web.HttpContext.Current.Server.ClearError()
Response.Redirect("/")
Exit Sub
End If
End If
MsgBody += "Exception: " & e.Message & vbCrLf & vbCrLf
MsgBody += e.ToString & vbCrLf & vbCrLf & vbCrLf
Else
MsgBody += "Unknown Error" & vbCrLf & vbCrLf & vbCrLf
End If
If System.Web.HttpContext.Current.Request.Url Is Nothing Then
MsgBody += "URL: ?" & vbCrLf & vbCrLf
Else
MsgBody += "URL: " & System.Web.HttpContext.Current.Request.Url.ToString & vbCrLf
If System.Web.HttpContext.Current.Request.RawUrl IsNot Nothing Then MsgBody += System.Web.HttpContext.Current.Request.RawUrl & vbCrLf
MsgBody += vbCrLf
End If
If System.Web.HttpContext.Current.Request.UrlReferrer Is Nothing Then
MsgBody += "Referer: <direct>" & vbCrLf & vbCrLf
Else
MsgBody += "Referer: " & System.Web.HttpContext.Current.Request.UrlReferrer.ToString() & vbCrLf & vbCrLf
End If
If User IsNot Nothing Then MsgBody += "User: " & User.Identity.Name & vbCrLf
MsgBody += "User-Agent: " & System.Web.HttpContext.Current.Request.UserAgent & vbCrLf
MsgBody += "User-IP: " & System.Web.HttpContext.Current.Request.UserHostAddress & vbCrLf
MsgBody += "Server: " & System.Environment.MachineName & vbCrLf
MsgBody += vbCrLf & "RequestType: " & System.Web.HttpContext.Current.Request.RequestType() & vbCrLf & vbCrLf
' dump request items
' QueryString, Form, Cookies, ServerVariables
MsgBody += "Querystring Variables ================" & vbCrLf
If Request.QueryString.Count > 0 Then
For Each key As String In Request.QueryString.Keys
MsgBody += key & " = " & Request.QueryString(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "Form Variables =======================" & vbCrLf
If Request.Form.Count > 0 Then
For Each key As String In Request.Form.Keys
MsgBody += key & " = " & Request.Form(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "Cookies ==============================" & vbCrLf
If Request.Cookies.Count > 0 Then
For Each key As String In Request.Cookies.Keys
MsgBody += key & " = " & Request.Cookies(key).Value & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
MsgBody += "ServerVariables ======================" & vbCrLf
If Request.ServerVariables.Count > 0 Then
For Each key As String In Request.ServerVariables.Keys
MsgBody += key & " = " & Request.ServerVariables(key) & vbCrLf
Next
Else
MsgBody += "(none)" & vbCrLf
End If
MsgBody += vbCrLf
' we send MsgBody via email using the System.Net.Mail.MailMessage & System.Net.Mail.SmtpClient classes
' we've handled the error
System.Web.HttpContext.Current.Server.ClearError()
' depending on the error we redirect to our homepage /default.aspx unless that is the faulting page then redirect to static /error.html

Related

How to create a JSON string in Visual Basic using json.net?

I'm using json.net to parse a JSON text. I got a JObject now:
Dim json_text As String
json_text = "{" & Chr(34) & "Venue" & Chr(34) & ": {" & Chr(34) & "ID" & Chr(34) & ":" & Chr(34) & "JSON" & Chr(34) & "}}"
Console.WriteLine(json_text)
Dim json As JObject
json = JObject.Parse(json_text)
Console.WriteLine(json.SelectToken("Venue").SelectToken("ID"))
Now I want to do the opposite and create a JSON text from the JSON variable.
Unfortunately, I cannot find any solution out there.
Imports Newtonsoft.Json.Linq
Imports Newtonsoft.Json
Dim json_text As String
json_text = "{" & Chr(34) & "Venue" & Chr(34) & ": {" & Chr(34) & "ID" & Chr(34) & ":" & Chr(34) & "JSON" & Chr(34) & "}}"
Console.WriteLine(json_text)
Dim json As JObject
json = JObject.Parse(json_text)
Console.WriteLine(json.SelectToken("Venue").SelectToken("ID"))
Dim json_string As String = JsonConvert.SerializeObject(json,
Formatting.Indented, New JsonSerializerSettings())
Console.WriteLine(json_string)
This results in:
{"Venue": {"ID":"JSON"}}
JSON
{
"Venue": {
"ID": "JSON"
}
}

asp.net paypal integration query-string encryption

I need some help and concept of PayPal payment integration. I have following to send order / payment data to PayPal:
Dim sString As String
sString = "https://www.paypal.com/cgi-bin/webscr?"
sString += "cmd=_xclick"
sString += "&business=" & BusinessEmail
sString += "&email=" & UserEmail
sString += "&address_override=1"
sString += "&currency_code=" & CurrencyCode
sString += "&invoice=" & InvoiceNumber
sString += "&item_name=" & PlanName
sString += "&item_number=" & ItemNumber
sString += "&quantity=1"
sString += "&amount=" & TotalAmount
sString += "&handling=0"
sString += "&display=1"
sString += "&first_name=" & Firstname
sString += "&last_name=" & LastName
sString += "&address1=" & AddressLine1
sString += "&address2=" & AddressLine2
sString += "&city=" & CityTitle
sString += "&state=" & State
sString += "&zip=" & Postcode
sString += "&lc=" & CountryISO
sString+= "&notify_url=" & notify_url
Response.Redirect(sString)
This is working OK but as it is passing as query-string it reveals all parameters, is there anyway I can encrypt this?
Can anyone suggest a better way to integrate PayPal?
How can I get payment confirmation?
Many thanks for help
is there anyway I can encrypt this?
You should encrypt the query string, but PayPal URL is https so it is protected.
Can anyone suggest a better way to integrate PayPal?
You need default protocol to be TLS 1.2 due to PayPal requirement. I also would like to suggest you to use StringBuilder.
StringBuilder builder = new StringBuilder();
builder.Append("https://www.paypal.com/cgi-bin/webscr?");
....
// PayPal requires TLS 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Response.Redirect(builder.ToString());
How can I get payment confirmation?
PayPal will send confirmation email to you after the payment is received.

User Control code keep calling repetedly

I have created a user control and registered inside asp.net page and
used that user control also. Everything works fine but user control
code executing repeatedly and thsi cycle goes on. I am not able to
find why this user control code keep on executing, Any help would be
highly appreciated.
Header.ascx code
<%# Control Language="C#" AutoEventWireup="true" Inherits="SSBilling.UserControl.header" %>
<script language="C#" runat="Server">
public void buffer()
{
try
{
Response.Buffer = true;
}
catch
{
}
}
public string cleanupCookie(string cookie)
{
string tmpcookie = cookie.Replace("%28", "(");
tmpcookie = tmpcookie.Replace("%29", ")");
tmpcookie = tmpcookie.Replace("%27", "'");
tmpcookie = tmpcookie.Replace("%2E", ".");
tmpcookie = tmpcookie.Replace("%3F", "?");
tmpcookie = tmpcookie.Replace("%2C", ",");
tmpcookie = tmpcookie.Replace("%5F", " ");
tmpcookie = tmpcookie.Replace("%2D", "-");
tmpcookie = tmpcookie.Replace('_', ' ');
tmpcookie = tmpcookie.Replace("ITEMCLICK2", "itemClick2");
return tmpcookie;
}
</script>
<%
//************************************************************************************************
//* 2012-06-05 HRHC
//* * migration updated
//************************************************************************************************
buffer();
%>
<script language=vbscript>
sub printthis()
window.focus()
window.print()
end sub
sub backbutton()
on error resume next
<%
Response.Write("' " + ((Request.Cookies["mID"] == null) ? String.Empty : Request.Cookies["mID"].Value) + "\r\n");
//response.write "self.parent.document.all.tmp.tmpMenu.value = """ & cleanupCookie(request.cookies("mID")) & """" & vbcrlf
Response.Write("top.document.all.tmp.tmpMenu.value = \"" + cleanupCookie((Request.Cookies["mID"] == null) ? String.Empty : Request.Cookies["mID"].Value) + "\"" + "\r\n");
//response.write " if instr(1, """ & request.cookies("deptlist") & """, "","" & self.parent.document.all.tmp.currDept.value & "","") > 0 then " & vbcrlf
Response.Write(" if instr(1, \"" + ((Request.Cookies["deptlist"] == null) ? String.Empty : Request.Cookies["deptlist"].Value) + "\", \",\" & top.document.all.tmp.currDept.value & \",\") > 0 then " + "\r\n");
Response.Write(" if err.number <> 0 then exit sub " + "\r\n");
Response.Write("top.go \"visible\"" + "\r\n");
//response.write "self.parent.document.all.menuadmin.style.visibility = ""visible""" & vbcrlf
Response.Write("else" + "\r\n");
Response.Write("top.go \"hidden\"" + "\r\n");
//response.write "self.parent.document.all.menuadmin.style.visibility = ""hidden""" & vbcrlf
Response.Write(" end if " + "\r\n");
//what?
//Session("CurrentUserAdmin") = "Y"
%>
end sub
' 2012-04-04 HRHC
' - modified to avoid scripting error after migrated
' the following if statement only works when the
' child and parent frames are under the same domain
'----------------------------------------------------
'If IsObject(self.parent.document.frames) Then
' If self.parent.document.frames.length = 0 Then
' loc = InStr(8, self.location.href, "/")
' loc = Mid(self.location.href, loc)
'
' location.href = "/default.asp?loc=" & loc
' Else
' Call backbutton
' End If
'End If
</script>
<script type="text/javascript">
if (top === self) {
/*
2012-08-18 HRHC
- no in the trinity frameset (both zone and new app), call the default page.
this will no longer be used after app migrated
*/
var loc = "";
top.location = "/default.aspx?loc=" + loc;
}
else {
/*
- in the frameset, do nothing
*/
}
</script>
<link REL="stylesheet" TYPE="text/css" HREF="/include/content.css">
<%
//response.write "hello from header.inc<br />"
%>
Registerd in asp.net page like this:
<%# Register TagPrefix="uc" TagName="header"
Src="~/UserControl/header.ascx" %>
And called the header.ascx like this:
<uc:header id="ucHeader" runat="server"></uc:header>
Thank You!

How to Send email with High Importance in asp.net VB

How do I set the code below to generate email with high priority in the subject line? Thank you for any guidance.
Private Sub SendEmail(ByVal pharmEmail As String, ByVal backupEmail As String)
Dim smtpClient As New System.Net.Mail.SmtpClient()
Dim message As New System.Net.Mail.MailMessage()
Try
Dim fromAddress As New System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings("EmailFromAddr"), WebConfigurationManager.AppSettings("EmailFromName"))
message.From = fromAddress
message.To.Add(pharmEmail)
message.Subject = WebConfigurationManager.AppSettings("EmailSubject")
If (WebConfigurationManager.AppSettings("backupEnabled") = True) Then
message.CC.Add(backupEmail)
End If
message.IsBodyHtml = True
Dim orderURL As New HyperLink
orderURL.Text = "here"
orderURL.NavigateUrl = "http://" & WebConfigurationManager.AppSettings("ServerName") & "/User/ReviewOrder.aspx?orderID=" & webOrderID
message.Body = "An order was created using the account of " + Profile.FirstName.ToString() + " " + Profile.LastName.ToString() + ". " + WebConfigurationManager.AppSettings("EmailBody") + "<a href='" + orderURL.NavigateUrl + "'>here.</a>"
'message.Body = WebConfigurationManager.AppSettings("EmailBody") & " " & orderURL.
smtpClient.Send(message)
Catch ex As Exception
ErrorHandler.WriteError(ex.ToString)
Throw ex
End Try
I believe you can set the Priority property on the MailMessage. See MSDN for more details.

Regarding to not calling of enquiry.cs in app code

I am a newcomer in .net , my problem is related to email. This code is well performed on my localhost. This is code of my enquiry.aspx.cs:-
protected void Button1_Click(object sender, EventArgs e)
{
Mail mm = new Mail();
if (DropDownList3.SelectedItem.Text == "--Select--")
{
Label5.Text = "Please Select Course";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
}
else if (TextBox1.Text == "")
{
Label5.Text = "Please Enter Name";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
TextBox1.Focus();
}
else if (mm.checkValidemail(TextBox2.Text) == false)
{
Label5.Text = "Please Enter E-Mail ID";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter E-Mail ID');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter E-Mail ID'); </script>");
TextBox2.Focus();
}
else if (mm.checkValidmobile(TextBox3.Text) == false)
{
Label5.Text = "Please Enter Mobile Number";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Mobile Number');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Mobile Number'); </script>");
TextBox3.Focus();
}
else
{
myenquiry ee = new myenquiry();
//myenquiry ee=new myenquiry();
int i = ee.add_enquiry(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, "-", "-", "NORMAL ENQUIRY FROM SITE", TextBox11.Text, DropDownList3.SelectedItem.Text, TextBox12.Text,locationlst.SelectedItem.Text);
if (i == 1)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(" Enquiry " + "<shila#gmail.com> ");
message.To.Add(new MailAddress("shu#gmail.com"));
message.CC.Add(new MailAddress("va_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
}
catch
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
}
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
and this is my appcode folder enquiry.cs:-
public class myenquiry
{
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=group;Integrated Security=True");
SqlCommand comm = new SqlCommand();
int result = 0;
public int add_enquiry(string nam,string email,string mob,string adr,string cit,string state,string country,string zip,string college,string tech,string query,string loc)
{
try
{
comm.Connection = conn;
comm.CommandText = "insert into enquiry(name,email,mobile,address,city,state,country,zip,college,technology,query,edate,location) values('" + nam + "','" + email + "','" + mob + "','" + adr + "','" + cit + "','" + state + "','" + country + "','" + zip + "','" + college + "','" + tech + "','" + query + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','"+loc+"')";
conn.Open();
comm.ExecuteNonQuery();
result = 1;
}
catch(Exception ee)
{
result = 0;
}
finally
{
conn.Close();
}
return result;
}
}
this is well perform on local. But at the server the appcode enquiry.cs is not called on enquiry.aspx.cs and the value of int i is becoming 0, so the else part is executing. Why?
You seem to have a hard coded connection string in the myenquiry class. If you are not dynamically setting the connection string from a configuration file or otherwise, the insert method will try to use that string which points to your local. Assuming your server is a different domain/machine with no access to your local DB, the connection will definitely fail, giving you the result 0.
As Shree.pat18 says Don't make hardcodded connection string in class file.instead of this make your connection string in web.config file something like this in your configuration tag
<connectionStrings>
<add name="cn" connectionString="Data Source=USER-PC;Initial Catalog=group;Integrated Security=True"/>
</connectionStrings>

Resources