How can I automatically add a date to my database in MVC? I don't know how to get the time from my computer without manually writing it in line c.Date = ;. My controller:
public ActionResult Add(Contact c)
{
bool Status = false;
string message = "";
if (ModelState.IsValid)
{
c.Date = DateTime;
db.Contact.Add(c);
db.SaveChanges();
Status = true;
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(c);
}
Just simply use DateTime class.
c.Date = DateTime.Now;
Regarding the format, you can check this site: C# DateTime Format
You need to use the DateTime.Now property, also don't forget you can easily format the DateTime.Now with additional functions like DateTime.Now.ToLongDateString(). I've added it in your code:
public ActionResult Add(Contact c)
{
bool Status = false;
string message = "";
if (ModelState.IsValid)
{
c.Date = DateTime.Now;
db.Contact.Add(c);
db.SaveChanges();
Status = true;
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(c);
}
Related
I'm trying to return a password from a foreach-loop to do some validations, but I can't get the password-variable to return. I keep getting errors. I do this in my controller.
My code:
[HttpPost]
public IActionResult Login(userModel user)
{
ViewBag.Password = pwd.GetPassword(user);
string password = "";
foreach(var pwdR in ViewBag.Password.Rows)
{
password = pwdR[1];
}
return password; // Here I get this error: CS0029: Cannot implicitly convert type 'string' to 'Microsoft.AspNetCore.Mvc.IActionResult'
// VALIDATION CODE
....................
}
What am I doing wrong?
Thank you!
UPDATE:
[HttpPost]
public IActionResult Login(userModel user)
{
ScryptEncoder enc = new ScryptEncoder();
UserModel pwd = new UserModel();
ViewBag.Password = pwd.GetPassword(user);
string password = "";
foreach(var pwdR in ViewBag.Password.Rows)
{
password = pwdR[1];
}
return password; // Here I get this error: CS0029: Cannot implicitly convert type 'string' to 'Microsoft.AspNetCore.Mvc.IActionResult'
// VALIDATION CODE
bool match = enc.Compare(user.pwd, password);
if (match)
{
ViewBag.Error = "You are now logged in.";
return View();
} else
{
ViewBag.Error = "Login failed.";
return View();
}
}
It is a big performance bug to load all users and to find one you need.
Try this code
[HttpPost]
public IActionResult Login(UserModel user)
{
ScryptEncoder enc = new ScryptEncoder();
var userNamePassword= GetUserNamePassword (user) ;
if( userNamePassword==null)
ViewBag.Error = "Login failed. User is not found";
return View();
}
// VALIDATION CODE
bool match = enc.Compare(userNamePassword.Password, password);
if (match)
{
ViewBag.Error = "You are now logged in.";
return View();
} else
{
ViewBag.Error = "Login failed.";
return View();
}
}
change your model class to this
public class UserNamePasswordModel
{
public string Username { get; set; }
public string Password { get; set; }
}
and place this code somewhere near the Login action
private UserNamePasswordModel GetUserNamePassword (UserModel user)
{
UserNamePasswordModel userNamePassword= null;
var connectionString = "Server=localhost;Database=xxxx; uid = xxxx;Password=xxxx;";
using (var connection = new MySqlConnection(connectionString))
{
var command = new MySqlCommand("SELECT UserName, Password FROM User WHERE Username = #Username", connection);
command.Parameters.AddWithValue("#Username", user.Username);
connection.Open();
var reader = command.ExecuteReader();
if (reader.HasRows)
{
if reader.Read()
{
userNamePassword= new UserNamePasswordModel
{
Username= reader.GetString(0),
Password = reader.GetString(1)
};
}
}
reader.Close();
}
}
return userNamePassword;
}
try returning Ok with password in it, something like: return Ok(password);
I am trying to set DateTime Field to display current time and date.
public DateTime Date { get; set; }
What I try so far to pass in setter Date.Now but doesn't work.
I am asking because I need to display DateTime.Now in View but this items should be hidden from User.
User can only see DateTime but can not Edit.
Also in Controller I use something like but doesn't work
DateTime Date = DateTime.Now;
Any idea where I made mistake and how to fix this issues ?
UPDATE
Here is my Controller
public NotesController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Notes> notes = _db.Notes.Include(u => u.Patient);
return View(notes);
}
//Upsert GET
public IActionResult Upsert(int? Id)
{
DateTime Date = DateTime.Now;
NotesVM notesVM = new NotesVM()
{
Notes = new Notes(),
PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
})
};
Notes notes = new Notes();
if (Id == null)
{
// this is for create
return View(notesVM);
}
else
{
// this is for edit
notesVM.Notes = _db.Notes.Find(Id);
if (notesVM.Notes == null)
{
return NotFound();
}
return View(notesVM);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(NotesVM notesVM)
{
if (ModelState.IsValid)
{
if (notesVM.Notes.Id == 0)
{
//Creating
_db.Notes.Add(notesVM.Notes);
}
else
{
//Updating
_db.Notes.Update(notesVM.Notes);
}
_db.SaveChanges();
return RedirectToAction("Index");
}
notesVM.PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
});
return View(notesVM);
}
If you have a constructor for your controller you can set the date property like this:
public NotesController(ApplicationDbContext db)
{
_db = db;
Date = DateTime.Now;
}
updated my answer now that i have seen your constructor.
I need your help. I'm trying to make a custom registration/login in MVC.Net, which uses SimpleCripto to encrypt the passwords. After I register a user everything is saved in my table and it seems all right, but when I try to LogIn I get an error - "The salt was not in an expected format of {int}.{string}", which comes from my "IsValid" method, in the statement "if (user.Password == crypto.Compute(user.PasswordSalt, password))". I'll post my AuthenticantionController with the Register and LogIn methods and if you can point where the problem is and how to solve it I'll be grateful. Thanks in advance !
namespace Final.Controllers
{
public class AuthenticationController : Controller
{
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Models.User user)
{
if (IsValid(user.Email, user.Password))
{
FormsAuthentication.SetAuthCookie(user.Email, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login details are wrong.");
}
return View(user);
}
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Models.User user)
{
try
{
if (ModelState.IsValid)
{
using (AppContext db = new AppContext())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrypPass = crypto.Compute(user.Password);
var newUser = db.Users.Create();
newUser.FirstName = user.FirstName;
newUser.LastName = user.LastName;
newUser.Email = user.Email;
newUser.CompanyName = user.CompanyName;
newUser.Password = encrypPass;
newUser.PasswordSalt = crypto.Salt;
newUser.AdminCode = 0;
user.Password = encrypPass;
user.PasswordSalt = crypto.Salt;
db.Users.Add(newUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Data is not correct");
}
}
catch (DbEntityValidationException e)
{
foreach (var validationErrors in e.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation(
"Class: {0}, Property: {1}, Error: {2}",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
return View();
}
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (AppContext db = new AppContext())
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(user.PasswordSalt, password))
{
IsValid = true;
}
}
}
return IsValid;
}
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
}
Please check the crypto.Compute function parameters. It requires textToHash(which is your password) and salt. You have to interchange the parameters.
you need to modify your IsValid function like this:
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (AppContext db = new AppContext())
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(password, user.PasswordSalt))
{
IsValid = true;
}
}
}
return IsValid;
}
I've been working on a website using ASP.NET MVC, in this website you can directly send an email to a specific email address. It's working properly, but the information being sent in the email (like Name, Email Address, ect.) don't have a database. So I tried adding a database for it, but somehow it's not working and I keep having some errors. I'm just new with this kind of stuff so I'm not sure if it's possible to send the email and at the same time save it to a database. I know there's something wrong with what I'm doing, so someone please help me. Thank you.
Here's my Controller for the sending of email:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
RegisterRepository regRepo = new RegisterRepository();
if (regRepo.Register(model))
{
List<string> paths = new List<string>();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
paths.Add(path);
}
}
var message = new MailMessage();
foreach (var path in paths)
{
var fileInfo = new FileInfo(path);
var memoryStream = new MemoryStream();
using (var stream = fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
string fileName = fileInfo.Name;
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p><b>Email From:</b> {0} ({1})</p><p><b>Message:<b></p><p>{2}</p>";
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "YesDubai.org (REGISTRATION)";
message.Body = string.Format(body, model.Talent_Name, model.Talent_Email, model.Talent_SelfPromotion);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.SendCompleted += (s, e) =>
{
//delete attached files
foreach (var path in paths)
System.IO.File.Delete(path);
};
await smtp.SendMailAsync(message);
ViewBag.Message = "Your message has been sent!";
ModelState.Clear();
return View("Register");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
} return View(model);
}
}
And here's the Modal class:
public partial class TalentInfo
{
[Display(Name = "ID")]
public int TalentID { get; set; }
[Display(Name = "Talent's Name")]
public string Talent_Name { get; set; }
[Display(Name = "Email Address")]
public string Talent_Email { get; set; }
[Display(Name = "Self Promotion")]
public string Talent_SelfPromotion { get; set; }
}
And here's the Repository:
public class RegisterRepository
{
//SqlTransaction transaction = null;
private SqlConnection con;
//To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
con = new SqlConnection(constr);
}
internal bool Register(TalentInfo model)
{
throw new NotImplementedException();
connection();
try
{
SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Talent_name", model.Talent_Name);
com.Parameters.AddWithValue("#Talent_email", model.Talent_Email);
com.Parameters.AddWithValue("#Talent_SelfPromotion", model.Talent_SelfPromotion);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return Register(model);
}
finally
{
con.Close();
}
}
}
This is simply a compile error. You need to return a result in all paths of your code.
You have a missing return here
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
//you have lots of code here....
}
else
{
//you need to return something here....because (ModelState.IsValid) might be false
}
}
There are 2 Errors in your code:
1) Return something when if (ModelState.IsValid) evaluates to false.
2) In the register method, remove this line :
throw new NotImplementedException();
Having trouble update users in AD
My Model:
public class UserModel
{
....
[ScaffoldColumn(false)]
[DisplayName("Fødselsdag")]
[DataType(DataType.Date)]
[NotMapped]
public DateTime extensionAttribute1_date
{
get
{
try
{
return DateTime.Parse(extensionAttribute1);
}
catch (Exception e)
{
return new DateTime();
}
}
set { }
}
}
My Controller:
[HttpPost]
public ActionResult Edit(string sAMAccountName, FormCollection collection, UserModel data)
{
if (ModelState.IsValid)
{
var config = new LdapConfiguration();
config.ConfigureFactory("domain.local").AuthenticateAs(new NetworkCredential("xxxx", "xxxxx"));
using (var context = new DirectoryContext(config))
{
var user = context.Query(new UserModel(), "OU=users,OU=xxx,DC=xxx,DC=dk", "User").FirstOrDefault(d => d.sAMAccountName == sAMAccountName);
if (user == null) return RedirectToAction("Index");
user.title = data.title;
user.mobile = data.mobile;
user.homePhone = data.homePhone;
user.streetAddress = data.streetAddress;
user.postalCode = data.postalCode;
user.l = data.l;
user.department = data.department;
user.physicalDeliveryOfficeName = data.physicalDeliveryOfficeName;
user.extensionAttribute1 = data.extensionAttribute1_date.ToLongDateString();
context.Update(user);
}
return RedirectToAction("Index");
}
return View();
}
When i submit to Edit Action i results in an error:
The requested attribute does not exist.
If i remove extensionAttribute1_date from the model i updates fine.
How do i exclude my calculated attributes from the update?
I have other attributes in the model such as Age which is calculated! Is this the wrong procedure for this?
/Michael