Esempio n. 1
0
        public ActionResult BlockMessage(int id)
        {
            try
             {
            Message message = messageService.GetById(id);
            message.AttemptsCount = 0;
            message.UpdatedDate = DateTime.UtcNow;
            message.Status = MessageStatus.NotSent;
            message.AttemptsCount = 3;

            messageService.Save(message);

            MessageModel messageModel = new MessageModel
            {
               Text = "The selected message has been blocked!",
               Icon = MessageModel.MessageIcon.Info,
            };
            RegisterMessage(messageModel, true);
             }
             catch (Exception ex)
             {
            log.Error("MessagesController.Delete", ex);

            MessageModel messageModel = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };

            RegisterMessage(messageModel, true);
             }

             return RedirectToAction("Index");
        }
        public ActionResult EnableAllSiteFeatures(int sid)
        {
            Site site = siteService.GetSiteById(sid);

             try
             {
            foreach (SiteFeature siteFeature in site.Features)
            {
               siteFeature.Enabled = true;
               featureService.SaveSiteFeature(siteFeature);
            }

            siteService.SaveSite(site);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("AllSiteFeaturesEnabled"),
               Icon = MessageModel.MessageIcon.Info,
            };
            RegisterMessage(message, true);
             }
             catch (Exception ex)
             {
            log.Error(ex.ToString());

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(message, true);
             }

             return View("SiteFeatures", siteService.GetAllSites());
        }
Esempio n. 3
0
        public ActionResult ChangeStatus(int id, CommentStatus status)
        {
            Comment comment = commentService.GetById(id);

             comment.Status = status;
             comment.UpdatedBy = Context.CurrentUser;
             comment.UpdatedDate = DateTime.Now.ToUniversalTime();

             try
             {
            commentService.SaveComment(comment);

            // send the updated comment view
            return View("~/Areas/Admin/Views/AdminComment/Comment.ascx", comment);
             }
             catch (Exception ex)
             {
            log.Error("AdminCommentController.Update", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 4
0
        public ActionResult Create(int id, string name, int[] rightIds)
        {
            Role role = new Role();
             role.Site = Context.ManagedSite;

             try
             {
            UpdateModel(role, new[] { "Name" });

            if (rightIds != null && rightIds.Length > 0)
            {
               IList<Right> rights = userService.GetRightsByIds(rightIds);
               foreach (Right right in rights)
               {
                  log.DebugFormat("RightId {0}", right.Id);
                  role.Rights.Add(right);
               }
            }

            userService.UpdateRole(role);

            // Show the confirmation message
            MessageModel message = new MessageModel
            {
               Text = "Role created successfully!",
               Icon = MessageModel.MessageIcon.Info,
               CssClass = "margin-topbottom",
               IsClosable = true
            };
            RegisterMessage(message, true);

            return RedirectToAction("Index");
             }
             catch (Exception ex)
             {
            log.Error("RolesController.Create", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };
            RegisterMessage(message);
             }

             RoleModel model = new RoleModel()
             {
            Role = userService.GetRoleById(id),
            AllRights = userService.GetAllRights()
             };

             return View("NewRole", model);
        }
Esempio n. 5
0
        public ActionResult Rebuild()
        {
            try
             {
            //only one thread at a time
            System.Threading.Monitor.Enter(lockObject);

            IContentItemService<IContentItem> contentItemService = IoC.Resolve<IContentItemService<IContentItem>>();
            ISearchService searchService = IoC.Resolve<ISearchService>();
            IEnumerable<IContentItem> contentItemsToIndex = from c in contentItemService.FindAllBySite(Context.ManagedSite)
                                                            where c.PublishedDate.HasValue == true
                                                               && c.PublishedDate.Value <= DateTime.Now
                                                            select c;

            searchService.RebuildIndex(Context.ManagedSite, contentItemsToIndex);

            MessageModel model = new MessageModel
            {
               Text = "Rebuild completed!",
               Icon = MessageModel.MessageIcon.Info,
               CssClass = "margin-topbottom",
               IsClosable = true
            };
            RegisterMessage(model, true);

             }
             catch (Exception ex)
             {
            log.Error(ex.ToString());

            // Show the confirmation message
            MessageModel model = new MessageModel
            {
               Text = ex.Message,
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };
            RegisterMessage(model, true);
             }
             finally
             {
            System.Threading.Monitor.Exit(lockObject);
             }

             return View("Index");
        }
Esempio n. 6
0
        public ActionResult Save()
        {
            SeoSettings seo = Context.ManagedSite.SeoSettings ?? new SeoSettings{Site = Context.ManagedSite};

             try
             {
            UpdateModel(seo);

            // TODO: add date
            //seo.UpdatedDate = DateTime.UtcNow;

            Context.ManagedSite.SeoSettings = seo;

            siteService.SaveSite(Context.ManagedSite);
             }
             catch (Exception ex)
             {
            log.Error("SiteController.SaveSettings", ex);

            foreach (string key in this.ModelState.Keys)
            {
               if (this.ModelState[key].Errors.Count > 0)
                  this.ModelState[key].Errors.Each().Do(error => log.Error(error.Exception.ToString()));
            }

            MessageModel model = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };
            RegisterMessage(model);

            return View("Index", seo);
             }

             return RedirectToAction("Index", "Site", Context.ManagedSite.SiteId);
        }
Esempio n. 7
0
        public ActionResult Change(int id, int? page)
        {
            Theme selectedTheme = themeService.GetById(id);

             Site managedSite = Context.ManagedSite;

             managedSite.Theme = selectedTheme;

             try
             {
            siteService.SaveSite(managedSite);

            MessageModel model = new MessageModel
            {
               Text = "The selected theme has been successfully applied to the site!",
               Icon = MessageModel.MessageIcon.Info,
               CssClass = "margin-topbottom"
            };
            RegisterMessage(model);

             }
             catch (Exception ex)
             {
            log.Error(ex.ToString());

            MessageModel model = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };
            RegisterMessage(model);
             }

             return View("Index", GetIndexData(page));
        }
Esempio n. 8
0
        public ActionResult OpenIdConnect(int id)
        {
            User user = userService.GetUserById(id);
             var response = openid.GetResponse();

             if (response == null)
             {
            // Stage 1: user submitting Identifier
            Identifier openIdIdentifier;

            if (Identifier.TryParse(Request.Form["openid_identifier"], out openIdIdentifier))
            {
               try
               {
                  return openid.CreateRequest(openIdIdentifier)
                                 .RedirectingResponse
                                 .AsActionResult();
               }
               catch (ProtocolException ex)
               {
                  log.ErrorFormat("UsersController: error sending OpenID request for id \"{0}\".\r\n{1}", Request.Form["openid_identifier"], ex.ToString());
                  //ViewData["AuthenticationFailed"] = "AuthenticationException failed!";
                  MessageModel message = new MessageModel
                  {
                     Text = "AuthenticationException failed!",
                     Icon = MessageModel.MessageIcon.Alert,
                  };
                  RegisterMessage(message, true);
               }
            }
            else
            {
               ViewData["AuthenticationFailed"] = "OpenID identifier invalid!";
               MessageModel message = new MessageModel
               {
                  Text = "OpenID identifier invalid!",
                  Icon = MessageModel.MessageIcon.Alert,
               };
               RegisterMessage(message, true);
            }
             }
             else
             {
            // Stage 2: OpenID Provider sending assertion response
            switch (response.Status)
            {
               case AuthenticationStatus.Authenticated:

                  try
                  {
                     //string userOpenId = response.FriendlyIdentifierForDisplay;
                     string userOpenId = response.ClaimedIdentifier;

                     user.ExternalId = userOpenId;
                     user.ExternalProviderUri = response.Provider.Uri.Authority;
                     user.UpdatedDate = DateTime.UtcNow;

                     userService.SaveUser(user);

                     MessageModel successMessage = new MessageModel
                     {
                        Text = string.Format("The user {0} is now associated with the selected provider!", user.DisplayName),
                        Icon = MessageModel.MessageIcon.Info,
                     };
                     RegisterMessage(successMessage, true);
                  }
                  catch (Exception ex)
                  {
                     log.Error("Unexpected error while logging in", ex);
                     MessageModel errorMessage = new MessageModel
                     {
                        Text = GlobalResource("Message_GenericError"),
                        Icon = MessageModel.MessageIcon.Alert,
                     };
                     RegisterMessage(errorMessage, true);
                  }
                  break;

               case AuthenticationStatus.Canceled:
                  MessageModel authCanceledMessage = new MessageModel
                  {
                     Text = "Canceled at provider",
                     Icon = MessageModel.MessageIcon.Alert,
                  };
                  RegisterMessage(authCanceledMessage, true);
                  break;

               case AuthenticationStatus.Failed:
                  MessageModel authFailedMessage = new MessageModel
                  {
                     Text = response.Exception.Message,
                     Icon = MessageModel.MessageIcon.Alert,
                  };
                  RegisterMessage(authFailedMessage, true);
                  break;
            }
             }

             return RedirectToAction("Details", new { id = user.UserId });
        }
Esempio n. 9
0
        //[HttpPost]
        public ActionResult OAuth(int id, string code, string state, string returnUrl)
        {
            FacebookOAuthResult oauthResult;
             SystemConfiguration configuration = systemConfigurationService.Get();
             string redirectUrl = Url.Action("OAuth", "Users");
             User user = userService.GetUserById(id);

             if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
             {
            if (oauthResult.IsSuccess)
            {
               var oAuthClient = new FacebookOAuthClient();
               oAuthClient.AppId = configuration.FacebookAppId.ToEmptyStringIfNull();
               oAuthClient.AppSecret = configuration.FacebookApiSecret;
               oAuthClient.RedirectUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + redirectUrl);
               dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
               string accessToken = tokenResult.access_token;

               DateTime expiresOn = DateTime.MaxValue;

               if (tokenResult.ContainsKey("expires"))
                  DateTimeConvertor.FromUnixTime(tokenResult.expires);

               FacebookClient fbClient = new FacebookClient(accessToken);
               dynamic me = fbClient.Get("me?fields=id,name");
               long facebookId = Convert.ToInt64(me.id);

               try
               {
                  user.ExternalId = facebookId.ToString();
                  user.ExternalProviderUri = "www.facebook.com"; //app.GetLoginUrl().Authority;
                  user.UpdatedDate = DateTime.UtcNow;

                  userService.SaveUser(user);

                  //MessageModel successMessage = new MessageModel
                  //{
                  //   Text = string.Format("The user {0} is now associated with the selected Facebook account!", user.DisplayName),
                  //   Icon = MessageModel.MessageIcon.Info,
                  //};
                  //RegisterMessage(successMessage, true);
               }
               catch (Exception ex)
               {
                  log.Error("Unexpected error while logging in", ex);
                  MessageModel authFailedMessage = new MessageModel
                  {
                     Text = GlobalResource("Message_GenericError"),
                     Icon = MessageModel.MessageIcon.Alert,
                  };
                  RegisterMessage(authFailedMessage, true);
               }
            }
            else
            {
               log.WarnFormat("LoginController.FacebookConnect - Facebook rejected authentication!");
               MessageModel authFailedMessage = new MessageModel
               {
                  Text = "Sorry, Facebook rejected the authentication!",
                  Icon = MessageModel.MessageIcon.Alert,
               };
               RegisterMessage(authFailedMessage, true);
            }
             }

             //ViewData["AuthenticationFailed"] = "Logon unsucessfull!";
             return RedirectToAction("Details", new {id = user.UserId});
        }
Esempio n. 10
0
        private void BuildIndexBySites()
        {
            ISearchService searchService = IoC.Resolve<ISearchService>();
             IContentItemService<IContentItem> contentItemService = IoC.Resolve<IContentItemService<IContentItem>>();

             IList<Site> sites = siteService.GetAllSites();
             bool isOk = false;

             foreach (Site site in sites)
             {
            IEnumerable<IContentItem> contentItemsToIndex = from c in contentItemService.FindAllBySite(site)
                                                            where c.PublishedDate.HasValue == true
                                                               && c.PublishedDate.Value <= DateTime.Now
                                                            select c;

            //only one thread at a time
            System.Threading.Monitor.Enter(lockObject);

            try
            {
               searchService.RebuildIndex(site, contentItemsToIndex);
               isOk = true;
            }
            catch (Exception ex)
            {
               log.Error(ex.ToString());

               // Show the confirmation message
               MessageModel model = new MessageModel
               {
                  Text = ex.Message,
                  Icon = MessageModel.MessageIcon.Alert,
                  CssClass = "margin-topbottom"
               };
               RegisterMessage(model, true);
            }
            finally
            {
               System.Threading.Monitor.Exit(lockObject);
            }

            if (isOk)
            {
               MessageModel model = new MessageModel
                                       {
                                          Text = string.Format("Site {0}: Rebuild completed!", site.Name),
                                          Icon = MessageModel.MessageIcon.Info,
                                          CssClass = "margin-topbottom",
                                          IsClosable = true
                                       };
               RegisterMessage(model, true);
            }
             }
        }
Esempio n. 11
0
        public ActionResult UpdatePermalink(string permalink, int id)
        {
            try
             {
            // due to the fact that the post title may be empty,
            // in that case the permalink is equal to the postid
            if (string.IsNullOrEmpty(permalink))
               permalink = id.ToString();

            ContentItem post = contentItemService.GetById(id);
            post.FriendlyName = permalink.Sanitize();

            contentItemService.Save(post);

            // Show the confirmation message
            MessageModel message = new MessageModel
            {
               Text = "Permalink updated!",
               Icon = MessageModel.MessageIcon.Info,
            };

            return View("MessageUserControl", message);
             }
             catch (Exception ex)
             {
            log.Error("AdminContentItemController.UpdatePermalink", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 12
0
        public ActionResult Delete(int id)
        {
            Post post = contentItemService.GetById(id);

             try
             {
            post.IsLogicallyDeleted = true;
            contentItemService.Save(post);

            MessageModel message = new MessageModel
            {
               Text = "The selected post has been deleted!",
               Icon = MessageModel.MessageIcon.Info,
            };

            return View("MessageUserControl", message);
             }
             catch (Exception ex)
             {
            log.Error("AdminPostController.Delete", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 13
0
        public ActionResult ChangePassword(int id, ChangePasswordModel changePasswordModel)
        {
            User user = userService.GetUserById(id);

             changePasswordModel.User = user;

             try
             {
            if (ModelState.IsValid && TryUpdateModel(changePasswordModel, new[] { "Password", "PasswordConfirmation" }))
            {
               user.Password = user.HashPassword(changePasswordModel.Password);
               user.PasswordConfirmation = user.HashPassword(changePasswordModel.PasswordConfirmation);
               user.UpdatedDate = DateTime.UtcNow;

               userService.SaveUser(user);

               MessageModel message = new MessageModel
               {
                  Text = GlobalResource("Message_UserPasswordChanged"),
                  Icon = MessageModel.MessageIcon.Info,
               };
               RegisterMessage(message, true);

               return RedirectToAction("Details", new {id = user.UserId});
            }
            else
            {
               StringBuilder errorMessage = new StringBuilder();

               if (!ModelState.IsValid)
               {
                  var errorList = (from item in ModelState
                                   where item.Value.Errors.Any()
                                   select item.Value.Errors[0].ErrorMessage).ToList();
                  errorList.Each().Do(error => errorMessage.AppendFormat("{0}<br/>", error));
               }

               log.Debug("ChangePassword[POST] - Error validating the model");
               log.Debug(errorMessage.ToString());
               MessageModel message = new MessageModel
               {
                  Text = GlobalResource("Message_GenericError") + "</br>" + errorMessage.ToString(),
                  Icon = MessageModel.MessageIcon.Alert,
                  CssClass = "margin-topbottom"
               };
               RegisterMessage(message);
            }
             }
             catch (Exception ex)
             {
            log.Error("UsersController.ChangePassword", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(message, true);
             }

             return View("ChangePassword", changePasswordModel);
        }
Esempio n. 14
0
        public ActionResult SaveNew(string name)
        {
            Tag tag = new Tag
             {
            Name = name,
            Site = Context.ManagedSite
             };

             try
             {
               tagService.Save(tag);

               // Show the confirmation message
               MessageModel message = new MessageModel
               {
              Text = GlobalResource("Message_TagSaved"),
              Icon = MessageModel.MessageIcon.Info,
              CssClass = "margin-topbottom"
               };

               return View("MessageUserControl", message);
             }
             catch (Exception ex)
             {
            log.Error("UsersController.Update", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 15
0
        public ActionResult Delete(int id)
        {
            // TODO: implement undo function

             Comment comment = commentService.GetById(id);

             try
             {
            commentService.DeleteComment(comment);

            MessageModel message = new MessageModel
            {
               Text = "The selected comment has been deleted!",
               Icon = MessageModel.MessageIcon.Info,
            };

            return View("MessageUserControl", message);
             }
             catch (Exception ex)
             {
            log.Error("AdminCommentController.Delete", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 16
0
        public ActionResult SaveReply(int replyToCommentId, string replyContent)
        {
            // get the original comment to reply to
             Comment originalComment = commentService.GetById(replyToCommentId);

             try
             {
            // ensure the content is valid
            if (string.IsNullOrEmpty(replyContent))
            {
               MessageModel noContentMessage = new MessageModel
               {
                  Text = "Please type the content of the reply!",
                  Icon = MessageModel.MessageIcon.Alert
               };

               RegisterMessage(noContentMessage, true);
               return Index(null, string.Empty);
            }

            // get the comment post
            Post post = contentItemService.GetById(originalComment.ContentItem.Id);

            // Check if post comments are already allowed
            if (!post.AllowComments)
            {
               MessageModel commentsCloseMessage = new MessageModel
               {
                  Text = "Sorry, comments are close on this post!",
                  Icon = MessageModel.MessageIcon.Alert
               };

               RegisterMessage(commentsCloseMessage, true);
               return Index(null, string.Empty);
            }

            // Create a new comment
            Comment comment = new Comment
            {
               ContentItem = post,
               Name = Context.CurrentUser.DisplayName,
               Email = Context.CurrentUser.Email,
               Url = Context.CurrentUser.WebSite,
               UserIp = Request.UserHostAddress,
               CommentText = replyContent.StripHtml(),
               CreatedDate = DateTime.UtcNow,
               CreatedBy = Context.CurrentUser
            };

            // Check if the comment is duplicated (by the same author)
            if (commentService.CheckIfCommentIsDuplicate(comment))
            {
               MessageModel duplicateCommentMessage = new MessageModel
               {
                  Text = "It seems that you have already added this comment",
                  Icon = MessageModel.MessageIcon.Alert
               };

               RegisterMessage(duplicateCommentMessage, true);
               return Index(null, string.Empty);
            }

            // Evaluate comment if valid for auto approval
            // this check if the comments contains spam or must be contained in the moderation queue
            // as set in the Site Settings
            comment.Status = commentService.EvaluateComment(comment);

            // add the new comment to the post
            post.Comments.Add(comment);

            // save the post (and the comment in cascade)
            contentItemService.Save(post);

            MessageModel message = new MessageModel
            {
               Text = "Reply saved!",
               Icon = MessageModel.MessageIcon.Info
            };

            RegisterMessage(message, true);
             }
             catch (Exception ex)
             {
            log.Error("AdminCommentController.SaveReply", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert
            };

            RegisterMessage(message, true);
             }

             // Refresh the comments list
             return Index(null, string.Empty);
        }
Esempio n. 17
0
        public ActionResult SaveNew(string name, int? parentCategoryId)
        {
            Category category = new Category
             {
            Name = name,
            Site = Context.ManagedSite
             };

             if (parentCategoryId.HasValue)
            category.SetParentCategory(categoryService.GetById(parentCategoryId.Value));
             else
            category.SetParentCategory(null);

             try
             {
               categoryService.Save(category);

               // Show the confirmation message
               MessageModel message = new MessageModel
               {
              Text = GlobalResource("Message_CategorySaved"),
              Icon = MessageModel.MessageIcon.Info,
              CssClass = "margin-topbottom"
               };

               return View("MessageUserControl", message);
             }
             catch (Exception ex)
             {
            log.Error("AdminCategoryController.SaveNew", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 18
0
        public ActionResult RemoveExternalId(int id)
        {
            User user = userService.GetUserById(id);

             try
             {
            user.ExternalId = null;
            user.ExternalProviderUri = null;

            userService.SaveUser(user);

            //MessageModel message = new MessageModel
            //{
            //   Text = GlobalResource("Message_ExternalIdRemoved"),
            //   Icon = MessageModel.MessageIcon.Info,
            //};
            //RegisterMessage(message, true);

            return RedirectToAction("Details", new { id = user.UserId });
             }
             catch (Exception ex)
             {
            log.Error("UsersController.RemoveExternalId", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(message, true);
             }

             return RedirectToAction("Details", new { id = user.UserId });
        }
Esempio n. 19
0
        public ActionResult Update(UserModel userModel, int id, int[] roleIds)
        {
            User user = userService.GetUserById(id);

             try
             {
            string invalidMessage = string.Empty;

            // Unique Email
            if (userService.CountOtherUsersBySiteAndEmail(Context.ManagedSite, userModel.Email, user) > 0)
            {
               invalidMessage = "Message_UserEmailIsNotUnique";
            }

            // Unique DisplayName Validation
            if (userService.CountOtherUsersBySiteAndDisplayName(Context.ManagedSite, user.DisplayName, user) > 0)
            {
               invalidMessage = "Message_UserDisplayNameIsNotUnique";
            }

            // try to update the User entity with the info from the model
            TryUpdateModel<User>(user, new[] { "DisplayName", "ExternalId", "FirstName", "LastName", "Email", "Website", "IsActive", "TimeZone", "Description", "AdminTheme", "AdminCulture" });

            if (ModelState.IsValid)
            {
               // Clear existing roles
               user.Roles.Clear();

               // update the roles
               if (roleIds != null && roleIds.Length > 0)
               {
                  IList<Role> roles = userService.GetRolesByIds(roleIds);
                  foreach (Role role in roles)
                  {
                     user.Roles.Add(role);
                  }
               }

               if (invalidMessage.Length == 0)
               {
                  user.UpdatedDate = DateTime.UtcNow;
                  ServiceResult result = userService.SaveUser(user);

                  // Show the confirmation message
                  MessageModel message = new MessageModel
                  {
                     Text = GlobalResource("Message_UserSaved"),
                     Icon = MessageModel.MessageIcon.Info,
                     CssClass = "margin-topbottom"
                  };
                  RegisterMessage(message, true);

                  return RedirectToAction("Index");
               }
               else
               {
                  MessageModel message = new MessageModel
                  {
                     // get the message by the token!!! uao!
                     Text = GlobalResource(invalidMessage),
                     Icon = MessageModel.MessageIcon.Alert,
                     CssClass = "margin-topbottom"
                  };
                  RegisterMessage(message);
               }
            }
            else
            {
               StringBuilder errorMessage = new StringBuilder();

               if (!ModelState.IsValid)
               {
                  var errorList = (from item in ModelState
                                   where item.Value.Errors.Any()
                                   select item.Value.Errors[0].ErrorMessage).ToList();
                  errorList.Each().Do(error => errorMessage.AppendFormat("{0}<br/>", error));
               }

               log.Debug("ChangePassword[POST] - Error validating the model");
               //log.Debug(errorMessage.ToString());

               MessageModel message = new MessageModel
               {
                  Text = GlobalResource("Message_GenericError") + "</br>" + errorMessage.ToString(),
                  Icon = MessageModel.MessageIcon.Alert,
                  CssClass = "margin-topbottom"
               };
               RegisterMessage(message);
            }
             }
             catch (Exception ex)
             {
            log.Error("UsersController.Update", ex);

            MessageModel message = new MessageModel
                                    {
                                       Text = GlobalResource("Message_GenericError"),
                                       Icon = MessageModel.MessageIcon.Alert,
                                       CssClass = "margin-topbottom"
                                    };
            RegisterMessage(message);
             }

             userModel.Roles = user.Roles;
             userModel.AllRoles = userService.GetRolesBySite(Context.ManagedSite);
             userModel.TimeZones = new SelectList(TimeZoneUtil.GetTimeZones(), "Key", "Value", user.TimeZone);
             userModel.AdminThemes = new SelectList(GetAdminThemesList(), user.AdminTheme);
             userModel.Cultures = new SelectList(Globalization.GetOrderedCultures(), "Name", "DisplayName", user.AdminCulture);

             return View("Details", userModel);
        }
Esempio n. 20
0
        public ActionResult Delete(int id)
        {
            Message message = messageService.GetById(id);

             try
             {
            messageService.DeleteComment(message);

            MessageModel messageModel = new MessageModel
            {
               Text = "The selected message has been deleted!",
               Icon = MessageModel.MessageIcon.Info,
            };

            return View("MessageUserControl", messageModel);
             }
             catch (Exception ex)
             {
            log.Error("MessagesController.Delete", ex);

            MessageModel messageModel = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };

            return View("MessageUserControl", messageModel);
             }
        }
Esempio n. 21
0
        public ActionResult SaveNew([Bind(Exclude = "Id,ParentPage")] Page page, int month, int day, int year, int hour, int minute, string WorkflowStatus, string ParentPage)
        {
            try
             {
            Page parentPage = null;

            if (!string.IsNullOrEmpty(ParentPage))
               parentPage = contentItemService.GetById(Convert.ToInt32(ParentPage));

            UpdateModel(page, "", new[] { "Title", "Content", "CustomTemplateFile", "EnableMeta", "MetaDescription", "MetaKeywords" });

            // set the sanitized friendlytitle
            page.FriendlyName = page.Title.Sanitize();
            page.PublishedDate = new DateTime(year, month, day, hour, minute, 0);
            page.ParentPage = parentPage;

            if (!string.IsNullOrEmpty(WorkflowStatus))
               page.WorkflowStatus = (Arashi.Core.Domain.WorkflowStatus)Enum.Parse(typeof(Arashi.Core.Domain.WorkflowStatus), WorkflowStatus);

            if (page.Content == null)
               page.Content = string.Empty;

            SaveOrUpdate(page);

            return RedirectToAction("Index");
             }
             catch (Exception ex)
             {
            log.Error("AdminPageController.SaveNew", ex);

            if (this.ModelState != null)
            {
               foreach (string key in this.ModelState.Keys)
               {
                  if (this.ModelState[key].Errors.Count > 0)
                  {
                     foreach (ModelError modelError in this.ModelState[key].Errors)
                     {
                        if ((modelError.Exception != null))
                           log.ErrorFormat("Error in Model[\"{0}\"]: {1}", key, modelError.Exception.ToString());
                        else if (!string.IsNullOrEmpty(modelError.ErrorMessage))
                           log.Error(modelError.ErrorMessage);
                     }
                  }
               }
            }

            MessageModel model = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(model, true);
             }

             return RedirectToAction("NewPage");
        }
Esempio n. 22
0
        /// <summary>
        /// Common function to save a new post or update an existing one
        /// </summary>
        /// <param name="post"></param>
        /// <param name="categoryid"></param>
        /// <param name="tagid"></param>
        private void SaveOrUpdate(Post post, int[] categoryid, int[] tagid)
        {
            // TODO: content filtering!!!

             // due to the fact that the post title may be empty,
             // in that case the permalink is equal to the postid
             if (string.IsNullOrEmpty(post.Title))
            post.Title = string.Empty;

             post.Site = Context.ManagedSite;
             post.Culture = Context.ManagedSite.DefaultCulture;
             post.PublishedBy = Context.CurrentUser;
             //post.WorkflowStatus = WorkflowStatus.Published;

             // Store the published dates in UTC
             post.PublishedDate = post.PublishedDate.Value.ToUniversalTime();
             //post.PublishedUntil = post.PublishedUntil.Value.ToUniversalTime();

             if (categoryid != null)
             {
            post.Categories.Clear();
            foreach (int id in categoryid)
            {
               post.Categories.Add(categoryService.GetById(id));
            }
             }

             if (tagid != null)
             {
            post.Tags.Clear();
            foreach (int id in tagid)
            {
               post.Tags.Add(tagService.GetById(id));
            }
             }

             contentItemService.Save(post);

             // Send the pings
             SendPings(post);

             // Show the confirmation message
             MessageModel model = new MessageModel
             {
            Text = GlobalResource("Message_PostSaved"),
            Icon = MessageModel.MessageIcon.Info,
             };

             RegisterMessage(model, true);
        }
Esempio n. 23
0
        public ActionResult Save(BoldyOptionsModel model)
        {
            try
             {
            if (ModelState.IsValid)
            {
               Site site = Context.ManagedSite;

               site.Options["boldy_logo_img"] = model.LogoPath;
               site.Options["boldy_logo_alt"] = model.LogoAlt;
               site.Options["boldy_cufon"] = model.EnableCufonFontReplacement.ToString().ToLowerInvariant();
               site.Options["boldy_slider"] = model.HomePageSliderImagesPage == null ? string.Empty : model.HomePageSliderImagesPage.Id.ToString();
               site.Options["boldy_portfolio"] = model.PortfolioPage == null ? string.Empty : model.PortfolioPage.Id.ToString();
               site.Options["boldy_home_box1"] = model.HomeBox1Page == null ? string.Empty : model.HomeBox1Page.Id.ToString();
               site.Options["boldy_home_box1_link"] = model.HomeBox1ReadMoreLink;
               site.Options["boldy_home_box2"] = model.HomeBox1Page == null ? string.Empty : model.HomeBox2Page.Id.ToString();
               site.Options["boldy_home_box2_link"] = model.HomeBox2ReadMoreLink;
               site.Options["boldy_home_box3"] = model.HomeBox3Page == null ? string.Empty : model.HomeBox3Page.Id.ToString();
               site.Options["boldy_home_box3_link"] = model.HomeBox3ReadMoreLink;
               site.Options["boldy_blurb_enable"] = model.DisplayHomepageBlurb.ToString().ToLowerInvariant();
               site.Options["boldy_blurb_text"] = model.BlurbText;
               site.Options["boldy_blurb_page"] = model.RequestQuotePage == null ? string.Empty : model.RequestQuotePage.Id.ToString();
               site.Options["boldy_blurb_link"] = model.RequestQuoteLink;

               siteService.SaveSite(site);

               // Show the confirmation message
               MessageModel message = new MessageModel
               {
                  Text = "The options has been saved successfully!",
                  Icon = MessageModel.MessageIcon.Info,
                  CssClass = "margin-topbottom"
               };
               RegisterMessage(message, true);
            }
             }
             catch (Exception ex)
             {
            log.Error("BoldyController.Update", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };
            RegisterMessage(message);
             }

             model.Pages = GetParentPages(false); // get the pages in flat tree list

             return View("Index", model);
        }
Esempio n. 24
0
        public ActionResult Sort(string ordereditems)
        {
            string[] pageIds = ordereditems.Split(',');

             try
             {
            pageService.Sort(pageIds);
             }
             catch (Exception ex)
             {
            log.Error("AdminPageController.Sort", ex);

            MessageModel model = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(model);
             }

             return Content("OK");
        }
Esempio n. 25
0
        public ActionResult SaveCustomField(string contentitemid, string key, string value)
        {
            try
             {
            ContentItem contentItem = contentItemService.GetById(Convert.ToInt32(contentitemid));

            // first check if the same key already exists
            if (contentItem.CustomFields.ContainsKey(key))
            {
               MessageModel duplicateFieldMessage = new MessageModel
               {
                  Text = "There is another custom field with the same key!",
                  Icon = MessageModel.MessageIcon.Alert,
                  CssClass = "margin-topbottom"
               };

               return View("MessageUserControl", duplicateFieldMessage);
            }

            contentItem.CustomFields.Add(key, value);
            contentItemService.Save(contentItem);

            // Show the confirmation message
            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_CustomFieldSaved"),
               Icon = MessageModel.MessageIcon.Info,
               CssClass = "margin-topbottom"
            };

            return View("MessageUserControl", message);
             }
             catch (Exception ex)
             {
            log.Error("AdminContentItemController.SaveCustomField", ex);

            MessageModel message = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom"
            };

            return View("MessageUserControl", message);
             }
        }
Esempio n. 26
0
        public ActionResult Update(int id, int month, int day, int year, int hour, int minute, string WorkflowStatusList, string ParentPage)
        {
            Page page = contentItemService.GetById(id);
             Page parentPage = null;

             if (!string.IsNullOrEmpty(ParentPage))
            parentPage = contentItemService.GetById(Convert.ToInt32(ParentPage));

             try
             {
            UpdateModel(page, new[] { "Title", "Content", "CustomTemplateFile", "EnableMeta", "MetaDescription", "MetaKeywords" });

            if (page.Content == null)
               page.Content = string.Empty;

            page.PublishedDate = new DateTime(year, month, day, hour, minute, 0);

            if (!string.IsNullOrEmpty(WorkflowStatusList))
               page.WorkflowStatus = (Arashi.Core.Domain.WorkflowStatus)Enum.Parse(typeof(Arashi.Core.Domain.WorkflowStatus), WorkflowStatusList);

            page.ParentPage = parentPage;

            SaveOrUpdate(page);

            MessageModel model = new MessageModel
            {
               Text = GlobalResource("Message_PageSaved"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(model, true);
             }
             catch (Exception ex)
             {
            log.Error("AdminPageController.Update", ex);

            if (this.ModelState != null)
            {
               foreach (string key in this.ModelState.Keys)
               {
                  if (this.ModelState[key].Errors.Count > 0)
                  {
                     foreach (ModelError modelError in this.ModelState[key].Errors)
                     {
                        if ((modelError.Exception != null))
                           log.Error(modelError.Exception.ToString());
                        else if (!string.IsNullOrEmpty(modelError.ErrorMessage))
                           log.Error(modelError.ErrorMessage);
                     }
                  }
               }
            }

            MessageModel model = new MessageModel
            {
               Text = GlobalResource("Message_GenericError"),
               Icon = MessageModel.MessageIcon.Alert,
            };
            RegisterMessage(model, true);
             }

             return RedirectToAction("Edit", new { id = id });
        }
Esempio n. 27
0
        public ActionResult TestTrackback()
        {
            IContentItemService<Post> contentItemService = IoC.Resolve<IContentItemService<Post>>();

             IList<Post> posts = contentItemService.FindAllBySite(Context.ManagedSite);

             Post post = (from p in posts
                      where p.PublishedDate <= DateTime.Now.ToUniversalTime() &&
                            p.WorkflowStatus == WorkflowStatus.Published &&
                            p.AllowPings == true
                      select p).FirstOrDefault();

             StringBuilder sb = new StringBuilder();

             if (post != null)
             {
            string postId = post.Id.ToString();
            string title = post.Title;
            string excerpt = "test";
            string blogName = Context.ManagedSite.Name;
            string partialUrl = post.GetContentUrl();
            string url = string.Concat(Request.Url.GetLeftPart(UriPartial.Authority),
                                       "/",
                                       partialUrl.StartsWith("~") || partialUrl.StartsWith("/")
                                          ? partialUrl.Substring(1)
                                          : partialUrl);

            string targetUrl = Request.Url.GetLeftPart(UriPartial.Authority) +
                              string.Format("/trackback.axd?id={0}&url={1}", postId, url.UrlEncode());

            // prepare POST parameters
            string postString = String.Format("title={0}&excerpt={1}&blog_name={2}", title, excerpt, blogName);
            byte[] formPostData = Encoding.UTF8.GetBytes(postString);

            log.Debug("TestTrackback: targetUrl = " + targetUrl);
            log.Debug("TestTrackback: postString = " + postString);

            // Send request with post parameters
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUrl);
            request.Credentials = CredentialCache.DefaultNetworkCredentials;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = formPostData.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
               requestStream.Write(formPostData, 0, formPostData.Length);
               requestStream.Close();
            }

            // Get the response
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
               sb.Append("Headers.AllKeys: ");
               foreach (string key in response.Headers.AllKeys)
                  sb.AppendFormat("{0} = {1}, ", key, response.Headers[key]);

               sb.AppendLine("");
               sb.AppendLine("ContentType: " + response.ContentType);

               using (StreamReader reader = new StreamReader(response.GetResponseStream()))
               {
                  sb.AppendLine(reader.ReadToEnd());
               }
            }

             }

             MessageModel model = new MessageModel
                                 {
                                    Text = "Trackback sended!",
                                    Icon = MessageModel.MessageIcon.Info,
                                    CssClass = "margin-topbottom",
                                    IsClosable = true
                                 };
             RegisterMessage(model, true);

             ViewData["TestTrackback"] = sb.ToString();

             return View("Index");
        }
Esempio n. 28
0
        /// <summary>
        /// Save or update a page
        /// </summary>
        /// <param name="page"></param>
        private void SaveOrUpdate(Page page)
        {
            // TODO: content filtering!!!

             page.Site = Context.ManagedSite;
             page.Culture = Context.ManagedSite.DefaultCulture;
             page.PublishedBy = Context.CurrentUser;
             //page.WorkflowStatus = WorkflowStatus.Published;

             // Store the published dates in UTC
             page.PublishedDate = page.PublishedDate.Value.ToUniversalTime();

             contentItemService.Save(page);

             // Send the pings
             //SendPings(page);

             // Show the confirmation message
             MessageModel model = new MessageModel
             {
            Text = GlobalResource("Message_PageSaved"),
            Icon = MessageModel.MessageIcon.Info,
             };

             RegisterMessage(model, true);
        }
Esempio n. 29
0
        public ActionResult DoPostBulkInsert(int numberOfPost)
        {
            string[] dummy = new string[6];
             dummy[0] = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
             dummy[1] = "Sed ut perspiciatis unde omnis iste natus error sit <u>voluptatem</u> accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?";
             dummy[2] = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat";
             dummy[3] = "<i>Lorem ipsum dolor sit amet</i>, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.";
             dummy[4] = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.";
             dummy[5] = "<b>At vero eos et accusamus</b> et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. ";

             Random rndPost = new Random(DateTime.Now.Millisecond);
             Random rndDay = new Random(DateTime.Now.Millisecond);
             Random rndMonth = new Random(DateTime.Now.Millisecond);

             ICategoryService categoryService = IoC.Resolve<ICategoryService>();
             ITagService tagService = IoC.Resolve<ITagService>();
             IContentItemService<Post> contentItemService = IoC.Resolve<IContentItemService<Post>>();

             IEnumerable<Category> categories = categoryService.GetAllCategoriesBySite(Context.ManagedSite);
             IList<Tag> tags = tagService.GetAllTagsBySite(Context.ManagedSite);

             int categoryCount;
             int tagCount;

             Random rndCat = new Random(DateTime.Now.Millisecond);
             Random rndTag = new Random(DateTime.Now.Millisecond);

             try
             {
            using (NHTransactionScope tx = new NHTransactionScope())
            {
               // Bulk Insert
               for (int postIndex = 0; postIndex < numberOfPost; postIndex++)
               {
                  int indexPost = rndPost.Next(6);
                  if (indexPost > 5)
                     indexPost = 0;

                  int day = rndDay.Next(1, 29); // get a number of the day between 1 and 29
                  int month = rndMonth.Next(1, 12); // get a number of the day between 1 and 29

                  categoryCount = rndCat.Next(categories.Count());
                  //tagCount = rndCat.Next(tags.Count);
                  tagCount = rndCat.Next(1, 2);

                  DateTime publishedDate = new DateTime(DateTime.Now.Year, month, day);

                  if (publishedDate > DateTime.Now)
                     publishedDate = DateTime.Now.Subtract(new TimeSpan(numberOfPost, 0, 0, 0));

                  Post post = new Post()
                  {
                     Title = dummy[indexPost].StripHtml().GetFirstWords(5) + " @ " + publishedDate.ToShortDateString(),
                     Summary = null,
                     Content = dummy[indexPost],
                     WorkflowStatus = WorkflowStatus.Published,
                     AllowComments = Context.ManagedSite.AllowComments,
                     AllowPings = Context.ManagedSite.AllowPings,
                     Site = Context.ManagedSite,
                     Culture = Context.ManagedSite.DefaultCulture,
                     PublishedBy = Context.CurrentUser,
                     PublishedDate = publishedDate.ToUniversalTime()
                  };

                  if (categoryCount > 0)
                  {
                     foreach (Category item in categories)
                     {
                        if (categoryCount >= 0)
                           post.Categories.Add(item);

                        categoryCount--;
                     }
                  }

                  if (tagCount > 0)
                  {
                     foreach (Tag item in tags)
                     {
                        if (tagCount >= 0)
                           post.Tags.Add(item);

                        tagCount--;
                     }
                  }

                  // Save
                  contentItemService.Save(post);
               }

               // Commit all
               tx.VoteCommit();
            }
            MessageModel model = new MessageModel
            {
               Text = "Bulk Insert Done!!!",
               Icon = MessageModel.MessageIcon.Info,
               CssClass = "margin-topbottom",
               IsClosable = true
            };
            RegisterMessage(model, true);

             }
             catch (Exception ex)
             {
            log.Error(ex.ToString());

            MessageModel model = new MessageModel
            {
               Text = ex.Message,
               Icon = MessageModel.MessageIcon.Alert,
               CssClass = "margin-topbottom",
               IsClosable = true
            };
            RegisterMessage(model, true);
             }

             return View("Index");
        }
Esempio n. 30
0
        public ActionResult Create(NewUserModel userModel, int[] roleIds)
        {
            User user = new User();

             try
             {
            if (ModelState.IsValid)
            {
               TryUpdateModel(userModel, new[] { "DisplayName", "Email", "Password", "PasswordConfirmation", "IsActive", "TimeZone", "AdminCulture" });

               // server validation
               string invalidMessage = string.Empty;

               // Unique Email
               if (userService.CountOtherUsersBySiteAndEmail(Context.ManagedSite, userModel.Email, user) > 0)
               {
                  invalidMessage = "Message_UserEmailIsNotUnique";
               }

               // Unique DisplayName Validation
               if (userService.CountOtherUsersBySiteAndDisplayName(Context.ManagedSite, userModel.DisplayName, user) > 0)
               {
                  invalidMessage = "Message_UserDisplayNameIsNotUnique";
               }

               if (invalidMessage.Length == 0)
               {
                  user.Password = user.HashPassword(userModel.Password);
                  user.PasswordConfirmation = user.HashPassword(userModel.PasswordConfirmation);

                  user.Roles.Clear();

                  if (roleIds != null && roleIds.Length > 0)
                  {
                     IList<Role> roles = userService.GetRolesByIds(roleIds);
                     foreach (Role role in roles)
                     {
                        user.Roles.Add(role);
                     }
                  }

                  user.Site = Context.ManagedSite;
                  user.CreatedDate = DateTime.UtcNow;

                  ServiceResult result = userService.SaveUser(user);

                  if (result.State == ServiceResult.ServiceState.Success)
                  {
                     // Show the confirmation message
                     MessageModel message = new MessageModel
                                               {
                                                  Text =
                                                     string.Format(GlobalResource("Message_UserCreated"),
                                                                   userModel.DisplayName),
                                                  Icon = MessageModel.MessageIcon.Info,
                                               };
                     RegisterMessage(message, true);

                     return RedirectToAction("Index");
                  }
                  else
                  {
                     MessageModel message = new MessageModel
                                               {
                                                  Text = GlobalResource(result.Message),
                                                  Icon = MessageModel.MessageIcon.Alert,
                                               };
                     RegisterMessage(message);
                  }
               }
               else
               {
                  MessageModel message = new MessageModel
                  {
                     Text = GlobalResource(invalidMessage),
                     Icon = MessageModel.MessageIcon.Alert,
                     CssClass = "margin-topbottom"
                  };
                  RegisterMessage(message);
               }

            }
             }
             catch (Exception ex)
             {
            log.Error("UsersController.Update", ex);

            MessageModel message = new MessageModel
                                    {
                                       Text = GlobalResource("Message_GenericError"),
                                       Icon = MessageModel.MessageIcon.Alert,
                                    };
            RegisterMessage(message);
             }

             userModel.Roles = user.Roles;
             userModel.AllRoles = userService.GetRolesBySite(Context.ManagedSite);
             userModel.TimeZones = new SelectList(TimeZoneUtil.GetTimeZones(), "Key", "Value", user.TimeZone);
             userModel.AdminThemes = new SelectList(GetAdminThemesList(), user.AdminTheme);
             userModel.Cultures = new SelectList(Globalization.GetOrderedCultures(), "Name", "DisplayName", user.AdminCulture);

             return View("NewUser", userModel);
        }