How to solve the error occurred in password recovery? - c#

I'm using asp.net c# with EF and i'm trying to reset the password when user forget it. And in there i'm sending an email link to the user's provided email if it is in the database.
But it'll give me an error at the point member = Membership.GetUser(foundemail); saying
{"An error occurred while attempting to initialize a System.Data.SqlClient.SqlConnection object. The value that was provided for the connection string may be wrong, or it may contain an invalid syntax.\r\nParameter name: connectionString"}
Here is my code in the controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordModel resetpasswordmodel)
{
if (ModelState.IsValid)
{
//User user;
MembershipUser member;
using (TheFoodyContext db = new TheFoodyContext())
{
/*var foundemail = (from e in db.Users
where e.email == resetpasswordmodel.Email
select e.email).FirstOrDefault();*/
var foundemail = (db.Users.Find(resetpasswordmodel.Email)).email.ToString();
if (foundemail != null)
{
member = Membership.GetUser(foundemail);
}
else
{
member = null;
}
}
if (member != null)
{
//Generate password token that will be used in the email link to authenticate user
var token = WebSecurity.GeneratePasswordResetToken(member.Email);
// Generate the html link sent via email
string resetLink = "<a href='"
+ Url.Action("ResetPasswordView", "Account", new { rt = token }, "http")
+ "'>Reset Password Link</a>";
// Email stuff
string subject = "Reset your password for TheFoody.com";
string body = "You link: " + resetLink;
string from = "abcd123#gmail.com";
string to = resetpasswordmodel.Email;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);
message.Subject = subject;
message.Body = body;
SmtpClient client = new SmtpClient();
// Attempt to send the email
try
{
client.Send(message);
}
catch (Exception e)
{
ModelState.AddModelError("", "Issue sending email: " + e.Message);
}
}
else // Email not found
{
ModelState.AddModelError("", "No user found by that email.");
}
}
return View(resetpasswordmodel);
}
And here is my connectionString in web.config
<add name="TheFoodyContext" connectionString="metadata=res://*/TheFoodyModel.csdl|res://*/TheFoodyModel.ssdl|res://*/TheFoodyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-NJOQTOK;initial catalog=TheFoody;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I'm very new to this environment and can anyone help me?

Related

Mailkit is sending emails with the incorrect from address

I've written a mail method and I'm setting the from email address but when the customer receives it, it's the same as the username that is used to authenticate the email.
I've tried to set the email right before the send and it still comes out wrong:
When I check the message, as shown above, the from is correct but the customer receives it from the username field instead.
public static EmailResults SendEmail(EmailSettings emailSettings)
{
var emailResults = new EmailResults();
try
{
// using mimekit that the msdn smtpclient webpage suggested using
// http://www.mimekit.net/docs/html/Introduction.htm
if (emailSettings.TestModeEnabled)
{
emailResults.IsSuccessful = true;
emailResults.Message = "SendEmail disabled due to TestModeEnabled being set to true.";
return emailResults;
}
// use the mimemessage to create the message to send
var message = new MimeMessage();
message.From.Add(emailSettings.FromEmail);
message.Subject = emailSettings.EmailSubject;
// to email has the option for multiple emails to be sent to
// loop through them and add them all to the message
foreach (var mailboxAddress in emailSettings.ToEmail)
{
message.To.Add(mailboxAddress);
}
// attach file if present
var builder = new BodyBuilder();
if (emailSettings.FileAttachments != null)
{
foreach (var file in emailSettings.FileAttachments)
{
if (File.Exists(file))
{
builder.Attachments.Add(file);
}
}
}
builder.HtmlBody = emailSettings.EmailBody;
message.Body = builder.ToMessageBody();
//// http://www.mimekit.net/docs/html/Creating-Messages.htm
//// A TextPart is a leaf-node MIME part with a text media-type. The first argument to the
//// TextPart constructor specifies the media-subtype, in this case, plain. Another media
//// subtype you are probably familiar with is the html subtype. Some other examples
//// include enriched, rtf, and xml.
//message.Body = new TextPart("html")
//{
// Text = emailSettings.EmailBody
//};
// bcc has the option for multiple emails to be sent to
// loop through them and add them all to the message
if (emailSettings.BccEmail != null)
{
foreach (var mailboxAddress in emailSettings.BccEmail)
{
message.Bcc.Add(mailboxAddress);
}
}
// *************** SEND EMAIL *******************
var client = emailSettings.EnableSmtpLog ? new MailKit.Net.Smtp.SmtpClient(new ProtocolLogger(GlobalVariables.SmptpLogFile)) : new MailKit.Net.Smtp.SmtpClient();
using (client)
{
if (emailSettings.SmtpServer.Contains("gmail.com"))
{
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
}
client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
//accept all SSL certificates
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
// client.Connect(emailSettings.SmtpServer, emailSettings.SmtpPort, emailSettings.IsSslEnabled);
client.Connect(emailSettings.SmtpServer, emailSettings.SmtpPort, emailSettings.AuthType);
if (emailSettings.IsAuthenticationRequired)
{
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailSettings.SmtpUsername, emailSettings.SmtpPassword);
}
if (emailSettings.TimeOut == 0) emailSettings.TimeOut = 10;
client.Timeout = emailSettings.TimeOut * 1000;
//message.From.Add(new MailboxAddress("someone#somewhere.net"));
client.Send(message);
client.Disconnect(true);
}
// if we reached this far, then the email was sent successfully
emailResults.Message = "Successfully sent.";
emailResults.IsSuccessful = true;
return emailResults;
}
catch (AuthenticationException e)
{
Logging.LogException("SmtpClient.SendEmail", "Error attempting to send email.", e);
emailResults.IsSuccessful = false;
emailResults.Message = "Invalid username or password.";
return emailResults;
}
catch (Exception e)
{
Logging.LogException("SmtpClient.SendEmail", "Error attempting to send email.", e);
emailResults.IsSuccessful = false;
if (e.Message.Contains("error occurred while attempting to establish an SSL or TLS connection"))
{
emailResults.Message = "An error occurred while attempting to establish a secure connection.\r\n\r\nPlease check your email settings.";
}
else
{
emailResults.Message = e.Message;
}
return emailResults;
}
}
Anyone have any suggestions on what I'm doing wrong?
For anyone who runs in to this again...
This particular issue is specific to Gmail. I'm not sure if other email hosts do the same.
If you are setting the from email address to "person1#email.com" but authenticating with "person2#gmail.com", Gmail will override the from email address with the authentication email address. You have no control over this.
Go to the Gmail account, into settings, and add the alias address in the "Send Mail As" section. The outgoing email should now display with the alias address rather than the authenticating address.

ModelState.AddModelError is setup to display Canned message instead of real Error

In my website i had a group of people working on my site and i have this code that they put a canned message in for an error. When i debug the code it is actually a different error but displays this canned message. For instance when i put the information in the form i used an email address that already exists in the database but it is showing a message to check the password requirements. How can this be fixed to show the actual error. To me it also seems like there is a lot code going on in this that may not need to be or can be achieved cleaner Your thoughts?
Code of Post Action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateCompanyUser(ExpandedUserDTO ExpandedUserDTO)
{
try
{
if (ExpandedUserDTO == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Email = ExpandedUserDTO.Email.Trim();
var UserName = ExpandedUserDTO.UserName.Trim();
var Password = ExpandedUserDTO.Password.Trim();
if (UserName == "")
{
throw new Exception("No Username");
}
if (Password == "")
{
throw new Exception("No Password");
}
// UserName is LowerCase of the Email
// UserName = Email.ToLower();
// Create user
var objNewAdminUser = new Models.ApplicationUser { UserName = UserName, Email = Email };
var AdminUserCreateResult = UserManager.Create(objNewAdminUser, Password);
if (AdminUserCreateResult.Succeeded == true)
{
string strNewRole = Convert.ToString(Request.Form["Roles"]);
if (strNewRole != "0")
{
// Put user in role
UserManager.AddToRole(objNewAdminUser.Id, strNewRole);
}
var viewModel = new Users();
{
viewModel.UsersId = Convert.ToString(Guid.NewGuid());
viewModel.Email = Email;
viewModel.FirstName = UserName;
viewModel.AspNetUsersId = objNewAdminUser.Id;
viewModel.CreatedDate = System.DateTime.Now;
viewModel.UpdatedDate = System.DateTime.Now;
};
UsersBusinessModels Login = new UsersBusinessModels();
var results = Login.insertUserWithougAsny(viewModel);
string[] roleRemove = new string[2] { "Administrator", "CompanyAdmin" };
ViewBag.Roles = GetAllRolesAsSelectList().Where(k => !roleRemove.Contains(k.Text)).ToList();
// return RedirectToAction();
Response.Redirect("/Customer/ManageUsers/" + User.Identity.GetUserId());
return PartialView();
}
else
{
ViewBag.Roles = GetAllRolesAsSelectList();
ModelState.AddModelError(string.Empty,
"Error: Failed to create the user. Check password requirements.");
return PartialView(ExpandedUserDTO);
}
}
catch (Exception ex)
{
ViewBag.Roles = GetAllRolesAsSelectList();
ModelState.AddModelError(string.Empty, "Error: " + ex);
string[] roleRemove = new string[2] { "Administrator", "CompanyAdmin" };
ViewBag.Roles = GetAllRolesAsSelectList().Where(k => !roleRemove.Contains(k.Text)).ToList();
return PartialView(ExpandedUserDTO);
}
}

ASP.net MVC 5 project SMTP function error [duplicate]

This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 3 years ago.
As the title above, I have created a project with simple log-in and registration. Inside the program, I have use System.Net.Mail.SmtpException to send the email verification to the user email. I have done created the email but when I click on create a new account, I met this problem as well.
System.Net.Mail.SmtpException: 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
From the information I search, I found out someone say I need to make my email 2-step verification. I did it but the problem still there.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using Food_Founder.Models;
namespace Food_Founder.Controllers
{
public class UserController : Controller
{
//Registration
[HttpGet]
public ActionResult Registration()
{
return View();
}
//Post Registration
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")]User user)
{
//Model Validation
bool Status = false;
string message = "";
//Email is already exist
if (ModelState.IsValid)
{
#region Email is already exist
var isExist = IsEmailExist(user.Email);
if (isExist)
{
ModelState.AddModelError("EmailExist", "Email already exist");
return View(user);
}
#endregion
#region Generate Activation Code
user.ActivationCode = Guid.NewGuid();
#endregion
#region Password Hashing
user.Password = Crypto.Hash(user.Password);
user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);
#endregion
user.IsEmailVerified = false;
#region Save Data to Database
using (myDatabaseEntities myDatabase = new myDatabaseEntities())
{
myDatabase.Users.Add(user);
myDatabase.SaveChanges();
//Send Email to User
SendVerificationLinkEmail(user.Email, user.ActivationCode.ToString());
message = "Registration successfully done. Account activation link" +
"has been send to your Email:" + user.Email + "Please go check and activate your account";
Status = true;
}
#endregion
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(user);
}
//Verify Email
//Verify Email Link
//Login
//Login POST
//Logout
[NonAction]
public Boolean IsEmailExist(string email)
{
using (myDatabaseEntities myDatabase = new myDatabaseEntities())
{
var v = myDatabase.Users.Where(a => a.Email == email).FirstOrDefault();
return v != null;
}
}
[NonAction]
public void SendVerificationLinkEmail(string email, string activationCode)
{
var verifyUrl = "/User/VerifyAccount/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
var fromEmail = new MailAddress("yukwokyao2#gmail.com", "yukwokyao");
var toEmail = new MailAddress(email);
var fromEmailPassword = "********";
string subject = "Your account is successfully created!";
string body = "<br/><br/>We are excited to tell you that your FoodFounder account is" +
"successfully created. Please click the below link to verify your FoodFounder account" +
"<a href = '" + link + "' >" + link + "</a>";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
}
}
The code above is the controller class I created. The problem I found is there so that I didn't put any other design html code in here. The most weird part is even I met this problem, the data I register still can key-in into the database but this annoying problem still exist there. Anywhere, if anything I miss put, please inform me ya.. Thank you.
If you are using your Gmail account as SMTP server you need to allow access from what Google calls "less secure apps". You can enable it from your Google settings.

How can I check if the user logged in successfully in Axosoft using AxosoftAPI.NET Winforms

I am trying to check if the user is successfully logged in to Axosoft. The code bellow never throws an error, even if the user provides the wrong credentials.
public void Login(string user, string pwd)
{
try
{
AxoClient.ObtainAccessTokenFromUsernamePassword
(
username: user,
password: pwd,
scope: ScopeEnum.ReadWrite
);
}
catch (AxosoftAPIException<ErrorResponse> ex)
{
ErrorResponse er = new ErrorResponse();
er.Error = ex.Source;
er.ErrorDescription = ex.StackTrace;
er.Message = ex.Message;
throw new AxosoftAPIException<ErrorResponse>(er);
}
}
I found the solution for my problem.
After a login you can get the value of the HasAccessToken in Proxy.
If you successfully logged in it will return true, otherwise it'll return false.
Proxy AxoClient = new Proxy
{
Url = "http://url",
ClientId = "ClientId",
ClientSecret = "ClientSecret",
};
AxoClient.ObtainAccessTokenFromUsernamePassword
(
username: user,
password: pwd,
scope: ScopeEnum.ReadWrite
);
MessageBox.Show(AxoClient.HasAccessToken);
I hope this will help others.

registration confirmation email

[HttpPost]
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
UserAPIController uApi = new UserAPIController(true);
HttpResponseMessage response = uApi.Register(user, Request.QueryString["TeamId"]);
if (response.StatusCode == System.Net.HttpStatusCode.Conflict)
{
ModelState.AddModelError("", HttpContext.GetGlobalResourceObject("LanguageResource", "DuplicateEmailErrorMessage").ToString());
return View();
}
//Send Registration Email
string EmailBodyStr = string.Empty;
string EmailFrom = Helpers.CommonFunctions.GetApplicationSettingValue("SystemEmailId");
string EmailSub = HttpContext.GetGlobalResourceObject("LanguageResource", "EmailTemplate_Reistration_Subject").ToString();
string userName = user.FullName;
if (string.IsNullOrEmpty(userName))
{
userName = user.Email;
}
EmailBodyStr = HttpContext.GetGlobalResourceObject("LanguageResource", "EmailTemplate_Registration_TeamLeader_Body").ToString();
EmailBodyStr = EmailBodyStr.Replace("[UserFullName]", userName);
string email = HttpUtility.UrlEncode(Helpers.Encrypt.EncryptString(user.Email));
EmailBodyStr = EmailBodyStr.Replace("[NavigationLink]", "click here");
if (EmailFrom != string.Empty)
{
Helpers.Emailer.SendEmail(user.Email, EmailSub, EmailBodyStr, EmailFrom);
}
ModelState.AddModelError("", HttpContext.GetGlobalResourceObject("LanguageResource", "SuccessfullRegistrationMessage").ToString());
}
return View(user);
}
I have created a registration form in mvc4 in which the user get confirmation email once it get registered but its sending the same registration email two times. Above is the code which is used for registration confirmation.
Please let me know where is the problem in code and why its triggering same event two times.

Categories

Resources