public ActionResult CreateForecast([DataSourceRequest] DataSourceRequest request, ForecastViewModel forecast, TownViewModel town, DateTime date) { if (!User.IsInRole("Author")) { throw new Exception("Current user is not an author!"); } if (ModelState.IsValid) { if (!(DateTime.Today <= date && date <= DateTime.Today.AddDays(11))) { throw new ArgumentException("Invalid date."); } Town townDb; if (string.IsNullOrEmpty(town.Name)) { townDb = this.Data.Towns.All().FirstOrDefault(); } else { townDb = this.Data.Towns.GetById(town.TownId); } Forecast newForecast = new Forecast() { AuthorId = User.Identity.GetUserId(), ForecastDate = date.Date, Town = townDb, }; var dayParts = Enum.GetValues(typeof(DayPart)); foreach (var dayPart in dayParts) { ForecastValues values = new ForecastValues() { DayPart = (DayPart)dayPart, Pressure = 700 }; newForecast.Values.Add(values); } this.Data.Forecasts.Add(newForecast); this.Data.SaveChanges(); forecast = GetForecastVMFromDb(newForecast.Id); } return Json((new[] { forecast }.ToDataSourceResult(request, ModelState)), JsonRequestBehavior.AllowGet); }
public JsonResult UpdateForecast([DataSourceRequest] DataSourceRequest request, ForecastViewModel forecast, TownViewModel town, DateTime date) { if (!(DateTime.Today <= date && date <= DateTime.Today.AddDays(11))) { throw new ArgumentException("Invalid date."); } var forecastCreatorUserName = this.Data.Forecasts.GetById(forecast.ForecastId).AuthorId; if (!((User.IsInRole("Author") && User.Identity.GetUserId() == forecastCreatorUserName) || User.IsInRole("Admin"))) { throw new Exception("Current user does not have the rights to update forecast!"); } var existingForecast = this.Data.Forecasts.GetById(forecast.ForecastId); if (existingForecast != null && ModelState.IsValid) { existingForecast.TownId = town.TownId; existingForecast.ForecastDate = date.Date; Data.SaveChanges(); forecast = GetForecastVMFromDb(existingForecast.Id); } return Json((new[] { forecast }.ToDataSourceResult(request, ModelState)), JsonRequestBehavior.AllowGet); }