コード例 #1
0
        private Boolean DeleteProject(Project project, ModelStateDictionary modelState)
        {
            if (project == null)
            {
                modelState.AddModelError("this", "A project must be supplied for deletion");
                return(false);
            }

            var existingProject = RavenSession.Load <Project>(project.Id);

            if (existingProject == null)
            {
                modelState.AddModelError("Id", "Project no longer exists");
                return(false);
            }
            else
            {
                var associatedUserStories = RavenSession.Query <UserStory>()
                                            .Where(us => us.ProjectId == existingProject.Id)
                                            .ToList();

                if (associatedUserStories != null)
                {
                    associatedUserStories.ForEach(RavenSession.Delete);
                }
            }

            RavenSession.Delete(existingProject);
            RavenSession.SaveChanges();

            return(true);
        }
コード例 #2
0
        public ActionResult Index()
        {
            var users     = RavenSession.Query <User>().Take(100);
            var onboarder = new UserOnboardProcess(RavenSession);

            RavenSession.Advanced.MaxNumberOfRequestsPerSession = 10000;
            foreach (var user in users)
            {
                if (!user.Roles.Contains(UserRoles.AccountAdmin.ToString()))
                {
                    user.Roles.Add(UserRoles.AccountAdmin.ToString());
                }

                if (user.AccountId == 0)
                {
                    var accountId = onboarder.CreateNewAccount();
                    user.AccountId = accountId;

                    if (!user.ClinicIds.Any())
                    {
                        var clinicId = onboarder.CreateNewClinic(accountId, "My Clinic");
                        user.ClinicIds.Add(clinicId);
                    }
                }
            }

            RavenSession.SaveChanges();

            return(View());
        }
コード例 #3
0
        public override SharedLink ExecuteWithResult()
        {
            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}");
            }
            if (evaluation.SharedLinks == null)
            {
                evaluation.SharedLinks = new SharedLinkList();
            }
            //regular expression for strings that starts with "Link#" and followed only by numbers
            var regExp         = new Regex(@"^Link#(\d+)$");
            var lastLinkNumber = evaluation.SharedLinks
                                 .Select(x => x.FriendlyName)
                                 .Select(x => regExp.Match(x))
                                 .Where(x => x.Success)
                                 .Select(x => int.Parse(x.Groups[1].Value))
                                 .OrderBy(x => x)
                                 .LastOrDefault();

            var newSharedLink = new SharedLink()
            {
                FriendlyName   = $"Link#{lastLinkNumber + 1}",
                ExpirationDate = DateTime.Now.AddDays(3).ToUniversalTime(),
                SharedCode     = GenerateSharedCode()
            };

            evaluation.SharedLinks.Add(newSharedLink);
            RavenSession.SaveChanges();
            return(newSharedLink);
        }
コード例 #4
0
ファイル: UserApiController.cs プロジェクト: jfreal/movidhep
        public ApiResponse SaveUser(UserPostedModel postedModel)
        {
            if (!ModelState.IsValid)
            {
                return(new ApiResponse("Validation errors occured."));
            }

            var user = RavenSession.Load <User>("users/" + postedModel.Id);

            if (user == null || user.AccountId != Account.Id)
            {
                return(new ApiResponse("User not found"));
            }

            if (!Ownership.Owns(user, this))
            {
                return(new ApiResponse("User not found"));
            }

            user.Name  = postedModel.Name;
            user.Email = postedModel.Email;
            RavenSession.SaveChanges();

            return(new ApiResponse(success: string.Format("User {0} edited", user.Email)));
        }
コード例 #5
0
        public ActionResult Delete(int id)
        {
            var user = RavenSession.Load <User>("users/" + id);

            if (user == null)
            {
                WarnUser("User could not be found.");
                return(RedirectToAction("Index"));
            }

            if (!Ownership.Owns(user, this))
            {
                return(HttpNotFound());
            }

            var exercises = RavenSession.Query <Exercise>(typeof(ByOwnableAndName).Name).
                            Where(x => !x.Master && (x.AccountId == user.AccountId)).Take(1024);

            foreach (var exercise in exercises)
            {
                RavenSession.Delete(exercise);
            }

            var account = RavenSession.Load <Account>("accounts/" + user.AccountId);

            RavenSession.Delete(account);
            RavenSession.Delete(user);

            RavenSession.SaveChanges();

            this.HighFive("User deleted.");

            return(RedirectToAction("Index"));
        }
コード例 #6
0
ファイル: UserApiController.cs プロジェクト: jfreal/movidhep
        public ApiResponse Disable(int userId)
        {
            var user = RavenSession.Load <User>("users/" + userId);

            if (user == null || user.AccountId != Account.Id)
            {
                return(new ApiResponse("User not found"));
            }

            if (!Ownership.Owns(user, this))
            {
                return(new ApiResponse("User not found"));
            }

            if (user.Status != UserStatus.Disabled)
            {
                user.Status = UserStatus.Active;
            }

            if (user.Status != UserStatus.Active)
            {
                user.Status = UserStatus.Disabled;
            }

            RavenSession.SaveChanges();

            return(new ApiResponse(success: "User status changed"));
        }
コード例 #7
0
ファイル: PlanApiController.cs プロジェクト: jfreal/movidhep
        public ApiResponse ChangePlan(ChangePlanRequest postedModel)
        {
            var stripeApi = new StripeApi();

            var expirationSplit = postedModel.Expiration.Split('/');

            try
            {
                if (string.IsNullOrWhiteSpace(Account.StripeCustomerId) || stripeApi.GetCustomer(Account.StripeCustomerId) == null)
                {
                    var response = stripeApi.StartMonthly(Account.Id.ToString(), LoggedInUser.Email, postedModel.PlanId,
                                                          postedModel.CardNumber, expirationSplit[0], expirationSplit[1],
                                                          postedModel.Cvc);

                    Account.StripeCustomerId = response;
                }
                else
                {
                    var response = stripeApi.UpdateMonthly(Account.StripeCustomerId, postedModel.PlanId,
                                                           postedModel.CardNumber, expirationSplit[0], expirationSplit[1],
                                                           postedModel.Cvc);
                }
            }
            catch (StripeException exception)
            {
                return(new ApiResponse(exception.StripeError.Message));
            }

            Account.ActivePlanId = postedModel.PlanId;
            RavenSession.SaveChanges();


            return(new ApiResponse(success: "Credit card added and your plan was changed successfuly, thanks for using Movid HEP."));
        }
コード例 #8
0
        public ActionResult NewProgram(Program newProgram)
        {
            if (string.IsNullOrWhiteSpace(newProgram.Email))
            {
                return(Json(new { success = false }));
            }

            newProgram.ShortUrl = ShortUrl.Create();
            newProgram.Created  = DateTime.Now;

            Ownership.Assign(newProgram, this);

            if (!LoggedInUser.OnboardingTasks.Contains(OnboardingTask.CreatedProgram.ToString()))
            {
                LoggedInUser.OnboardingTasks.Add(OnboardingTask.CreatedProgram.ToString());
            }

            RavenSession.Store(newProgram);
            RavenSession.SaveChanges();

            new Emailer(this).SendEmail(EmailEnum.SendToPatient, newProgram.Email, newProgram.ShortUrl, newProgram.Id);

            // new ProgramEmailer(this).SendToPatient(newProgram.Id, newProgram.Email, newProgram.ShortUrl);

            return(Json(true));
        }
コード例 #9
0
ファイル: AccountController.cs プロジェクト: jfreal/movidhep
        public ActionResult Invite(string id, string password, string confirmPassword)
        {
            var vm = UserInvitationBuilder.Build(id, RavenSession);

            CheckUserInvitationValidity(vm);
            if (password != confirmPassword)
            {
                ModelState.AddModelError("DifferentPasswords", "Passwords must match.");
            }

            if (!ModelState.IsValid)
            {
                return(View(vm));
            }

            var hashed = Hash(password);

            var user = vm.To;

            user.Status   = UserStatus.Active;
            user.Password = hashed;
            RavenSession.SaveChanges();

            HighFive("Your account was created and password saved.  Login to get started using Movid HEP");

            return(RedirectToAction("Login"));
        }
コード例 #10
0
ファイル: AccountController.cs プロジェクト: jfreal/movidhep
        public ActionResult ResetPassword(PasswordResetViewModel postedModel)
        {
            var pr = RavenSession.Query <PasswordReset>().FirstOrDefault(x => x.Token == postedModel.Token);

            if (pr == null || pr.Generated > DateTime.Now.AddHours(2))
            {
                return(View("Reset", new PasswordResetViewModel()));
            }

            if (postedModel.Password != postedModel.ConfirmPassword)
            {
                ModelState.AddModelError("NoMatch", "Passwords must match.");
                return(View("Reset", postedModel));
            }

            var user = RavenSession.Load <User>("users/" + pr.UserId);

            if (user == null)
            {
                ModelState.AddModelError("NoUserMatch", "User account not found.");
                return(View("Reset", postedModel));
            }

            var pw = Hash(postedModel.Password);

            user.Password = pw;

            RavenSession.Delete(pr);
            RavenSession.SaveChanges();

            HighFive("Your password has been changed.");
            return(RedirectToAction("Login"));
        }
コード例 #11
0
ファイル: ExerciseController.cs プロジェクト: jfreal/movidhep
        public ActionResult Edit(ExerciseViewModel postedModel, string categories)
        {
            if (!ModelState.IsValid)
            {
                return(View(postedModel));
            }

            var exr = RavenSession.Load <Exercise>("exercises/" + postedModel.Id);

            if (!Ownership.Owns(exr, this))
            {
                return(HttpNotFound());
            }


            //if (exr.AccountId != LoggedInUser.AccountId)
            //{
            //    if (!ApplicationAdministrator)
            //    {
            //        return HttpNotFound();
            //    }
            //}

            UpdateModel(exr);

            string[] lines = categories.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
            exr.Categories = new List <string>(lines.Where(x => !string.IsNullOrWhiteSpace(x)));

            exr.Name = exr.Name.Trim();

            RavenSession.SaveChanges();
            HighFive("Exercise edited ok.");

            return(RedirectToAction("List"));
        }
コード例 #12
0
ファイル: ProtocolController.cs プロジェクト: jfreal/movidhep
        public ActionResult Delete(int protocolId)
        {
            var plan = RavenSession.Load <Protocol>("protocols/" + protocolId);

            if (plan == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound, "Protocol not found"));
            }

            if (!Ownership.Owns(plan, this))
            {
                return(HttpNotFound());
            }

            if (LoggedInUser.ClinicIds.Contains(plan.ClinicId))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound, "Protocol not found"));
            }

            RavenSession.Delete(plan);
            RavenSession.SaveChanges();

            HighFive("Protocol deleted successfuly");

            return(RedirectToAction("List"));
        }
コード例 #13
0
        public void GetTransactions_GivesAllTransactions()
        {
            var testAccountId = "account/10";
            var target        = new TransactionService(RavenSession);

            target.Store(new Transaction()
            {
                PayeeId = testAccountId,
                PayerId = "account/12",
                Amount  = 12M
            });
            target.Store(new Transaction()
            {
                PayeeId = "account/12",
                PayerId = testAccountId,
                Amount  = 6M
            });
            target.Store(new Transaction()
            {
                PayeeId = testAccountId,
                PayerId = "account/14",
                Amount  = 5M
            });

            RavenSession.SaveChanges();

            var result = target.GetTransactionsFor(testAccountId);
            var list   = new List <Transaction>(result);

            Assert.AreEqual(3, result.Count());
            Assert.AreEqual(12M, list[0].Amount);
            Assert.AreEqual(6M, list[1].Amount);
            Assert.AreEqual(5M, list[2].Amount);
        }
コード例 #14
0
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                var changePasswordSucceeded = false;
                try
                {
                    var currentUser = RavenSession.GetUser(User.Identity.Name, false);
                    if (currentUser.ValidatePassword(model.OldPassword))
                    {
                        currentUser.SetPassword(model.NewPassword);
                        RavenSession.SaveChanges();
                        changePasswordSucceeded = true;
                    }
                }
                catch (Exception)
                {
                    // TODO: Log e
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return(RedirectToAction("ChangePasswordSuccess"));
                }

                ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #15
0
        public void GetBalance_AggregatesCorrectly()
        {
            var testAccountId = "account/10";
            var target        = new TransactionService(RavenSession);

            target.Store(new Transaction()
            {
                PayeeId = testAccountId,
                PayerId = "account/12",
                Amount  = 12.2M
            });
            target.Store(new Transaction()
            {
                PayeeId = "account/12",
                PayerId = testAccountId,
                Amount  = .2M
            });
            target.Store(new Transaction()
            {
                PayeeId = testAccountId,
                PayerId = "account/14",
                Amount  = 5M
            });

            RavenSession.SaveChanges();

            var result = target.GetBalance(testAccountId);

            Assert.AreEqual(17, result);
        }
コード例 #16
0
        public ActionResult Index()
        {
            var exercises = RavenSession.Query <Exercise>().Where(x => x.Master).Take(1024);

            RavenSession.Advanced.MaxNumberOfRequestsPerSession = 10000;
            foreach (var exer in exercises)
            {
                var newMaster = new MasterExercise();

                newMaster.AccountId        = 0;
                newMaster.Name             = exer.Name;
                newMaster.Categories       = exer.Categories;
                newMaster.ClinicId         = 0;
                newMaster.Description      = exer.Description;
                newMaster.ExerciseDetails  = exer.ExerciseDetails;
                newMaster.MasterExerciseId = exer.Id;
                newMaster.Master           = true;
                newMaster.UserId           = 0;
                newMaster.VideoId          = exer.VideoId;
                newMaster.CreatedOn        = DateTime.Now;

                RavenSession.Store(newMaster);
            }

            RavenSession.SaveChanges();

            return(View());
        }
コード例 #17
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var newUser = new User();
                    newUser.SetPassword(model.Password);
                    newUser.UserName = model.UserName;
                    newUser.Email    = model.Email;
                    newUser.Enabled  = true;

                    RavenSession.Store(newUser);

                    RavenSession.SaveChanges();

                    //WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    FormsAuthentication.SetAuthCookie(newUser.UserName, true);



                    //WebSecurity.Login(model.UserName, model.Password);
                    return(RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #18
0
        public virtual ActionResult Index(BlogConfig config)
        {
            if (ModelState.IsValid == false)
            {
                ViewBag.Message = ModelState.FirstErrorMessage();
                if (Request.IsAjaxRequest())
                {
                    return(Json(new { Success = false, ViewBag.Message }));
                }
                return(View(BlogConfig));
            }

            var current = RavenSession.Load <BlogConfig>(BlogConfig.Key);

            if (IsFuturePostsEncryptionOptionsChanged(current, config))
            {
                RemoveFutureRssAccessOnEncryptionConfigChange();
            }

            RavenSession.Advanced.Evict(current);
            RavenSession.Store(config, BlogConfig.Key);
            RavenSession.SaveChanges();

            OutputCacheManager.RemoveItem(MVC.Section.Name, MVC.Section.ActionNames.ContactMe);

            ViewBag.Message = "Configurations successfully saved!";
            if (Request.IsAjaxRequest())
            {
                return(Json(new { Success = true, ViewBag.Message }));
            }
            return(View(config));
        }
コード例 #19
0
ファイル: ExerciseController.cs プロジェクト: jfreal/movidhep
        public bool RefreshThumb(string exerciseId, string videoId)
        {
            var exr = RavenSession.Load <Exercise>("exercises/" + exerciseId);

            Thumbnailer.GenerateThumbs(exr.Id, exr.VideoId);

            RavenSession.SaveChanges();

            return(true);
        }
コード例 #20
0
        public virtual async Task <ActionResult> ResetFailedRedditSubmission(string postId, string sr)
        {
            var post           = RavenSession.Load <Post>(postId);
            var postSubmission = post.Integration.Reddit.GetPostSubmissionForSubreddit(sr);

            postSubmission.Status   = null;
            postSubmission.Attempts = 0;
            RavenSession.SaveChanges();
            return(RedirectToAction(MVC.Admin.Settings.ActionNames.RedditSubmission));
        }
コード例 #21
0
ファイル: ExerciseController.cs プロジェクト: jfreal/movidhep
        public ActionResult Create(ExerciseViewModel postedModel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(postedModel));
                }

                //this code could use some TLC

                var newExercise = new Exercise();

                string[] lines = postedModel.Categories.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                newExercise.Categories = new List <string>(lines.Where(x => !string.IsNullOrWhiteSpace(x)));


                if (!string.IsNullOrWhiteSpace(postedModel.VideoId))
                {
                    newExercise.VideoId = postedModel.VideoId.Trim();
                }

                Ownership.Assign(newExercise, this);

                if (this.ApplicationAdministrator)
                {
                    newExercise.Master = true;
                }
                newExercise.CreatedOn   = DateTime.Now;
                newExercise.Name        = postedModel.Name.Trim();
                newExercise.Description = postedModel.Description;

                RavenSession.Store(newExercise);
                RavenSession.SaveChanges();

                if (!string.IsNullOrWhiteSpace(postedModel.VideoId))
                {
                    var success = Thumbnailer.GenerateThumbs(newExercise.Id, newExercise.VideoId);
                    if (!success)
                    {
                        this.WarnUser("We couldn't generate a thumbnail image for this exercise.  The video id could be wrong or Vimeo may be not be " +
                                      "responding.  We'll try to generate the thumbnail again but it would be a good idea to double" +
                                      "check the video id. Sorry about that.");
                    }
                }

                HighFive("New exercise created ok.");

                return(RedirectToAction("List"));
            }
            catch
            {
                return(View(postedModel));
            }
        }
コード例 #22
0
        public object Delete(Day dayInput)
        {
            var username = User.Identity.Name.Split('@')[0];
            var day      = dayInput.Date;
            var docId    = String.Format("work/{0}/{1:0000}-{2:00}", username, day.Year, day.Month);
            var month    = RavenSession.Load <Month>(docId);

            month.Days.Remove(day);
            RavenSession.SaveChanges();
            return(new { Success = true });
        }
コード例 #23
0
        //
        // GET: /Scheduler/

        public ActionResult Index()
        {
            var schedule = RavenSession.Load <ScheduleSettings>("scheduleSettings/1");
            var data     = new List <EmailReminderData>();

            int delayHours = 4;

            if (schedule == null)
            {
                schedule = new ScheduleSettings {
                    Id = "scheduleSettings/1"
                }; RavenSession.Store(schedule); ViewBag.Message = "This is the first run!";
                ViewBag.Error = "First run, creating session";
                return(View());
            }


            if ((DateTime.Now - schedule.LastRun).TotalHours > delayHours)
            {
                try
                {
                    var logic = new ReminderHelper(RavenSession, Server.MapPath("/Views/Templates/"));

                    var reminders = logic.GetAllRemindersDueBefore(DateTime.Now);
                    var msgs      = logic.ComposeMessages(reminders);
                    ViewBag.Messages = msgs;
                    var emails = logic.SendEmails(msgs);
                    ViewBag.SentMessages = emails;
                    logic.UpdateMsgCount(reminders);
                }
                catch (Exception ex)
                {
                    ViewBag.Error = ex.Message;
                }

                ViewBag.Message = "Last run: " + schedule.LastRun;

                if (data.Count > 0)
                {
                    string emailText = GetEmailText(data);
                    RavenSession.Store(new TempTextEmail {
                        Text = emailText
                    });
                }
                schedule.LastNumberOfNotifications = data.Count;
                schedule.LastRun = DateTime.Now;
                RavenSession.SaveChanges();
            }
            else
            {
                ViewBag.Error = "Scheduler will not run before" + (delayHours - (DateTime.Now - schedule.LastRun).TotalHours).ToString() + " hours";
            }
            return(View(data));
        }
コード例 #24
0
        public void DeleteOldExercises()
        {
            var exercises = RavenSession.Query <Exercise>()
                            .Where(x => !x.Master).Take(1024).ToList();

            foreach (var exercise in exercises)
            {
                RavenSession.Delete(exercise);
            }

            RavenSession.SaveChanges();
        }
コード例 #25
0
        public ActionResult UpdateProject(Project existingProject)
        {
            var isValid = ModelState.IsValid && ValidateProject(existingProject, ModelState);

            if (isValid)
            {
                RavenSession.Store(existingProject);
                RavenSession.SaveChanges();
            }

            return(GetJsonResult(existingProject));
        }
コード例 #26
0
        public ActionResult CreateUserStory(UserStory newUserStory)
        {
            if (ModelState.IsValid)
            {
                RavenSession.Store(newUserStory);
                RavenSession.SaveChanges();

                DomainEventService.PublishUserStoryCreated(newUserStory);
            }

            return(GetJsonResult(newUserStory));
        }
コード例 #27
0
        public ApiResponse Add(int clinicId)
        {
            var clinic = RavenSession.Load <Clinic>("clinics/" + clinicId);

            RavenSession.Delete(clinic);
            RavenSession.SaveChanges();

            return(new ApiResponse(success: clinic.Name + " deleted")
            {
                Model = clinic
            });
        }
コード例 #28
0
ファイル: PublicController.cs プロジェクト: jfreal/movidhep
        private void SaveView(Program program)
        {
            var viewEvent = new ProgramView()
            {
                When    = DateTime.Now,
                Ip      = HttpContext.Request.UserHostAddress,
                Browser = HttpContext.Request.Browser.Browser,
                User    = HttpContext.Request.IsAuthenticated ? LoggedInUser.Email : ""
            };

            program.PlanViews.Add(viewEvent);
            RavenSession.SaveChanges();
        }
コード例 #29
0
        public virtual async Task <ActionResult> SubmitToReddit(string postId, string sr)
        {
            var post            = RavenSession.Load <Post>(postId);
            var redditSubmitUrl = RedditHelper.SubmitUrl(sr, post);
            var postSubmission  = post.Integration.Reddit.GetPostSubmissionForSubreddit(sr);

            postSubmission.Status   = Reddit.SubmissionStatus.ManualSubmissionPending;
            postSubmission.Attempts = 0;

            RavenSession.SaveChanges();

            return(Redirect(redditSubmitUrl));
        }
コード例 #30
0
        public RedirectToRouteResult Edit(EditViewModel viewModel)
        {
            if (viewModel.Id.StartsWith(Id.TemplatePrefix))
            {
                // Create new message
                viewModel.Message.Id = Id.Messages(ShopName);
            }

            RavenSession.Store(viewModel.Message);
            RavenSession.SaveChanges();

            return(RedirectToAction("Index", "Home"));
        }