Return message after form is submitted - c#

I am sorry if this has been posted before. I have searched many websites and forms to fix it but I can not get it. I have a simple contact form that allows potential customers to fill out their info click submit and then email a copy of what they inputted to us. I have the email part working fine. However, the part that's not working is message after the form is submitted. I'm try to use a try and catch to display a message when they submit or a err message when it didn't work. Not sure why it is not working. Thank you for the help. My controller code is below.
public ActionResult ContactForm()
{
return View();
}
public ActionResult Message()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactForm(ContactModel emailModel)
{
if (ModelState.IsValid)
{
bool isOk = false;
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("no-reply#bobcravens.com", "Website Contact Form");
msg.To.Add("thovden#hovdenoil.com");
msg.Subject = emailModel.Subject;
string body = "Name: " + emailModel.Name + "\n"
+ "Email: " + emailModel.Email + "\n"
+ "Website: " + emailModel.Website + "\n"
+ "Phone: " + emailModel.Phone + "\n\n"
+ emailModel.Message;
msg.Body = body;
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtpout.server.net", 25);
NetworkCredential Credentials = new NetworkCredential("thovden#hovdenoil.com", "****");
smtp.Credentials = Credentials;
smtp.Send(msg);
msg.Dispose();
isOk = true
ContactModel rcpt = new ContactModel();
rcpt.Title = "Thank You";
rcpt.Content = "Your email has been sent.";
return View("Message", rcpt);
}
catch (Exception ex)
{
}
// If we are here...something kicked us into the exception.
//
ContactModel err = new ContactModel();
err.Title = "Email Error";
err.Content = "The website is having an issue with sending email at this time. Sorry for the inconvenience. My email address is provided on the about page.";
return View("Message", err);
}
else
{
return View();
}
}
}

The problem is that view that you return:
return View("Messgae", err):
You should return the same view after error on "postback", with the invalid model
return View(err);
One time you call that Message view with MessageModel and in this line you called it with ContactModel, so there must be an error over here...
Side notes:
You're catching the Global Exception exception it isn't good practice. Not every exception you can and should handle.
You have an isOK flag that doesn't do a thing.
Move the exception Handel inside the catch block, not afterwards
Updated based on the comments:
Instead of return View you should Redirect:
return RedirectToAction("Message", err);
return RedirectToAction("Message", rcpt);
public ActionResult Message(ContactModel model)
{
return View(model);
}

I would start by emitting the exception so that you can figure out exactly what went wrong. Additionally, you might want to step through the code.

Related

Mail confirmation issue in ASP.NET Core Mvc

I am working on a project which is in ASP.NET Core.
In this project users have to confirm their mail before using their panel. I have written this part of code but there is a problem.
When I debug project and I get the confirmation link, copy it and
paste it to browser, mail confirmation goes successful
but
when I send confirmation Url by email to user's mail and user clicks on it to redirect to my website confirmation fails.
I don't understand the issue because it's weird. I have hard coded some part to test it but nothing changed.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
try
{
if (ModelState.IsValid)
{
if (model.ReferralCode != null)
{
var tmpUser = userManager.Users.FirstOrDefault(f => f.IntroductionCode == model.ReferralCode);
if(tmpUser == null)
{
return Json(new { result = "error", target = "register", message = $"No user found with this({model.ReferralCode}) referral code" });
}
}
var user = new ApplicationUser
{
Id = Guid.NewGuid().ToString(),
FullName = model.FullName,
Email = model.Email,
UserName = model.Email,
Balance = 0,
ReferralCode = model.ReferralCode,
IntroductionCode = new Random().RandomString(16),
IsVerified = false
};
var signUpResut = await userManager.CreateAsync(user, model.Password);
if (signUpResut == IdentityResult.Success)
{
var token = await userManager.GenerateEmailConfirmationTokenAsync(user);
var emailActivationUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, verifyToken = token });
new MailHelper(_logger).SendConfirmationEmail(user.FullName,user.Id, user.Email, token);
_logger.Log(LogLevel.Information, $"User {model.Email} Registered Successfully.");
return Json(new { result = "success", target = "register", message = "You have successfully registered. Check your mail to activate account." });
}
return Json(new { result = "error", target = "register", message = "Something went wrong in server side." });
}
return Json(new { result = "error", target = "register", message = "Something went wrong in server side." });
}
catch (Exception exc)
{
_logger.Log(LogLevel.Critical, $"Failed Registeration : {exc.Message}");
return Json(new { result = "error", target = "register", message = "Something went wrong in server side." });
}
}
here is mail sender code
public bool SendConfirmationEmail(string name, string id, string email, string confirmationToken)
{
try
{
var mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress("***", "***"));
mailMessage.To.Add(new MailboxAddress(name, email));
mailMessage.Subject = "subject";
var configurationUrl = $"https://localhost:44323/Account/ConfirmEmail?userId={id}&verifyToken={confirmationToken}";
mailMessage.Body = MailBodyMaker($"Click here", "Click here");
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("smtp.gmail.com", 465, true);
smtpClient.Authenticate("***", "****");
smtpClient.Send(mailMessage);
smtpClient.Disconnect(true);
}
return true;
}
catch(Exception exc)
{
_logger.Log(LogLevel.Critical, $"Email sending finished with exception ${exc.Message}");
return false;
}
}
The confirmation link looks like below in debug mode
https://localhost:44323/Account/ConfirmEmail?userId=9bb1a751-813b-48d2-a44c-74fd32a2db9a&verifyToken=CfDJ8A%2FFQtr0XBRFinX98FbsJc5LpPXqjstNllYq%2Br7kr6BHFfA7lBINCCoviE0nqJ6EQc1sJ7RW87jNsaR3fEkEbKoOhemFE62GCrTfn9gEizWV99lZhMrLxJPzGm1u6j3x%2FARoBqVuCVpp34ki0OZM%2BEJi31hNbwyowZ4YwoOnKjMqAOdu2bVG46WfXZBRG9AiOaFNTy326ijQmaTVDNSBl8lQR4gBWkmmRAdkcdFfOasLHD24wyUjmqgkOM2yTJ19Dw%3D%3D
and it looks like below in email body
https://localhost:44323/Account/ConfirmEmail?userId=9bb1a751-813b-48d2-a44c-74fd32a2db9a&verifyToken=CfDJ8A/FQtr0XBRFinX98FbsJc5LpPXqjstNllYq+r7kr6BHFfA7lBINCCoviE0nqJ6EQc1sJ7RW87jNsaR3fEkEbKoOhemFE62GCrTfn9gEizWV99lZhMrLxJPzGm1u6j3x/ARoBqVuCVpp34ki0OZM+EJi31hNbwyowZ4YwoOnKjMqAOdu2bVG46WfXZBRG9AiOaFNTy326ijQmaTVDNSBl8lQR4gBWkmmRAdkcdFfOasLHD24wyUjmqgkOM2yTJ19Dw==
Certain characters must be escaped in url, and your verification token contains such characters, however you put it as is into your url here:
var configurationUrl = $"https://localhost:44323/Account/ConfirmEmail?userId={id}&verifyToken={confirmationToken}";
To escape them - use Uri.EscapeDataString:
var configurationUrl = $"https://localhost:44323/Account/ConfirmEmail?userId={Uri.EscapeDataString(id)}&verifyToken={Uri.EscapeDataString(confirmationToken)}";

Constructing HTML table as Email Data in controller

I have C# code for sending Email (in Controller), that is working fine, Email gets shoot with no Problem
public ActionResult SendEmail(string msg, int formNum)
{
var sent = false;
try
{
var emailClient = new EmailServiceReference.EmailServiceClient();
sent = emailClient.SendEmail(fromEmail, toEmail, emailsubject+""+ formNum, msg);
// from and to values are defined.
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while sending Email " + ex.Message);
}
return Json(sent, JsonRequestBehavior.AllowGet);
}
As you can see there are two parameters for SendEmail() method "msg" & "formNum". I am using those parameters to send the email as Subject(formNum) and Body(msg).
Now, I have 8- 10 parameters getting in SendEmail(FirstName, LastName, ID, Age, PhoneNumber, etc) Method and those I want to use in Email Body. The task for me is to create HTML table in Email body with all details and email it to XYZ#xyz.com
I need help to construct data in HTML table with data in Controller and how can I send it as argument (msg) in method call.?
Thank You
I have modified your code. See if this works.
using System.Net.Mail;
//...
public ActionResult SendEmail(string msg, int formNum)
{
var sent = false;
try
{
var emailClient = new SmtpClient();
var mailMessage = new MailMessage(fromEmail, toEmail);
mailMessage.Subject = emailsubject +" " + formNum;
mailMessage.Body = msg;
mailMessage.IsBodyHtml = true;
emailClient.Send(mailMessage);
sent = true;
// from and to values are defined.
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while sending Email " + ex.Message);
}
return Json(sent, JsonRequestBehavior.AllowGet);
}

Not all code paths return a value. I was just wondering what was the fix to this?

When I hover over the Index it has a red line underneath and says
'UnauthEnquiryController.index(UnauthenticatedEnquiryViewModel)': not all code paths return a value.
I was just wondering what was the fix to this?
[HttpPost]
public ActionResult Index(UnauthenticatedEnquiryViewModel unauthenticatedEnquiryViewModel)
{
//unauthenticatedEnquiryViewModel.EnquiryType;
//NEED TO ADD A METHOD THAT SENDS FILE TO CRM HERE
if (ModelState.IsValid)
{
if (1 == 0) //take off
{
string fromAddress = WebConfigurationManager.AppSettings["FromEmail"]; //gets email from web.config file
//var toAddress = new MailAddress(); //need to get this from crm
var enquiry = DataAccessEnquiry.GetEnquiryCategoryEmail(unauthenticatedEnquiryViewModel.EnquiryType); //gets the to address based on CRm
string UnauthEmailSubject = WebConfigurationManager.AppSettings["UnauthEmailSubject"]; //gets subject from web.config file
MailMessage mailMessage = new MailMessage(fromAddress, enquiry.Email); //put to address frrom variable declared above
mailMessage.Subject = UnauthEmailSubject;
StringBuilder mailbuilder = new StringBuilder();
mailbuilder.AppendLine("First name: " + unauthenticatedEnquiryViewModel.FirstName);
mailbuilder.AppendLine("Last name: " + unauthenticatedEnquiryViewModel.LastName);
mailbuilder.AppendLine("Communication: " + unauthenticatedEnquiryViewModel.CCommmunication);
mailbuilder.AppendLine("Email: " + unauthenticatedEnquiryViewModel.Email);
mailbuilder.AppendLine("Confiirmation of email: " + unauthenticatedEnquiryViewModel.ConfirmEmailAddress);
mailbuilder.AppendLine("Mobile telephone No: " + unauthenticatedEnquiryViewModel.MobileTelephoneNo);
mailbuilder.AppendLine("Confiirmation of mobile telephone no: " + unauthenticatedEnquiryViewModel.ConfirmMobileTelephoneNo);
mailbuilder.AppendLine("Alternative telephone no: " + unauthenticatedEnquiryViewModel.AlternativeTelephoneNo);
mailbuilder.AppendLine("Confiirmation of alternative telephone no: " + unauthenticatedEnquiryViewModel.ConfirmAlternativeTelephoneNo);
mailbuilder.AppendLine("I am a: " + unauthenticatedEnquiryViewModel.Profession);
mailbuilder.AppendLine("Enquiry Type: " + unauthenticatedEnquiryViewModel.EnquiryType);
mailbuilder.AppendLine("Your message: " + unauthenticatedEnquiryViewModel.YourMessage);
if (unauthenticatedEnquiryViewModel.File != null) // this finds overall null
{
foreach (var file in unauthenticatedEnquiryViewModel.File) // loop through every File
{
if (file != null) //Finds induvidual null
{
var extension = new FileInfo(file.FileName).Extension.ToUpper();
mailMessage.Attachments.Add(new Attachment(file.InputStream, file.FileName));
}
}
}
mailMessage.Body = mailbuilder.ToString();
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
}
return View("Unauthsuccess", unauthenticatedEnquiryViewModel);
}
unauthenticatedEnquiryViewModel.Professions = DataAccessEnquiry.GetProfessionUnauthenticated();
unauthenticatedEnquiryViewModel.EnquiryTypes = new List<EnquiryType>();
}
[HttpPost]
public ActionResult Index(UnauthenticatedEnquiryViewModel unauthenticatedEnquiryViewModel)
{
//unauthenticatedEnquiryViewModel.EnquiryType;
//NEED TO ADD A METHOD THAT SENDS FILE TO CRM HERE
if (ModelState.IsValid)
{
...
return View("Unauthsuccess", unauthenticatedEnquiryViewModel);
}
unauthenticatedEnquiryViewModel.Professions = DataAccessEnquiry.GetProfessionUnauthenticated();
unauthenticatedEnquiryViewModel.EnquiryTypes = new List<EnquiryType>();
//THIS path doesn't return value.
//HERE return somethig
}
You return value only if if (ModelState.IsValid) is true but what want you return if this is false?
Here you have created a condition,
if(ModelState.Isvalid)
{
{// LOTS OF CODE}
return View(....);
}
But if
ModelState.Isvalid == false
is true then the function wouldn't return anything
You are returning value in if condition only that's way its saying. You must have to return after if condition as well

Mail Code Issue(It works time to time)

Hello I'm building a new site. But my usual mail code working only sometimes with this site.I was able to send mail within 01.00 - 01.10 and get a error "Failure to send mail" for 15 minutes.And now I'm able to send again. Its probably a issue with my hosting firm but can you review the code just to be safe? Thanks in advance.
[HttpPost]
public string processData(PersonDTO p)
{
try
{
var bdy = string.Format("Alınacak Yer: {0}\nAd Soyad: {1}\nTarih: {2}\nSaat: {3}\nBırakılacak Yer:{4}\nEmail: {5}\nUçuş No: {6}\nTelefon: {7}\nAdres Tarifi: {8}\nYolcu Sayısı: {9}", p.PickupSite, p.Name, p.Date, p.Time, p.DropSite, p.Email, p.FlightNumber, p.Phone, p.AddressLocation, p.NumberOfPassengers);
var msg = new MailMessage();
msg.From = new MailAddress("system#globalairporttransfer.com");
msg.To.Add("info#globalairporttransfer.com");
msg.Subject = "Yeni Istek";
msg.Body = bdy;
msg.IsBodyHtml = false;
var client = new SmtpClient("mail.globalairporttransfer.com", 25);
client.Credentials = new NetworkCredential("system#globalairporttransfer.com", "mypasswordishere");
client.EnableSsl = false;
client.Send(msg);
return "Kaydınız alındı. En kısa sürede ileşime geçeceğiz.";
}
catch (SmtpException e){return "Mesaj Gönderilemedi ! Hata Mesajı: \n" +e.Message;}
catch (SocketException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
catch (FormatException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
}
}
After fighting several hours with my hosting firm I proved that there is a problem with their end. After some configuration from their end I noticed Dns couldnt be resolved. If you have that problem you can try write ip adress of smtp instead of name.. I hope it helps some
var client = new SmtpClient("Ip of the smtp server", 25);

NullReferenceException on *setting* value in ViewBag

I'm at my wit's end here. I keep getting a NullReferenceException on the following line of code:
ViewBag.PaypalError = "we were unable to retreive your cart.";
I know it's that line - I added some code elsewhere in the file which caused it to get a new line number, and the line number in my error changed to follow it. I know ViewBag is not null, because I specifically inserted an if (ViewBag == null) test before it.
To make matters weirder, I have code to send an email when execution enters the logic that leads to the above statement. That email never gets set, yet this line of code, which happens afterwards, throws an exception, and I get the email from the try/catch block that catches it.
I know I should probably just eschew ViewBag, and I have some ideas for refactoring the code to not need it here, but none of that tells me where this exception is coming from.
Any ideas? Tests to try?
Edit:
Here's the rest of the code. It's definitely not code I'm proud of, but it ought to work...
public ActionResult PaypalConfirmation(string token, string payerID)
{
try
{
Cart cart = GetCurrentCart();
if (cart == null)
{
// I never get this email.
SendEmail("Paypal confirmation with null cart", "Token: " + token + ".<br><br>", requestData: Request);
if (token != null && token != "")
{
var tempCart = Cart.GetByAlternateOrderNumber(token);
if (tempCart != null)
{
cart = tempCart;
}
else
{
ViewBag.PaypalError = "we were unable to retreive your cart.";
return View("~/Views/Error/PayPal.cshtml");
}
}
else
{
if (ViewBag == null)
{
SendEmail("VIEWBAG WAS NULL", "Token: " + token + ".<br><br>", requestData: Request);
return View("~/Views/Error/PayPal.cshtml");
}
else
{
// Line which errors
ViewBag.PaypalError = "we were unable to retreive your cart.";
return View("~/Views/Error/PayPal.cshtml");
}
}
}
// More execution code here, including the "Everything worked" return.
}
catch (Exception ex)
{
try
{
var isNull = "";
if (ViewBag == null) isNull = "ViewBag was null!<br><br>";
SendEmail("Crash in Paypal Payment", isNull + ex.ToString(), requestData: Request);
return View("~/Views/Error/PayPal.cshtml");
}
catch (Exception ex2)
{
SendEmail("Crash in reporting Paypal Crash!", ex.ToString() + "<br><br>---------------------<br><br>" + ex2.ToString());
return View("~/Views/Error/PayPal.cshtml");
}
}
}
Email from the catch block:
System.NullReferenceException: Object reference not set to an instance of an object. at Website.Controllers.CartController.PaypalConfirmation(String token, String payerID) in C:#############\Website\Controllers\CartController.cs:line 137
Timestamp: 3/6/2012 10:43:13 AM
IP: #############
URL Requested: /Cart/PaypalConfirmation?token=EC-10L01937X56050826&PayerID=############
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
I doubt this is coming from ViewBag being null. When you add or remove lines, it changes the line numbers of everything below it. So it could have been any code below what you changed. If the new code required you to add a new using statement to the class, it could have changed every line number in the output bytecode.
Have you tried using email as a form of logging instead of just exception catching? For example, what happens when you try this? Not sure whether the ex.Source property would help?
public ActionResult PaypalConfirmation(string token, string payerID)
{
var message = "Trying to confirm paypal.";
SendEmail(message, message);
try
{
message = "Getting current cart.";
SendEmail(message, message);
Cart cart = GetCurrentCart();
message = cart == null
? "Current cart is null."
: "Current cart is not null.";
SendEmail(message, message);
if (cart == null)
{
if (token != null && token != "")
{
message = "Getting temp cart by alternate order number.";
SendEmail(message, message);
var tempCart = Cart.GetByAlternateOrderNumber(token);
message = "Getting temp cart by alternate order number.";
SendEmail(message, message);
if (tempCart != null)
{
message = "Temp cart is not null";
SendEmail(message, message);
cart = tempCart;
}
else
{
message = "Temp cart was null.";
SendEmail(message, message);
ViewBag.PaypalError = "we were unable to retreive your cart.";
message = "ViewBag.PayPalError set, returning view.";
SendEmail(message, message);
return View("~/Views/Error/PayPal.cshtml");
}
}
else
{
message = "Setting ViewBag.PayPalError message.";
SendEmail(message, message);
// Line which errors
ViewBag.PaypalError = "we were unable to retreive your cart.";
message = "ViewBag.PayPalError set, returning view.";
SendEmail(message, message);
return View("~/Views/Error/PayPal.cshtml");
}
}
// More execution code here, including the "Everything worked" return.
message = "Executing more code.";
SendEmail(message, message);
}
catch (Exception ex)
{
SendEmail(ex.GetType().Name + " caught", ex.Source);
return View("~/Views/Error/PayPal.cshtml");
}
}

Categories