Calculated attributes in model results in The requested attribute does not exist - c#

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

Related

How to initialize DateTime property to show Date.Now

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.

how to pass a Model from a controller to another controller

I'm starter in .NET MVC. I want to pass a model from one controller to another controller, model contain a password. My first controller is auth method, in that I used Claims, but another controller is a vote method there I need to Post an ID, Password and Vote. Password I need in vote controller for voting confirmation in database.
My code:
My model:
public class LoginModel
{
public string IDNP { get; set; }
public string VnPassword { get; set;
}
My first controller:
public class AuthController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(LoginModel model)
{
var data = new LoginData();
data.IDNP = model.IDNP;
data.VnPassword = model.VnPassword;
var response = await session.Login(data);
if (response.Status == true)
{
var authclaims = new List<Claim>()
{
new Claim(ClaimTypes.Name, data.IDNP),
};
var authIdentity = new ClaimsIdentity(authclaims, "User Identity");
var userPrincipal = new ClaimsPrincipal(new[] {authIdentity});
HttpContext.SignInAsync(userPrincipal);
return RedirectToAction("Index", "Vote",new{pass=data.VnPassword});
}
else
{
return View();
}
}
}
My second controller:
public class VoteController : Controller
{
private IVote connection;
public VoteController()
{
var bl = new BusinessManager();
connection = bl.GetVote();
}
[Authorize]
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(VoteModel vote)
{
var identity = (ClaimsIdentity)User.Identity;
var voteindex = new VoteData();
voteindex.IDNP = identity.Name;
voteindex.VnPassword = ;
voteindex.Party = vote.Party;
var response = await connection.Vote(voteindex);
if (response.Status == true)
return RedirectToAction("Index", "Home");
else
{
return RedirectToAction("Index", "Auth");
}
}
}
Actually, it's a bad idea to send Id and Password to another controller. It conflicts SRP rule.
You should have only one controller that gets and uses password.
However, if you want to use this action, you can use this

How to Update Employee and Identity User with one to one/zero relation

I am trying to update employee record and want to update identity user too.
If i update Identity User first separately
For Example:
UserManager.Update(user);
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
Context.SaveChanges();
and then update the employee.
maybe it is possible identity user updates with success but employee update process gets an error.
so IdentityUser is updated now but the employee is not.
how to handle this situation.
please guide.
public class Employee
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string AppUserId { get; set; }
[ForeignKey("AppUserId")]
public virtual AppUser AppUser { get; set; }
}
public class AppUser : IdentityUser<string, AppUserLogin, AppUserRole, AppUserClaim>, IUser<string>
{
public AppUser()
{
this.Id = Guid.NewGuid().ToString();
}
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<AppUser, string> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
}
public JsonResult Create(EmployeeVM evm, AppUserVM appUser)
{
var jsonResult = new JsonResult();
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
if (ModelState.IsValid)
{
var user = new AppUser();
evm.CreatedDate = DateTime.Now.Date;
appUser.PasswordHash = "dummypass";
user = Mapper.Map<AppUser>(appUser);
var employee = Mapper.Map<Employee>(evm);
employee.AppUser = user;
try
{
if (userService.CreateEmployee(employee))
{
jsonResult.Data = new { Success = true, message = "Success Added Record"};
}
}
catch (Exception ex)
{
jsonResult.Data = new { Success = false, message =ex.Message};
}
}
else
{
jsonResult.Data = new { Success = false, message = ModelErrors() };
}
return jsonResult;
}
public bool CreateEmployee(Employee employee)
{
Context.Employees.Add(employee);
return Context.SaveChanges()>0;
}
Adding new record works fine.
but when i update the record. i don't know how to update both records at once.
For Example:
public JsonResult Edit(EmployeeVM evm, AppUserVM appUserVM)
{
ModelState.Remove(nameof(evm.CreatedDate));
var jsonResult = new JsonResult();
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
if (ModelState.IsValid)
{
appUserVM.UserName = appUserVM.Email;
var user = UserManager.FindById(evm.UserId);
user.Email = appUserVM.Email;
user.UserName = appUserVM.UserName;
user.FirstName = appUserVM.FirstName;
user.LastName = appUserVM.LastName;
user.IsActive = appUserVM.IsActive;
user.PhoneNumber = appUserVM.PhoneNumber;
var employee = Mapper.Map<Employee>(evm);
employee.AppUser = user;
employee.Id = evm.Id;
employee.AppUserId = user.Id;
try
{
if(userService.UpdateEmployee(employee))
jsonResult.Data = new { Success = true, message = "Success" };
}
catch (Exception ex)
{
jsonResult.Data = new { Success = false, message = ex.Message };
}
}
else
{
jsonResult.Data = new { Success = false, message = ModelErrors() };
}
return jsonResult;
}
public bool UpdateEmployee(Employee employee)
{
Context.Entry(employee).State = System.Data.Entity.EntityState.Modified;
return Context.SaveChanges() > 0;
}
Without seeing the exception, I'm not sure what the issue is, but you could trying using an attached entity and set values like the following.
var dbEmployee = Context.Emplyoees.SingleOrDefault(s => s.Id == employee.Id);
if (dbEmployee!= null)
Context.Entry(dbEmployee).CurrentValues.SetValues(employee);
The User employee service should be
public bool UpdateEmployee(Employee employee)
{
var existingEmployee = Context.Emplyoees.FirstOrDefault(s => s.Id == employee.Id);
if (existingEmployee != null)
{
//do the update to the database
Context.Entry(existingEmployee).CurrentValues.SetValues(employee);
Context.Entry(existingEmployee).State = System.Data.Entity.EntityState.Modified;
return Context.SaveChanges() > 0;
}
else return false;
}

Perform CRUD in controller with ViewModel in ASP.NET MVC

From my two models Student and InventoryRecord. I created a ViewModel named TestViewModel. I'm confused as to how do I write my controller?
public class TestViewModel
{
//from Student model
[Key]
public string UserID { get; set; }
public string PhoneNumber{ get; set; }
public string Address{ get; set; }
//other properties
//from Inventory model
public string FathersName { get; set; }
public string FathersAddress { get; set; }
//other properties
}
When I'm using only my main model Student. This is how I write my controller:
// GET: Students/CreateEdit
public ActionResult InventoryRecord()
{
var currentUserId = User.Identity.GetUserId();
var newid = db.Students.FirstOrDefault(d => d.UserID == currentUserId);
if (newid == null)
{
newid = db.Students.Create();
newid.UserID = currentUserId;
db.Students.Add(newid);
}
Student student = db.Students.Find(newid.UserID);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: Students/CreateEdit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult InventoryRecord(Student student)
{
var currentUserId = User.Identity.GetUserId();
var userName = User.Identity.GetUserName();
var u = db.Students.FirstOrDefault(d => d.UserID == currentUserId);
if (u == null)
{
u = db.Students.Create();
u.UserID = currentUserId;
db.Students.Add(u);
}
if (ModelState.IsValid)
{
u.PhoneNumber = student.PhoneNumber;
u.Address = student.Address;
//other properties
db.SaveChanges();
TempData["Message"] = "User: " + userName + ", details successfully updated!";
}
return View(student);
}
Now, I'm really confused how to proceed here. How should I write my controller if I'm using my TestViewModel? Someone please point me in the right direction. Thank you.
Well personally I would move the code out of the controller.
However for example you just need to create an instance of your TestViewModel and pass that to your view. You may also need to update your View if you specific the model in the cshtml.
public ActionResult InventoryRecord()
{
var currentUserId = User.Identity.GetUserId();
var newid = db.Students.FirstOrDefault(d => d.UserID == currentUserId);
if (newid == null)
{
newid = db.Students.Create();
newid.UserID = currentUserId;
db.Students.Add(newid);
}
Student student = db.Students.Find(newid.UserID);
if (student == null)
{
return HttpNotFound();
}
TestViewModel model = new TestViewModel
{
UserID = student.UserId,
PhoneNumber = student.PhoneNumber,
//add the rest.
};
return View(model);
}
Rather than returning Student , return TestViewModel
Student student = db.Students.Find(newid.UserID);
if (student == null)
{
return HttpNotFound();
}
TestViewModel tvm = new TestViewModel()
{
UserID =student.Id,
PhoneNumber = student.PhoneNumber,
Address= student.Address
};
return View(tvm);
}
and second method will be
public ActionResult InventoryRecord(TestViewModel tvm)

parameter with value when assigned to a list item it becomes null

I have this method which passes in parameters and all the parameters hold a value but when i assign them to my viewModel one of them becomes null and not sure why:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
viewModel.AssociatedCasesSelected = associatedCasesSelected;
viewModel.PartiesSelected = selectedParties;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
This is the line:
viewModel.PartiesSelected = selectedParties;
selectedParties should hold one value but when i assign it to partiesSelected - it shows me while debugging that PartiesSelected = null;
This is partiesSelected in my viewModel:
public IList<Guid> PartiesSelected { get; set; }

Categories