public ActionResult Delete(int thisTripId, FormCollection collection) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) { if (!UserRoleHelper.IsEmployee(User.Identity.GetUserId()))// check if current user has admin or employee rights { return(RedirectToAction("AccessDenied", "Manage")); } } int NumberOfReservations = countReservavtionsMade((int)thisTripId); Trip trip = dbcontext.Trips.Find(thisTripId); //get current trip //check for reservations. Cannot edit while there are any and trip is yet to end var currTime = DateTime.Now; if (NumberOfReservations > 0 && trip.DateBack > currTime) { return(RedirectToAction("Index", new { Message = ManageMessageId.CannotEditEntry })); } dbcontext.Trips.Remove(trip); dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.DeleteEntrySuccess })); }
public ActionResult Create(Coach model) //public ActionResult Create(CoachesViewModel model) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } if (ModelState.IsValid) { /*Coach coach = new Coach() // this commented code was when Coach Entity had TripID FK in it, but it * always required TripID in creation, so it was scrapped. A possible soluiton is to only * Create a coach from a Trip edit link containing its Id, but that would mean a coach would * only be created for a trip (bad idea) * { * Brand = model.Brand, * VehModel = model.VehModel, * Seats = model.Seats, * DateAdded = model.DateAdded, * VehicleNumber = model.VehicleNumber, * VehScreenshot = model.VehScreenshot * };*/ //model.Id_Trip = 0; -> commented TripID FK line In DBentities\Coach.cs dbcontext.Coaches.Add(model); dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.CreateEntrySuccess })); } return(View(model)); }
// GET: Trip/Delete/5 public ActionResult Delete(int?thisTripId) { if (thisTripId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) { if (!UserRoleHelper.IsEmployee(User.Identity.GetUserId()))// check if current user has admin or employee rights { return(RedirectToAction("AccessDenied", "Manage")); } } //check for reservations. Cannot edit while there are any. Placeholder int NumberOfReservations = countReservavtionsMade((int)thisTripId); Trip trip = dbcontext.Trips.Find(thisTripId); //get current trip if (trip == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } //check for reservations. Cannot edit while there are any and trip is yet to end var currTime = DateTime.Now; if (NumberOfReservations > 0 && trip.DateBack > currTime) { return(RedirectToAction("Index", new { Message = ManageMessageId.CannotEditEntry })); } return(View(trip)); }
// GET: /Coaches/Index public ActionResult Index(ManageMessageId?message) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } ViewBag.StatusMessage = message == ManageMessageId.EditDetailsSuccess ? "All changes have been saved." : message == ManageMessageId.CreateEntrySuccess ? "Successfully added a new vehicle." : message == ManageMessageId.DeleteEntrySuccess ? "Successfully deleted a vehicle." : message == ManageMessageId.Error ? "An error has occured." : ""; CoachesViewModels model = new CoachesViewModels(); // add every coach item to the list, then save the list in model's List: Coach. Return the model to view var list = new List <Coach>(); foreach (var item in dbcontext.Coaches.ToList()) { list.Add(item); } model.List = list; return(View(model)); }
public async Task <ActionResult> ManageView() { try { Log.Info("ManageView"); var templates = await new TemplateController().GetTemplates(); if (templates.Count > 0) { ViewBag.Templates = templates.OrderBy(s => s.TemplateName).Where(t => t.IsManageTemplate).ToList(); } ViewBag.IsAdmin = UserRoleHelper.IsAdmin(System.Web.HttpContext.Current.User.Identity.Name); return(View()); } catch (Exception exception) { ViewBag.ErrorMessage = "Error"; ViewBag.ErrorDetails = exception.Message; Log.Error(exception); return(View("Error")); } }
// GET: Location/Create public ActionResult Create() { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } return(View()); }
// duplicated action EDIT POST/GET and changed to EditUserRoles // GET: ManageUsers/EditUserRoles/5 public ActionResult EditUserRoles(string Id) { if (Id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } ApplicationUser CurrUser = dbcontext.Users.Find(Id); if (CurrUser == null) { return(HttpNotFound()); } EditUserRoleViewModel field = new EditUserRoleViewModel(); // get access to model fields we will be showing var userStore = new UserStore <ApplicationUser>(dbcontext); // access to roles using Identity Framework var userManager = new UserManager <ApplicationUser>(userStore); // update db info with new data given by user in form View field.Id = CurrUser.Id; field.UserName = CurrUser.UserName; field.Email = CurrUser.Email; field.Name = CurrUser.Name; field.Surname = CurrUser.Surname; field.Country = CurrUser.Country; field.Town = CurrUser.Town; field.Street = CurrUser.Street; field.NumHouse = CurrUser.NumHouse; field.NumFlat = CurrUser.NumFlat; field.ZIPCode = CurrUser.ZIPCode; field.PhoneNumber = CurrUser.PhoneNumber; if (UserRoleHelper.IsAdmin(field.Id)) { field.RoleType = UserRoleTypes.Administrator; } if (UserRoleHelper.IsEmployee(field.Id)) { field.RoleType = UserRoleTypes.Employee; } if (UserRoleHelper.IsUser(field.Id)) { field.RoleType = UserRoleTypes.Customer; } return(View(field)); }
public ActionResult Create(Location model) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } if (ModelState.IsValid) { dbcontext.Locations.Add(model); dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.CreateEntrySuccess })); } return(View(model)); }
// GET: Location/Edit/5 public ActionResult Edit(int id) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } Location CurrLoc = dbcontext.Locations.Find(id); if (CurrLoc == null) { return(HttpNotFound()); } return(View(CurrLoc)); }
// GET: Coaches/Delete/5 public ActionResult Delete(int id) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } Coach CurrVeh = dbcontext.Coaches.Find(id); if (CurrVeh == null) { return(HttpNotFound()); } return(View(CurrVeh)); }
// what does Bind do: 2 approches: we can either create a model with all properties we want to edit in this Action OR we can // use Bind(Exclude = "") Bind(Include = "") to tell which properties from a given model to take and edit or exclude // usually first approach is better via: https://cpratt.co/stop-using-bind/ // but here I do not want to create a new model since Im not going to use this too often and have no // plans to change this Action often PLUS UserModel is build in and not something I created from scratch so I dont want to edit it more than needed public ActionResult Edit([Bind(Include = "Id,Name,Surname,Street,NumHouse,NumFlat,Town,ZIPCode,Country,Email," + " EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled," + " LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } if (ModelState.IsValid) { dbcontext.Entry(applicationUser).State = System.Data.Entity.EntityState.Modified; dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.EditUserSuccess })); } return(View(applicationUser)); }
// GET: ManageUsers/Edit/5 public ActionResult Edit(string Id) { if (Id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } ApplicationUser CurrUser = dbcontext.Users.Find(Id); if (CurrUser == null) { return(HttpNotFound()); } return(View(CurrUser)); }
// GET: ManageUsers public ActionResult Index(ManageMessageId?message) // from ManageController { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } ViewBag.StatusMessage = message == ManageMessageId.EditUserSuccess ? "All changes have been saved." : message == ManageMessageId.ChangeRoleToCustomer ? "Changed account permissions to : Customer/Basic." : message == ManageMessageId.ChangeRoleToEmployee ? "Changed account permissions to : Employee." : message == ManageMessageId.ChangeRoleToAdmin ? "Changed account permissions to : Administrator." : message == ManageMessageId.DeleteUserSuccess ? "Successfully deleted user account." : message == ManageMessageId.ChangeOwnRoleErr ? "Cannot change own account permission type!" : message == ManageMessageId.Error ? "An error has occured." : ""; return(View(dbcontext.Users.ToList())); }
// GET: Coaches/Edit/5 public ActionResult Edit(int id) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } // get info about currently edited coach and return it to view Coach CurrVeh = dbcontext.Coaches.Find(id); if (CurrVeh == null) { return(HttpNotFound()); } //for View ViewBag.DateAdded = CurrVeh.DateAdded; return(View(CurrVeh)); }
public ActionResult Edit(int thisTripId, ViewEditTripsViewModel model) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } //check for reservations. Cannot edit while there are any. Placeholder int NumberOfReservations = countReservavtionsMade((int)thisTripId); //check for reservations. Cannot edit while there are any and trip is yet to end var currTime = DateTime.Now; if (NumberOfReservations > 0 && model.TripInstance.DateBack > currTime) { return(RedirectToAction("Index", new { Message = ManageMessageId.CannotEditEntry })); } try { Trip trip = dbcontext.Trips.Find(thisTripId); //get current trip if (trip == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } trip.Name = model.TripInstance.Name; trip.DateDeparture = model.TripInstance.DateDeparture; trip.DateBack = model.TripInstance.DateBack; trip.NumSpots = model.TripInstance.NumSpots; trip.Price = model.TripInstance.Price; trip.Description = model.TripInstance.Description; trip.Banner = model.TripInstance.Banner; trip.CoachNumberId = model.TripInstance.CoachNumberId; dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.EditDetailsSuccess })); } catch { return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } }
public ActionResult Edit(int id, Coach model) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } if (ModelState.IsValid) { try { // first get info about currently edited coach, so it can be overwritten var modelItem = dbcontext.Coaches.Find(id); if (modelItem == null) { return(HttpNotFound()); } // overwrite old data with new data provided from the view form modelItem.Brand = model.Brand; modelItem.VehModel = model.VehModel; modelItem.Seats = model.Seats; modelItem.VehScreenshot = model.VehScreenshot; modelItem.VehicleNumber = model.VehicleNumber; if (model.DateAdded != null) { modelItem.DateAdded = model.DateAdded; } dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.EditDetailsSuccess })); } catch { return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } } return(View(model)); }
public ActionResult Create(Trip model) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) { if (!UserRoleHelper.IsEmployee(User.Identity.GetUserId()))// check if current user has admin or employee rights { return(RedirectToAction("AccessDenied", "Manage")); } } if (ModelState.IsValid) { // CoachNumberId is a required field in Trip Table BUT because when assigning a coach to a trip we need to be sure its not already // assigned to a different trip going on in the time of creating this trip (checked by looking for trips in progress) // there is no way to know at the time of this action what coaches can be used since we dont know when THIS trip will start-end. // we know that only after its created. so we assign a coachID which will never be created by DB and later assign a proprt value in edit action model.CoachNumberId = -1; dbcontext.Trips.Add(model); dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.CreateEntrySuccess })); } return(View(model)); }
public ActionResult Delete(int id, FormCollection collection) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } try { // TODO: Add delete logic here Location CurrLoc = dbcontext.Locations.Find(id); if (CurrLoc == null) { return(HttpNotFound()); } dbcontext.Locations.Remove(CurrLoc); dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.DeleteEntrySuccess })); } catch { return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } }
public ActionResult Edit(int id, Location model) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } if (ModelState.IsValid) { try { // first get info about currently edited coach, so it can be overwritten var modelItem = dbcontext.Locations.Find(id); if (modelItem == null) { return(HttpNotFound()); } // overwrite old data with new data provided from the view form modelItem.Country = model.Country; modelItem.Town = model.Town; modelItem.Name = model.Name; modelItem.Description = model.Description; modelItem.LocationImage = model.LocationImage; dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.EditDetailsSuccess })); } catch { return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } } return(View(model)); }
// all fields will be used so instead of Bind we can use just the ready Model for it public ActionResult EditUserRoles(EditUserRoleViewModel model) { if (ModelState.IsValid) { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } ApplicationUser CurrUser = dbcontext.Users.Find(model.Id); if (CurrUser == null || model.Id == null) { return(HttpNotFound()); } // user cannot change his own role. Check if user currently editing has same id as the one being edited if (model.Id == User.Identity.GetUserId()) { return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeOwnRoleErr })); } // declaration of needed variables to have the ability to change user roles : Identity Framework. Takes role types and users we will be later using from DB var userStore = new UserStore <ApplicationUser>(dbcontext); var userManager = new UserManager <ApplicationUser>(userStore); // change user role to Administrator if (model.RoleType == UserRoleTypes.Administrator) { if (userManager.IsInRole(CurrUser.Id, "User")) { userManager.RemoveFromRole(CurrUser.Id, "User"); } if (userManager.IsInRole(CurrUser.Id, "Employee")) { userManager.RemoveFromRole(CurrUser.Id, "Employee"); } userManager.AddToRole(CurrUser.Id, "Administrator"); dbcontext.Entry(CurrUser).State = System.Data.Entity.EntityState.Modified; dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeRoleToAdmin })); } // change user role to Employee if (model.RoleType == UserRoleTypes.Employee) { if (userManager.IsInRole(CurrUser.Id, "User")) { userManager.RemoveFromRole(CurrUser.Id, "User"); } if (userManager.IsInRole(CurrUser.Id, "Administrator")) { userManager.RemoveFromRole(CurrUser.Id, "Administrator"); } userManager.AddToRole(CurrUser.Id, "Employee"); dbcontext.Entry(CurrUser).State = System.Data.Entity.EntityState.Modified; dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeRoleToEmployee })); } // change user role to Customer\User if (model.RoleType == UserRoleTypes.Customer) { if (userManager.IsInRole(CurrUser.Id, "Employee")) { userManager.RemoveFromRole(CurrUser.Id, "Employee"); } if (userManager.IsInRole(CurrUser.Id, "Administrator")) { userManager.RemoveFromRole(CurrUser.Id, "Administrator"); } userManager.AddToRole(CurrUser.Id, "User"); dbcontext.Entry(CurrUser).State = System.Data.Entity.EntityState.Modified; dbcontext.SaveChanges(); return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeRoleToCustomer })); } return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } return(View(model)); }
public ActionResult Statistics() { if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) // check if current user has admin rights { return(RedirectToAction("AccessDenied", "Manage")); } // get DB objects var bookings = dbcontext.Reservations.ToList(); var trips = dbcontext.Trips.ToList(); var coaches = dbcontext.Coaches.ToList(); var locations = dbcontext.Locations.ToList(); var users = dbcontext.Users.ToList(); // model holding the data + default values StatisticsViewModel model = new StatisticsViewModel(); //COACH model.TotalVehicles = 0; model.AvgVehicleSeats = 0; //LOCATION model.TotalLocations = 0; //TRIP model.TotalTrips = 0; model.TotalTripsSpots = 0; model.AvgTripPrice = 0; model.AvgTripSpots = 0; model.TotalActiveTrips = 0; //USERS model.TotalUsers = 0; model.TotalEmployee = 0; //RESERVATIONS model.TotalReservationSpotsBooked = 0; model.AvgTotalSpotsReserved = 0;; // in % model.TotalTripsBooked = 0; model.TotalReservationsLastMonth = 0; // COACH Data model.TotalVehicles = coaches.Count(); foreach (var coach in coaches) { model.AvgVehicleSeats = coach.Seats + model.AvgVehicleSeats; } if (model.AvgVehicleSeats != 0) { model.AvgVehicleSeats = model.AvgVehicleSeats / model.TotalVehicles; } else { model.AvgVehicleSeats = 0; } //LOCATION DATA model.TotalLocations = locations.Count(); //TRIP DATA model.TotalTrips = trips.Count(); foreach (var trip in trips) { model.TotalTripsSpots = trip.NumSpots + model.TotalTripsSpots; model.AvgTripPrice = trip.Price + model.AvgTripPrice; model.AvgTripSpots = trip.NumSpots + model.AvgTripSpots; if (trip.DateBack > DateTime.Now) { model.TotalActiveTrips++; } } if (model.TotalTrips != 0) { model.AvgTripPrice = model.AvgTripPrice / model.TotalTrips; model.AvgTripSpots = model.AvgTripSpots / model.TotalTrips; } else { model.AvgTripPrice = 0; model.AvgTripSpots = 0; } //USER DATA model.TotalUsers = users.Count(); foreach (var user in users) { if (UserRoleHelper.IsUserInRole(user.Id, "Employee")) { model.TotalEmployee++; } } //RESERVATION DATA model.TotalTripsBooked = bookings.Count(); foreach (var item in bookings) { model.TotalReservationSpotsBooked = item.NumPeople + model.TotalReservationSpotsBooked; } model.AvgTotalSpotsReserved = model.TotalReservationSpotsBooked * 100 / model.TotalTripsSpots; // per month reservations int month = DateTime.Now.Month; int year = DateTime.Now.Year - 1; model.ReservationsPerMonth = new List <ReservationsInMonth>(); for (int i = 0; i < 12; i++) { model.ReservationsPerMonth.Add(new ReservationsInMonth { Month = month, Year = year, MonthTotalReservations = 0, MonthName = "test" }); month++; if (month > 12) { month -= 12; year++; } } foreach (var item in model.ReservationsPerMonth) { switch (item.Month) { case 1: item.MonthName = "January"; break; case 2: item.MonthName = "February"; break; case 3: item.MonthName = "March"; break; case 4: item.MonthName = "April"; break; case 5: item.MonthName = "May"; break; case 6: item.MonthName = "June"; break; case 7: item.MonthName = "July"; break; case 8: item.MonthName = "August"; break; case 9: item.MonthName = "September"; break; case 10: item.MonthName = "October"; break; case 11: item.MonthName = "November"; break; case 12: item.MonthName = "December"; break; } } // count reservations per month foreach (var booking in bookings) { foreach (var item in model.ReservationsPerMonth) { if (booking.DateBooked.Month == item.Month && booking.DateBooked.Year == item.Year) { item.MonthTotalReservations++; } } TimeSpan timespan = DateTime.Now - booking.DateBooked; if (timespan.Days <= 31) { model.TotalReservationsLastMonth++; } } var axis_X = model.ReservationsPerMonth.Select(i => i.MonthName).ToArray(); var axis_Y = model.ReservationsPerMonth.Select(i => new object[] { i.MonthTotalReservations }).ToArray(); // ***************************************************************** // HIGHCHART # 1 FOR RESERVATIONS PER MONTH ************************ // ***************************************************************** // https://www.c-sharpcorner.com/article/dotnet-highcharts-with-asp-net-mvc/ Highcharts columnChart = new Highcharts("columnchart"); columnChart.InitChart(new Chart() { Type = DotNet.Highcharts.Enums.ChartTypes.Column, BackgroundColor = new BackColorOrGradient(System.Drawing.Color.AliceBlue), Style = "fontWeight: 'bold', fontSize: '17px'", BorderColor = System.Drawing.Color.LightBlue, BorderRadius = 0, BorderWidth = 2 }); columnChart.SetTitle(new Title() { Text = "Reservations" }); columnChart.SetSubtitle(new Subtitle() { Text = "12 month data" }); columnChart.SetXAxis(new XAxis() { Type = AxisTypes.Category, Title = new XAxisTitle() { Text = "Month", Style = "fontWeight: 'bold', fontSize: '17px'" }, Categories = axis_X }); columnChart.SetYAxis(new YAxis() { Title = new YAxisTitle() { Text = "Number of reservations", Style = "fontWeight: 'bold', fontSize: '17px'" }, ShowFirstLabel = true, ShowLastLabel = true, Min = 0 }); columnChart.SetLegend(new Legend { Enabled = true, BorderColor = System.Drawing.Color.CornflowerBlue, BorderRadius = 6, BackgroundColor = new BackColorOrGradient(ColorTranslator.FromHtml("#FFADD8E6")) }); columnChart.SetSeries(new Series[] { new Series { Name = "Monthly reservations", Data = new Data(axis_Y) }, } ); columnChart.SetPlotOptions(new PlotOptions { Line = new PlotOptionsLine { DataLabels = new PlotOptionsLineDataLabels { Enabled = true }, EnableMouseTracking = false } } ); model.ReservationChart = columnChart; return(View(model)); }
// GET: Trip/Edit/5 public ActionResult Edit(int?thisTripId) { if (thisTripId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (!UserRoleHelper.IsAdmin(User.Identity.GetUserId())) { if (!UserRoleHelper.IsEmployee(User.Identity.GetUserId()))// check if current user has admin or employee rights { return(RedirectToAction("AccessDenied", "Manage")); } } //check for reservations. Cannot edit while there are any. int NumberOfReservations = countReservavtionsMade((int)thisTripId); Trip trip = dbcontext.Trips.Find(thisTripId); //get current trip if (trip == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } ViewEditTripsViewModel model = new ViewEditTripsViewModel(); model.TripInstance = trip; //check for reservations. Cannot edit while there are any and trip is yet to end var currTime = DateTime.Now; if (NumberOfReservations > 0 && model.TripInstance.DateBack > currTime) { return(RedirectToAction("Index", new { Message = ManageMessageId.CannotEditEntry })); } //get a list of all sub-locations that this trip has var list = new List <TripLocationsInstanceViewModels>(); foreach (var item in dbcontext.Trip_Locations.ToList()) { if (item.Id_Trip == thisTripId) { foreach (var location in dbcontext.Locations.ToList()) { if (item.Id_Location == location.Id) { list.Add(new TripLocationsInstanceViewModels { Country = location.Country, Town = location.Town, Name = location.Name, Description = location.Description, LocationImage = location.LocationImage, Number = item.Number, RouteInstanceId = item.Id }); } } } } model.Route = new TripLocationsViewModels(); if (list.Count() > 0) { model.Route.ListElement = list; } if (thisTripId != null && dbcontext.Trips.Find(thisTripId) != null) { model.Route.Id_Trip = (int)thisTripId; } // list that has every coach in database var listOfCoaches = dbcontext.Coaches.ToList(); var currDate = DateTime.Now; // go through every trip in db that is in progress atm. A coach assigned to that trip will be removed from our list, so it cant be assigned //to this currently edited trip foreach (var coach in dbcontext.Coaches.ToList()) { foreach (var tripInstance in dbcontext.Trips.ToList()) { if (tripInstance.DateDeparture < model.TripInstance.DateDeparture && model.TripInstance.DateDeparture < tripInstance.DateBack) { if (coach.Id == tripInstance.CoachNumberId) { listOfCoaches.Remove(coach); } } } } ViewBag.DateDeparture = model.TripInstance.DateDeparture; ViewBag.DateBack = model.TripInstance.DateBack; model.CoachVehicleIdList = new SelectList(listOfCoaches, "Id", "VehicleNumber"); return(View(model)); }
// GET: Deployments public async Task <ActionResult> DeploymentsView() { try { // Get all subscriptions for this tenant var subscriptions = await new SubscriptionController().GetSubscriptions(); var subscriptionId = subscriptions.FirstOrDefault()?.SubscriptionId; var token = await ServicePrincipal.GetAccessToken(); var client = new RestApiClient(); // Get all resource groups var resourceGroupUri = string.Format(UriConstants.GetAllResourceGroupsUri, Url.Encode(subscriptionId), ""); var resourceGroups = await client.CallGetListAsync <ResourceGroup>(resourceGroupUri, token); // Get all deployments var deployments = new List <DeploymentExtended>(); foreach (var resourceGroup in resourceGroups.Result) { var deploymentsUri = string.Format(UriConstants.GetDeploymentsByResourceGroup, subscriptionId, resourceGroup.Name); client = new RestApiClient(); var result = await client.CallGetListAsync <DeploymentExtended>(deploymentsUri, token); var deployment = result.Result; deployments.AddRange(deployment); } var email = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; var resultDeployments = new List <DeploymentViewModel>(); using (WebAppContext context = new WebAppContext()) { var localDeployments = await context.Deployments.ToListAsync(); foreach (var localDeployment in localDeployments) { foreach (var deployment in deployments) { if (localDeployment.DeploymentName != deployment?.Name) { continue; } if (UserRoleHelper.IsAdmin(email) || email == localDeployment.Owner) { var newDeployment = new DeploymentViewModel() { TemplateName = localDeployment.TemplateName, DeploymentId = localDeployment.DeploymentId, DeploymentName = localDeployment.DeploymentName, SubscriptionId = localDeployment.SubscriptionId, SubscriptionName = localDeployment.SubscriptionName, Owner = localDeployment.Owner, TemplateVersion = localDeployment.TemplateVersion, Timestamp = localDeployment.Timestamp, ProvisioningState = deployment?.Properties?.ProvisioningState, Outputs = deployment?.Properties?.Outputs?.ToString() }; resultDeployments.Add(newDeployment); } } } } var deploymentsList = resultDeployments.OrderByDescending(d => d.Timestamp).ToList(); ViewBag.FileLogName = $"{DateTime.Today:yyyy-MM-dd}.log"; return(View(deploymentsList)); } catch (Exception ex) { ViewBag.ErrorMessage = "Error"; ViewBag.ErrorDetails = ex.Message; return(View("Error")); } }
// GET: RunBooks public async Task <ActionResult> RunBooksView() { try { Log.Info("Start RunBooksController"); var subscriptions = await new SubscriptionController().GetSubscriptions(); var subscriptionId = subscriptions.FirstOrDefault()?.SubscriptionId; var token = await ServicePrincipal.GetAccessToken(); var automationAccountClient = new RestApiClient(); var automationAccountUri = string.Format(UriConstants.GetAutomationAccounts, Url.Encode(subscriptionId)); var automationAccounts = await automationAccountClient.CallGetListAsync <AutomationAccount>(automationAccountUri, token); var automationAccountsResult = automationAccounts.Result; var email = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; Log.Info($"RunBooksController Owner: {email}"); List <Job> localJobs; using (var webAppContext = new WebAppContext()) { localJobs = await webAppContext.Jobs.ToListAsync(); } Log.Info($"LocalJobs: {TemplateHelper.ToJson(localJobs)}"); var jobList = new List <JobViewModel>(); foreach (var account in automationAccountsResult) { var jobAccountClient = new RestApiClient(); var jobsUrl = string.Format(UriConstants.GetJobs, account.Id); var jobs = await jobAccountClient.CallGetListAsync <JobViewModel>(jobsUrl, token); var jobsResult = jobs.Result; foreach (var job in jobsResult) { var isUserOwner = localJobs.Any(j => j.Id == job.Properties.JobId && j.Owner == email); Log.Info($"job status: {isUserOwner}"); if (UserRoleHelper.IsAdmin(email) || isUserOwner) { var jobOutputClient = new RestApiClient(); var jobOutputUrl = string.Format(UriConstants.GetJobOutput, job.Id); var jobOutput = await jobOutputClient.CallGetText(jobOutputUrl, token); var newJob = job; newJob.Outputs = jobOutput; jobList.Add(newJob); } } } return(View(jobList)); } catch (Exception ex) { ViewBag.ErrorMessage = "Error"; ViewBag.ErrorDetails = ex.Message; Log.Error(ex); return(View("Error")); } }