public ActionResult Register(RegisterModel model) { if (ModelState.IsValid == false) { return(View()); } // Attempt to register the user RavenSession.Advanced.UseOptimisticConcurrency = true; // make sure we are not overwriting an existing user model.SendOutKey = Guid.NewGuid().ToString(); RavenSession.Store(new User { Id = "users/" + model.Email.ToLower(), FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, DateJoined = DateTimeOffset.Now, Enabled = false, }.SetPassword(model.Password)); try { RavenSession.SaveChanges(); RavenSession.Advanced.UseOptimisticConcurrency = false; //TaskExecutor.ExcuteLater(new SendEmailTask //{ // ReplyTo = "*****@*****.**", // Subject = "You have a user in HibernatingRhinos.com!", // SendTo = new[] { model.Email, "*****@*****.**" }, // ViewName = "RegistrationSuccessful", // Model = model, //}); return(RedirectToAction("RegistrationSuccessful")); } catch (ConcurrencyException) { ModelState.AddModelError("", "A user name for that e-mail address already exists. Please enter a different e-mail address."); RavenSession.Dispose(); RavenSession = null; } //ModelState.AddModelError("", "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."); // If we got this far, something failed, redisplay form return(View(model)); }
public override EmployeeSearchResult[] Execute() { RavenQueryStatistics stats; IQueryable <Employee_QuickSearch.Projection> query = RavenSession .Query <Employee_QuickSearch.Projection, Employee_QuickSearch>() .Statistics(out stats) .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite()); query = query.Where(x => x.IsEmployee); Expression <Func <Employee_QuickSearch.Projection, bool> > predicate = x => x.FullName1.StartsWith(Parameters.Term) || x.FullName2.StartsWith(Parameters.Term) || x.Skills.StartsWith(Parameters.Term) || x.AttachmentNames.Any(y => y.StartsWith(Parameters.Term)) || x.CurrentPosition.StartsWith(Parameters.Term) || x.CurrentProject.StartsWith(Parameters.Term) || x.FileId.StartsWith(Parameters.Term) || x.Platform.StartsWith(Parameters.Term) || x.Terms.StartsWith(Parameters.Term); if (Parameters.SearchInNotes) { predicate = predicate.Or(x => x.Notes.StartsWith(Parameters.Term)); } if (Parameters.SearchInAttachments) { predicate = predicate.Or(x => x.AttachmentContent.Any(y => y.StartsWith(Parameters.Term))); } query = query.Where(predicate).OrderBy(x => x.LastName).ThenBy(x => x.FirstName); if (Parameters.Skip > 0) { query = query.Skip(Parameters.Skip); } if (Parameters.Take > 0) { query = query.Take(Parameters.Take); } var result = query.AsProjection <EmployeeSearchResult>().ToArray(); Stats = stats; return(result); }
public override List <EmployeeEvaluationDTO> ExecuteWithResult() { RavenQueryStatistics stats; IQueryable <EmployeeToEvaluate_Search.Projection> query = RavenSession .Query <EmployeeToEvaluate_Search.Projection, EmployeeToEvaluate_Search>() .Statistics(out stats) .Where(e => (e.Period == _period) && (e.UserName == _loggedUser || e.ResponsibleId == _loggedUser || e.Evaluators.Any(ev => ev == _loggedUser))); var employeesProjection = query.ToList(); var mapper = new EmployeeEvaluationHelper(RavenSession, _loggedUser); return(mapper.MapEmployeeEvaluation(employeesProjection)); }
public ActionResult Index(string id) { var items = RavenSession .Query <Board>() .Where(x => x.Id == id && x.IsPublic) .TransformWith <LeaderboardViewModelTransformer, LeaderboardViewModel.Item>() .OrderByDescending(x => x.Points) .Take(10) .ToList(); var model = new LeaderboardViewModel { Items = items }; return(PartialView(model)); }
public ApiResponse Add(Clinic postedModel) { var clinic = new Clinic() { AccountId = Account.Id, Name = postedModel.Name }; RavenSession.Store(clinic); RavenSession.SaveChanges(); return(new ApiResponse(success: postedModel.Name + " created successfuly") { Model = clinic }); }
public void GetAll_Test() { RavenSession.Store(new Account() { Name = "Joe", About = "Friendly" }); RavenSession.SaveChanges(); MemberController controller = new MemberController(RavenSession); var result = controller.GetAll(); Assert.AreEqual(1, result.Count()); CleanUp(); }
public ActionResult Index(AccountSettings settings) { if (!ModelState.IsValid) { return(View(settings)); } UpdateModel(Account.Settings); LoggedInUser.OnboardingTasks.Add(OnboardingTask.SavedSettings.ToString()); HighFive("Settings Saved"); RavenSession.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult CreateProject(Project newProject) { var isValid = ModelState.IsValid && ValidateProject(newProject, ModelState); if (isValid) { newProject = Project.CreateNewProject(newProject.Name); RavenSession.Store(newProject); RavenSession.SaveChanges(); DomainEventService.PublishProjectCreated(newProject); } return(GetJsonResult(newProject)); }
private void ResetNumberOfSpamComments(PostComments.Comment comment) { if (comment.CommenterId == null) { return; } var commenter = RavenSession.Load <Commenter>(comment.CommenterId); if (commenter == null) { return; } commenter.NumberOfSpamComments = 0; }
public ActionResult Reset(string token) { var pr = RavenSession.Query <PasswordReset>().FirstOrDefault(x => x.Token == token); if (pr == null || pr.Generated > DateTime.Now.AddHours(2)) { return(View(new PasswordResetViewModel())); } var vm = new PasswordResetViewModel() { Token = pr.Token }; return(View(vm)); }
public virtual ActionResult Edit(int id, BlogEntryViewModel model) { try { // TODO: Add update logic here BlogEntry entry = new BlogEntry(); UpdateModel(entry); RavenSession.Store(entry); return(RedirectToAction("Details", new { Id = entry.Id })); } catch { return(View()); } }
public ActionResult Delete(int id) { var exr = RavenSession.Load <Exercise>("exercises/" + id); if (!Ownership.Owns(exr, this)) { return(HttpNotFound()); } RavenSession.Delete(exr); RavenSession.SaveChanges(); HighFive("Exercise deleted."); return(RedirectToAction("List")); }
public ActionResult SetPostDate(int id, long date) { var post = RavenSession .Include <Post>(x => x.CommentsId) .Load(id); if (post == null) { return(Json(new { success = false })); } post.PublishAt = post.PublishAt.WithDate(DateTimeOffsetUtil.ConvertFromJsTimestamp(date)); RavenSession.Load <PostComments>(post.CommentsId).Post.PublishAt = post.PublishAt; return(Json(new { success = true })); }
// // GET: /Blog/BlogEntry/ public virtual ActionResult Index() { int take = Convert.ToInt32(Request.QueryString["take"]); int skip = Convert.ToInt32(Request.QueryString["skip"]); if (take == 0) { take = 5; } // Get results from database RavenQueryStatistics stats; var dbResult = RavenSession.Query <BlogEntry>().Statistics(out stats).OrderByDescending(x => x.DateTime).Skip(skip).Take(take).ToList(); var totalResults = stats.TotalResults; ViewBag.TotalResults = stats.TotalResults; ViewBag.Take = take; // Convert list to view Model List <BlogEntryViewModel> output = dbResult.Select(b => b.ToBlogEntryViewModel(RavenSession)).ToList(); // Disable PreviousLink if at beginning of collection. if (skip <= 0) { ViewBag.PreviousButtonState = "disabled"; int next = skip + take; ViewBag.NextButtonLink = string.Format("?take={0}&skip={1}", take, next); } else { int previous = skip - take; ViewBag.PreviousButtonLink = string.Format("?take={0}&skip={1}", take, previous); int next = skip + take; if (next > totalResults) { ViewBag.NextButtonState = "disabled"; } else { ViewBag.NextButtonLink = string.Format("?take={0}&skip={1}", take, next); } } return(View(output)); }
private ActionResult ListView(int count, IList <Post> posts) { ViewBag.ChangeViewStyle = true; var summaries = posts.MapTo <PostsViewModel.PostSummary>(); var serieTitles = summaries .Select(x => TitleConverter.ToSeriesTitle(x.Title)) .Where(x => string.IsNullOrEmpty(x) == false) .Distinct() .ToList(); var series = RavenSession .Query <Posts_Series.Result, Posts_Series>() .Where(x => x.Series.In(serieTitles) && x.Count > 1) .ToList(); foreach (var post in posts) { var postSummary = summaries.First(x => x.Id == RavenIdResolver.Resolve(post.Id)); postSummary.IsSerie = series.Any(x => string.Equals(x.Series, TitleConverter.ToSeriesTitle(postSummary.Title), StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrWhiteSpace(post.AuthorId)) { continue; } var author = RavenSession.Load <User>(post.AuthorId); if (author == null) { continue; } postSummary.Author = author.MapTo <PostsViewModel.PostSummary.UserDetails>(); } return(View("List", new PostsViewModel { PageSize = BlogConfig.PostsOnPage, CurrentPage = CurrentPage, PostsCount = count, Posts = summaries })); }
public override void Execute() { var evaluation = RavenSession.Load <EmployeeEvaluation>(EmployeeEvaluation.GenerateEvaluationId(_period, _userName)); if (evaluation == null) { throw new ApplicationException($"Could not find evaluation for period {_period} and user name {_userName}"); } var updatedLink = evaluation.SharedLinks.Where(x => x.SharedCode == _sharedLink.SharedCode).FirstOrDefault(); if (updatedLink == null) { throw new ApplicationException($"This evaluation does not contain a Shared link with code {_sharedLink.SharedCode}. Unable to update"); } updatedLink.FriendlyName = _sharedLink.FriendlyName; updatedLink.ExpirationDate = _sharedLink.ExpirationDate; }
private ActionResult AssertConfigurationIsNeeded() { BlogConfig bc; // Bypass the aggressive caching to force loading the BlogConfig object, // otherwise we might get a null BlogConfig even though a valid one exists using (RavenSession.Advanced.DocumentStore.DisableAggressiveCaching()) { bc = RavenSession.Load <BlogConfig>("Blog/Config"); } if (bc != null) { return(Redirect("/")); } return(null); }
public ActionResult Delete(int id) { var section = RavenSession.Load <Section>(id); if (section == null) { return(HttpNotFound("Section does not exist.")); } RavenSession.Delete(section); if (Request.IsAjaxRequest()) { return(Json(new { Success = true })); } return(RedirectToAction("List")); }
public ActionResult Update(Section section) { if (!ModelState.IsValid) { return(View("Edit", section)); } if (section.Position == 0) { section.Position = RavenSession.Query <Section>() .OrderByDescending(sec => sec.Position) .Select(sec => sec.Position) .FirstOrDefault() + 1; } RavenSession.Store(section); return(RedirectToAction("Index")); }
public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here var data = RavenSession.Load <Reminder>(id); UpdateModel <Reminder>(data, collection); RavenSession.SaveChanges(); return(RedirectToAction("Index")); } catch { return(View()); } }
public Month GetMonth(DateTime?monthReturn = null) { var username = User.Identity.Name.Split('@')[0]; DateTime day = monthReturn ?? DateTime.Today; var docId = string.Format("work/{0}/{1:0000}-{2:00}", username, day.Year, day.Month); var month = RavenSession.Load <Month>(docId); if (month == null) { month = new Month { UserName = username, }; } return(month); }
public ActionResult Config() { Settings settings; using (RavenSession.Advanced.DocumentStore.DisableAggressiveCaching()) { settings = RavenSession.Load <Settings>(Settings.DefaultId); } if (settings == null) { return(RedirectToAction("Auth")); } var model = Mapper.Map <Config>(settings); return(ConfigView(settings, model)); }
public override VacationsSearchResult[] Execute() { RavenQueryStatistics stats; var query = RavenSession .Query <Employee>() .Statistics(out stats) .Customize(x => x.WaitForNonStaleResultsAsOfLastWrite()) .AsProjection <VacationsSearchResult>() .OrderBy(x => x.LastName).ThenBy(x => x.FirstName) .ApplyPagination(Parameters); var result = query.ToArray(); Stats = stats; return(result); }
public bool Exer() { //DeleteOldExercises(); var accounts = RavenSession.Query <Account>().Where(x => !x.ExercisesUpToDate); foreach (Account account in accounts) { var onboardProcess = new UserOnboardProcess(RavenSession); onboardProcess.CopyExercises(account.Id); account.LastMasterPush = DateTime.Now; account.ExercisesUpToDate = true; RavenSession.SaveChanges(); } //var enumerator = RavenSession.Advanced.Stream(exercises); //using (var bulkInsert = MvcApplication.Store.BulkInsert()) //{ // while (enumerator.MoveNext()) // { // var exer = enumerator.Current.Document; // var copy = exer.Copy(); // copy.Id = 0; // copy.AccountId = accountId; // copy.OriginalExercise = exer.Id; // //_ravenSession.Store(copy); // bulkInsert.Store(copy); // } // //_ravenSession.SaveChanges(); //} return(true); }
public async Task <UserChatSettings> Post(SetSettings request) { var session = Request.ThrowIfUnauthorized(); var settingsId = session?.UserAuthId + "/settings"; var settings = Mapper.Map <Settings>(request); settings.Id = settingsId; await RavenSession.StoreAsync(settings); await RavenSession.SaveChangesAsync(); var mapped = Mapper.Map <UserChatSettings>(settings); return(mapped); }
protected override void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext.IsChildAction) { return; } using (RavenSession) { if (filterContext.Exception != null) { return; } if (RavenSession != null) { RavenSession.SaveChanges(); } } }
public virtual ActionResult CommentsRss(int?id) { RavenQueryStatistics stats = null; var commentsTuples = RavenSession.QueryForRecentComments(q => { if (id != null) { var postId = "posts/" + id; q = q.Where(x => x.PostId == postId); } return(q.Statistics(out stats).Take(30)); }); string responseETagHeader; if (CheckEtag(stats, out responseETagHeader)) { return(HttpNotModified()); } var rss = new XDocument( new XElement("rss", new XAttribute("version", "2.0"), new XElement("channel", new XElement("title", BlogConfig.Title), new XElement("link", Url.RelativeToAbsolute(Url.RouteUrl("homepage"))), new XElement("description", BlogConfig.MetaDescription ?? BlogConfig.Title), new XElement("copyright", String.Format("{0} (c) {1}", BlogConfig.Copyright, DateTime.Now.Year)), new XElement("ttl", "60"), from commentsTuple in commentsTuples let comment = commentsTuple.Item1 let post = commentsTuple.Item2 let link = Url.AbsoluteAction("Details", "PostDetails", new { Id = RavenIdResolver.Resolve(post.Id), Slug = SlugConverter.TitleToSlug(post.Title) }) + "#comment" + comment.Id select new XElement("item", new XElement("title", comment.Author + " commented on " + post.Title), new XElement("description", comment.Body), new XElement("link", link), new XElement("guid", link), new XElement("pubDate", comment.CreatedAt.ToString("R")) ) ) ) ); return(Xml(rss, responseETagHeader)); }
private bool TryCreateAndStoreUser(RegisterViewModel model, out User user) { user = new User { Email = model.Email, UserName = model.UserName, IsPublic = true, Name = model.Name, Boards = new List <string> { model.BoardName }, DefaultBoard = model.BoardName }; RavenSession.Store(user); return(UserManager.Create(user, model.Password).Succeeded); }
public ActionResult Details(string id) { try { var project = RavenSession.Load <Project>(id); if (project == null) { throw new ArgumentException("Cannot find project " + id); } return(View("Details", project)); } catch (Exception e) { ViewBag.ErrorMessage = e.Message; return(View("Error")); } }
public ActionResult SingleAccount(int accountId) { var account = RavenSession.Load <Account>("accounts/" + accountId); var users = RavenSession.Query <User>().Where(x => x.AccountId == accountId).ToList(); var clinics = RavenSession.Query <Clinic>().Where(x => x.AccountId == accountId).ToList(); var exercises = RavenSession.Query <Exercise>().Where(x => x.AccountId == accountId).ToList().OrderBy(x => x.Name).ToList(); var vm = new AccountAdministrationViewModel() { Account = account, Users = users, Clinics = clinics, Exercises = exercises }; return(View(vm)); }