Catch block executing even when try block throws no exception? - c#

I am trying to send a mail via goDaddy mail server. The mail is being sent (I am receiving it in my mailbox) but the catch block is executing and landing me to the contact page with querystring msg as "fail"
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["username"] != null && Request.QueryString["email"] != null && Request.QueryString["msg"] != null)
{
try
{
string name = Request.QueryString[0];
string email = Request.QueryString[1];
string msg = Request.QueryString[2];
SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net", 25);
//smtp.EnableSsl = false;
smtp.Send("feedback#solutionpoint98.com", "b.soham1991#gmail.com", "feedback", "Name:" + name + "\n e-mail:" + email + "\n Subject:" + msg);
Response.Redirect("contact.html?msg=success");
}
catch(Exception ex)
{
Response.Redirect("contact.html?msg=fail");
}
}
else
{
Response.Redirect("contact.html");
}
}
If the mail is being sent, shouldn't it redirect to "contact.html?msg=success"?

The problem is that your first Response.Redirect() is actually throwing a ThreadAbortException. This is due to the fact that .Redirect internally calls the Response.End method, prematurely ending the Response in this case.
The correct way to do this is to use the overloaded Response.Redirect(string url, bool endResponse), which allows you to suppress the internal call to Response.End by setting endResponse to false ... which will prevent this error from being thrown.
This is all covered in this MS support article: http://support.microsoft.com/kb/312629/EN-US/
Just modify your code to look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["username"] != null && Request.QueryString["email"] != null && Request.QueryString["msg"] != null)
{
try
{
string name = Request.QueryString[0];
string email = Request.QueryString[1];
string msg = Request.QueryString[2];
SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net", 25);
//smtp.EnableSsl = false;
smtp.Send("feedback#solutionpoint98.com", "b.soham1991#gmail.com", "feedback", "Name:" + name + "\n e-mail:" + email + "\n Subject:" + msg);
Response.Redirect("contact.html?msg=success", false);
}
catch(Exception ex)
{
Response.Redirect("contact.html?msg=fail", false);
}
}
else
{
Response.Redirect("contact.html", false);
}
}

Related

C# if statement not working

My code works within a local network and I know it will not work outside of the local network as I am using Dns.GetHostEntry to resolve the IP address to hostname and thats fine...
But my if statement is not working, I am getting error "No Host Found" message when trying to resolve hostname from different subnet.
I thought my if statement would stop this error but its not working, can someone help please or tell me how to fix it, code below...
public partial class _Default : System.Web.UI.Page
{
//public string IPaddr1 { get; private set; }
string serviceDesk = "eg#mail.co.uk";
string emailSubject = "MyPc";
string IPaddr = "";
string deviceName = "";
protected void Page_Load(object sender, EventArgs e)
{
getIP();
}
protected void getIP()
{
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"] != null)
{
IPaddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"].ToString();
}
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
IPaddr = HttpContext.Current.Request.UserHostAddress;
deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
}
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
deviceName = "Device name could be found";
}
Label1.Text = "IP Address: " + " " + IPaddr;
Label2.Text = "PC Name: " + " " + deviceName;
}
private void EmailVerificationRequest(string recepientEmail, string subject)
{
try
{
using (MailMessage mailMessage = new MailMessage())
{
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("IP address " + IPaddr + "<br/>");
sbEmailBody.Append("Hostname " + " " + deviceName);
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["FromEmail"]);
mailMessage.Subject = subject;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
if (string.IsNullOrWhiteSpace(NetworkCred.UserName))
{
smtp.UseDefaultCredentials = true;
}
else
{
smtp.Credentials = NetworkCred;
smtp.UseDefaultCredentials = false;
}
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
try
{
smtp.Send(mailMessage);
}
catch (SmtpException e)
{
}
}
}
catch
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
EmailVerificationRequest(serviceDesk, emailSubject);
Response.Redirect("~/message.aspx");
}
}
From the MSDN Documentation:
If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried.
Therefore, I suspect your code isn't getting as far as the third if condition because an exception is being thrown by the call to GetHostEntry(), which you're seeing as the 'error "No Host Found" message'.
The most straightforward way to deal with this is to use a try...catch block to catch the specific exception and handle it, something such as:
try
{
deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
}
catch (SocketException)
{
deviceName = "Device name could be found";
}
This says that if a SocketException occurs during the call to GetHostEntry(), the code is to jump to the catch block, rather than the exception stopping your application.
Note that this assumes that any SocketException means that the IP address wasn't found, but it could mean that the DNS server wasn't contactable, or some other error.
MSDN has quite a lot on exception handling and how try...catch blocks work.
Hope this helps
Before you get a value from a dictionary, you must check if the dictionary contains the key you pass. You achieve this by calling "Contains" method.
if (HttpContext.Current.Request.ServerVariables.Contains("HTTP_X_FORWARDER_FOR"))
{
// Your Code...
}
If you retrieve the content of a dictionary directly and the key you are requesting doesn't exist in the dictionary pairs, the dictionary doesn't return null. Instead, it throws KeyNotFoundException.

C# CodeBehind Error When Using Webforms Front End

I'm attempting to learn about generating an email with attachment(s) using C# CodeBehind. I would like the web page to use the FileUpload control or something similar to select the file on the network.
I get a "Could not find a part of the path 'E:\Web Sites\myNet\Ztest\TrailerPics\'."
I'm wondering if I'm on the right path... or if there is a better approach.
Thx for any help ~j
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
//Get file names from the fileUpload control
var fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
var fileName2 = Path.GetFileName(FileUpload2.PostedFile.FileName);
var fileName3 = Path.GetFileName(FileUpload3.PostedFile.FileName);
//Code block to send email with keyed data
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("DoNotReply#smiley.com");
mail.To.Add("guy.smiley#sesamestreet.com");
mail.Subject = ("IMG");
mail.IsBodyHtml = true;
var client = new SmtpClient("mailout.smiley.com", 25);
string htmlBody;
htmlBody = string.Format("Email Testing for attaching an image");
mail.Body = htmlBody;
//Create the instance of attachments by using the mapped path concatenated with the file name
Attachment addon = new Attachment(Server.MapPath("~/TrailerPics/" + fileName));
Attachment addon2 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName2));
Attachment addon3 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName3));
//Add the attachments as long as the fileUpload control has a file selected
if (FileUpload1.PostedFile.FileName != "")
{
mail.Attachments.Add(addon);
}
if (FileUpload2.PostedFile.FileName != "")
{
mail.Attachments.Add(addon2);
}
if (FileUpload3.PostedFile.FileName != "")
{
mail.Attachments.Add(addon3);
}
//Send mail
client.Send(mail);
//Notify that email was sent
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Email Sent!')", true);
//Close all connections to the files
if (FileUpload1.PostedFile.FileName != "")
{
addon.Dispose();
}
if (FileUpload2.PostedFile.FileName != "")
{
addon2.Dispose();
}
if (FileUpload3.PostedFile.FileName != "")
{
addon3.Dispose();
}
}
catch(Exception ex)
{
//inform user that the email failed
errorLabel.Text = "Something went wrong with the email : " + ex.Message;
}
}

Why URL address is repeating?

I have website hosted over here: but when I login then the url into the address bar keeps repeating and getting longer like: this and here if you click on to the left side menu then you can see into the address bar that the URL keeps getting bigger and bigger. Please suggest me on the above why the URL is getting bigger like this?
please find the website credential as below:
username: int123
password: 123
Here is code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["type"] == "logout")
{
Session.Clear();
Response.Cookies.Clear();
//FormsAuthentication.SignOut();
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/login.aspx");
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = string.Empty;
string userid = string.Empty;
string address = string.Empty;
string company = string.Empty;
if ((txtUsername.Value.Trim() == string.Empty || txtUsername.Value.Trim() == "Username") && (txtPassword.Value.Trim() == string.Empty || txtPassword.Value.Trim() == "Password"))
{
//divError.Visible = true;
lblError.Text = "Please type the correct username and password";
ResetFields();
}
else if (txtUsername.Value.Trim() == string.Empty || txtUsername.Value.Trim() == "Username")
{
//divError.Visible = true;
lblError.Text = "User name is incorrect.";
ResetFields();
}
else if (txtPassword.Value.Trim() == string.Empty || txtPassword.Value.Trim() == "Password")
{
//divError.Visible = true;
lblError.Text = "Password is incorrect.";
ResetFields();
}
else
{
DataTable dtuserLogin = db.GetLoginDetails(txtUsername.Value.Trim(), txtPassword.Value.Trim());
try
{
if (dtuserLogin.Rows.Count > 0)
{
userid = Convert.ToString(dtuserLogin.Rows[0]["srno"]).Trim();
username = Convert.ToString(dtuserLogin.Rows[0]["username"]).Trim();
company = Convert.ToString(dtuserLogin.Rows[0]["company"]).Trim();
address = Convert.ToString(dtuserLogin.Rows[0]["address"]).Trim();
//FormsAuthentication.SetAuthCookie(username + ";" + company + ";" + address, true);
}
}
catch (Exception ex)
{
throw new Exception("Error in btnLogin_Click()" + ex.Message);
}
if (username == "admin")
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/Admin/Default.aspx", true);
}
else
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/User/Default.aspx", true);
}
}
}
private void ResetFields()
{
txtUsername.Value = "Username";
txtPassword.Value = "Password";
}
It is just the code at the end of the btn click event that redirects you to that url:
if (username == "admin")
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/Admin/Default.aspx", true);
}
else
{
Response.Redirect("http://103.252.236.33/plesk-site-preview/2wayglobal.com/103.252.236.33/User/Default.aspx", true);
}
I can't see the code that is causing the issue, but I will bet $1 you are calling Redirect and passing what you think is an absolute URL but is actually a relative URL. The browser is seeing the redirect as relative and simply adding on the path to the end of the URL that is already in the address bar. It will do this over and over until the URL overflows its buffer and you get a Bad Request error.
Instead of
Response.Redirect("AbsolutePath/PageName.aspx") //This is a relative URL!
you should use
Response.Redirect("~/AbsolutePath/PageName.aspx")
or
Response.Redirect("/AbsolutePath/PageName.aspx")
or
Response.Redirect("https://ServerName.com/AbsolutePath/PageName.aspx")
...depending on what you are trying to accomplish.

How can i define "DisplayErrorMessage" in this case?

This is a code that I wrote for my open button ... but I have error on "DisplayErrorMessage" part.
What should I write instead? or how can I define it in order not to have the error again.
protected void btnOpen_Click(object sender, EventArgs e)
{
txtFileName.Text = txtFileName.Text.Trim();
if (txtFileName.Text == string.Empty)
{
string strErrorMessage = "you did Not specify file for opening!";
DisplayErrorMessage(strErrorMessage);
}
string strFileName = txtFileName.Text;
string strRootRelativePath = "~/app_data/pageContent";
string strRootRelativePathName =
string.Format("{0}/{1}", strRootRelativePath, strFileName);
string strPathName = Server.MapPath(strRootRelativePathName);
System.IO.StreamReader ostreamReader = null;
try
{
ostreamReader = new System.IO.StreamReader(strPathName, System.Text.Encoding.UTF8);
litPageMessages.Text = ostreamReader.ReadToEnd();
}
catch (Exception ex)
{
litPageMessages.Text = ex.Message;
}
finally
{
if (ostreamReader != null)
{
ostreamReader.Dispose();
ostreamReader= null;
}
}
}
If you want to alert your error message in the browser, you could do the following.
Add a class file in your App_Code folder, say Helpers.cs
Then, open it and add the following code:
public class Helpers
{
public static void DisplayErrorMessage(Page page, string msg)
{
string script = "<script>alert('" + msg + "');</script>";
if (!page.ClientScript.IsStartupScriptRegistered("MyAlertMsgHandler"))
page.ClientScript.RegisterStartupScript(page.GetType(), "MyAlertMsgHandler", script);
}
}
Lately, call this method from your code behind like this:
Helpers.DisplayErrorMessage(this.Page, "Error message details.");
Either create a function which takes message in the parameter and use MessageBox.Show() method to Display the error message.
or
Just Call MessageBox.Show( this, strErrorMessage ) instead of DisplayErrorMessage(strErrorMessage);
Try This...
void DisplayErrorMessage(string msg)
{
string script = "<script>alert('" + msg + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}

Need to send email using background worker process

I have code written for sending email in C#, but the application hangs up when the application is sending mails size of attachments more than 2 MB. I was advised to use background worker process for the same by SO users.
I have gone thru the background worker process example from MSDN and google it also, but i don't know how to integrate in my code.
Please guide me in that...
thanks
UPDATED: Email-Code Added
public static void SendMail(string fromAddress, string[] toAddress, string[] ccAddress, string[] bccAddress, string subject, string messageBody, bool isBodyHtml, ArrayList attachments, string host, string username, string pwd, string port)
{
Int32 TimeoutValue = 0;
Int32 FileAttachmentLength = 0;
{
try
{
if (isBodyHtml && !htmlTaxExpression.IsMatch(messageBody))
isBodyHtml = false;
// Create the mail message
MailMessage objMailMsg;
objMailMsg = new MailMessage();
if (toAddress != null) {
foreach (string toAddr in toAddress)
objMailMsg.To.Add(new MailAddress(toAddr));
}
if (ccAddress != null) {
foreach (string ccAddr in ccAddress)
objMailMsg.CC.Add(new MailAddress(ccAddr));
}
if (bccAddress != null) {
foreach (string bccAddr in bccAddress)
objMailMsg.Bcc.Add(new MailAddress(bccAddr));
}
if (fromAddress != null && fromAddress.Trim().Length > 0) {
//if (fromAddress != null && fromName.trim().length > 0)
// objMailMsg.From = new MailAddress(fromAddress, fromName);
//else
objMailMsg.From = new MailAddress(fromAddress);
}
objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = subject;
objMailMsg.Body = messageBody;
objMailMsg.IsBodyHtml = isBodyHtml;
if (attachments != null) {
foreach (string fileName in attachments) {
if (fileName.Trim().Length > 0 && File.Exists(fileName)) {
Attachment objAttachment = new Attachment(fileName);
FileAttachmentLength=Convert.ToInt32(objAttachment.ContentStream.Length);
if (FileAttachmentLength >= 2097152) {
TimeoutValue = 900000;
} else {
TimeoutValue = 300000;
}
objMailMsg.Attachments.Add(objAttachment);
//objMailMsg.Attachments.Add(new Attachment(fileName));
}
}
}
//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
if (objSMTPClient.Credentials != null) { } else {
objSMTPClient.UseDefaultCredentials = false;
NetworkCredential SMTPUserInfo = new NetworkCredential(username, pwd);
objSMTPClient.Host = host;
objSMTPClient.Port = Int16.Parse(port);
//objSMTPClient.UseDefaultCredentials = false;
objSMTPClient.Credentials = SMTPUserInfo;
//objSMTPClient.EnableSsl = true;
//objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
}
//objSMTPClient.Host = stmpservername;
//objSMTPClient.Credentials
//System.Net.Configuration.MailSettingsSectionGroup mMailsettings = null;
//string mailHost = mMailsettings.Smtp.Network.Host;
try {
objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.Send(objMailMsg);
//objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objMailMsg.Dispose();
}
catch (SmtpException smtpEx) {
if (smtpEx.Message.Contains("secure connection")) {
objSMTPClient.EnableSsl = true;
objSMTPClient.Send(objMailMsg);
}
}
}
catch (Exception ex)
{
AppError objError = new AppError(AppErrorType.ERR_SENDING_MAIL, null, null, new AppSession(), ex);
objError.PostError();
throw ex;
}
}
}
I can't modify the code here as it is common method that is called whenever mail is to be sent from my application.
You could start a background thread to continuously loop and send email:
private void buttonStart_Click(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
this.Controls.Add(bw);
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}
private bool quit = false;
void bw_DoWork(object sender, DoWorkEventArgs e)
{
while (!quit)
{
// Code to send email here
}
}
Alternative way to do it:
private void buttonStart_Click(object sender, EventArgs e)
{
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(client_SendCompleted);
client.SendAsync("from#here.com", "to#there.com", "subject", "body", null);
}
void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
MessageBox.Show("Successful");
else
MessageBox.Show("Error: " + e.Error.ToString());
}
Specific to your example, you should replace the following:
try
{
objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.Send(objMailMsg);
//objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objMailMsg.Dispose();
}
catch (SmtpException smtpEx)
{
if (smtpEx.Message.Contains("secure connection"))
{
objSMTPClient.EnableSsl = true;
objSMTPClient.Send(objMailMsg);
}
}
with the following:
objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objSMTPClient.SendAsync(objMailMsg, objSMTPClient);
and further down, include:
void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
MessageBox.Show("Successful");
else if (e.Error is SmtpException)
{
if ((e.Error as SmtpException).Message.Contains("secure connection"))
{
(e.UserState as SmtpClient).EnableSsl = true;
(e.UserState as SmtpClient).SendAsync(objMailMsg, e.UserState);
}
else
MessageBox.Show("Error: " + e.Error.ToString());
}
else
MessageBox.Show("Error: " + e.Error.ToString());
}
There's a great example of how to do this with a "Service Broker" in Chapter 8 of Richard Kiessig's book "Ultra-Fast ASP.NET."
Here's the link to the book on the publisher's website where you can download the sample code from the book. Again, chapter 8...
http://apress.com/book/view/9781430223832

Categories

Resources