Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [HttpPost]
- public ActionResult Create(CreateModel model) {
- // Retrieve and encode the user supplied arguments.
- string email = HttpUtility.HtmlEncode(model.Email.GetNullSafe()).Trim();
- string firstName = HttpUtility.HtmlEncode(model.FirstName.GetNullSafe()).Trim();
- string lastName = HttpUtility.HtmlEncode(model.LastName.GetNullSafe()).Trim();
- // Check if the model state currently has any errors.
- if (ModelState.IsValid) {
- // Retrieve the session for the current request.
- var session = GlobalApplication.SessionFactory.GetCurrentSession();
- // Query the system for the user that matches the supplied user name.
- var query =
- from user in session.Query<User>()
- where user.Email.ToLower() == email.ToLower() &&
- (user.Status & UserStatusTypes.Active) != 0
- select user;
- // Check if the query returned any matching results.
- if (query.Any()) {
- // Add an error to the model state describing the failure.
- ModelState.AddModelError("_FORM", "Oh no! It looks like a user already exists with the same e-mail address.");
- } else {
- // Initialize the transaction for the account creation attempt.
- using (var transaction = session.BeginTransaction()) {
- // Generate the new random password for the user.
- string password = GeneratePassword();
- // Create the new user account using the supplied details.
- var user = Domain.User.Create(
- email.ToLower(),
- password);
- // Save the newly created user.
- session.Save(user);
- // Create the user's profile using the supplied details.
- var profile = Profile.Create(
- user,
- firstName,
- null,
- lastName);
- // Initialize the profile for the user.
- user.WithProfile = profile;
- // Save the newly created user profile.
- session.Save(profile);
- // Commit the changes for the user creation transaction.
- transaction.Commit();
- // Return a successful completion for the creation of the new user.
- return Json(new {
- status = "OK",
- values = new {
- id = user.Id.ToString("000000"),
- name = user.GetName(),
- timestamp = user.DateLastModified.ToLocalTime().ToShortDateString()
- }
- });
- }
- }
- }
- // Attempt to retreive the first error from the model state.
- var error = ModelState.Values.FirstOrDefault(s => s.Errors.Count() > 0);
- // Initialize the message that was returned for the call.
- string message = (error == null) ?
- "An unexpected error has occurred. Please contact support." :
- error.Errors.First().ErrorMessage;
- // Return data pertaining to the creation of the user.
- return Json(new {
- status = "ERROR",
- message = message
- });
- }
Add Comment
Please, Sign In to add comment