Exemplo n.º 1
0
        public IActionResult GetSubscriberDates([FromRoute] int locationID)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            //Declare The Util method so we can call it later
            DateCalculation dc = new DateCalculation();
            //Get all the locations from the DB
            Location location = _context.Location.FirstOrDefault(l => l.locationID == locationID);

            int regID;

            //This is to check to see if the subscribers location is assigned to a region
            if (location.regionID != null)
            {
                //Set an int equal to the locations regionID
                regID = (int)location.regionID;
            }
            else
            {
                //Return OK here so we do not search and execute the rest of the code on a region that does not exist
                return(Ok());
            }

            //Get all the Regions From the DB
            Region region = _context.Region.FirstOrDefault(r => r.regionID == regID);

            //Return the results of the Helper method along with OK as an indication of success
            return(Ok(dc.GetNextDates(3, region)));
        }
Exemplo n.º 2
0
        public async void IsRouteCreatedAfterRouteCompletion_RouteSetToComplete_RouteIsCreated()
        {
            _webApp.Load(_webApp.DBContext);

            Route updateRoute = _webApp.DBContext.Route.FirstOrDefault(r => !r.completed);   //Getting the first Incomplete Route

            Assert.NotNull(updateRoute);
            //Region region = _webApp.DBContext.Region.Where(reg => reg.regionID == updateRoute.regionID).First();    //Get the Region the previous Route corresponds to
            Region region = updateRoute.region;

            updateRoute.completed = true;       //Set the Route to Completed

            //convert the Route to a string for posting to the database
            var StringContent = new StringContent(JsonConvert.SerializeObject(updateRoute), Encoding.UTF8, "application/json");

            //send a PUT request to API to update the Route to completed
            HttpResponseMessage response = await _client.PutAsync("api/Routes/" + updateRoute.routeID, StringContent);

            List <Route> newRoute = _webApp.DBContext.Route.Where(r => r.regionID == region.regionID && !r.completed).ToList();

            DateCalculation dateCalculation = new DateCalculation();

            Assert.Single(newRoute);
            Assert.Equal(updateRoute.routeName, newRoute[0].routeName);
            Assert.Equal(updateRoute.regionID, newRoute[0].regionID);
            Assert.False(newRoute[0].completed);
            Assert.False(newRoute[0].inactive);
            Assert.Equal(dateCalculation.GetOneDate(region), newRoute[0].routeDate);
        }
        public IActionResult GetAllRegions()
        {
            //Checks if model state is valid - checks for errors coming from model binding and validation
            if (!ModelState.IsValid)
            {
                //Returns 400 status code with the model state as content
                return(BadRequest(ModelState));
            }

            //Create and instance of the datecalculation
            DateCalculation dc = new DateCalculation();
            //Gets a list of all Routes in the context table and appends a next collection date to the returned regions
            var dbRegions = _context.Region.Select(r => new { regionID = r.regionID, regionName = r.regionName, frequency = r.frequency, firstDate = r.firstDate, nextDate = dc.GetNextDates(1, r), inactive = r.inactive }).ToList();


            //If region list is null or contains no regions, return 404 Code with "No regions Found" message
            if (dbRegions == null || dbRegions.Count <= 0)
            {
                return(NotFound("No regions found"));
            }
            else
            {
                //Return 200 Code with Route List as content
                return(Ok(dbRegions));
            }
        }
        }                                                       //folder name of ASPNet Core project

        protected WebAppFixture(string relativeTargetProjectPatentDir)
        {
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Testing");

            var builder = new WebHostBuilder()
                          .ConfigureServices(services =>
            {
                //Find and Remove the webapp's database context "CosmoContext" registration.
                var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions <CosmoContext>));
                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                // Add new database context "CosmoContext" that points to testing database "TestCosmoDB"
                //services.AddDbContext<CosmoContext>(options => { options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=TestCosmoDB;Trusted_Connection=True;MultipleActiveResultSets=true"); });
                services.AddDbContext <CosmoContext>(options => options.UseInMemoryDatabase("TestDB"));
            })
                          .UseEnvironment("Testing")
                          .UseStartup <Startup>();

            _testServer = new TestServer(builder)
            {
                BaseAddress = new Uri("http://localhost:5002")
            };

            TestClient             = _testServer.CreateClient();
            TestClient.BaseAddress = _testServer.BaseAddress;

            dateCalculation = new DateCalculation();
        }
        public async Task <IActionResult> DeleteRoute([FromRoute] int id)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Route result = (Route)await _context.Route.FindAsync(id);

            if (result == null)
            {
                return(BadRequest("Archiving Failed - Route ID was not found"));
            }

            if (!result.inactive)
            {
                result.inactive = true;
                _context.Route.Update(result);
                await _context.SaveChangesAsync();
            }

            if (_context.Route.AsNoTracking().Where(r => r.routeID == id).Single().inactive)
            {
                //Get Region associated with archived Route
                Region region = _context.Region.AsNoTracking().Where(re => re.regionID == result.regionID).Single();

                //If the Region is ACTIVE and there are no INCOMPLETE Routes associated with the Region
                if (!region.inactive && _context.Route.AsNoTracking().Where(r => r.regionID == region.regionID && !r.inactive && !r.completed).Count() == 0)
                {
                    DateCalculation calc     = new DateCalculation();
                    Route           newRoute = new Route
                    {
                        //routeID = default(int),
                        routeName = result.routeName,
                        regionID  = region.regionID,
                        completed = false,
                        inactive  = false,
                        routeDate = calc.GetOneDate(region)
                    };
                    await _context.Route.AddAsync(newRoute);
                }

                await _context.SaveChangesAsync();

                return(Ok("Route " + result.routeName + " was archived"));
            }
            else
            {
                return(BadRequest());
            }
        }
        public async Task <IActionResult> PostRegion([FromBody] Region region)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Region.Add(region);
            await _context.SaveChangesAsync();

            //Queries the Route table for Routes which have a region ID matching the created regions ID.
            //If no Routes are found AND added region is not inactive, create a Route with derived information
            if (_context.Route.Where(r => r.regionID == region.regionID).Count() == 0 && !region.inactive)
            {
                DateTime nextDate = dateCalculation.GetNextDates(1, region).FirstOrDefault();

                Route newRoute = new Route
                {
                    routeName = region.regionName + " - " + nextDate.ToString("MMMM dd, yyyy"),
                    regionID  = region.regionID,
                    region    = region,
                    completed = false,
                    inactive  = false,
                    routeDate = nextDate
                };

                _context.Route.Add(newRoute);
                await _context.SaveChangesAsync();
            }

            DateCalculation dc = new DateCalculation();

            //Create an anonymous object that contains the nextPickupDate
            //Is used to send back the next collection date, to be displayed on the front end
            var returnRegion = new
            {
                regionID   = region.regionID,
                regionName = region.regionName,
                frequency  = region.frequency,
                firstDate  = region.firstDate,
                nextDate   = dc.GetNextDates(1, region),
                inactive   = region.inactive
            };


            return(CreatedAtAction("GetRegion", new { id = returnRegion.regionID }, returnRegion));
        }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, CosmoContext context)
        {
            //Checks if the environment the webApp is hosted in is a development environment
            if (env.IsDevelopment())
            {
                dateCalculation = new DateCalculation();
                app.UseDeveloperExceptionPage();        //Provides the Developer Exception Page. Page gives information on errors thrown, requests, queries, and others

                context.Database.EnsureDeleted();
                context.Database.EnsureCreated(); //Checks that the context's database is created. Returns true if it is, false if not

                unloadDB(context);                //Helper method to unload items in the context database (ensures fresh dummy data)


                List <Region> regions = loadRegions(); //Helper method to load dummy Regions into Region table
                context.AddRange(regions);             //Adds Regions list to context
                context.SaveChanges();                 //Saves changes

                //List<Location> locations = loadLocations(regions); //Create locations with regions passed in
                //context.Location.AddRange(locations);
                //context.SaveChanges();

                loadLocations(context, regions);
                List <Location> locations = context.Location.ToList();

                List <Subscriber> subscribers = loadSubscribers(locations);                  //Create the subscribers with the locations passed in
                context.Subscriber.AddRange(subscribers);
                context.SaveChanges();                                                       //Save changes to DB

                List <Route> routes = loadRoutes(regions);                                   //Helper method to load dummy Routes into Route table
                context.AddRange(routes);                                                    //Adds routes list to context
                context.SaveChanges();                                                       //Saves changes

                List <Admin> admins = loadAdmins();                                          //Create the admins
                context.Admin.AddRange(admins);
                context.SaveChanges();                                                       //Save changes to DB

                List <LocationRoute> locationRoutes = loadLocationRoutes(locations, routes); //Create the locationRoutes with the locations and routes passed in
                context.LocationRoute.AddRange(locationRoutes);
                context.SaveChanges();                                                       //Save changes to DB
                //Highly populate route 'S90 A Past Route'
                HighlyPopulateRoute(context, routes[0]);

                //Added for Enable CORS Tutorial https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
                //Tells the application to run the given policy name
                app.UseCors(MyAllowSpecificOrigins);

                context.SaveChanges();
            }
            app.UseAuthentication();
            app.UseMvc();   //Adds MVC to the .Net Core REquest Execution Pipeline
        }
        public IActionResult GetSubscriberDates([FromRoute] int regionID)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            //Declare The Util method so we can call it later
            DateCalculation dc = new DateCalculation();

            //Get all the Regions From the DB
            Region region = _context.Region.FirstOrDefault(r => r.regionID == regionID);



            //Return the results of the Helper method along with OK as an indication of success
            return(Ok(dc.GetOneDate(region)));
        }
Exemplo n.º 9
0
        public RouteTests(WebAppFixture <Startup> webApp)
        {
            _webApp = webApp; //set this _webApp to the WebAppFixture that is passed in

            //Builds up a HTTP client object that handles redirects to the API
            //_client = _webApp.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
            _client         = _webApp.TestClient;
            dateCalculation = new DateCalculation();

            //This sets up the TokenClient, which handles the authentication tokens that IdentityServer hands out upon user authorization
            //var disco = DiscoveryClient.GetAsync("https://localhost:5000").Result;
            //_tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");

            //var tokenResponse = _tokenClient.RequestResourceOwnerPasswordAsync("alice", "password", "api1").Result;
            //_client.SetBearerToken(tokenResponse.AccessToken);

            admin = new Admin
            {
                username = "******",
                password = "******", //The SHA-256 hash of Cosmo123
            };
        }
Exemplo n.º 10
0
 public WebAppController(CosmoContext context)
 {
     _cosmoContext   = context;
     dateCalculation = new DateCalculation();
 }
        public async Task <IActionResult> PutRoute([FromRoute] int id, [FromBody] Route route)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != route.routeID)
            {
                return(BadRequest());
            }

            //Get the date of the corresponding Route in the DB. Using "AsNoTracking" to prevent the entity from being tracked as information is being read, not edited
            DateTime dbRouteDate = _context.Route.AsNoTracking().Where(r => r.routeID == id).Single().routeDate;


            //If the incoming Route's date is in the past, and the date has been changed, return an error
            if (route.routeDate.Date < DateTime.Now.Date && !route.routeDate.ToShortDateString().Equals(dbRouteDate.ToShortDateString()))
            {
                //Return a Bad Request is the incoming Route's date was chnaged to a date in the past
                return(BadRequest(new ValidationResult("Invalid Date", new[] { "routeDate" })));
            }
            else
            {
                _context.Route.Update(route);
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RouteExists(id))
                {
                    return(NotFound("Route was not found"));
                }
                else
                {
                    throw;
                }
            }

            CompareModels cmpRoutes = new CompareModels();
            //Route dbRoute = (Route) await _context.Route.FindAsync(id);
            Route dbRoute = _context.Route.AsNoTracking().Where(r => r.routeID == id).Single();

            dbRoute.region = _context.Region.AsNoTracking().Single(reg => reg.regionID == dbRoute.regionID);

            //Route dbRoute = (Route)await _context.Route.FindAsync(id);

            if (cmpRoutes.CompareRoutes(dbRoute, route) == 0)

            {
                //If original route was incomplete and updated Route is complete,
                //no incomplete Routes exist for the Region
                //and the Region is Active, Create a new Route
                if (dbRoute.completed &&
                    _context.Route.AsNoTracking().Where(r => r.regionID == route.regionID && !r.inactive && !r.completed).Count() == 0 &&
                    _context.Region.AsNoTracking().Where(r => r.regionID == route.regionID).FirstOrDefault().inactive == false)
                {
                    Region          dbRegion = _context.Region.AsNoTracking().Where(r => r.regionID == route.regionID).FirstOrDefault(); //Get the associated Region for the Route
                    DateCalculation calc     = new DateCalculation();
                    //Create a new Route object with values taken from old Route

                    Route newRoute = new Route
                    {
                        routeName = route.routeName,
                        regionID  = dbRegion.regionID,
                        region    = dbRegion,
                        completed = false,
                        inactive  = false,
                        routeDate = calc.GetOneDate(dbRegion)
                    };

                    //Add the new Route to DB and save it
                    await _context.Route.AddAsync(newRoute);
                }
                await _context.SaveChangesAsync();

                //Return resulting updated Route
                return(Ok(dbRoute));
            }
            else
            {
                return(BadRequest());
            }
        }
 public RegionsController(CosmoContext context)
 {
     _context        = context;
     dateCalculation = new DateCalculation();
 }
        public async Task <IActionResult> PutRegion([FromRoute] int id, [FromBody] Region region)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != region.regionID)
            {
                return(BadRequest());
            }


            DateCalculation dc = new DateCalculation();

            //get the oldRegion to check if the active changed after saving changes
            Region oldRegion = _context.Region.AsNoTracking().Where <Region>(e => e.regionID == id).FirstOrDefault();

            _context.Region.Update(region);
            await _context.SaveChangesAsync();

            //Check to see if the region has been set back to active
            if (oldRegion.inactive == true && region.inactive == false)
            {
                //Get a list of all the routes associated with the region ID that are not completed
                List <Route> routes = _context.Route.Where <Route>(e => e.regionID == region.regionID && e.completed == false && e.inactive == false).ToList();

                //if routes active incomplete is 0 Create a new route
                if (routes.Count == 0)
                {
                    DateTime nextDate = dc.GetNextDates(1, region).Single();

                    Route newRoute = new Route
                    {
                        routeName = region.regionName + " - " + nextDate.ToString("MMMM dd, yyyy"),
                        regionID  = region.regionID,
                        region    = region,
                        completed = false,
                        inactive  = false,
                        routeDate = nextDate
                    };

                    _context.Route.Update(newRoute);


                    await _context.SaveChangesAsync();
                }
            }

            //Create an anonymous object that contains the nextPickupDate
            //Is used to send back the next collection date, to be displayed on the front end
            var returnRegion = new
            {
                regionID   = region.regionID,
                regionName = region.regionName,
                frequency  = region.frequency,
                firstDate  = region.firstDate,
                nextDate   = dc.GetNextDates(1, region),
                inactive   = region.inactive
            };


            return(Ok(returnRegion));
        }