Example #1
0
        public MatchResponse Match(string text, string subText)
        {
            var response = new MatchResponse();

            if (text.IsEmpty() || subText.IsEmpty())
            {
                return(response);
            }

            var matches       = new List <int>();
            var indexAddition = 0;

            while (true)
            {
                var index = text.IndexOf(subText, StringComparison.InvariantCultureIgnoreCase);
                if (index < 0)
                {
                    break;
                }

                matches.Add(index + indexAddition);

                var nextPosition = index + 1;
                indexAddition += nextPosition;
                text           = text.Substring(nextPosition, text.Length - nextPosition);
            }

            return(new MatchResponse {
                MatchCharacterPositions = matches
            });
        }
Example #2
0
        public async Task <BaseResponse <MatchesAtivosResponse> > Handle(GetAllMatchesQuery request, CancellationToken cancellationToken)
        {
            var response = new BaseResponse <MatchesAtivosResponse>();
            MatchesAtivosResponse matchesAtivosResponse = new MatchesAtivosResponse
            {
                IdUser = request.UserId
            };

            List <MatchResponse> matchesList = new List <MatchResponse>();

            var matchesQuery = _dbContext.Matches.Where(m => m.IdUser == request.UserId);

            if (!matchesQuery.Any())
            {
                response.SetValidationErrors(new[] { "Usuário não possui matches ativos" });
            }
            else
            {
                var matches = matchesQuery.ToList();
                foreach (var m in matches)
                {
                    MatchResponse matchResponse = new MatchResponse();
                    matchResponse.IdAmigo     = m.IdAmigo;
                    matchResponse.DataConexão = m.dataConexao;
                    matchesList.Add(matchResponse);
                }

                matchesAtivosResponse.Matches = matchesList;

                response.SetIsOk(matchesAtivosResponse);
            }

            return(response);
        }
Example #3
0
        private async Task <bool> RegisterInVANAsync(Voter voter)
        {
            bool registered = false;

            // Check if a user is already registered in VAN; it not, create a record for them

            PersonDTO person = Mapper.MapPersonDTO(voter);

            Repository    repo     = new Repository();
            MatchResponse response = await repo.FindOrCreatePersonInVANAsync(person);

            string[] validStatuses = new string[] {
                Statuses.Matched.ToString(),
                     Statuses.UnmatchedStored.ToString()
            };

            if (validStatuses.Contains(response.status))
            {
                registered = true;

                voter.van_id = response.vanId;
                repo.SaveVoter(voter);
            }

            return(registered);
        }
Example #4
0
        private void newMatchResponsesNotification(MatchResponse matchResponse)
        {
            //send push Notification using socket;
            WC_MatchTicker.PushTicker(matchResponse.Pair, matchResponse);

            //ME_Gateway.Instance.MatchResponseQueue.Add(matchResponse);
        }
Example #5
0
        public async Task <ActionResult <MatchResponse> > MatchRequest(MatchRequest request)
        {
            var matchResponse = new MatchResponse();

            try
            {
                using var channel = GrpcChannel.ForAddress(FrontendUrl);
                var client = new FrontendServiceClient(channel);

                var searchFields = new SearchFields();
                searchFields.Tags.Add(request.GameMode.ToString());
                var ticket = new Ticket();
                ticket.SearchFields = searchFields;

                CreateTicketRequest createTicketRequest = new CreateTicketRequest();
                createTicketRequest.Ticket = ticket;

                var response = await client.CreateTicketAsync(createTicketRequest);

                matchResponse.TicketId = response.Id;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(matchResponse);
        }
        public async Task <float> getAverageScore(string userId)
        {
            _repository = new AmIGoodRepository(_clientFactory);
            SummonerResponse summonerData = await _repository.getSummonerResponse(userId);

            MatchResponse matchResponse = await _repository.getMatchesResponse(summonerData.accountId);

            List <MatchDetail> listMatchDetail = new List <MatchDetail>();

            if (matchResponse.matches == null)
            {
                return(0f);
            }
            foreach (MatchResume resume in matchResponse.matches)
            {
                try
                {
                    MatchDetail match = await _repository.getMatchInformation(resume.gameId);

                    listMatchDetail.Add(match);
                } catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                Thread.Sleep(100);
            }

            return(getScoreFromList(summonerData.accountId, listMatchDetail));
        }
        public static bool VerifyMatchResponse(MatchResponse mat, bool isCacheImage = false)
        {
            string error = "";

            try
            {
                if (isCacheImage)
                {
                    VerifyCacheId(isCacheImage, mat.CacheID);
                }

                if (mat.IsMatch == null)
                {
                    error += "IsMatch is null";
                }
                if (mat.Matches == null)
                {
                    error += "Matches object is null";
                }
                else
                {
                    foreach (Match m in mat.Matches)
                    {
                        if (m.MatchId == null)
                        {
                            error += "MatchId is null";
                        }
                        if (m.Score == null)
                        {
                            error += "Score is null";
                        }
                        if (m.Source == null)
                        {
                            error += "Source is null";
                        }
                        if (m.MatchId == null)
                        {
                            error += "MatchId is null";
                        }
                    }
                }
                if (!VerifyStatus(mat.Status))
                {
                    error += TestBase.ErrorMessage;
                }
                if (mat.TrackingId == null)
                {
                    error += "Trackingid is null";
                }

                TestBase.ErrorMessage = error;
                return(string.IsNullOrEmpty(TestBase.ErrorMessage));
            }
            catch (Exception e)
            {
                TestBase.ErrorMessage += "Unable to verify the Match response . Error:" + e.InnerException.Message;
                return(false);
            }
        }
Example #8
0
        /// <summary>
        /// Checks the VAN to see if a certain person is registered.
        /// </summary>
        /// <param name="person">Person to find</param>
        /// <returns>Whether the person was found in the VAN</returns>
        public async Task <MatchResponse> FindPersonInVANAsync(PersonDTO person)
        {
            MatchResponse response = new MatchResponse();
            const string  path     = "people/find";

            response = JsonConvert.DeserializeObject <MatchResponse>(await VANAPIRequestAsync(path, HttpMethod.Post, person));

            return(response);
        }
        private async Task EditMatch(MatchResponse match, Guid existingMatchId)
        {
            var date  = TryParseDate(match.dateEvent, match.strTime);
            var score = Score.CreateNew("Placeholder", TryParseInt(match.intHomeScore), TryParseInt(match.intAwayScore));

            var command = new EditMatchGeneralAttributesCommand(existingMatchId, match.strEvent, date.GetValueOrDefault(),
                                                                score, match.strSeason, "Placeholder");

            await CommandsExecutor.Execute(command);
        }
        public async Task <IHttpActionResult> GetMatchesToPredict(int tournamentId, int userId)
        {
            var qry = await(from t in db.Tournaments
                            join d in db.Dates on t.TournamentId equals d.TournamentId
                            join m in db.Matches on d.DateId equals m.DateId
                            where t.TournamentId == tournamentId && m.StatusId != 3
                            select new { m }).ToListAsync();
            var predictions = await db.Predictions.Where(p => p.UserId == userId).ToListAsync();

            var matches = new List <MatchResponse>();

            // ***
            var dateTimeLocal = DateTime.Now.ToLocalTime();
            var dateTimeUtc   = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now);
            var timeDiff      = dateTimeLocal.Subtract(dateTimeUtc).Hours;

            foreach (var item in qry)
            {
                if (item.m.DateTime > DateTime.Now.AddHours(-5))
                {
                    var matchResponse = new MatchResponse
                    {
                        DateId            = item.m.DateId,
                        DateTime          = item.m.DateTime,
                        Local             = item.m.Local,
                        LocalGoals        = item.m.LocalGoals,
                        LocalId           = item.m.LocalId,
                        MatchId           = item.m.MatchId,
                        StatusId          = item.m.StatusId,
                        TournamentGroupId = item.m.TournamentGroupId,
                        Visitor           = item.m.Visitor,
                        VisitorGoals      = item.m.VisitorGoals,
                        VisitorId         = item.m.VisitorId,
                    };

                    var prediction = predictions.Where(p => p.MatchId == item.m.MatchId).FirstOrDefault();

                    if (prediction != null)
                    {
                        matchResponse.LocalGoals   = prediction.LocalGoals;
                        matchResponse.VisitorGoals = prediction.VisitorGoals;
                        matchResponse.WasPredicted = true;
                    }
                    else
                    {
                        matchResponse.WasPredicted = false;
                    }

                    matches.Add(matchResponse);
                }
            }

            return(Ok(matches.OrderBy(m => m.DateTime)));
        }
        public async Task <IActionResult> Post()
        {
            var           matchConfidence = 0F;
            MatchResponse response;

            try
            {
                string testPhotoId;
                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    // Fetch file content fomr base64 encoded body
                    var fileBase64 = await reader.ReadToEndAsync();

                    byte[] bytes = Convert.FromBase64String(fileBase64);

                    // Assign S3 object name and save to S3
                    testPhotoId = $"tmp_{Guid.NewGuid().ToString("D")}";
                    await _s3Connector.WriteObjectDataAsync(testPhotoId, bytes);
                }

                const int minThresholdPercentage = 85;

                //We extract the employee data from the id card
                (int employeeNumber, string employeeNameWithoutSpaces)employeeData = await _rekognitionConnector.ExtractNameAndCodeInS3Object(testPhotoId);

                var employee = await _dynamoDBConnector.GetEmployeeAsync(new EmployeeId(employeeData.employeeNameWithoutSpaces, employeeData.employeeNumber));

                if (employee == null)
                {
                    throw new Exception("Employee not found");
                }

                //we ensure that the faces are legit.
                matchConfidence = await _rekognitionConnector.FindFaceOrThrowException(employee.ActiveIdCard.PictureObjectId, testPhotoId, minThresholdPercentage, employee.ActiveIdCard.Name);

                response = new MatchResponse
                {
                    StatusCode      = 200,
                    MatchConfidence = matchConfidence,
                    Message         = "Welcome " + employee.ActiveIdCard.Name
                };
            }
            catch (Exception ex)
            {
                response = new MatchResponse
                {
                    StatusCode = 503,
                    Message    = ex.Message
                };
            }

            // Return the response to the UI
            return(Ok(response));
        }
        private async Task AddMatch(MatchResponse match, TeamDto homeTeam, TeamDto awayTeam)
        {
            var date = TryParseDate(match.dateEvent, match.strTime);

            var score = Score.CreateNew("Placeholder", TryParseInt(match.intHomeScore), TryParseInt(match.intAwayScore));

            var command = new CreateMatchCommand(match.strEvent, homeTeam.Id, awayTeam.Id, date.GetValueOrDefault(), "Placeholder",
                                                 score, match.strSeason,
                                                 match.idEvent);

            await CommandsExecutor.Execute(command);
        }
Example #13
0
 public static void AddMatchData(this Match currentMatch, MatchResponse matchData)
 {
     currentMatch.MapId         = matchData.MapId;
     currentMatch.MatchCreation = matchData.MatchCreation;
     currentMatch.MatchDuration = matchData.MatchDuration;
     currentMatch.MatchMode     = matchData.MatchMode;
     currentMatch.MatchType     = matchData.MatchType;
     currentMatch.MatchVersion  = matchData.MatchVersion;
     currentMatch.PlatformId    = matchData.PlatformId;
     currentMatch.QueueType     = matchData.QueueType;
     currentMatch.Region        = matchData.Region;
     currentMatch.Season        = matchData.Season;
 }
        public static TeamMatchupResponse From(teammatchup tm)
        {
            var tmr = new TeamMatchupResponse();

            tmr.Id          = tm.id;
            tmr.Mc          = tm.matchComplete;
            tmr.TeamIds     = tm.teams.Select(x => x.id).ToList();
            tmr.WId         = tm.weekId;
            tmr.Matches     = tm.matches.Select(x => MatchResponse.From(x)).ToList();
            tmr.PlayoffType = tm.playoffType;
            tmr.MatchOrder  = tm.matchOrder;
            return(tmr);
        }
Example #15
0
        public FixtureMapperTests()
        {
            var autoFixture = new AutoFixture.Fixture();

            _competition = autoFixture.Create <Data.Models.Competition>();
            _gameweek    = autoFixture.Create <Gameweek>();
            _homeTeam    = autoFixture.Create <Data.Models.Team>();
            _awayTeam    = autoFixture.Create <Data.Models.Team>();
            _source      = autoFixture.Create <MatchResponse>();

            var mapper = new FixtureMapper(this, this, this);

            _result = mapper.MapAsync(_source).Result;
        }
Example #16
0
 public static Participant MapParticipant(MatchResponse matchData, ParticipantResponse participant, ParticipantStat stats)
 {
     return(new Participant
     {
         MatchId = matchData.MatchId,
         ChampionId = participant.ChampionId,
         HighestAchievedSeasonTier = participant.HighestAchievedSeasonTier,
         ParticipantId = participant.ParticipantId,
         ParticipantStat = stats,
         Spell1Id = participant.Spell1Id,
         Spell2Id = participant.Spell2Id,
         TeamId = participant.TeamId
     });
 }
Example #17
0
        public async Task <IHttpActionResult> GetMatchesToPredict(int tournamentId, int userId)
        {
            //usando linq para hacer
            var qry = await(from t in db.Tournaments
                            join d in db.Dates on t.TournamentId equals d.TournamentId
                            join m in db.Matches on d.DateId equals m.DateId
                            where t.TournamentId == tournamentId && m.StatusId != 3 && m.DateTime > DateTime.Now
                            select new { m }).ToListAsync();

            var predictions = await db.Predictions.Where(p => p.UserId == userId).ToListAsync();

            var matches = new List <MatchResponse>();

            foreach (var item in qry)
            {
                var matchResponse = new MatchResponse
                {
                    DateId            = item.m.DateId,
                    DateTime          = item.m.DateTime,
                    Local             = item.m.Local,
                    LocalGoals        = item.m.LocalGoals,
                    LocalId           = item.m.LocalId,
                    MatchId           = item.m.MatchId,
                    StatusId          = item.m.StatusId,
                    TournamentGroupId = item.m.TournamentGroupId,
                    Visitor           = item.m.Visitor,
                    VisitorGoals      = item.m.VisitorGoals,
                    VisitorId         = item.m.VisitorId,
                };

                var prediction = predictions.Where(p => p.MatchId == item.m.MatchId).FirstOrDefault();

                if (prediction != null)
                {
                    matchResponse.LocalGoals   = prediction.LocalGoals;
                    matchResponse.VisitorGoals = prediction.VisitorGoals;
                    matchResponse.WasPredicted = true;
                }
                //else //el boleano se asume en false
                //{
                //    matchResponse.WasPredicted = false;
                //}

                matches.Add(matchResponse);
            }

            return(Ok(matches.OrderBy(m => m.DateTime)));
        }
Example #18
0
        public async Task <IEnumerable <Fixture> > MapAsync(MatchResponse source)
        {
            var fixtures = new List <Fixture>();

            foreach (var match in source.Matches)
            {
                var fixture = await BuildFixtureAsync(match);

                if (fixture != null)
                {
                    fixtures.Add(fixture);
                }
            }

            return(fixtures);
        }
Example #19
0
        public List <MatchResponse> GetBookings(ApplicationUser user)
        {
            List <MatchResponse> matches = new List <MatchResponse>();
            Rider rider = carpoolDb.Riders.FirstOrDefault(c => c.ApplicationUserId.Equals(user.Id));

            if (rider == null)
            {
                return(matches);
            }
            List <Booking> Bookings = carpoolDb.Bookings.Where(c => c.RiderId.Equals(rider.Id)).ToList();

            foreach (Booking booking in Bookings)
            {
                Driver          driver      = carpoolDb.Drivers.FirstOrDefault(c => c.Id.Equals(booking.DriverId));
                ApplicationUser driverUser  = carpoolDb.ApplicationUsers.FirstOrDefault(c => c.Id.Equals(driver.ApplicationUserId));
                Ride            ride        = carpoolDb.Rides.FirstOrDefault(c => c.Id.Equals(booking.RideId));
                Bill            bill        = carpoolDb.Bills.FirstOrDefault(c => c.Id.Equals(booking.BillId));
                Location        Source      = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(booking.BoardingPointId));
                Location        Destination = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(booking.DropOffPointId));
                MatchResponse   match       = new MatchResponse()
                {
                    Name        = driverUser.Name,
                    Source      = Source.Name,
                    Destination = Destination.Name,
                    Date        = Convert.ToString(ride.Date),
                    Time        = ride.Time,
                    Id          = booking.Id,
                    Price       = new
                    {
                        Amount         = bill.Amount,
                        CGST           = bill.CGST,
                        SGST           = bill.SGST,
                        DriverDiscount = bill.DriverDiscount,
                        AppDiscount    = bill.AppDiscount,
                        Total          = bill.TotalAmount()
                    },
                    CancellationCharges = booking.CancellationCharges,
                    Status = Convert.ToString(booking.BookingState),
                };
                matches.Add(match);
            }
            return(matches);
        }
Example #20
0
    internal List <Match> GetMatchesForPlayer()
    {
        JSONObject obj = new JSONObject();

        obj.AddField("userid", this.Player.Id);

        MatchResponse matchResponse = new MatchResponse(connection.MakeRequest("getMatches", obj));

        if (!matchResponse.hasFailed())
        {
            var matches = matchResponse.GetMatches();
            return(matches);
        }
        else
        {
            Debug.Log("Es konnten keine Matches gefunden werden, weil ein Error aufgetaucht ist!");
            return(null);
        }
    }
Example #21
0
        public List <MatchResponse> GetRequests(ApplicationUser user)
        {
            List <MatchResponse> matches = new List <MatchResponse>();
            Rider rider = carpoolDb.Riders.FirstOrDefault(c => c.ApplicationUserId.Equals(user.Id));

            if (rider == null)
            {
                return(matches);
            }
            List <RideRequest> requests = carpoolDb.RideRequests.Where(c => c.RiderId.Equals(rider.Id)).ToList();

            foreach (RideRequest request in requests)
            {
                Driver          driver      = carpoolDb.Drivers.FirstOrDefault(c => c.Id.Equals(request.DriverId));
                ApplicationUser driverUser  = carpoolDb.ApplicationUsers.FirstOrDefault(c => c.Id.Equals(driver.ApplicationUserId));
                Ride            ride        = carpoolDb.Rides.FirstOrDefault(c => c.Id.Equals(request.RideId));
                Bill            bill        = carpoolDb.Bills.FirstOrDefault(c => c.Id.Equals(request.BillId));
                Location        Source      = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(request.BoardingPointId));
                Location        Destination = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(request.DropoffPointId));
                MatchResponse   match       = new MatchResponse()
                {
                    Name        = driverUser.Name,
                    Source      = Source.Name,
                    Destination = Destination.Name,
                    Date        = Convert.ToString(ride.Date),
                    Time        = ride.Time,
                    Id          = request.Id,
                    Price       = new
                    {
                        Amount         = bill.Amount,
                        CGST           = bill.CGST,
                        SGST           = bill.SGST,
                        DriverDiscount = bill.DriverDiscount,
                        AppDiscount    = bill.AppDiscount,
                        Total          = bill.TotalAmount()
                    },
                    Status = Convert.ToString(request.Status)
                };
                matches.Add(match);
            }
            return(matches);
        }
Example #22
0
        public List <MatchResponse> GetRides(ApplicationUser user)
        {
            List <MatchResponse> matches = new List <MatchResponse>();

            try
            {
                Driver driver = carpoolDb.Drivers.FirstOrDefault(c => c.ApplicationUserId.Equals(user.Id));
                if (driver == null)
                {
                    return(matches);
                }
                List <Ride> rides = carpoolDb.Rides.Where(c => c.DriverId.Equals(driver.Id) && c.RideState.Equals(RideState.Active)).ToList();
                foreach (Ride ride in rides)
                {
                    List <Seat>   seats       = carpoolDb.Seats.Where(c => c.RideId.Equals(ride.Id) && c.State.Equals(SeatState.Free)).ToList();
                    Location      Source      = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(ride.SourceId));
                    Location      Destination = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(ride.DestinationId));
                    MatchResponse match       = new MatchResponse()
                    {
                        Name        = user.Name,
                        Source      = Source.Name,
                        Destination = Destination.Name,
                        Date        = Convert.ToString(ride.Date),
                        Time        = ride.Time,
                        Id          = ride.Id,
                        SeatCount   = seats.Count
                    };
                    matches.Add(match);
                }
                return(matches);
            }
            catch (Exception e)
            {
                matches = null;
                return(matches);
            }
        }
        public MatchResponse getNextLocation(Int32 iCurLocation)
        {
            LocationMap loc1   = (LocationMap)arrLocationGrid[iCurLocation];
            int         iToUse = 0;
            int         Count  = 0;

            Int32 curDuration = 10000;

            foreach (Int32 duration in loc1.arrDistances)
            {
                Count = Count + 1;
                if (duration != 0 && duration < curDuration)
                {
                    curDuration = duration;
                    iToUse      = Count;
                }
            }

            MatchResponse resp = new MatchResponse();

            resp.iLocationId = iToUse;
            resp.iDuration   = curDuration;
            return(resp);
        }
Example #24
0
        //Stop Orders(STOP LIMIT, STOP MARKET) Never Comes directly here.
        //Self match allowed
        public MatchResponse MatchMyOrder(Order order)
        {
            //var stopwatch = new Stopwatch();
            //stopwatch.Start();
            var           CurrentTime = DateTime.UtcNow;
            MatchResponse response    = new MatchResponse
            {
                Pair              = order.Pair,
                UpdatedBuyOrders  = new List <Order>(),
                UpdatedSellOrders = new List <Order>(),
                NewTrades         = new List <Trade>()
            };


            if (order.Side == OrderSide.Buy)
            {
                //Cancellation Request
                if (order.Status == OrderStatus.CancellationPending && order.ID != 0)
                {
                    LinkedList <Order> gropued_list;
                    if (BuyOrdersDict.TryGetValue(order.Rate, out gropued_list))
                    {
                        var orderToBeCancelled = gropued_list.FirstOrDefault(x => x.ID == order.ID);
                        if (orderToBeCancelled != null)
                        {
                            lock (buyLock)
                            {
                                if (gropued_list.Count <= 1)
                                {
                                    BuyOrdersDict.Remove(orderToBeCancelled.Rate);
                                }
                                else
                                {
                                    gropued_list.Remove(orderToBeCancelled);
                                }
                            }
                            orderToBeCancelled.Status = OrderStatus.CancellationAccepted;
                            response.UpdatedBuyOrders.Add(orderToBeCancelled);
                        }
                    }
                    else if (Stop_BuyOrdersDict.TryGetValue(order.Rate, out gropued_list))
                    {
                        var orderToBeCancelled = gropued_list.FirstOrDefault(x => x.ID == order.ID);
                        if (orderToBeCancelled != null)
                        {
                            lock (buyLock)
                            {
                                if (gropued_list.Count <= 1)
                                {
                                    Stop_BuyOrdersDict.Remove(orderToBeCancelled.Rate);
                                }
                                else
                                {
                                    gropued_list.Remove(orderToBeCancelled);
                                }
                            }
                            orderToBeCancelled.Status = OrderStatus.CancellationAccepted;
                            response.UpdatedBuyOrders.Add(orderToBeCancelled);
                        }
                    }
                }
                else
                {
                    response.UpdatedBuyOrders.Add((Order)order.Clone());
                    while (order.PendingVolume > 0 && SellOrdersDict.Count > 0)
                    {
                        var PossibleMatches_ = SellOrdersDict.FirstOrDefault();
                        if (PossibleMatches_.Key > order.Rate && order.Type != OrderType.Market)
                        {
                            break;  //Break as No Match Found for New
                        }
                        if (order.TimeInForce == OrderTimeInForce.FOK && PossibleMatches_.Value.Sum(x => x.PendingVolume) < order.PendingVolume)
                        {
                            break;
                        }

                        var sellOrder_Node = PossibleMatches_.Value.First;

                        while (sellOrder_Node != null)
                        {
                            var next_Node = sellOrder_Node.Next;

                            var trade = new Trade(CurrentTime);

                            var sellOrder = sellOrder_Node.Value;
                            if ((sellOrder.PendingVolume * sellOrder.Rate).TruncateDecimal(deciaml_precision) < dust_size)
                            {
                                sellOrder.Status = OrderStatus.Rejected;
                                orderIndexer.Remove(sellOrder.ID);
                                response.UpdatedSellOrders.Add(sellOrder);
                                this.statistic.DustOrders++;
                            }
                            else
                            {
                                if (sellOrder.PendingVolume >= order.PendingVolume)//CompleteMatch_New/Both  PartiallyMatch None/Existing
                                {
                                    sellOrder.PendingVolume -= order.PendingVolume;
                                    if (sellOrder.PendingVolume <= 0)
                                    {
                                        sellOrder.Status = OrderStatus.FullyFilled;
                                        orderIndexer.Remove(sellOrder.ID);
                                    }
                                    else
                                    {
                                        sellOrder.Status = OrderStatus.PartiallyFilled;
                                    }
                                    sellOrder.ModifiedOn = CurrentTime;
                                    order.PendingVolume  = 0;
                                    order.Status         = OrderStatus.FullyFilled;
                                    orderIndexer.Remove(order.ID);
                                    order.ModifiedOn = CurrentTime;

                                    trade.ID            = this.getTradeID();
                                    trade.Pair          = order.Pair;
                                    trade.OrderID_Buy   = order.ID;
                                    trade.OrderID_Sell  = sellOrder.ID;
                                    trade.Side          = order.Side;
                                    trade.Rate          = sellOrder.Rate;
                                    trade.Volume        = order.Volume;
                                    trade.UserID_Buyer  = order.UserID;
                                    trade.UserID_Seller = sellOrder.UserID;
                                }
                                else //CompleteMatch_Existing  PartiallyMatch New
                                {
                                    order.PendingVolume    -= sellOrder.PendingVolume;
                                    order.Status            = OrderStatus.PartiallyFilled;
                                    order.ModifiedOn        = CurrentTime;
                                    sellOrder.PendingVolume = 0;
                                    sellOrder.Status        = OrderStatus.FullyFilled;
                                    orderIndexer.Remove(sellOrder.ID);
                                    sellOrder.ModifiedOn = CurrentTime;


                                    trade.ID            = this.getTradeID();
                                    trade.Pair          = order.Pair;
                                    trade.OrderID_Buy   = order.ID;
                                    trade.OrderID_Sell  = sellOrder.ID;
                                    trade.Side          = order.Side;
                                    trade.Rate          = sellOrder.Rate;
                                    trade.Volume        = sellOrder.Volume;
                                    trade.UserID_Buyer  = order.UserID;
                                    trade.UserID_Seller = sellOrder.UserID;
                                }
                                response.UpdatedBuyOrders.Add((Order)order.Clone());
                                response.UpdatedSellOrders.Add((Order)sellOrder.Clone());
                                response.NewTrades.Add(trade);

                                Trades.Enqueue(trade);
                                current_Market_Price = trade.Rate;
                            }

                            if (EnumHelper.getOrderStatusBool(sellOrder.Status))
                            {
                                if (PossibleMatches_.Value.Count == 1)
                                {
                                    lock (sellLock)
                                        SellOrdersDict.Remove(sellOrder.Rate);  //The Order was Only Order at the given rate;
                                    break;                                      //Break from foreach as No Pending Order at given rate
                                }
                                else
                                {
                                    lock (sellLock)
                                        PossibleMatches_.Value.Remove(sellOrder_Node);
                                }
                            }
                            this.statistic.Trades++;

                            if (order.Status == OrderStatus.FullyFilled)
                            {
                                break;  //Break as Completely Matched New
                            }
                            sellOrder_Node = next_Node;
                        }
                    }
                    if (!EnumHelper.getOrderStatusBool(order.Status))
                    {
                        if (order.Type == OrderType.Market)
                        {
                            order.Status = OrderStatus.Rejected;//Rejected or Cencelled
                            orderIndexer.Remove(order.ID);
                            response.UpdatedBuyOrders.Add(order);
                        }
                        else if (order.TimeInForce == OrderTimeInForce.IOC || order.TimeInForce == OrderTimeInForce.FOK)
                        {
                            order.Status = OrderStatus.CancellationAccepted;
                            orderIndexer.Remove(order.ID);
                            response.UpdatedBuyOrders.Add(order);
                        }
                        else
                        {
                            //lock (buyLock)
                            LinkedList <Order> orderList;
                            if (BuyOrdersDict.TryGetValue(order.Rate, out orderList))
                            {
                                lock (buyLock)
                                    orderList.AddLast(order);
                            }
                            else
                            {
                                lock (buyLock)
                                    BuyOrdersDict[order.Rate] = new LinkedList <Order>(new List <Order> {
                                        order
                                    });
                            }
                        }
                    }
                }
            }
            else if (order.Side == OrderSide.Sell)
            {
                if (order.Status == OrderStatus.CancellationPending && order.ID != 0)
                {
                    LinkedList <Order> gropued_list;
                    if (SellOrdersDict.TryGetValue(order.Rate, out gropued_list))
                    {
                        var orderToBeCancelled = gropued_list.FirstOrDefault(x => x.ID == order.ID);
                        if (orderToBeCancelled != null)
                        {
                            lock (buyLock)
                            {
                                if (gropued_list.Count <= 1)
                                {
                                    SellOrdersDict.Remove(orderToBeCancelled.Rate);
                                }
                                else
                                {
                                    gropued_list.Remove(orderToBeCancelled);
                                }
                            }
                            orderToBeCancelled.Status = OrderStatus.CancellationAccepted;
                            response.UpdatedSellOrders.Add(orderToBeCancelled);
                        }
                    }
                    else if (Stop_SellOrdersDict.TryGetValue(order.Rate, out gropued_list))
                    {
                        var orderToBeCancelled = gropued_list.FirstOrDefault(x => x.ID == order.ID);
                        if (orderToBeCancelled != null)
                        {
                            lock (buyLock)
                            {
                                if (gropued_list.Count <= 1)
                                {
                                    Stop_SellOrdersDict.Remove(orderToBeCancelled.Rate);
                                }
                                else
                                {
                                    gropued_list.Remove(orderToBeCancelled);
                                }
                            }
                            orderToBeCancelled.Status = OrderStatus.CancellationAccepted;
                            response.UpdatedSellOrders.Add(orderToBeCancelled);
                        }
                    }
                }
                else
                {
                    response.UpdatedSellOrders.Add((Order)order.Clone());

                    while (order.PendingVolume > 0 && BuyOrdersDict.Count > 0)
                    {
                        var PossibleMatches_ = BuyOrdersDict.Reverse().FirstOrDefault();
                        if (PossibleMatches_.Key < order.Rate && order.Type != OrderType.Market)
                        {
                            break;  //Break as No Match Found for New
                        }
                        if (order.TimeInForce == OrderTimeInForce.FOK && PossibleMatches_.Value.Sum(x => x.PendingVolume) < order.PendingVolume)
                        {
                            break;
                        }

                        var buyOrder_Node = PossibleMatches_.Value.First;
                        while (buyOrder_Node != null)
                        {
                            var next_Node = buyOrder_Node.Next;

                            var trade = new Trade(CurrentTime);

                            var buyOrder = buyOrder_Node.Value;
                            if ((buyOrder.PendingVolume * buyOrder.Rate).TruncateDecimal(deciaml_precision) < dust_size)
                            {
                                buyOrder.Status = OrderStatus.Rejected;
                                orderIndexer.Remove(buyOrder.ID);
                                response.UpdatedSellOrders.Add(buyOrder);
                                this.statistic.DustOrders++;
                            }
                            else
                            {
                                if (buyOrder.PendingVolume >= order.PendingVolume)//CompleteMatch_New  PartiallyMatch Existing
                                {
                                    buyOrder.PendingVolume -= order.PendingVolume;
                                    if (buyOrder.PendingVolume <= 0)
                                    {
                                        buyOrder.Status = OrderStatus.FullyFilled;
                                        orderIndexer.Remove(buyOrder.ID);
                                    }
                                    else
                                    {
                                        buyOrder.Status = OrderStatus.PartiallyFilled;
                                    }

                                    buyOrder.ModifiedOn = CurrentTime;
                                    order.PendingVolume = 0;
                                    order.Status        = OrderStatus.FullyFilled;
                                    orderIndexer.Remove(order.ID);
                                    order.ModifiedOn = CurrentTime;

                                    trade.ID            = this.getTradeID();
                                    trade.Pair          = order.Pair;
                                    trade.OrderID_Buy   = buyOrder.ID;
                                    trade.OrderID_Sell  = order.ID;
                                    trade.Side          = order.Side;
                                    trade.Rate          = buyOrder.Rate;
                                    trade.Volume        = order.Volume;
                                    trade.UserID_Buyer  = buyOrder.UserID;
                                    trade.UserID_Seller = order.UserID;
                                }
                                else //CompleteMatch_Existing  PartiallyMatch New
                                {
                                    order.PendingVolume   -= buyOrder.PendingVolume;
                                    order.Status           = OrderStatus.PartiallyFilled;
                                    order.ModifiedOn       = CurrentTime;
                                    buyOrder.PendingVolume = 0;
                                    buyOrder.Status        = OrderStatus.FullyFilled;
                                    orderIndexer.Remove(buyOrder.ID);
                                    buyOrder.ModifiedOn = CurrentTime;


                                    trade.ID            = this.getTradeID();
                                    trade.Pair          = order.Pair;
                                    trade.OrderID_Buy   = buyOrder.ID;
                                    trade.OrderID_Sell  = order.ID;
                                    trade.Side          = order.Side;
                                    trade.Rate          = buyOrder.Rate;
                                    trade.Volume        = buyOrder.Volume;
                                    trade.UserID_Buyer  = buyOrder.UserID;
                                    trade.UserID_Seller = order.UserID;
                                }

                                response.UpdatedBuyOrders.Add((Order)buyOrder.Clone());
                                response.UpdatedSellOrders.Add((Order)order.Clone());
                                response.NewTrades.Add(trade);


                                Trades.Enqueue(trade);
                                current_Market_Price = trade.Rate;
                            }
                            if (EnumHelper.getOrderStatusBool(buyOrder.Status))
                            {
                                if (PossibleMatches_.Value.Count == 1)
                                {
                                    lock (buyLock)
                                        BuyOrdersDict.Remove(buyOrder.Rate);  //The Order was Only Order at the given rate;
                                    break;                                    //Break from foreach as No Pending Order at given rate
                                }
                                else
                                {
                                    lock (buyLock)
                                        PossibleMatches_.Value.Remove(buyOrder_Node);
                                }
                            }

                            this.statistic.Trades++;
                            if (order.Status == OrderStatus.FullyFilled)
                            {
                                break;  //Break as Completely Matched New
                            }
                            buyOrder_Node = next_Node;
                        }
                    }
                    if (!EnumHelper.getOrderStatusBool(order.Status))
                    {
                        if (order.Type == OrderType.Market)
                        {
                            order.Status = OrderStatus.Rejected;//Rejected or Cencelled
                            orderIndexer.Remove(order.ID);
                            response.UpdatedSellOrders.Add(order);
                        }
                        else if (order.TimeInForce == OrderTimeInForce.IOC || order.TimeInForce == OrderTimeInForce.FOK)
                        {
                            order.Status = OrderStatus.CancellationAccepted;
                            orderIndexer.Remove(order.ID);
                            response.UpdatedSellOrders.Add(order);
                        }
                        else
                        {
                            //lock (sellLock)
                            LinkedList <Order> orderList;
                            if (SellOrdersDict.TryGetValue(order.Rate, out orderList))
                            {
                                lock (sellLock)
                                    orderList.AddLast(order);
                            }
                            else
                            {
                                lock (sellLock)
                                    SellOrdersDict[order.Rate] = new LinkedList <Order>(new List <Order> {
                                        order
                                    });
                            }
                        }
                    }
                }
            }

            MatchResponses.Enqueue(response);
            this.statistic.inc_processed();
            //stopwatch.Stop();
            //Console.WriteLine($"{order.ID} => {stopwatch.ElapsedTicks}");
            return(response);
        }
Example #25
0
        public List <MatchResponse> GetMatches(ApplicationUser user, MatchRequest model)
        {
            List <Ride>          rides   = new List <Ride>();
            List <MatchResponse> matches = new List <MatchResponse>();

            rides = carpoolDb.Rides.Where(c => c.Date.Equals(Convert.ToDateTime(model.Date)) && c.Time.Equals(model.Time) && c.RideState.Equals(RideState.Active)).ToList();
            foreach (Ride ride in rides)
            {
                string[] viaPointIds = ride.ViaPointIds.Split(',');
                for (int i = 0; i < viaPointIds.Length; i++)
                {
                    if (viaPointIds[i] == model.Source.Id)
                    {
                        for (int j = i; j < viaPointIds.Length; j++)
                        {
                            if (viaPointIds[j] == model.Destination.Id)
                            {
                                List <Seat> seats = carpoolDb.Seats.Where(c => c.RideId.Equals(ride.Id) && c.State.Equals(SeatState.Free)).ToList();
                                if (seats.Count > 0)
                                {
                                    Driver          driver    = carpoolDb.Drivers.FirstOrDefault(c => c.Id.Equals(ride.DriverId));
                                    Promotion       promotion = carpoolDb.Promotions.FirstOrDefault(c => c.Id.Equals(driver.PromotionId));
                                    ApplicationUser userMatch = carpoolDb.ApplicationUsers.FirstOrDefault(c => c.Id.Equals(driver.ApplicationUserId));
                                    if (user != userMatch)
                                    {
                                        var amount      = Math.Round(model.Distance * Constants.Price, 2, MidpointRounding.ToEven);
                                        var appDiscount = 0.0;
                                        if (model.Distance > Constants.MinimumDistance)
                                        {
                                            appDiscount = Constants.AppDiscount * amount;
                                        }
                                        var driverDiscount = 0.0;
                                        if (model.Distance > promotion.Distance)
                                        {
                                            driverDiscount = promotion.Discount * amount;
                                        }
                                        var           cgst  = (amount - driverDiscount - appDiscount) * Constants.CGST;
                                        var           sgst  = (amount - driverDiscount - appDiscount) * Constants.SGST;
                                        MatchResponse match = new MatchResponse()
                                        {
                                            Name        = userMatch.Name,
                                            Source      = model.Source.Name,
                                            Destination = model.Destination.Name,
                                            Date        = model.Date,
                                            Time        = ride.Time,
                                            Id          = ride.Id,
                                            Price       = new
                                            {
                                                Amount              = amount,
                                                CGST                = cgst,
                                                SGST                = sgst,
                                                DriverDiscount      = driverDiscount,
                                                AppDiscount         = appDiscount,
                                                CancellationCharges = 0,
                                                Total               = amount + cgst + sgst - driverDiscount - appDiscount
                                            },
                                            SeatCount = seats.Count,
                                        };
                                        matches.Add(match);
                                    }
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            return(matches);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //SETUP OUR VARIABLES
            arrMapLocations = new ArrayList();
            arrRoutes       = new ArrayList();
            arrLocationGrid = new ArrayList();


            DAL     dal          = new DAL();
            DataSet dsInspectors = dal.getAllInspectors();

            //SETUP OUR ROUTES
            foreach (DataRow dr in dsInspectors.Tables[0].Rows)
            {
                List <string> strLoc = new List <string> {
                    dr["Inspector_Home_Geolocation"].ToString()
                };

                Route_Info ri = new Route_Info();
                ri.iUserId      = Convert.ToInt32(dr["User_Id"]);
                ri.arrLocations = strLoc;
                arrRoutes.Add(ri);

                bool bAdd = true;

                foreach (string strLocation in arrMapLocations)
                {
                    if (strLocation == dr["Inspector_Home_Geolocation"].ToString())
                    {
                        bAdd = false;
                    }
                }

                if (bAdd == true)
                {
                    arrMapLocations.Add(dr["Inspector_Home_Geolocation"].ToString());
                }
            }

            //GET TODAY'S ORDERS
            DataSet dsOrders = dal.getTodaysOrders();

            //CREATE OUR 'DESTINATIONS' STRING
            String strDestinations = "";

            foreach (DataRow dr in dsOrders.Tables[0].Rows)
            {
                if (strDestinations == "")
                {
                    strDestinations = dr["Address_Geocode"].ToString();
                }
                else
                {
                    strDestinations = strDestinations + "|" + dr["Address_Geocode"].ToString();
                }
                arrMapLocations.Add(dr["Address_Geocode"].ToString());
            }

            //GET THE DISTANCE FOR ALL OF THE GEOLOCATIONS TO EACH OTHER
            int iCount = 0;

            foreach (string strLoc in arrMapLocations)
            {
                LocationMap lm = new LocationMap();
                lm.iLocationId  = iCount;
                lm.arrDistances = new List <Int32>();

                String      strURL   = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + strLoc + "&destinations=" + strDestinations + "&mode=bicycling&language=en-EN&key=AIzaSyAdK4V1d-ZqO9Bf6jFe-N0rtJd3Dd9WnPY";
                WebRequest  request  = WebRequest.Create(strURL);
                WebResponse response = request.GetResponse();
                XDocument   xdoc     = XDocument.Load(response.GetResponseStream());

                Response.Write("<br><br><br>");
                Response.Write(xdoc);
                Response.Write("<br><br><br>");

                foreach (XElement el in xdoc.Descendants("duration"))
                {
                    lm.arrDistances.Add(Convert.ToInt32(el.Element("value").Value));
                }

                arrLocationGrid.Add(lm);
                iCount = iCount + 1;
            }

            //CREATE OUR FIRST ROUTE

            //GET THE NEAREST POINT TO THE FIRST ELEMENT
            Int32 iTotalDuration   = 0;
            Int32 iCurrentLocation = 0;

            while (iTotalDuration < 36000)
            {
                MatchResponse mr = getNextLocation(iCurrentLocation);

                Response.Write(mr.iLocationId.ToString() + ":" + mr.iDuration.ToString() + "<br>");
                iCurrentLocation = mr.iLocationId;
                iTotalDuration   = iTotalDuration + mr.iDuration;
            }
        }
Example #27
0
        static async Task Main(string[] args)
        {
            const string SUBSCRIPTION_KEY = "PON AQUI TU CLAVE DE CONTENT MODERATOR";
            const string ENDPOINT         = "PON AQUI TU ENDPOINT DE CONTENT MODERATOR";
            const string IMAGEN           = "https://moderatorsampleimages.blob.core.windows.net/samples/sample1.jpg";
            const string TEXTO            = @"La direción IP deel serviDor es 176.34.21.23 (para cualquier poblema escribir al f*****g master
                                   del Administrador: [email protected] o buscarlo en Facebook)";

            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(SUBSCRIPTION_KEY))
            {
                Endpoint = ENDPOINT
            };

            /////////////////////////
            //Moderación de texto (Text-Screen)
            /////////////////////////
            Console.WriteLine("---Moderación de texto---");
            Console.WriteLine($"Texto original:{TEXTO}");

            //Creamos la lista de términos
            string listaTerminosId = await CrearListaTerminos(client);


            //Preparamos el texto para el procesado
            string textoSinSaltos = TEXTO.Replace(Environment.NewLine, " ");

            byte[]       textoBytes = Encoding.UTF8.GetBytes(textoSinSaltos);
            MemoryStream stream     = new MemoryStream(textoBytes);

            //Invocamos el método de la API para el análisis del texto
            Screen resultadoTexto = await client.TextModeration.ScreenTextAsync("text/plain", stream, "spa", true, true, listaTerminosId, false);

            //Procesamos el resultado
            //Texto autocorregido
            Console.WriteLine($"Texto autocorregido:{resultadoTexto.AutoCorrectedText}");

            //Información personal
            Console.WriteLine($"Información personal");
            if (resultadoTexto.PII != null)
            {
                foreach (Email correo in resultadoTexto.PII.Email)
                {
                    Console.WriteLine($"\tCorreo electrónico:{correo.Text}");
                }
                foreach (IPA direccionIP in resultadoTexto.PII.IPA)
                {
                    Console.WriteLine($"\tDirección IP:{direccionIP.Text}");
                }
            }

            //Términos encontrados (palabras soeces o coincidencias en una lista)
            Console.WriteLine($"Términos encontrados");
            if (resultadoTexto.Terms != null)
            {
                foreach (DetectedTerms termino in resultadoTexto.Terms)
                {
                    Console.WriteLine($"\t{termino.Term}");
                }
            }

            //Eliminamos la lista de términos
            await EliminarListaTerminos(client, listaTerminosId);

            /////////////////////////
            //Moderación de imagen (Image-Evaluate)
            /////////////////////////
            Console.WriteLine("\n---Moderación de imagen---");

            BodyModel imagenUrl = new BodyModel("URL", IMAGEN);

            //Invocamos el método de la API para el análisis de la imagen
            Evaluate resultadoImagen = await client.ImageModeration.EvaluateUrlInputAsync("application/json", imagenUrl);

            //Procesamos el resultado
            Console.WriteLine($"Contenido adultos:{resultadoImagen.IsImageAdultClassified} ({resultadoImagen.AdultClassificationScore})");
            Console.WriteLine($"Contenido sugerente:{resultadoImagen.IsImageRacyClassified} ({resultadoImagen.RacyClassificationScore})");

            /////////////////////////
            //Comprobación de imagen en lista (Image-Match)
            /////////////////////////
            Console.WriteLine("\n---Comprobación de imagen en lista---");

            //Creamos la lista de imágenes
            string listaImagenesId = await CrearListaImagenes(client);

            //Invocamos el método de la API para la coprobación de la imagen en la lista
            MatchResponse resultadoComprobacion = await client.ImageModeration.MatchUrlInputAsync("application/json", imagenUrl);

            //Procesamos el resultado
            if (resultadoComprobacion.IsMatch.Value)
            {
                foreach (Match comprobacion in resultadoComprobacion.Matches)
                {
                    Console.WriteLine($"Descripción: {comprobacion.Label} - Etiqueta:{comprobacion.Tags[0]}");
                }
            }

            //Eliminamos la lista de imágenes
            await EliminarListaImagenes(client, listaImagenesId);
        }
Example #28
0
 public object GetRideDetails(string rideId)
 {
     try
     {
         Ride            ride   = carpoolDb.Rides.FirstOrDefault(c => c.Id.Equals(rideId));
         Driver          driver = carpoolDb.Drivers.FirstOrDefault(c => c.Id.Equals(ride.DriverId));
         ApplicationUser user   = carpoolDb.ApplicationUsers.FirstOrDefault(c => c.Id.Equals(driver.ApplicationUserId));
         if (ride != null)
         {
             Location            source      = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(ride.SourceId));
             Location            destination = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(ride.DestinationId));
             List <Booking>      bookings    = carpoolDb.Bookings.Where(c => c.RideId.Equals(rideId) && c.BookingState.Equals(BookingState.Ongoing)).ToList();
             List <RideRequest>  requests    = carpoolDb.RideRequests.Where(c => c.RideId.Equals(rideId) && c.Status.Equals(RequestState.Pending)).ToList();
             List <Seat>         seats       = carpoolDb.Seats.Where(c => c.RideId.Equals(rideId) && c.State.Equals(SeatState.Free)).ToList();
             RideDetailsResponse model       = new RideDetailsResponse(
                 ride.Id,
                 user.Name,
                 source.Name,
                 destination.Name,
                 ride.Time,
                 Convert.ToString(ride.Date),
                 seats.Count(),
                 bookings.Count(),
                 requests.Count()
                 );
             List <MatchResponse> bookingsResponse = new List <MatchResponse>();
             List <MatchResponse> requestsResponse = new List <MatchResponse>();
             foreach (Booking booking in bookings)
             {
                 Location        boardingPoint = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(booking.BoardingPointId));
                 Location        dropoffPoint  = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(booking.DropOffPointId));
                 Bill            bill          = carpoolDb.Bills.FirstOrDefault(c => c.Id.Equals(booking.BillId));
                 Rider           rider         = carpoolDb.Riders.FirstOrDefault(c => c.Id.Equals(booking.RiderId));
                 ApplicationUser userBooking   = carpoolDb.ApplicationUsers.FirstOrDefault(c => c.Id.Equals(rider.ApplicationUserId));
                 MatchResponse   data          = new MatchResponse
                 {
                     Name        = userBooking.Name,
                     Source      = boardingPoint.Name,
                     Destination = dropoffPoint.Name,
                     Id          = booking.Id,
                     Price       = bill.TotalAmount()
                 };
                 bookingsResponse.Add(data);
             }
             foreach (RideRequest request in requests)
             {
                 Location        boardingPoint = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(request.BoardingPointId));
                 Location        dropoffPoint  = carpoolDb.Locations.FirstOrDefault(c => c.Id.Equals(request.DropoffPointId));
                 Bill            bill          = carpoolDb.Bills.FirstOrDefault(c => c.Id.Equals(request.BillId));
                 Rider           rider         = carpoolDb.Riders.FirstOrDefault(c => c.Id.Equals(request.RiderId));
                 ApplicationUser userBooking   = carpoolDb.ApplicationUsers.FirstOrDefault(c => c.Id.Equals(rider.ApplicationUserId));
                 MatchResponse   data          = new MatchResponse()
                 {
                     Name        = userBooking.Name,
                     Source      = boardingPoint.Name,
                     Destination = dropoffPoint.Name,
                     Id          = request.Id,
                     Price       = bill.TotalAmount()
                 };
                 requestsResponse.Add(data);
             }
             return(new { Status = 200, Ride = model, Bookings = bookingsResponse, Requests = requestsResponse });
         }
         return(null);
     }
     catch (Exception e)
     {
         return(null);
     }
 }
 public Task <IEnumerable <Data.Models.Fixture> > MapAsync(MatchResponse source)
 {
     mapperCalled = true;
     return(Task.FromResult(_expectedResult));
 }
Example #30
0
 public MatchInfoArgs(MatchResponse match)
 {
     Match = match;
 }