I'm going to create form contact in asp.net mvc 4. I have yet form in html and code in controller. And his looks like:
[HttpPost]
public ActionResult Kontakt(KontaktModel k)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(k.Mail.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myemail#gmail.com");
msg.Subject = k.Temat.ToString();
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
sb.Append("Nick / Imię i nazwisko: " + k.Name);
sb.Append(Environment.NewLine);
sb.Append("Typ problemu: " + k.TypProblemu);
sb.Append(Environment.NewLine);
sb.Append("Treść:");
sb.Append(Environment.NewLine);
sb.Append(k.Tresc);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("SUCCESS");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}
}
But when I clicked to button app return Error.cshtml. I have a question, how I can know how exception catched? I don't know why it does not work. Any ideas?
The answer should be to get the Exception Message and put inside a ViewBag.Message and show it in the Error.cshtml view.
Error:
#ViewBag.Message
But is good to know little more about Exception and Exception Handling. If you only declare a try catch and a exception happen it will go inside the catch is the same if you do try catch(Exception) if you want to know more detail about the exception is happening you can declare a variable, example :
try{
///code
}catch(Exception e){}
and then you can watch inside the variable for more detail.
The good practice is to know what type of exception you can receive and handle, here is a link that have a good explanation Exception and Exception Handling
Example:
try
{
//code
}
catch(Exception c)
{
ViewBag.Message = c.Message
return View("ERROR");
}
Related
i wanna ask again. How can i resolve this problem
Eror Picture
always find error, and i won't stop. I must be try with help from you guys.
after you look my error, this is my code:
using System;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Web.SessionState;
namespace FormsAuthAd
{
public class ChangePasswordPSI
{
public bool ChangePass(HttpSessionState Session, string OldPassword, string NewUPassword)
{
string Domain = Session["domain"].ToString();
string Username = Session["username"].ToString();
try
{
string ldapPath = "LDAP://MyDomain.com";
DirectoryEntry user = new DirectoryEntry(ldapPath, Domain + "\\" + Username, OldPassword);
if (user != null)
{
DirectorySearcher search = new DirectorySearcher(user);
search.Filter = "(SAMAccountName=" + Username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
object ret = user.Invoke("ChangeUserPassword", new object[] { OldPassword, NewUPassword });
user.CommitChanges();
return true;
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
}
}
can somebody tell me, what should i do?
thank you
If you are using try..catch and cannot find where exactly the exception occurred, delete try and catch and execute the code again. In your example, it might happen on Invoke("ChangeUserPassword"... - as far as I see the method name should be "ChangePassword"
https://msdn.microsoft.com/en-us/library/ms180896(v=vs.80).aspx
Is there any way I can track (through the code) the bounced emails.
Consider the email id like 'skdfisdcnsodioifs#gmail.com'. This is valid email id but does not exists so certainly it will be bounced backed.
I am using ASP.Net's SmtpClient with "message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure". However it still shows the message sent successfully and after ~20-25 minutes I get the fail delivery notification email.
Below is my code
class Program
{
static void Main(string[] args)
{
SmtpClient client = new SmtpClient("xxxx.xxxxxx.xxx", 25);
client.Credentials = new NetworkCredential("xxxxxx#xxxxxx.com", "xxxxxx");
MailAddress to = new MailAddress("abcdsfasdfasdfasdfasdf2342342defgh#gmail12333.com");
MailAddress from = new MailAddress("xxxxxx#xxxxxx.com");
MailMessage message = new MailMessage(from, to);
message.Headers.Add("Return-Path", "xxxxxx#gmail.com");
message.ReplyToList.Add(new MailAddress("xxxxxx#gmail.com"));
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
message.Subject = "Test POC";
message.Body = "This is a test e-mail message sent by an application. ";
client.SendCompleted += client_SendCompleted;
string UserState = "test";
client.Timeout = 3;
try
{
Console.WriteLine("start to send email ...");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.SendAsync(message,UserState);
Console.WriteLine("email was sent successfully!");
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
Console.WriteLine("test.");
Console.ReadKey();
}
static void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
//String token = (string)e.UserState;
if (e.Cancelled)
{
Console.WriteLine("Send canceled.");
}
if (e.Error != null)
{
Console.WriteLine("[{0}] ", e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
}
}
Thanks in advance.
Abhishek
I've written code for sending a newsletter, all is working fine, but there is a problem if one of the email addresses in the list, doesn't exit or the domain does not exist.
In this case the script stops immediately and the sending of the mail list is not finished.
Here is the part of the code I want to modify.
public static void SendMessage(String sender, String recipient, String message, String object)
{
try
{
MailMessage mail = new MailMessage(sender, recipient);
mail.Subject = object;
mail.IsBodyHtml = true;
mail.Body = message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "my.smtp.com";
smtp.Send(mail);
}
catch (Exception e)
{ throw new Exception("AdminEmail - SendMessage >> recipient: " + recipient + " - generic error: " + e.Message); }
}
Hope somone can help me, thank you very much!
Welcome to SO.
From what I can infer from your description your are not handling the exception that is thrown by SendMessage.
Handle the exception in the caller method. Or do a dirty fix as shown below...
This is not a real fix. But will help you understand the issue...You have to determine in your calling method what to do if SendMessage throws an exception.
public static void SendMessage(String sender, String recipient, String message, String object)
{
try
{
MailMessage mail = new MailMessage(sender, recipient);
mail.Subject = object;
mail.IsBodyHtml = true;
mail.Body = message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "my.smtp.com";
smtp.Send(mail);
}
catch (Exception e)
{
//Just log error and continue to process
}
}
I'm currently working on a asp.net website using Visual Studio 2010... I'm trying to send email from my contact us page... I'm getting this error:
Warning 9 CA2000 : Microsoft.Reliability :
In method 'Default2.Button1_Click(object, EventArgs)',
call System.IDisposable.Dispose on object 'msg'
before all references to it are out of scope.
c:\Users\toshiba\Documents\Visual Studio 2010\WebSites\Carp-MacDental\ContactUs.aspx.cs 29
C:\...\Carp-MacDental\
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
public partial class Default2 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("Site#gmail.com", "password");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("Site#gmail.com");
msg.To.Add(new MailAddress(txtEmail.Text));
msg.Bcc.Add(new MailAddress("Site#gmail.com"));
msg.Subject = "Notification from:" + url;
msg.Body = "A message form," + txtName.Text + ", <br/>" + txtMessage.Text;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
lblMessage.Text = "Thank you for contacting us.. we will get back to you as soon as we read your message";
}
}
Its my first time working with this so I'm pretty confused.. Also my mail message that was supposed to be sent through the website wasn't sent...
As Aristos indicated with his link to Msdn, the warning you see is a code analysis warning. Visual Studio has identified that there is a small problem with your code and shows the warning to alert you about the problem.
The problem is that you are creating a couple of instances of classes that implement the IDisposable interface. Classes that implement this interface have a Dispose method that should be called when you are finished with the instance. The Dispose method is used to clean up unmanaged resources that the instance is using behind the scene, thus making sure that memory and other unmanaged resources are freed up for use by other processes.
Both MailMessage and SmtpClient implement this interface. So intances of these classes should have their respective Dispose method called before they go out of scope. The first thought might be to simply add a couple of lines to you existing code:
...
client.Send(msg);
msg.Dispose();
client.Dispose();
...
But a better soultion would probably be to wrap these in using() { } blocks. Doing this will make the compiler insert code that automatically calls the Dispose method, and it will even be called even if there is an exception thrown from inside the using() { } block. Try this:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("Site#gmail.com", "password");
using(MailMessage msg = new MailMessage())
using(SmtpClient client = new SmtpClient("smtp.gmail.com"))
{
msg.From = new MailAddress("Site#gmail.com");
msg.To.Add(new MailAddress(txtEmail.Text));
msg.Bcc.Add(new MailAddress("Site#gmail.com"));
msg.Subject = "Notification from:" + url;
msg.Body = "A message form," + txtName.Text + ", <br/>" + txtMessage.Text;
msg.IsBodyHtml = true;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
lblMessage.Text = "Thank you for contacting us.. we will get back to you as soon as we read your message";
}
That should hopefully get rid of the compiler warning for you. The fact that the email is not really sent is another matter. I cannot help with that without a lot more details. If you need help with that, I suggest you post a new question and add as much info about the problem as possible in that question.
I have feedback form on my mvc site and I send this form to email.
In my controller I created ErrorMessage in case email sending is failed and SuccessMessage in case email sending is successful
/*Feedback*/
[HttpGet]
public ActionResult Feedback(string ErrorMessage)
{
if (ErrorMessage != null)
{
}
return View();
}
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
string ErrorMessage, SuccessMessage;
//email
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
msg.Priority = MailPriority.High;
msg.From = new MailAddress(Model.Email, Model.Name);
msg.To.Add("tayna-anita#mail.ru");
msg.Subject = #Resources.Global.Feedback_Email_Title + " " + Model.Company;
string message = #Resources.Global.Feedback_Email_From + " " + Model.Name + "\n"
+ #Resources.Global.Feedback_Email + " " + Model.Email + "\n"
+ #Resources.Global.Feedback_Phone + " " + Model.Phone + "\n"
+ #Resources.Global.Feedback_Company + " " + Model.Company + "\n\n"
+ Model.AdditionalInformation;
msg.Body = message;
msg.IsBodyHtml = false;
//Attachment
if (Model.ProjectInformation != null && !(String.IsNullOrEmpty(Model.ProjectInformation.FileName)))
{
HttpPostedFileBase attFile = Model.ProjectInformation;
if (attFile.ContentLength > 0)
{
var attach = new Attachment(attFile.InputStream, attFile.FileName);
msg.Attachments.Add(attach);
}
}
SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
try
{
client.Send(msg);
SuccessMessage = "Email sending was successful"
}
catch (Exception ex)
{
return RedirectToAction("Feedback", "Home", ErrorMessage = "Email sending failed");
}
return RedirectToAction("Feedback", "Home");
}
How can I add showing this messages in my view?
As you are redirecting to new page use the TempData , which will be available in next request after redirect. Put the message in TempData["Message"] and output in the Feedback view. To be more better check if
<% TempData["Message"] != null { %>
<%= TempData["Message"] %>;
<%} %>
Can't you try to access those as Model properties as follows:
<%= Model.ErrorMessage %>
<%= Model.SuccessMessage %>
use TempData.
You can use a TempDataDictionary object to pass data in the same way that you use a ViewDataDictionary object. However, the data in a TempDataDictionary object persists only from one request to the next, unless you mark one or more keys for retention by using the Keep method. If a key is marked for retention, the key is retained for the next request.
A typical use for a TempDataDictionary object is to pass data from an action method when it redirects to another action method. For example, an action method might store information about an error in the controller's TempData property (which returns a TempDataDictionary object) before it calls the RedirectToAction method. The next action method can then handle the error and render a view that displays an error message.
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
bool error = true;
if(error){
TempData["Message"] = "Error";
TempData["Error"] = true;
}
else{
TempData["Message"] = "Success";
TempData["Error"] = false;
}
return RedirectToAction("Feedback", "Home");
}
[HttpGet]
public ActionResult Feedback()
{
string message = TempData["Message"].ToString();
bool error = Convert.ToBoolean(TempData["Error"]);
var model = new FeedbackModel{Message = message, Error = error};
return View(model);
}