Example #1
0
        public ActionResult Index()
        {
            string fragment = Request.QueryString["_escaped_fragment_"];

            if (fragment != null)
            {
                try
                {
                    var file = Server.MapPath(string.Format(@"~/App/redirected.html"));
                    if (!string.IsNullOrWhiteSpace(file))
                    {
                        var fileContent = System.IO.File.ReadAllText(file);
                        return Content(fileContent);
                    }

                    var message = string.Format("Offline content not found. Escaped fragment: '{0}'", fragment);
                    return Content(message);
                }
                catch (Exception ex)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine(ex.Message);
                    if (ex.InnerException != null)
                    {
                        sb.AppendLine("------------------------------");
                        sb.AppendLine(ex.InnerException.Message);
                    }
                    return Content(ex.Message);
                }
            }

            ErrorViewModel vm = new ErrorViewModel();

            return View(vm);
        }
        public static ErrorViewModel GetInstance(string title, string message, EErrorButtons buttonSet, IObserver<EErrorResult> observer, Exception ex)
        {
            ErrorViewModel evm = new ErrorViewModel(ex, _logger, buttonSet);
            evm.Title = title;
            evm.Message = message;
            evm.ButtonSet = buttonSet;
            evm.Subscribe(observer);

            return evm;
        }
 static void RenderMvcErrorView(HttpRequestBase request,
                                HttpResponseBase response,
                                string redirectPath,
                                Exception currentError)
 {
     var controllerContext = NewControllerContext(request);
     var view = new RazorView(controllerContext, redirectPath, null, false, null);
     var viewModel = new ErrorViewModel {Exception = currentError};
     var viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary(viewModel), new TempDataDictionary(),
                                       response.Output);
     view.Render(viewContext, response.Output);
 }
Example #4
0
 protected override void OnException(ExceptionContext filterContext)
 {
     // Bail if we can't do anything; app will crash.
     if (filterContext == null)
         return;
     if (!filterContext.HttpContext.IsCustomErrorEnabled) return;
     var ex = filterContext.Exception ?? new Exception("No further information exists.");
     filterContext.ExceptionHandled = true;
     if ((ex.GetType() != typeof(HttpRequestValidationException)))
     {
         Logger.Error(ex, filterContext.HttpContext.Request.Path, filterContext.HttpContext.Request.RawUrl);
         var data = new ErrorViewModel
         {
             ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
             DisplayMessage = "Unhandled exception",
             ErrorCode = ErrorCode.Unknown,
             Severity = ErrorSeverity.Error
         };
         filterContext.Result = View("Error", data);
     }
 }
Example #5
0
        public virtual IActionResult NotesIdDeletePost([FromRoute] int id)
        {
            bool exists = _context.HetNote.Any(a => a.NoteId == id);

            // not found
            if (!exists)
            {
                return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
            }

            HetNote note = _context.HetNote.First(a => a.NoteId == id);

            if (note != null)
            {
                _context.HetNote.Remove(note);

                // save the changes
                _context.SaveChanges();
            }

            return(new ObjectResult(new HetsResponse(note)));
        }
Example #6
0
        //Insert or Update action for Maintenance line item
        public IActionResult Upsert(int?id)
        {
            MaintenanceLineItemViewModel mliVM = new MaintenanceLineItemViewModel()
            {
                MaintenanceLineItem = new MaintenanceLineItem(),
                BusList             = _unitOfWork.GarageAssignment.GetAll(b => b.CheckOut == null, includeProperties: "Bus").
                                      Select(i => new SelectListItem
                {
                    Text  = i.Bus.RegistrationNumber,
                    Value = i.Bus.Id.ToString()
                }),
                RequestTypeList = _unitOfWork.MaintenanceRequestType.GetAll(b => b.IsActive == true).Select(i => new SelectListItem
                {
                    Text  = i.Name,
                    Value = i.Id.ToString()
                })
            };

            try
            {
                if (id == null)
                {
                    return(View(mliVM));
                }
                mliVM.MaintenanceLineItem = _unitOfWork.MaintenanceLineItem.Get(id.GetValueOrDefault());
                if (mliVM == null)
                {
                    throw new Exception("Unable to find the maintenance line item");
                }
            }
            catch (Exception ex)
            {
                var evm = new ErrorViewModel();
                evm.ErrorMessage = ex.Message.ToString();
                return(View("Error", evm));
            }

            return(View(mliVM));
        }
Example #7
0
        public ActionResult UserActivate(Guid id)
        {
            RepositoryLayerResult <Users> user = ur.ActivateUser(id);

            if (user.Errors.Count > 0)
            {
                ErrorViewModel erModel = new ErrorViewModel()
                {
                    Title = "Account not valid.",
                    Items = user.Errors
                };
                return(View("Error", erModel));
            }

            OkViewModel okModel = new OkViewModel()
            {
                Title         = "Account Activation Successful",
                RedirectinUrl = "/Home/Login"
            };

            return(View("Ok", okModel));
        }
Example #8
0
        public ActionResult UserActivate(Guid activateID)
        {
            EvernoteUserManager eum = new EvernoteUserManager();
            BusinessLayerResult <EvernoteUser> blr = eum.ActivateUser(activateID);

            if (blr.Result != null)
            {
                if (blr.Informations.Count > 0)
                {
                    InfoViewModel model = new InfoViewModel();

                    blr.Informations.ForEach(x =>
                    {
                        model.Items.Add(x.Value);
                    });

                    return(View("Info", model));
                }
                else
                {
                    OkViewModel model = new OkViewModel();

                    model.Items.Add("Hesap aktivasyon işleminiz başarılı bir şekilde gerçekleştirilmiştir.");

                    return(View("Ok", model));
                }
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel();

                blr.Errors.ForEach(x =>
                {
                    model.Items.Add(x.Value);
                });

                return(View("Error", model));
            }
        }
        public ActionResult UserActivate(Guid id)
        {
            BusinessLayerResult <EvernoteUser> res = eum.ActivateUser(id);

            if (res.Errors.Count > 0)
            {
                ErrorViewModel errorNotify = new ErrorViewModel()
                {
                    Title = "Geçersiz İşlem",
                    Items = res.Errors
                };
                return(View("Error", errorNotify));
            }
            OkViewModel okNotify = new OkViewModel()
            {
                Title          = "Hesap Aktifleştirildi.",
                RedirectingUrl = "/Home/Login"
            };

            okNotify.Items.Add("Hesap Aktifleştirildi.Artık not paylaşabilir ve begenme yapabilirsiniz.");
            return(View("Ok", okNotify));
        }
        public ActionResult Authenticate(Credentials credentials)
        {
            try
            {
                int result = service.Authenticate(credentials);

                if (result == 0)
                {
                    ModelState.AddModelError("Email", "Invalid UserId or Password");

                    return(View("Authenticate", credentials));
                }

                return(RedirectToAction("Search", "Search", new { area = "" }));
            }
            catch (Exception e)
            {
                ErrorViewModel m = new ErrorViewModel();
                m.RequestId = e.Message;
                return(View("Error", m));
            }
        }
        public ActionResult Delete(long id)
        {
            var errorViewModel = new ErrorViewModel();

            if (Session["MasterId"] != null)
            {
                Session["MasterId"] = null;
            }
            // Clear detail list
            if (Session["lstPettyCashVoucherDetails"] != null)
            {
                Session["lstPettyCashVoucherDetails"] = null;
            }

            try
            {
                var model = _pettyCashVoucherInfoService.BMSUnit.WebVoucherMasterRepository.GetByID(id);

                if (model != null)
                {
                    VoucherViewModel viewModel = new VoucherViewModel
                    {
                        Id = Convert.ToInt32(model.Id)
                    };

                    return(PartialView("_Delete", viewModel));
                }
                else
                {
                    errorViewModel.ErrorMessage = CommonMessage.ErrorOccurred;
                    return(PartialView("_ErrorPopUp", errorViewModel));
                }
            }
            catch (Exception ex)
            {
                errorViewModel.ErrorMessage = CommonExceptionMessage.GetExceptionMessage(ex);
                return(PartialView("_ErrorPopUp", errorViewModel));
            }
        }
Example #12
0
        public IActionResult Attend(int id)
        {
            var matchExists = this.matchesService.MatchExistsById(id);

            if (!matchExists)
            {
                var errorViewModel = new ErrorViewModel
                {
                    ErrorMessage = ErrorMessages.MatchDoesNotExistsErrorMessage
                };

                return(this.View(viewName: GlobalConstants.ErrorViewName, model: errorViewModel));
            }

            var matchHasAreferee = this.matchesService.MatchHasReferee(id);

            if (matchHasAreferee)
            {
                var errorViewModel = new ErrorViewModel
                {
                    ErrorMessage = ErrorMessages.MatchHasRefereeErrorMessage
                };

                return(this.View(viewName: GlobalConstants.ErrorViewName, model: errorViewModel));
            }

            var user = this.User.Identity.Name;

            this.refereesService.AttendAMatch(user, id);

            var match     = this.matchesService.GetMatchById <Match>(id);
            var fixtureId = match.Fixture.Id;

            var routeValues = new { Id = fixtureId };

            return(this.RedirectToAction(controllerName: GlobalConstants.FixturesControllerName,
                                         actionName: GlobalConstants.DetailsActionName,
                                         routeValues: routeValues));
        }
Example #13
0
        public ActionResult DeleteProfile()
        {
            EvernoteUser currentUser = Session["login"] as EvernoteUser;

            BusinessLayerResult <EvernoteUser> res =
                evernoteUserManager.RemoveUserById(CurrentSession.User.Id);

            if (res.Errors.Count > 0)
            {
                ErrorViewModel errorNotifyObj = new ErrorViewModel()
                {
                    Items = res.Errors,
                    Title = "Profil Silinemedi.",
                };

                return(View("Error", errorNotifyObj));
            }

            Session.Clear();

            return(RedirectToAction("Index"));
        }
        public ActionResult TestNotify()
        {
            ErrorViewModel model = new ErrorViewModel()
            {
                Header             = "Yönlendirme..",
                Title              = "Ok Test",
                RedirectingTimeout = 10000,
                Items              = new List <ErrorMessageObj>()
                {
                    new ErrorMessageObj()
                    {
                        Message = "bu bir denemedir1"
                    },
                    new ErrorMessageObj()
                    {
                        Message = "bu bir denemedir2"
                    }
                }
            };

            return(View("Error", model));
        }
Example #15
0
        /// <summary>
        /// Delete rental agreement conditions
        /// </summary>
        /// <param name="id">id of Project to delete</param>
        /// <response code="200">OK</response>
        /// <response code="404">Project not found</response>
        public virtual IActionResult RentalagreementconditionsIdDeletePostAsync(int id)
        {
            bool exists = _context.RentalAgreementConditions.Any(a => a.Id == id);

            if (exists)
            {
                RentalAgreementCondition item = _context.RentalAgreementConditions.First(a => a.Id == id);

                if (item != null)
                {
                    _context.RentalAgreementConditions.Remove(item);

                    // save the changes
                    _context.SaveChanges();
                }

                return(new ObjectResult(new HetsResponse(item)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
Example #16
0
        public async Task <IActionResult> Error()
        {
            await sessionLogic.TryDeleteSessionAsync();

            var errorViewModel = new ErrorViewModel
            {
                CreateTime = DateTimeOffset.Now,
                RequestId  = HttpContext.TraceIdentifier
            };

            var exceptionHandlerPathFeature = HttpContext.Features.Get <IExceptionHandlerPathFeature>();
            var exception = exceptionHandlerPathFeature?.Error;

            if (exception is SequenceTimeoutException)
            {
                var timeout = new TimeSpan(0, 0, HttpContext.GetRouteBinding().SequenceLifetime);
                errorViewModel.ErrorTitle = localizer["Timeout"];
                errorViewModel.Error      = string.Format(localizer["It should take a maximum of {1} minutes from start to finish. Please try again."], timeout.TotalMinutes);
            }

            return(View(errorViewModel));
        }
Example #17
0
        public ActionResult ShowProfile()
        {
            EvernoteUser currentUser = Session["login"] as EvernoteUser;

            EvernoteUserManager eum = new EvernoteUserManager();

            BusinessLayerResult <EvernoteUser> res = eum.GetUserById(currentUser.Id);

            if (res.Errors.Count > 0)
            {
                // Kullanıcıyı Hata Ekranına Yönlendiricez

                ErrorViewModel errorNotifyObj = new ErrorViewModel()
                {
                    Title = "Hata Oluştu",
                    Items = res.Errors
                };
            }


            return(View(res.Result));
        }
        public ActionResult ShowProfile()
        {
            //   EvernoteUser currentUser = Session["login"] as EvernoteUser;

            // Kullanıcının id'sini fonksiyon yardımı ile buluyoruz.
            BusinessLayerResult <EvernoteUser> res = evernoteUserManager.GetUserById(CurrentSession.User.Id);

            // eğer hata var ise
            if (res.Errors.Count > 0)
            {
                // TODO : Kullanıcıyı bir hata ekranına yönlendirmek gerekiyor..
                ErrorViewModel ErrorNotifyObj = new ErrorViewModel()
                {
                    Title = "Hata Oluştu",
                    Items = res.Errors
                };
                // Hata var ise hata ekranına yönlendir.
                return(View("Error", ErrorNotifyObj));
            }
            // Eğer yok ise ShowProfile sayfasını aç ve sonucu yolla
            return(View(res.Result));
        }
Example #19
0
        public async Task <IActionResult> AddProjectEmployeeToProject(List <EstWorkingHoursEmployeeViewModel> items)
        {
            try
            {
                var projectEmployees = items.Where(x => x.EstWorkingHours > 0).Select(x => new ProjectEmployeeViewModel()
                {
                    EmployeeId      = x.Id,
                    ProjectId       = x.ProjectId,
                    EstWorkingHours = x.EstWorkingHours,
                });
                await _employeeService.AddProjectEmployeeAsync(ProjectEmployeeMapper.Map(projectEmployees).ToList()).ConfigureAwait(false);

                return(RedirectToAction("details", "project", new { id = items[0].ProjectId }));
            }
            catch (Exception)
            {
                ErrorViewModel model = new ErrorViewModel {
                    RequestId = "Medarbejderen kunne ikke tilknyttes projektet"
                };
                return(View("Error", model));
            }
        }
        public async Task <IActionResult> CreateCompanyAsync(CreateCompanyViewModel model)
        {
            try
            {
                CompanyDto company = new CompanyDto
                {
                    Title   = model.Title,
                    Address = model.Address
                };

                await companyService.CreateAsync(company);

                return(RedirectToAction("CompaniesList", "Company"));
            }
            catch (Exception ex)
            {
                ErrorViewModel errorModel = new ErrorViewModel();
                errorModel.ErrorMessage = ex.Message.ToString();

                return(View("Views/Shared/Error.cshtml", errorModel));
            }
        }
        public async Task <IActionResult> Lecturer(int id)
        {
            try
            {
                var viewModels = await _missedClassesFacade.GetLecturerMissedClassesAsync(id);

                _logger.LogInformation("Fetched lecturer's missed classes");

                return(View(nameof(List), viewModels));
            }
            catch (BusinessLogicException ex)
            {
                _logger.LogError(ex.Message);
                var error = new ErrorViewModel
                {
                    ErrorMessage = ex.Message,
                    ReturnUrl    = Request.GetReferer(),
                };

                return(View("Error", error));
            }
        }
        public IActionResult Task(ProjectModel projectModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    ProjectBLO projectBLO = new ProjectBLO();
                    projectBLO = converter.Convert(projectModel);
                    ProjectModel project = new ProjectModel();

                    if (projectModel.ProjectId == 0)
                    {
                        int id = projectService.Insert(projectBLO);
                        project = converter.Convert(projectService.GetById(id));
                    }
                    else
                    {
                        projectService.Update(projectBLO);
                        project = projectModel;
                    }
                    return(RedirectToAction("CreateByProject", "Task", project));
                }
                else
                {
                    return(RedirectToAction("Create"));
                }
            }
            catch (Exception ex)
            {
                logger.LogError("Не удалось внести информацию о проекте");
                ErrorViewModel error = new ErrorViewModel()
                {
                    source     = ex.Source,
                    message    = ex.Message,
                    stackTrace = ex.StackTrace
                };
                return(RedirectToAction("Error", "Home", error));
            }
        }
        public async Task <IActionResult> Delete(int id)
        {
            try
            {
                await _missedClassesFacade.DeleteAsync(id);

                _logger.LogInformation("Deleted missed class");

                return(RedirectToAction(nameof(List)));
            }
            catch (BusinessLogicException ex)
            {
                _logger.LogError(ex.Message);
                var error = new ErrorViewModel
                {
                    ErrorMessage = ex.Message,
                    ReturnUrl    = Request.GetReferer(),
                };

                return(View("Error", error));
            }
        }
        public async Task <ActionResult> Login(RegisterLoginViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View("Index", model));
                }

                var userManager = NewUserManager();
                var user        = await userManager.FindAsync(model.LoginViewModel.UserName, model.LoginViewModel.Password);

                if (user == null)
                {
                    ModelState.AddModelError("", "Kullanıcı adı veya şifre hatalı");
                    return(View("Index", model));
                }
                var authManager  = HttpContext.GetOwinContext().Authentication;
                var userIdentity =
                    await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                authManager.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = model.LoginViewModel.RememberMe
                }, userIdentity);
                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception ex)
            {
                TempData["Model"] = new ErrorViewModel()
                {
                    Text           = $"Bir hata oluştu {ex.Message}",
                    ActionName     = "Index",
                    ControllerName = "Account",
                    ErrorCode      = 500
                };
                return(RedirectToAction("Error", "Home"));
            }
        }
Example #25
0
        /// <summary>
        /// Delete local area rotation list
        /// </summary>
        /// <param name="id">id of DumpTruck to delete</param>
        /// <response code="200">OK</response>
        /// <response code="404">DumpTruck not found</response>
        public virtual IActionResult LocalarearotationlistsIdDeletePostAsync(int id)
        {
            bool exists = _context.LocalAreaRotationLists.Any(a => a.Id == id);

            if (exists)
            {
                LocalAreaRotationList item = _context.LocalAreaRotationLists.First(a => a.Id == id);

                if (item != null)
                {
                    _context.LocalAreaRotationLists.Remove(item);

                    // Save the changes
                    _context.SaveChanges();
                }

                return(new ObjectResult(new HetsResponse(item)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
        public async Task <IActionResult> Create(AppointmentViewModel model)
        {
            AppointmentDateError result = _service.ValidateDate(model.Start, User.Identity.Name, model.MechanicId);

            if (result != AppointmentDateError.None)
            {
                ErrorViewModel errorModel = new ErrorViewModel();
                if (result == AppointmentDateError.InvalidDate)
                {
                    errorModel.ErrorMessage = "Sikertelen művelet - a megadott időpont nem foglalható.";
                }
                else if (result == AppointmentDateError.Conflicting)
                {
                    errorModel.ErrorMessage = "Sikertelen művelet - a megadott időpontra már létezik foglalás.";
                }
                else if (result == AppointmentDateError.ConflictingWithOwn)
                {
                    errorModel.ErrorMessage = "Sikertelen művelet - a megadott időpontra önnek már létezik foglalása.";
                }
                return(View("Error", errorModel));
            }

            if (!ModelState.IsValid)
            {
                return(View("NewAppointment", model));
            }

            Appointment newAppointment = new Appointment
            {
                Time     = model.Start,
                WorkType = model.WorkType.ToString(),
                Note     = model.Note,
                Mechanic = _service.GetMechanic(model.MechanicId),
                Partner  = await _userManager.FindByNameAsync(User.Identity.Name)
            };

            _service.SaveAppointment(newAppointment);
            return(RedirectToAction("ResetDate", "Home", model.Start));
        }
Example #27
0
        public ActionResult EditProfile(EvernoteUser model, HttpPostedFileBase ProfileImage)
        {
            ModelState.Remove("ModifiedUsername");

            if (ModelState.IsValid)
            {
                if (ProfileImage != null &&
                    (ProfileImage.ContentType == "image/jpeg" ||
                     ProfileImage.ContentType == "image/jpg" ||
                     ProfileImage.ContentType == "image/png"))
                {
                    string filename = $"user_{model.Id}.{ProfileImage.ContentType.Split('/')[1]}";

                    ProfileImage.SaveAs(Server.MapPath($"~/images/{filename}"));
                    model.ProfileImageFilename = filename;
                }

                BusinessLayerResult <EvernoteUser> res = evernoteUserManager.UpdateProfile(model);

                if (res.Errors.Count > 0)
                {
                    ErrorViewModel errorNotifyObj = new ErrorViewModel()
                    {
                        Items          = res.Errors,
                        Title          = "Profil Güncellenemedi.",
                        RedirectingUrl = "/Home/EditProfile"
                    };

                    return(View("Error", errorNotifyObj));
                }

                // Profil güncellendiği için session güncellendi.
                CurrentSession.Set <EvernoteUser>("login", res.Result);

                return(RedirectToAction("ShowProfile"));
            }

            return(View(model));
        }
Example #28
0
        /// <summary>
        /// Generic error page to show in case of unhandled exceptions
        /// </summary>
        /// <returns>HTML</returns>
        public ActionResult Error(Exception exception)
        {
            var code = GetStatusCode(exception);

            Response.TrySkipIisCustomErrors = true;

            var message        = string.Format(Strings_Errors.Msg_Error500, code);
            var additionalInfo = string.Empty;
            var appSpecific    = (exception is YbqAppException);

            if (code == 404)
            {
                message = Strings_Errors.Msg_Error404;
            }
            if (code == 500)
            {
                if (appSpecific)
                {
                    message = exception.Message;
                }
                else
                {
                    additionalInfo = exception.Message;
                }
            }

            var model = new ErrorViewModel(message, appSpecific)
            {
                ErrorOccurred = { StatusCode = code, AdditionalInfo = additionalInfo }
            };

            if (appSpecific)
            {
                var actualException = (YbqAppException)exception;
                model.ErrorOccurred.RecoveryLinks.Clear();
                model.ErrorOccurred.RecoveryLinks.AddRange(actualException.RecoveryLinks);
            }
            return(View("error", model));
        }
        public ActionResult ApplyLinkFlair(int?submissionID, int?flairId)
        {
            if (submissionID == null || flairId == null)
            {
                return(HybridError(ErrorViewModel.GetErrorViewModel(ErrorType.NotFound)));
                //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var submission = _db.Submission.Find(submissionID);

            if (submission == null || submission.IsDeleted)
            {
                return(HybridError(ErrorViewModel.GetErrorViewModel(ErrorType.NotFound)));
                //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            if (!ModeratorPermission.HasPermission(User, submission.Subverse, Domain.Models.ModeratorAction.AssignFlair))
            {
                return(HybridError(ErrorViewModel.GetErrorViewModel(ErrorType.Unauthorized)));
                //return new HttpUnauthorizedResult();
            }

            // find flair by id, apply it to submission
            var flairModel = _db.SubverseFlair.Find(flairId);

            if (flairModel == null || flairModel.Subverse != submission.Subverse)
            {
                return(HybridError(ErrorViewModel.GetErrorViewModel(ErrorType.NotFound)));
            }
            //return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            // apply flair and save submission
            submission.FlairCss   = flairModel.CssClass;
            submission.FlairLabel = flairModel.Label;
            _db.SaveChanges();
            DataCache.Submission.Remove(submissionID.Value);

            return(JsonResult(CommandResponse.FromStatus(Status.Success)));
            //return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
        public IActionResult Details(int id)
        {
            var fixtureExists = this.fixturesService.FixtureExistsById(id);

            if (!fixtureExists)
            {
                var errorViewModel = new ErrorViewModel
                {
                    ErrorMessage = ErrorMessages.FixtureDoesNotExistsErrorMessage
                };

                return(this.View(viewName: GlobalConstants.ErrorViewName, model: errorViewModel));
            }

            var matches          = this.matchesService.MatchesByFixture <MatchDetailsViewModel>(id).ToList();
            var matchesViewModel = new AllMatchesViewModel
            {
                Matches = matches
            };

            return(this.View(matchesViewModel));
        }
Example #31
0
        public async Task <ActionResult> ModeratorDelete(string subverse, int submissionID, ModeratorDeleteContentViewModel model)
        {
            var q       = new QueryComment(model.ID);
            var comment = await q.ExecuteAsync();

            if (comment == null || comment.SubmissionID != submissionID)
            {
                ModelState.AddModelError("", "Can not find comment. Who did this?");
                return(View(new ModeratorDeleteContentViewModel()));
            }
            if (!comment.Subverse.IsEqual(subverse))
            {
                ModelState.AddModelError("", "Data mismatch detected");
                return(View(new ModeratorDeleteContentViewModel()));
            }

            if (!ModeratorPermission.HasPermission(User, comment.Subverse, Domain.Models.ModeratorAction.DeleteComments))
            {
                return(HybridError(ErrorViewModel.GetErrorViewModel(ErrorType.Unauthorized)));
            }

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

            var cmd = new DeleteCommentCommand(model.ID, model.Reason).SetUserContext(User);
            var r   = await cmd.Execute();

            if (r.Success)
            {
                return(RedirectToRoute("SubverseCommentsWithSort_Short", new { subverseName = subverse, submissionID = submissionID }));
            }
            else
            {
                ModelState.AddModelError("", r.Message);
                return(View(model));
            }
        }
Example #32
0
        public async Task <IActionResult> Error(string errorId)
        {
            var vm = new ErrorViewModel();

            // retrieve error details from identity server
            var message = await _interaction.GetErrorContextAsync(errorId);

            if (message != null)
            {
                vm.Error = message;

                if (!_environment.IsDevelopment())
                {
                    message.ErrorDescription = null;
                }
            }

            var output = View("Error", vm);

            output.StatusCode = (int)HttpStatusCode.InternalServerError;
            return(output);
        }
Example #33
0
        public Task <IActionResult> Error()
        {
            // Build breadcrumb
            _breadCrumbManager.Configure(builder =>
            {
                builder.Add(S["Home"], home => home
                            .Action("Index", "Home", "Plato.Core")
                            .LocalNav()
                            ).Add(S["Error"]);
            });

            Response.StatusCode = 500;

            // Build model
            var model = new ErrorViewModel()
            {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            };

            // Return view
            return(Task.FromResult((IActionResult)View(model)));
        }
        public async Task <IActionResult> NotFoundError()
        {
            var errorViewModel = new ErrorViewModel();

            errorViewModel.StatusCode = StatusCodes.NotFound;

            this.ViewData["DessertsCategoryId"] = await this.categoryService
                                                  .GetIdByTitleAsync(GlobalConstants.DessertsCategoryTitle);

            if (this.TempData["ErrorParams"] is Dictionary <string, string> dict)
            {
                errorViewModel.RequestId   = dict["RequestId"];
                errorViewModel.RequestPath = dict["RequestPath"];
            }

            if (errorViewModel.RequestId == null)
            {
                errorViewModel.RequestId = Activity.Current?.Id ?? this.HttpContext.TraceIdentifier;
            }

            return(this.View(errorViewModel));
        }
 public virtual Task<System.IO.Stream> Error(IDictionary<string, object> env, ErrorViewModel model)
 {
     return Render(model, "error");
 }
 protected void SetError(Exception ex, Action retry)
 {
     if (ex == null)
     {
         Error = null;
     }
     else
     {
         Error = new ErrorViewModel(ex, retry);
     }
 }
Example #37
0
        public bool ValidateAndMapCreateTransaction(TransactionViewModel vm, Controller controller, string userId, out Transaction transaction, out ErrorViewModel errors)
        {
            var modelState = controller.ModelState;
            transaction = null;
            errors = null;

            if (vm.Total == null || vm.Total <= 0)
            {
                errors = new ErrorViewModel { Error = TransactionErrors.ValidationErrors.TransactionInvalidTotalError };
                return false;
            }

            var transactionType = this.transTypeRepo.FindById(vm.TransactionTypeId, tt => tt.From, tt => tt.To);
            if (transactionType == null)
            {
                errors = new ErrorViewModel { Error = string.Format(TransactionErrors.ValidationErrors.TransactionTypeNotFoundError, vm.TransactionTypeId) };
                return false;
            }

            if (vm.FromId == vm.ToId)
            {
                errors = new ErrorViewModel { Error = TransactionErrors.ValidationErrors.TransactionToSameCategoryError };
                return false;
            }

            var fromCategory = this.categoryRepo.FindById(vm.FromId, c => c.CategoryType);
            if (fromCategory == null || !string.Equals(fromCategory.AccountingUserId, userId))
            {
                errors = new ErrorViewModel { Error = string.Format(TransactionErrors.ValidationErrors.TransactionFromCategoryNotFoundError, vm.FromId) };
                return false;
            }

            var toCategory = this.categoryRepo.FindById(vm.ToId, c => c.CategoryType);
            if (toCategory == null || !string.Equals(toCategory.AccountingUserId, userId))
            {
                errors = new ErrorViewModel { Error = string.Format(TransactionErrors.ValidationErrors.TransactionToCategoryNotFoundError, vm.ToId) };
                return false;
            }

            if (toCategory.CategoryType.Id != transactionType.To.Id || fromCategory.CategoryType.Id != transactionType.From.Id)
            {
                errors = new ErrorViewModel { Error = TransactionErrors.ValidationErrors.TransactionTypeCategoryTypeMismatchError };
                return false;
            }

            if (!modelState.IsValid)
            {
                modelState.Clear();
                controller.TryValidateModel(vm);
            }

            if (!modelState.IsValid)
            {
                errors = new ErrorViewModel
                {
                    Error = TransactionErrors.ValidationErrors.TransactionInvalidError,
                    Errors = modelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList()
                };

                this.logger.LogWarning("Invalid transaction model:" + string.Join(";",
                    modelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)));
                return false;
            }

            transaction = Mapper.Map<Transaction>(vm);
            transaction.Id = 0;
            transaction.Total = Math.Round(transaction.Total, 2);
            transaction.From = fromCategory;
            transaction.To = toCategory;
            transaction.TransactionType = transactionType;
            transaction.AccountingUserId = userId;

            return true;
        }
        public void InvalidateErrors()
        {
            var allErrors = new List<ErrorViewModel>();
            var toRemove = new List<ErrorViewModel>();
            var hasChanged = false;

            foreach (var document in DocumentTabs.Documents.OfType<EditorViewModel>())
            {
                if (document.Model.CodeAnalysisResults != null)
                {
                    foreach (var diagnostic in document.Model.CodeAnalysisResults.Diagnostics)
                    {
                        var error = new ErrorViewModel(diagnostic);
                        var matching = allErrors.FirstOrDefault(err => err.IsEqual(error));

                        if (matching == null)
                        {
                            allErrors.Add(error);
                        }
                    }
                }
            }

            foreach (var error in ErrorList.Errors)
            {
                var matching = allErrors.SingleOrDefault(err => err.IsEqual(error));

                if (matching == null)
                {
                    toRemove.Add(error);
                }
            }

            foreach (var error in toRemove)
            {
                hasChanged = true;
                ErrorList.Errors.Remove(error);
            }

            foreach (var error in allErrors)
            {
                var matching = ErrorList.Errors.SingleOrDefault(err => err.IsEqual(error));

                if (matching == null)
                {
                    hasChanged = true;
                    ErrorList.Errors.Add(error);
                }
            }

            if (hasChanged)
            {
                BottomTabs.SelectedTool = ErrorList;
            }
        }
Example #39
0
        public bool ValidateAndMapUpdateCategory(long id, CategoryViewModel vm, Category previous, Controller controller, string userId, out Category category, out ErrorViewModel errors)
        {
            var modelState = controller.ModelState;
            category = null;
            errors = null;

            if (vm.Id != id)
            {
                errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryInvalidRouteError };
                return false;
            }

            if (!modelState.IsValid)
            {
                errors = new ErrorViewModel
                {
                    Error = CategoryErrors.ValidationErrors.CategoryInvalidError,
                    Errors = modelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList()
                };

                this.logger.LogWarning("Invalid category model:" + string.Join(";",
                    modelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)));
                return false;
            }

            // Does a different category exist with the same name?
            if (this.categoryRepo.FindAllWhere(c => string.Equals(c.NormalizedName, Category.NormalizeName(vm.Name)) && c.Id != id).Any())
            {
                errors = new ErrorViewModel { Error = string.Format(CategoryErrors.ValidationErrors.CategoryNameAlreadyExistsError, vm.Name) };
                return false;
            }

            if (vm.CategoryTypeId != previous.CategoryType.Id)
            {
                errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryCannotChangeTypeError };
                return false;
            }

            if (vm.ParentCategoryId.HasValue && vm.ParentCategoryId.Value == id)
            {
                errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryCannotBeOwnParentError };
                return false;
            }

            Category parentCategory = null;
            if (vm.ParentCategoryId.HasValue || previous.ParentCategoryId.HasValue)
            {
                var hasChildren = this.categoryRepo.FindAllWhere(c => c.ParentCategoryId == id).Any();

                if (hasChildren && vm.ParentCategoryId != previous.ParentCategoryId)
                {
                    errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryMoveWithChildrenError };
                    return false;
                }

                if (vm.ParentCategoryId.HasValue)
                {
                    parentCategory = this.categoryRepo.FindById(vm.ParentCategoryId.Value, c => c.CategoryType);
                    if (parentCategory == null || !string.Equals(parentCategory.AccountingUserId, userId))
                    {
                        errors = new ErrorViewModel { Error = string.Format(CategoryErrors.ValidationErrors.CategoryParentCategoryNotFoundError, vm.ParentCategoryId) };
                        return false;
                    }

                    if (parentCategory.CategoryType.Id != vm.CategoryTypeId)
                    {
                        errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryParentTypeMismatchError };
                        return false;
                    }

                    if (parentCategory.ParentCategoryId.HasValue
                        && this.categoryRepo.FindById(parentCategory.ParentCategoryId.Value).ParentCategoryId.HasValue)
                    {
                        errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryDepthTooGreatError };
                        return false;
                    }
                }
            }

            category = previous;
            category.Name = vm.Name;
            category.NormalizedName = Category.NormalizeName(category.Name);
            category.ParentCategoryId = parentCategory?.Id;
            category.ParentCategory = parentCategory;

            return true;
        }
Example #40
0
        public bool ValidateAndMapCreateCategory(CategoryViewModel vm, Controller controller, string userId, out Category category, out ErrorViewModel errors)
        {
            var modelState = controller.ModelState;
            category = null;
            errors = null;

            if (!modelState.IsValid)
            {
                errors = new ErrorViewModel
                {
                    Error = CategoryErrors.ValidationErrors.CategoryInvalidError,
                    Errors = modelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList()
                };

                this.logger.LogWarning("Invalid category model:" + string.Join(";",
                    modelState.Values.SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)));
                return false;
            }

            if (this.categoryRepo.FindAllWhere(c => string.Equals(c.NormalizedName, Category.NormalizeName(vm.Name))).Any())
            {
                errors = new ErrorViewModel { Error = string.Format(CategoryErrors.ValidationErrors.CategoryNameAlreadyExistsError, vm.Name) };
                return false;
            }

            CategoryType catType;
            if ((catType = this.categoryTypeRepo.FindById(vm.CategoryTypeId)) == null)
            {
                errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryNoCategoryTypeError };
                return false;
            }

            Category parentCategory = null;
            if(vm.ParentCategoryId.HasValue){
                parentCategory = this.categoryRepo.FindById(vm.ParentCategoryId.Value, c => c.CategoryType);
                if (parentCategory == null || !string.Equals(parentCategory.AccountingUserId, userId))
                {
                    errors = new ErrorViewModel { Error = string.Format(CategoryErrors.ValidationErrors.CategoryParentCategoryNotFoundError, vm.ParentCategoryId) };
                    return false;
                }

                if (parentCategory.CategoryType.Id != catType.Id)
                {
                    errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryParentTypeMismatchError };
                    return false;
                }

                if (parentCategory.ParentCategoryId.HasValue
                    && this.categoryRepo.FindById(parentCategory.ParentCategoryId.Value).ParentCategoryId.HasValue){
                    errors = new ErrorViewModel { Error = CategoryErrors.ValidationErrors.CategoryDepthTooGreatError };
                    return false;
                }
            }

            category = Mapper.Map<Category>(vm);
            category.Id = 0;
            category.Total = 0;
            category.NormalizedName = Category.NormalizeName(category.Name);
            category.ParentCategoryId = null;
            category.ParentCategory = parentCategory;
            category.CategoryType = catType;
            category.ChildCategories = null;
            category.ExitingTransactions = null;
            category.AccountingUserId = userId;

            return true;
        }
 public ErrorEventArgs(ErrorViewModel error)
 {
     this.Error = error;
 }