public async Task <Models.ActionResult <Tracking> > Get(int id)
        {
            Models.ActionResult <Tracking> result = null;
            try
            {
                if (id > 0)
                {
                    var trackingEntry = await TrackingManager.GetLastTrackingRecord(id);

                    result = new Models.ActionResult <Tracking>(HttpStatusCode.OK, trackingEntry);
                }
                else
                {
                    result = new Models.ActionResult <Tracking>(HttpStatusCode.BadRequest, "id should be greater than zero.");
                }
            }
            catch (ArgumentException ex)
            {
                result = new Models.ActionResult <Tracking>(HttpStatusCode.BadRequest, ex.Message); // In the case of argument exception we will be getting meaning full error message.
            }
            catch (Exception)
            {
                result = new Models.ActionResult <Tracking>(HttpStatusCode.InternalServerError, "Internal server error has accured while getting last location of the vehicle."); // no need to share implementation details with the consumer.
            }

            return(result);
        }
        public async Task <Models.ActionResult <SearchResult> > Search(TrackingSearcher searcher)
        {
            Models.ActionResult <SearchResult> result = null;
            try
            {
                if (searcher != null && ModelState.IsValid)
                {
                    var searchResult = await TrackingManager.Search(searcher);

                    result = new Models.ActionResult <SearchResult>(HttpStatusCode.OK, searchResult);
                }
                else
                {
                    result = searcher == null ? new Models.ActionResult <SearchResult>(HttpStatusCode.BadRequest, "Search parameters are required") : new Models.ActionResult <SearchResult>(HttpStatusCode.BadRequest, ModelState);
                }
            }
            catch (ArgumentException ex)
            {
                result = new Models.ActionResult <SearchResult>(HttpStatusCode.BadRequest, ex.Message); // In the case of argument exception we will be getting meaning full error message.
            }
            catch (Exception)
            {
                result = new Models.ActionResult <SearchResult>(HttpStatusCode.InternalServerError, $"Internal server error has accured while searching tracking records for the vehicle:{searcher?.VehicleID}"); // no need to share implementation details with the consumer.
            }

            return(result);
        }
Beispiel #3
0
        // POST: api/Account
        // For security purpose we should require this application to run on SSL. I am not enforcing SSL to make the deployment simple for the demo purpose.
        public async Task <Models.ActionResult <string> > Post(User user)
        {
            Models.ActionResult <string> result = null;
            try
            {
                if (ModelState.IsValid)
                {
                    var loggedInUser = await AccountManager.Authenticate(user);

                    if (loggedInUser != null)
                    {
                        var token = Models.JWTHelper.GenerateJWTToken(ConfigurationManager.AppSettings["jwt_issuer"], ConfigurationManager.AppSettings["jwt_secret"], user.ID.ToString(), user.Username, user.Role);
                        result = new Models.ActionResult <string>(HttpStatusCode.OK, data: token);
                    }
                    else
                    {
                        result = new Models.ActionResult <string>(HttpStatusCode.NotFound, "Invalid username or password");
                    }
                }
                else
                {
                    result = new Models.ActionResult <string>(HttpStatusCode.BadRequest, ModelState);
                }
            }
            catch (ArgumentException ex)
            {
                result = new Models.ActionResult <string>(HttpStatusCode.BadRequest, ex.Message);
            }
            catch (Exception)
            {
                result = new Models.ActionResult <string>(HttpStatusCode.InternalServerError, $"Internal server error has accured authenticating user {user.Username}.");
            }

            return(result);
        }
Beispiel #4
0
        // POST: api/Vehicle
        public async Task <Models.ActionResult <Vehicle> > Post(Vehicle vehicle)
        {
            Models.ActionResult <Vehicle> result = null;
            try
            {
                if (ModelState.IsValid)
                {
                    await VehicleManager.RegisterVehicle(vehicle);

                    vehicle.Token = Models.JWTHelper.GenerateJWTToken(ConfigurationManager.AppSettings["jwt_issuer"], ConfigurationManager.AppSettings["jwt_secret"], vehicle.ID.ToString(), vehicle.RegNumber, "vehicle");
                    result        = new Models.ActionResult <Vehicle>(HttpStatusCode.OK, vehicle);
                }
                else
                {
                    result = new Models.ActionResult <Vehicle>(HttpStatusCode.BadRequest, ModelState);
                }
            }
            catch (ArgumentException ex)
            {
                result = new Models.ActionResult <Vehicle>(HttpStatusCode.BadRequest, ex.Message); // In the case of argument exception we will be getting meaning full error message.
            }
            catch (Exception)
            {
                result = new Models.ActionResult <Vehicle>(HttpStatusCode.InternalServerError, "Internal server error has accured while registering the vehicle."); // no need to share implementation details with the consumer.
            }

            return(result);
        }
        public async Task <Models.ActionResult <bool> > Post(Tracking tracking)
        {
            Models.ActionResult <bool> result = null;
            try
            {
                if (tracking != null && ModelState.IsValid)
                {
                    //JWT sub claim will be translated into NameIdentifier
                    var claim = ClaimsPrincipal.Current.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase));
                    if (claim == null || !int.TryParse(claim.Value, out int vid) || vid != tracking.VehicleID)
                    {
                        result = new Models.ActionResult <bool>(HttpStatusCode.Unauthorized, "You are not authorized to update the position of requested vehicle");
                    }
                    else
                    {
                        await TrackingManager.Record(tracking);

                        result = new Models.ActionResult <bool>(HttpStatusCode.OK, true);
                    }
                }
                else
                {
                    result = tracking == null ? new Models.ActionResult <bool>(HttpStatusCode.BadRequest, "Tracking data is required") : new Models.ActionResult <bool>(HttpStatusCode.BadRequest, ModelState);
                }
            }
            catch (ArgumentException ex)
            {
                result = new Models.ActionResult <bool>(HttpStatusCode.BadRequest, ex.Message); // In the case of argument exception we will be getting meaning full error message.
            }
            catch (Exception)
            {
                result = new Models.ActionResult <bool>(HttpStatusCode.InternalServerError, "Internal server error has accured while recording tracking entry."); // no need to share implementation details with the consumer.
            }

            return(result);
        }
        // GET: Queue
        public JsonResult QueueMe()
        {
            var userName = User.Identity.GetUserName();
            var userId   = User.Identity.GetUserId();
            var response = new Models.ActionResult <Match>();

            var queue = db.queueIn.FirstOrDefault(u => u.Opponent2 == null);

            if (queue == null)
            {
                queue           = db.queueIn.Create();
                queue.Opponent1 = userName;
                db.queueIn.AddOrUpdate(queue);
                db.SaveChanges();
            }
            else
            {
                if (queue.Opponent1 != userName)
                {
                    queue.Opponent2 = userName;
                    db.queueIn.AddOrUpdate(queue);
                    db.SaveChanges();
                    bool MatchTransfered = false;
                    //get newly created match
                    while (!MatchTransfered)
                    {
                        //re-init application context so data is updated
                        db = new ApplicationDbContext();
                        var matchCreated = db.Match.FirstOrDefault(u => u.Opponent2 == userName && u.Opponent1 == queue.Opponent1 ||
                                                                   u.Opponent1 == userName && u.Opponent2 == queue.Opponent1
                                                                   );

                        if (matchCreated != null)
                        {
                            MatchTransfered = true;

                            response = new Models.ActionResult <Match>
                            {
                                Object = matchCreated,
                                Status = new HttpStatusCodeResult(200)
                            };
                            return(Json(response, JsonRequestBehavior.AllowGet));
                        }
                        else
                        {
                            System.Threading.Thread.Sleep(1000);
                        }
                    }
                }
            }

            //Waiting for opponent
            bool OpponentFound = false;

            while (!OpponentFound)
            {
                //re-init application context so data is updated
                db    = new ApplicationDbContext();
                queue = db.queueIn.FirstOrDefault(u => u.Opponent1 == userName);
                if (!string.IsNullOrEmpty(queue.Opponent2))
                {
                    OpponentFound = true;
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }

            bool queueContains = db.queueIn.Any(t => t.Opponent1 != null && t.Opponent2 != null && t.Opponent1 == userName);

            //transfer from queue to actual match
            Match newMatch = null;

            if (queueContains)
            {
                db    = new ApplicationDbContext();
                queue = db.queueIn.FirstOrDefault(u => u.Opponent1 == userName);

                QueueIn queueData = db.queueIn.Where(x => x.Opponent1 == userName || x.Opponent2 == userName).Select(x => x).FirstOrDefault();

                newMatch = new Match {
                    Opponent1 = queueData.Opponent1, Opponent2 = queueData.Opponent2, Date = DateTime.Now
                };

                db.Match.AddOrUpdate(newMatch);
                db.SaveChanges();

                newMatch = db.Match.FirstOrDefault(x => x.Opponent1 == newMatch.Opponent1 && x.Opponent2 == newMatch.Opponent2);

                db.MatchData.Add(new MatchData {
                    MatchId    = newMatch.MatchId,
                    MatchState = MatchState.PENDINGBET
                });

                db.queueIn.Remove(queue);
                db.SaveChanges();
            }

            response = new Models.ActionResult <Match>
            {
                Object = newMatch,
                Status = new HttpStatusCodeResult(200)
            };

            return(Json(response, JsonRequestBehavior.AllowGet));
        }