public async Task TripProcessor([CosmosDBTrigger(
                                             databaseName: "ContosoAuto",
                                             collectionName: "telemetry",
                                             ConnectionStringSetting = "CosmosDBConnection",
                                             LeaseCollectionName = "leases",
                                             LeaseCollectionPrefix = "trips",
                                             CreateLeaseCollectionIfNotExists = true,
                                             StartFromBeginning = true)] IReadOnlyList <Document> vehicleEvents,
                                        ILogger log)
        {
            log.LogInformation($"Evaluating {vehicleEvents.Count} events from Cosmos DB to optionally update Trip and Consignment metadata.");

            // Retrieve the Trip records by VIN, compare the odometer reading to the starting odometer reading to calculate miles driven,
            // and update the Trip and Consignment status and send an alert if needed once completed.
            if (vehicleEvents.Count > 0)
            {
                foreach (var group in vehicleEvents.GroupBy(singleEvent => singleEvent.GetPropertyValue <string>("vin")))
                {
                    var vin          = group.Key;
                    var odometerHigh = group.Max(item => item.GetPropertyValue <double>("odometer"));
                    var averageRefrigerationUnitTemp =
                        group.Average(item => item.GetPropertyValue <double>("refrigerationUnitTemp"));

                    // First, retrieve the metadata Cosmos DB container reference:
                    var metadataContainer = _cosmosClient.GetContainer(Database, MetadataContainerName);
                    // Next, retrieve the alerts Cosmos DB container reference. This is used to retrieve alert settings and keep track of when batch messages are sent.
                    var alertsContainer = _cosmosClient.GetContainer(Database, AlertsContainerName);

                    // Create a query, defining the partition key so we don't execute a fan-out query (saving RUs), where the entity type is a Trip and the status is not Completed, Canceled, or Inactive.
                    var query = metadataContainer.GetItemLinqQueryable <Trip>(requestOptions: new QueryRequestOptions {
                        PartitionKey = new Microsoft.Azure.Cosmos.PartitionKey(vin)
                    })
                                .Where(p => p.status != WellKnown.Status.Completed &&
                                       p.status != WellKnown.Status.Canceled &&
                                       p.status != WellKnown.Status.Inactive &&
                                       p.entityType == WellKnown.EntityTypes.Trip)
                                .ToFeedIterator();

                    if (query.HasMoreResults)
                    {
                        // Only retrieve the first result.
                        var trip = (await query.ReadNextAsync()).FirstOrDefault();

                        if (trip != null)
                        {
                            var tripHelper = new TripHelper(trip, metadataContainer, alertsContainer, _httpClientFactory, _queueResolver, log);

                            var sendTripAlert = await tripHelper.UpdateTripProgress(odometerHigh);

                            if (sendTripAlert)
                            {
                                // Send a trip alert.
                                await tripHelper.SendTripAlert(averageRefrigerationUnitTemp);
                            }
                        }
                    }
                }
            }
        }
        public async Task SendQueuedAlerts([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"SendQueuedAlerts timer executed at: {DateTime.Now}");

            // Retrieve the alerts Cosmos DB container reference. This is used to retrieve alert settings and keep track of when batch messages are sent.
            var alertsContainer = _cosmosClient.GetContainer(Database, AlertsContainerName);

            var tripHelper = new TripHelper(null, null, alertsContainer, _httpClientFactory, _queueResolver, log);
            await tripHelper.SendAlertSummary();
        }
Beispiel #3
0
        public void Test_MissInputSort()
        {
            //arrange
            var card1 = new TripCard(new City("Мельбурн"), new City("Кельн"));
            var card2 = new TripCard(new City("Кельн"), new City("Прага"));
            var card3 = new TripCard(new City("Прага"), new City("Париж"));
            var card4 = new TripCard(new City("Москва"), new City("Берлин"));

            TripHelper.Sort(new List <TripCard>()
            {
                card1, card3, card2, card4
            });
        }
Beispiel #4
0
        public void Test_CorrectInputSort()
        {
            //arrange
            var card1 = new TripCard(new City("Мельбурн"), new City("Кельн"));
            var card2 = new TripCard(new City("Кельн"), new City("Москва"));
            var card3 = new TripCard(new City("Москва"), new City("Париж"));

            var sortedCards = new List <TripCard>()
            {
                card1, card2, card3
            };
            var unsordedCards = new List <TripCard>()
            {
                card1, card3, card2,
            };

            //act
            var result = TripHelper.Sort(unsordedCards);

            //assert
            CollectionAssert.AreEqual(sortedCards, result);
        }
Beispiel #5
0
 public void Test_NullInputSort()
 {
     TripHelper.Sort(null);
 }
Beispiel #6
0
        public async Task <IActionResult> Get()
        {
            using (HttpClient client = new HttpClient())
            {
                // Call asynchronous network methods in a try/catch block to handle exceptions
                try
                {
                    HttpResponseMessage response = await client.GetAsync("https://maps.googleapis.com/maps/api/directions/json?origin=Golf City Mall&destination=Modern Academyin Maadi&key=AIzaSyCezD7oizzzd8QqHw5tVSveIxjyemdpwVU&language=ar");

                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    // Above three lines can be replaced with new helper method below
                    // string responseBody = await client.GetStringAsync(uri);
                    var x = JsonConvert.DeserializeObject <Directions>(responseBody);
                    return(Ok(new TripInfoDto {
                        EncodedRoute = x.Routes[0].OverviewPolyline, Info = x.Routes[0].Legs[0], ExcpectedPayment = await TripHelper.calculateTripFeesRange(x)
                    }));
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }

            return(null);
        }
Beispiel #7
0
        public async Task <IActionResult> Post([FromBody] TripReserveDto tripReserveDto)
        {
            await _HubContext.Clients.All.SendAsync("Driver", "Hello From Another Application");

            return(Ok());


            string userId      = User.FindFirstValue(ClaimTypes.NameIdentifier);
            string userRole    = User.FindFirstValue(ClaimTypes.Role);
            var    currentUser = await this.userRepository.FindOneById(int.Parse(userId));

            if (currentUser == null || currentUser.Role.ToString() != userRole.ToString())
            {
                return(Unauthorized());
            }

            var originPoint = new Point(tripReserveDto.OriginLocation.Lat, tripReserveDto.OriginLocation.Lng)
            {
                SRID = 4326
            };
            var destinationPoint = new Point(tripReserveDto.DistanceLocation.Lat, tripReserveDto.DistanceLocation.Lng)
            {
                SRID = 4326
            };
            var trip = await this.tripRepository.FindTripNearestByLocation(originPoint, destinationPoint);

            var originPlace = new Place {
                Location = originPoint, Name = tripReserveDto.OriginAddress
            };
            var destantPlace = new Place {
                Location = destinationPoint, Name = tripReserveDto.DistantAddress
            };


            if (trip == null)
            {
                Driver driver = await this.driverRepository.FindAnyDriver();

                await _HubContext.Clients.All.SendAsync("Driver", "Hello From Another Application");

                return(Ok());

                if (driver == null)
                {
                    return(UnprocessableEntity());
                }
                else
                {
                    var newTrip = new Trip
                    {
                        StartLocation = originPlace,
                        FinalLocation = destantPlace,
                        DriverId      = driver.Id,
                        Status        = Models.enums.TripStatus.PICKING_USER,
                    };
                    tripRepository.Add(newTrip);
                    await this.tripRepository.SaveAll();

                    var clientInTrip = new ClientTrip()
                    {
                        ClientId     = currentUser.Id,
                        Status       = Models.enums.ClientTripStatus.WAITING_FOR_DRIVER,
                        FromLocation = originPlace,
                        ToLocation   = destantPlace,
                        StartedAt    = DateTime.Now,
                    };

                    newTrip.Clients.Add(clientInTrip);
                    tripRepository.Add(newTrip);
                    await this.tripRepository.SaveAll();

                    var point = new ClientTripPointAtTime {
                        ClientId = currentUser.Id, TripId = newTrip.Id, Location = originPoint, Time = DateTime.Now
                    };


                    clientInTrip.Points.Add(point);

                    clientTripRepository.Add(clientInTrip);
                    await this.clientTripRepository.SaveAll();

                    var expectedPoints = TripHelper.convertFromDirectionToListOfExpectedRoutes(
                        await getDirectionInfo(new TripCheckQuery {
                        OriginLat = tripReserveDto.OriginLocation.Lat, OriginLng = tripReserveDto.OriginLocation.Lng, DestinationLat = tripReserveDto.DistanceLocation.Lat, DestinationLng = tripReserveDto.DistanceLocation.Lng
                    })
                        );

                    //trip.ExpectedRoad = expectedPoints;

                    tripRepository.Add(newTrip);


                    if (await tripRepository.SaveAll())
                    {
                        return(Ok(trip));
                    }
                    else
                    {
                        return(StatusCode(500));
                    }
                }
            }
            else
            {
                var clientInTrip = new ClientTrip()
                {
                    ClientId     = currentUser.Id,
                    Status       = Models.enums.ClientTripStatus.WAITING_FOR_DRIVER,
                    FromLocation = originPlace,
                    ToLocation   = destantPlace,
                    StartedAt    = DateTime.Now
                };

                var point = new ClientTripPointAtTime {
                    ClientId = currentUser.Id, TripId = trip.Id, Location = originPoint, Time = DateTime.Now
                };


                clientInTrip.Points.Add(point);

                trip.Clients.Add(clientInTrip);
                trip.Status = Models.enums.TripStatus.ANOTHER_CLIENT;
                tripRepository.Update(trip);

                if (await tripRepository.SaveAll())
                {
                    return(Ok(trip));
                }
                else
                {
                    return(StatusCode(500));
                }
            }
        }
Beispiel #8
0
        public async Task <IActionResult> Get([FromBody] TripCheckQuery query)
        {
            using (HttpClient client = new HttpClient())
            {
                // Call asynchronous network methods in a try/catch block to handle exceptions
                try
                {
                    var uriBuilder = new UriBuilder("https://maps.googleapis.com/maps/api/directions/json");
                    var uriQuery   = HttpUtility.ParseQueryString(uriBuilder.Query);
                    uriQuery["language"]    = "ar";
                    uriQuery["key"]         = "AIzaSyCezD7oizzzd8QqHw5tVSveIxjyemdpwVU";
                    uriQuery["origin"]      = "" + query.OriginLat + "," + query.OriginLng;
                    uriQuery["destination"] = "" + query.DestinationLat + "," + query.DestinationLng;
                    uriBuilder.Query        = uriQuery.ToString();

                    HttpResponseMessage response = await client.GetAsync(uriBuilder.ToString());

                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();

                    // Above three lines can be replaced with new helper method below
                    // string responseBody = await client.GetStringAsync(uri);
                    var x = JsonConvert.DeserializeObject <Directions>(responseBody);
                    x.Routes[0].Legs[0].Steps = null;
                    return(Ok(new TripInfoDto {
                        EncodedRoute = x.Routes[0].OverviewPolyline, Info = x.Routes[0].Legs[0], ExcpectedPayment = await TripHelper.calculateTripFeesRange(x)
                    }));
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }

            return(Ok());
        }