Esempio n. 1
0
        public async Task <IActionResult> PutLocationRoute([FromRoute] int id, [FromBody] LocationRoute locationRoute)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != locationRoute.locationRouteID)
            {
                return(BadRequest());
            }

            _context.Entry(locationRoute).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LocationRouteExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> PostSubscriber([FromBody] Subscriber subscriber)
        {
            var tokenIn = this.HttpContext.Request.Headers.GetCommaSeparatedValues("GoogleAuth");

            if (tokenIn.Count <string>() == 0)
            {
                return(Unauthorized());
            }

            var validPayload = await GoogleJsonWebSignature.ValidateAsync(tokenIn[0]);

            if (validPayload != null)
            {
                if (validPayload.Email.Equals(subscriber.email.ToLower()))
                {
                    //If the object is not valid, return 422
                    if (!ModelState.IsValid)
                    {
                        return(UnprocessableEntity(ModelState));
                    }

                    //Add the object to the context
                    _context.Subscriber.Add(subscriber);
                    //Save the changes
                    await _context.SaveChangesAsync();

                    //Return 201
                    return(CreatedAtAction("GetSubscriber", new { id = subscriber.subscriberID }, subscriber));
                }
                else
                {
                    return(Unauthorized());
                }
            }
            //If the object is not valid, return 422
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            //Add the object to the context
            _context.Subscriber.Add(subscriber);
            //Save the changes
            await _context.SaveChangesAsync();

            //Return 201
            return(CreatedAtAction("GetSubscriber", new { id = subscriber.subscriberID }, subscriber));
        }
 private static Task <int> unloadDB(CosmoContext context)
 {
     context.RemoveRange(context.Subscriber); //Remove contents of Subscriber table from context
     context.RemoveRange(context.Location);   //Remove contents of Location table from context
     context.RemoveRange(context.Route);      //Remove contents of Route table from context
     context.RemoveRange(context.Region);     //Remove contents of Region table from context
     context.RemoveRange(context.Admin);
     return(context.SaveChangesAsync());      //Save changes
 }
        public async Task <IActionResult> PostAdmin([FromBody] Admin administrator)
        {
            //If we failed the Authorize claims check, the response code will be set to 401
            if (this.Response.StatusCode == 401)
            {
                return(Unauthorized());
            }

            //Check to see if it is valid
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Check to see if the username exists
            if (!AdminUserNameExists(administrator.username))
            {
                //create a random salt for this new admin
                byte[] salt = new byte[128 / 8];
                using (var rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(salt);
                }
                //Set the salt to the new admin
                administrator.salt = salt;


                //hash the password value of the uiAdmin with its password salted
                string encryptedPass = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                                  password: administrator.password,
                                                                  salt: administrator.salt,
                                                                  prf: KeyDerivationPrf.HMACSHA256,
                                                                  iterationCount: 10000,
                                                                  numBytesRequested: 256 / 8
                                                                  ));

                administrator.password = encryptedPass;

                //Save/add the valid admin
                _context.Admin.Add(administrator);
                await _context.SaveChangesAsync();

                //Return the created code
                return(Created("adminCreated", administrator));
            }
            else
            {
                //Return our error message for username already existing
                ModelState.AddModelError("username", "Username already exists");
                return(BadRequest(ModelState));
            }
        }
Esempio n. 5
0
        public async Task <IActionResult> PostLocation([FromBody] Location location)
        {
            //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.Location.Add(location);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetLocation", new { id = location.locationID }, location));
        }
        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 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));
        }