public async Task <EntityState> Update(string id, DriverResult driverResult)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                db.Entry(driverResult).State = EntityState.Modified;

                try
                {
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (db.DriverResults.Count(e => e.Id == id) == 0)
                    {
                        return(EntityState.Unchanged);
                    }
                    else
                    {
                        throw;
                    }
                }

                return(db.Entry(driverResult).State);
            }
        }
예제 #2
0
        public RaceBuilder AddDrivers(IEnumerable <SeasonDriver> drivers)
        {
            // Check if given parameters aren't null
            if (drivers is null)
            {
                throw new NullReferenceException();
            }

            foreach (var driver in drivers)
            {
                // Ensures that dropped drivers won't be added to a race by not creating a result object for them
                if (driver.Dropped)
                {
                    continue;
                }

                DriverResult driverResult = new DriverResult {
                    SeasonDriver = driver
                };
                foreach (var stint in _race.Stints)
                {
                    StintResult driverStint = new StintResult
                    {
                        StintStatus = StintStatus.Concept,
                        Number      = stint.Number
                    };
                    driverResult.StintResults.Add(driverStint);
                }
                _race.DriverResults.Add(driverResult);
            }
            return(this);
        }
        public void DriverResultDTO_Test()
        {
            // Act
            DriverResultDTO driverResultDTO  = Mapper.Map <DriverResultDTO>(driverResult);
            DriverResult    testDriverResult = Mapper.Map <DriverResult>(driverResultDTO);

            // Assert
            Assert.AreEqual(driverResult.Id, driverResultDTO.Id);
            Assert.AreEqual(driverResult.BestLapTime, driverResultDTO.BestLapTime);
            Assert.AreEqual(driverResult.CarId, driverResultDTO.CarId);
            Assert.AreEqual(driverResult.ControllerNumber, driverResultDTO.ControllerNumber);
            Assert.AreEqual(driverResult.ApplicationUserId, driverResultDTO.DriverId);
            Assert.AreEqual(driverResult.Finished, driverResultDTO.Finished);
            Assert.AreEqual(driverResult.Fuel, driverResultDTO.Fuel);
            Assert.AreEqual(driverResult.Laps, driverResultDTO.Laps);
            Assert.AreEqual(driverResult.Position, driverResultDTO.Position);
            Assert.AreEqual(driverResult.RaceSessionId, driverResultDTO.RaceSessionId);
            Assert.AreEqual(driverResult.TimeOffPace, driverResultDTO.TimeOffPace);
            Assert.AreEqual(driverResult.TotalTime, driverResultDTO.TotalTime);

            Assert.AreEqual(driverResult.Id, testDriverResult.Id);
            Assert.AreEqual(driverResult.BestLapTime, testDriverResult.BestLapTime);
            Assert.AreEqual(driverResult.CarId, testDriverResult.CarId);
            Assert.AreEqual(driverResult.ControllerNumber, testDriverResult.ControllerNumber);
            Assert.AreEqual(driverResult.ApplicationUserId, testDriverResult.ApplicationUserId);
            Assert.AreEqual(driverResult.Finished, testDriverResult.Finished);
            Assert.AreEqual(driverResult.Fuel, testDriverResult.Fuel);
            Assert.AreEqual(driverResult.Laps, testDriverResult.Laps);
            Assert.AreEqual(driverResult.Position, testDriverResult.Position);
            Assert.AreEqual(driverResult.RaceSessionId, testDriverResult.RaceSessionId);
            Assert.AreEqual(driverResult.TimeOffPace, testDriverResult.TimeOffPace);
            Assert.AreEqual(driverResult.TotalTime, testDriverResult.TotalTime);
        }
예제 #4
0
        public void TrackTraits_SetTo_DriverResult()
        {
            // Arrange
            DriverResult driverResult = new DriverResult();
            TrackTrait   trackTrait1  = new TrackTrait {
                Trait = new Trait {
                    QualyPace = 1
                }
            };
            TrackTrait trackTrait2 = new TrackTrait {
                Trait = new Trait {
                    QualyPace = 2
                }
            };
            List <TrackTrait> trackTraits = new List <TrackTrait> {
                trackTrait1, trackTrait2
            };
            Weather weather = Weather.Sunny;

            // Act
            RaceService.SetTrackTraitMods(driverResult, trackTraits, weather);
            // Assert
            int expected = 3; // QualyMod should add up all QualyPace which results in an expected of 3

            Assert.Equal(expected, driverResult.QualyMod);
        }
예제 #5
0
        public async Task <IActionResult> Return(int seasonId, int raceId)
        {
            var race = await Context.Races
                       .SingleAsync(r => r.RaceId == raceId);

            var previousRace = await Context.Races
                               .AsNoTracking()
                               .Include(r => r.DriverResults)
                               .FirstOrDefaultAsync(r => r.SeasonId == seasonId && r.Round == (race.Round - 1));

            var qualyresults = await Context.Qualification
                               .Where(q => q.RaceId == raceId)
                               .ToListAsync();

            var seasonResults = await Context.DriverResults
                                .Where(d => d.Race.SeasonId == seasonId)
                                .ToListAsync();

            var raceResults = seasonResults
                              .Where(sr => sr.RaceId == raceId)
                              .ToList();

            //Adds results from Qualification to Grid in DriverResults (Penalties may be applied here too)
            foreach (Qualification result in qualyresults)
            {
                DriverResult driver = raceResults.Single(d => d.SeasonDriverId == result.DriverId);

                result.PenaltyPosition = result.Position;
                if (previousRace != null)
                {
                    DriverResult lastDriverResult = previousRace.DriverResults.FirstOrDefault(dr => dr.SeasonDriverId == result.DriverId);
                    // Checks if a driver should get a penalty
                    SetDriverPenalty(lastDriverResult, driver, result, seasonResults);
                }
            }

            // Orders the qualifications after applying penalties to positions, then assigns the grid position to it
            int assignedPosition = 1;

            foreach (var result in qualyresults.OrderBy(q => q.PenaltyPosition))
            {
                DriverResult driver = raceResults.Single(d => d.SeasonDriverId == result.DriverId);
                if (driver == null)
                {
                    return(StatusCode(500));
                }
                driver.Grid     = assignedPosition;
                driver.Position = assignedPosition;

                assignedPosition++;
            }

            race.RaceState = RaceState.Race;
            Context.Update(race);
            Context.UpdateRange(raceResults);
            await Context.SaveChangesAsync();

            return(RedirectToAction("RaceWeekend", new { id = seasonId, raceId }));
        }
예제 #6
0
        public GlimpseDriverResult(DriverResult originalDriverResult, IGlimpseService glimpseService)
        {
            _glimpseService      = glimpseService;
            OriginalDriverResult = originalDriverResult;

            ContentField = originalDriverResult?.ContentField;
            ContentPart  = originalDriverResult?.ContentPart;
        }
예제 #7
0
        /// <summary>
        /// Parses practice or qualifying results from a result file and updates drivers with a driver result for the session.
        /// </summary>
        /// <param name="drivers">Reference to the current list of drivers.</param>
        /// <param name="table">The table containing the race results.</param>
        /// <param name="race">Reference to the current race.</param>
        private static void ParsePracQual(ref List <Driver> drivers, List <HtmlNode> table, decimal length)
        {
            //remove first row of table with column names
            table.RemoveAt(0);

            //fastest time is now last cell of first row
            TimeSpan fastTime = ParseTime(table[0].ChildNodes.Where(d => d.Name.Equals("td")).Last().InnerText.Trim(), false);
            TimeSpan prevTime = fastTime;

            foreach (var row in table)
            {
                /* get the cells in this row, which can be defined as:
                 *      cells[0] = finishing position
                 *      cells[1] = driver number
                 *      cells[2] = driver name
                 *      cells[3] = lap time
                 */
                var cells = row.ChildNodes.Where(d => d.Name.Equals("td")).Select(t => t.InnerText.Trim()).ToList();

                //note: "--" for time means that driver did not make a lap in the session, thus time is set to 0

                TimeSpan thisTime = (cells[3].Equals("--")) ? new TimeSpan() : ParseTime(cells[3], false);

                DriverResult driverResult = new DriverResult
                {
                    finish        = Convert.ToInt16(cells[0]),
                    time          = thisTime,
                    timeOffLeader = (cells[3].Equals("--")) ? new TimeSpan(): thisTime.Subtract(fastTime),
                    timeOffNext   = (cells[3].Equals("--")) ? new TimeSpan() : thisTime.Subtract(prevTime),
                    speed         = (cells[3].Equals("--")) ? 0 : (length / (decimal)thisTime.TotalMilliseconds) * 1000 * 3600
                };

                Driver driver = new Driver
                {
                    number    = cells[1],
                    firstName = cells[2][0].ToString(),
                    lastName  = cells[2].Substring(2, cells[2].Length - 2),
                    result    = driverResult
                };


                //set previous time to 0
                prevTime = (cells[3].Equals("--")) ? new TimeSpan() : thisTime;

                if (drivers.Contains(driver))
                {
                    // simply update the result if a driver already exists in the list
                    drivers.ElementAt(drivers.IndexOf(driver)).result = driverResult;
                }
                else
                {
                    drivers.Add(driver);
                }
            }

            //in case some drivers were in the roster but not in the race, remove them
            drivers = drivers.Where(d => d.result != null).ToList();
        }
예제 #8
0
        /// <summary>
        /// Parses race results from a result file and updates drivers with a driver result for the session.
        /// </summary>
        /// <param name="drivers">Reference to the current list of drivers.</param>
        /// <param name="table">The table containing the race results.</param>
        /// <param name="race">Reference to the current race.</param>
        private static void ParseRace(ref List <Driver> drivers, List <HtmlNode> table, ref Race race)
        {
            //remove first row of table with column names
            table.RemoveAt(0);

            //gets leader's cell to get their laps and avg. speed
            var cells = table[0].ChildNodes.Where(d => d.Name.Equals("td")).Select(t => t.InnerText.Trim()).ToList();

            race.laps  = Convert.ToInt16(cells[5]);
            race.speed = Convert.ToDecimal(cells[4]);

            foreach (var row in table)
            {
                /* get the cells in this row, which can be defined as:
                 *      cells[0] = finishing position
                 *      cells[1] = starting position
                 *      cells[2] = driver number
                 *      cells[3] = driver name
                 *      cells[4] = interval
                 *      cells[5] = laps completed
                 *      cells[6] = laps led
                 *      cells[7] = IGNORE
                 *      cells[8] = status
                 */
                cells = row.ChildNodes.Where(d => d.Name.Equals("td")).Select(t => t.InnerText.Trim()).ToList();

                DriverResult driverResult = new DriverResult
                {
                    finish        = Convert.ToInt16(cells[0]),
                    start         = Convert.ToInt16(cells[1]),
                    timeOffLeader = (cells[4].Contains('L')) ? new TimeSpan() : ParseTime(cells[4], true),
                    lapsDown      = (cells[4].Contains('L')) ? Convert.ToInt16(cells[4].Replace("L", String.Empty)):0,
                    laps          = Convert.ToInt16(cells[5]),
                    lapsLed       = (cells[6].Contains('*')) ? Convert.ToInt16(cells[6].Replace("*", String.Empty)) : Convert.ToInt16(cells[6]),
                    status        = cells[8]
                };

                Driver driver = new Driver
                {
                    number    = cells[2],
                    firstName = cells[3][0].ToString(),
                    lastName  = cells[3].Substring(2, cells[3].Length - 2),
                    result    = driverResult
                };

                if (drivers.Contains(driver))
                {
                    // simply update the result if a driver already exists in the list
                    drivers.ElementAt(drivers.IndexOf(driver)).result = driverResult;
                }
                else
                {
                    drivers.Add(driver);
                }
            }
            //in case some drivers were in the roster but not in the race, remove them
            drivers = drivers.Where(d => d.result != null).ToList();
        }
        public IQueryable <LapTime> GetForId(string driverResultId)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                DriverResult dr = db.DriverResults.Find(driverResultId);

                return(db.LapTimes.Where(lt => lt.DriverResultId == driverResultId));
            }
        }
            public async Task <IHttpActionResult> DeleteDriverResult(string id)
            {
                DriverResult driverResult = await repo.Delete(id);

                if (driverResult == null)
                {
                    return(NotFound());
                }

                return(Ok(Mapper.Map <DriverResultDTO>(driverResult)));
            }
        public async Task <DriverResult> Insert(DriverResult driverResult)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                driverResult.Id = string.IsNullOrEmpty(driverResult.Id) ? Guid.NewGuid().ToString() : driverResult.Id;
                driverResult    = db.DriverResults.Add(driverResult);
                await db.SaveChangesAsync();
            }

            return(driverResult);
        }
예제 #12
0
        public static void SetRubberEffect(DriverResult driverRes, Rubber rubber)
        {
            if (driverRes is null || rubber is null)
            {
                return;
            }

            driverRes.MaxRNG      += rubber.PaceMod;
            driverRes.MinRNG      += rubber.PaceMod;
            driverRes.MaxTyreWear += rubber.MaxWearMod;
            driverRes.MinTyreWear += rubber.MinWearMod;
        }
예제 #13
0
 public static void SetTeamTraitMods(DriverResult driver, IEnumerable <TeamTrait> teamTraits, Weather weather)
 {
     // Null-check, since I don't like warnings
     if (driver is null || teamTraits is null)
     {
         throw new NullReferenceException();
     }
     // Loops through all the traits the team of a driver may have and adds them to the driverresult modifiers
     foreach (var trait in teamTraits)
     {
         SetIndividualTraitMod(driver, trait.Trait, weather);
     }
 }
예제 #14
0
        public static void SetRandomStrategy(DriverResult driverRes, Strategy strategy)
        {
            if (driverRes is null || strategy is null)
            {
                throw new NullReferenceException();
            }

            var currentTyre = strategy.Tyres.Single(t => t.StintNumberApplied == 1).Tyre;

            driverRes.Strategy = strategy;
            driverRes.CurrTyre = currentTyre;
            driverRes.TyreLife = currentTyre.Pace;
        }
예제 #15
0
        /// <summary>
        /// We build a dummy content item in order to execute the drivers for a specific ContentPart and its ContentFields.
        /// This way we can process the resulting shapes one by one and set the placement to "-" (don't place) for
        /// those we don't want to show on front end editors. We need this to prevent their UpdateEditor methods to
        /// be executed.
        /// </summary>
        /// <param name="definition">The definition of the ContentType we are working on.</param>
        /// <param name="partDefinition">The definition for the part we are processing.</param>
        /// <param name="showEditor">The new value for the flag telling wheter the editor should be shown on frontend.</param>
        /// <returns>The PlacementSettings objects for the ContentPart and its ContentFields.</returns>
        private IEnumerable <PlacementSettings> GetEditorPlacement(
            ContentTypeDefinition definition, ContentPartDefinition partDefinition, bool showEditor)
        {
            var contentType = definition.Name;

            var context = BuildContext(definition);

            var placementSettings = new List <PlacementSettings>();

            var partDrivers  = _contentPartDrivers;
            var fieldDrivers = _contentFieldDrivers;

            if (partDefinition != null)   // Only drivers for the part
            {
                partDrivers = partDrivers
                              .Where(cpd => cpd.GetPartInfo()
                                     .Any(pi => pi.PartName == partDefinition.Name ||
                                          pi.PartName == "ContentPart")); // this handles metadata parts that do not have their own driver
            }

            var resultsDictionary = GetPartDriversResults(context);

            foreach (var driver in partDrivers)
            {
                DriverResult result = null;
                if (resultsDictionary.TryGetValue(driver, out result) && result != null)
                {
                    placementSettings.AddRange(ProcessEditDriverResult(result, context, contentType, showEditor));
                }
            }

            foreach (var results in GetFieldDriversResults(context).Values
                     .Where(dr => dr != null && dr.Any()))
            {
                foreach (var result in results.Where(dr => dr != null &&
                                                     dr.ContentPart != null &&
                                                     dr.ContentPart.PartDefinition.Name == partDefinition.Name))
                {
                    placementSettings.AddRange(ProcessEditDriverResult(result, context, contentType, showEditor));
                }
            }

            foreach (var placementSetting in placementSettings)
            {
                yield return(placementSetting);
            }
        }
        private DriverResult Filter(DriverResult driverResult, ContentField field)
        {
            DriverResult result             = null;
            var          combinedResult     = driverResult as CombinedResult;
            var          contentShapeResult = driverResult as ContentShapeResult;

            if (combinedResult != null)
            {
                result = combinedResult.GetResults().SingleOrDefault(x => x.ContentField != null && x.ContentField.Name == field.Name);
            }
            else if (contentShapeResult != null)
            {
                result = contentShapeResult.ContentField != null && contentShapeResult.ContentField.Name == field.Name ? contentShapeResult : driverResult;
            }

            return(result);
        }
예제 #17
0
        public static async Task <DriverResult> GetUserDetails(string url)
        {
            DriverResult objData = new DriverResult();

            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(url);
                    var result = await client.GetAsync(url);

                    var place = result.Content.ReadAsStringAsync().Result;
                    objData = JsonConvert.DeserializeObject <DriverResult>(await result.Content.ReadAsStringAsync());
                }
            }
            catch (Exception ex)
            {
            }
            return(objData);
        }
예제 #18
0
        private static void ParseRace(ref List <Driver> drivers, ref List <string> finalResults, ref decimal length)
        {
            //decimal fastTime = Convert.ToDecimal(finalResults.GetRange(0, 9)[4]);
            for (int i = 0; i < finalResults.Count - 8; i += 9)
            {
                string[] result = finalResults.GetRange(i, 9).ToArray();

                if (result[6].Contains('*'))
                {
                    result[6] = result[6].Replace("*", String.Empty);
                }
                DriverResult driverRes = new DriverResult
                {
                    finish        = Convert.ToInt16(result[0]),
                    start         = Convert.ToInt16(result[1]),
                    timeOffLeader = (result[4].Contains('L')) ? .000001m : Convert.ToDecimal(result[4]),
                    lapsDown      = (result[4].Contains('L')) ? result[4].Replace("L", String.Empty) : String.Empty,
                    laps          = Convert.ToInt16(result[5]),
                    lapsLed       = Convert.ToInt16(result[6]),
                    status        = result[8]
                };

                string[] name = result[2].Split(' ');

                Driver driver = new Driver
                {
                    number    = result[2],
                    firstName = result[3][0].ToString(),
                    lastName  = result[3].Substring(2, result[3].Length - 2),
                    result    = driverRes
                };

                if (drivers.Contains(driver))
                {
                    drivers[drivers.IndexOf(driver)].result = driverRes;
                }
            }

            //in case some drivers were in the roster but not in the race, remove them
            drivers = drivers.Where(d => d.result != null).ToList();
        }
 /// <summary>
 /// Extract the PlacementSetting objects for the shapes returned by a driver.
 /// </summary>
 /// <param name="result">The result of executing a Driver.BuildEditor method.</param>
 /// <param name="context">The execution context for the driver.</param>
 /// <param name="typeName">The name of the ContentType we are processing.</param>
 /// <returns>The PlacementSetting objects for the results of the driver.</returns>
 private IEnumerable <PlacementSettings> ProcessEditDriverResult(
     DriverResult result, BuildShapeContext context, string typeName)
 {
     if (result is CombinedResult)
     {
         foreach (var subResult in ((CombinedResult)result).GetResults())
         {
             foreach (var placement in ProcessEditDriverResult(subResult, context, typeName))
             {
                 yield return(placement);
             }
         }
     }
     else if (result is ContentShapeResult)
     {
         var part = result.ContentPart;
         if (part != null)   // sanity check: should always be true
         {
             var  typePartDefinition = part.TypePartDefinition;
             bool hidePlacement      = false;
             if (_frontEndProfileService.MayAllowPartEdit(typePartDefinition, typeName))
             {
                 var field = result.ContentField;
                 if (field != null)   // we ran a driver for a ContentField rather than a ContentPart
                 {
                     hidePlacement = !(_frontEndProfileService.MayAllowFieldEdit(field.PartFieldDefinition));
                 }
             }
             else
             {
                 // don't show anything of this part
                 hidePlacement = true;
             }
             if (hidePlacement)   // Override placement only if the part/field have to be hidden
             {
                 yield return(GetPlacement((ContentShapeResult)result, context, typeName, hidePlacement));
             }
         }
     }
 }
예제 #20
0
        private static void ParsePracticeQual(ref List <Driver> drivers, ref List <string> finalResults, ref decimal length)
        {
            decimal fastTime = Convert.ToDecimal(finalResults.GetRange(0, 4)[3]);
            decimal prevTime = fastTime;

            for (int i = 0; i < finalResults.Count - 3; i += 4)
            {
                string[]     result    = finalResults.GetRange(i, 4).ToArray();
                DriverResult driverRes = new DriverResult
                {
                    finish        = Convert.ToInt16(result[0]),
                    time          = (result[3].Equals("--")) ? 0 : Convert.ToDecimal(result[3]),
                    timeOffLeader = fastTime - Convert.ToDecimal(result[3]),
                    timeOffNext   = prevTime - Convert.ToDecimal(result[3]),
                    speed         = (length / Convert.ToDecimal(result[3])) * 3600
                };


                string[] name = result[2].Split(' ');

                Driver driver = new Driver
                {
                    number    = result[1],
                    firstName = result[2][0].ToString(),
                    lastName  = result[2].Substring(2, result[2].Length - 2),
                    result    = driverRes
                };

                prevTime = Convert.ToDecimal(result[3]);


                if (drivers.Contains(driver))
                {
                    drivers[drivers.IndexOf(driver)].result = driverRes;
                }
            }

            //in case some drivers were in the roster but not in the race, remove them
            drivers = drivers.Where(d => d.result != null).ToList();
        }
            public async Task <IHttpActionResult> PostDriverResult(DriverResultDTO driverResultDTO)
            {
                DriverResult driverResult = Mapper.Map <DriverResult>(driverResultDTO);

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

                driverResult = await repo.Insert(driverResult);

                // Remove this driver from registered drivers
                DriversRepository <Driver, DriverDTO> driversRepo = new DriversRepository <Driver, DriverDTO>();
                Driver driver = driversRepo.GetForUser(driverResult.ApplicationUserId);

                if (driver != null)
                {
                    await driversRepo.Delete(driver.Id);
                }

                return(CreatedAtRoute("DefaultApi", new { id = driverResult.Id }, Mapper.Map <DriverResultDTO>(driverResult)));
            }
예제 #22
0
        public bool ResultTest(string machine, string accession, string test, string value,
                               DateTime dt, string logicalMachine = "",
                               string interpretation = "", string linkTest = "")
        {
            var request = new RestRequest("driver-results", Method.POST);

            DriverResult result = new DriverResult();

            result.accession = accession;
            result.tests     = new List <Test> ();


            Test testResult = new Test();

            testResult.alias  = test;
            testResult.result = value;

            testResult.resultDate = new ResultDate();
            testResult.resultDate.formattedDate = dt.ToString("d");

            testResult.resultDate.formattedTime = dt.ToString("HH:mm");;
            testResult.interpretation           = interpretation;
            testResult.linkedTest        = linkTest;
            testResult.performingMachine = logicalMachine;
            result.tests.Add(testResult);

            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("X-Laas-Machine", machine);
            request.AddHeader("Accept", "application/json");
            request.RequestFormat = DataFormat.Json;
            request.AddJsonBody(result);



            IRestResponse <DriverResultRoot> response2 = client.Execute <DriverResultRoot>(request);


            return(true);
        }
예제 #23
0
 /// <summary>
 /// Extract the PlacementSetting objects for the shapes returned by a driver.
 /// </summary>
 /// <param name="result">The result of executing a Driver.BuildEditor method.</param>
 /// <param name="context">The execution context for the driver.</param>
 /// <param name="typeName">The name of the ContentType we are processing.</param>
 /// <param name="showEditor">A boolean telling whether the results being processed should appear on the frontend.</param>
 /// <returns>The PlacementSetting objects for the results of the driver.</returns>
 private IEnumerable <PlacementSettings> ProcessEditDriverResult(
     DriverResult result, BuildShapeContext context, string typeName, bool showEditor = true)
 {
     if (result is CombinedResult)
     {
         foreach (var subResult in ((CombinedResult)result).GetResults())
         {
             foreach (var placement in ProcessEditDriverResult(subResult, context, typeName, showEditor))
             {
                 yield return(placement);
             }
         }
     }
     else if (result is ContentShapeResult)
     {
         var part = result.ContentPart;
         if (part != null && !showEditor)   // sanity check: part should always be true; override placement only if the part/field have to be hidden
         {
             yield return(GetPlacement((ContentShapeResult)result, context, typeName, !showEditor));
         }
     }
 }
예제 #24
0
        private bool BuildTnetDriverLicLog(TnetDriveLicLog oldTnetDriveLicLog, DriverResult driResult, AuthDriverLicenseReq req)
        {
            string host = HttpContext.Current.Request.Url.Host;

            host = "http://images2." + host.Substring(host.IndexOf('.') + 1);
            oldTnetDriveLicLog.Name            = driResult.姓名.words;
            oldTnetDriveLicLog.Addr            = driResult.住址.words;
            oldTnetDriveLicLog.Birthday        = driResult.出生日期 == null ? "" : driResult.出生日期.words;
            oldTnetDriveLicLog.Cardimg         = req.FrontImgUrl.Replace("/images2", host);
            oldTnetDriveLicLog.CardimgAppendix = req.AppendixImgUrl.Replace("/images2", host);
            oldTnetDriveLicLog.Cardno          = driResult.证号 == null ? "" : driResult.证号.words;
            oldTnetDriveLicLog.Country         = driResult.国籍 == null ? "" : driResult.国籍.words;
            oldTnetDriveLicLog.Enddate         = driResult.至 == null ? "" : driResult.至.words;
            oldTnetDriveLicLog.VehicleType     = driResult.准驾车型 == null ? "" : driResult.准驾车型.words;
            oldTnetDriveLicLog.ValidPeriod     = driResult.效期限 == null ? "" : driResult.效期限.words;
            oldTnetDriveLicLog.Sex             = driResult.性别 == null ? "" : driResult.性别.words;
            oldTnetDriveLicLog.Nodeid          = req.Nodeid;
            oldTnetDriveLicLog.Firtdate        = driResult.初次领证日期 == null ? "" : driResult.初次领证日期.words;
            oldTnetDriveLicLog.Remarks         = "";
            oldTnetDriveLicLog.Status          = 1;
            oldTnetDriveLicLog.Fileno          = req.FileNo;
            return(true);
        }
예제 #25
0
        private IEnumerable <DriverResult> ProcessDriverResults(IEnumerable <Lap> laps)
        {
            /*
             * TODO - O SRP está sendo violado nesse método !
             * Esse método poderia ser movido para uma classe especializada em calcular resultados de
             * corridas a partir das voltas, podendo assim ser testado unitariamente.
             */
            List <DriverResult> driverResults = new List <DriverResult>();

            var lapGrouping = from l in laps
                              group l by new { l.DriverNumber, l.DriverName } into lapGroup
            select lapGroup;

            foreach (var lapGroup in lapGrouping)
            {
                DriverResult result = new DriverResult();
                result.AverageSpeed  = lapGroup.Sum(l => l.AverageSpeed) / lapGroup.Count();
                result.BestLap       = lapGroup.OrderBy(l => l.Time).First().Time;
                result.DriverName    = lapGroup.Key.DriverName;
                result.DriverNumber  = lapGroup.Key.DriverNumber;
                result.Laps          = lapGroup.Count();
                result.TotalRaceTime = lapGroup.Aggregate(TimeSpan.Zero, (current, next) => current + next.Time);
                driverResults.Add(result);
            }

            driverResults = driverResults.OrderByDescending(dr => dr.Laps).ThenBy(dr => dr.TotalRaceTime).ToList();

            //Preencher posição e gap.
            for (int i = 0; i < driverResults.Count; i++)
            {
                driverResults[i].Position = i + 1;
                driverResults[i].Gap      = i > 0 ? driverResults[i].TotalRaceTime - driverResults[i - 1].TotalRaceTime : (TimeSpan?)null;
            }

            return(driverResults);
        }
예제 #26
0
        private IEnumerable <DriverResultPlacement> ExtractPlacement(DriverResult result, BuildShapeContext context)
        {
            if (result is CombinedResult)
            {
                foreach (var subResult in ((CombinedResult)result).GetResults())
                {
                    foreach (var placement in ExtractPlacement(subResult, context))
                    {
                        yield return(placement);
                    }
                }
            }
            else if (result is ContentShapeResult)
            {
                var contentShapeResult = (ContentShapeResult)result;

                var placement = context.FindPlacement(
                    contentShapeResult.GetShapeType(),
                    contentShapeResult.GetDifferentiator(),
                    contentShapeResult.GetLocation()
                    );

                string zone     = placement.Location;
                string position = String.Empty;

                // if no placement is found, it's hidden, e.g., no placement was found for the specific ContentType/DisplayType
                if (placement.Location != null)
                {
                    var delimiterIndex = placement.Location.IndexOf(':');
                    if (delimiterIndex >= 0)
                    {
                        zone     = placement.Location.Substring(0, delimiterIndex);
                        position = placement.Location.Substring(delimiterIndex + 1);
                    }
                }

                var content = _contentManager.New(context.ContentItem.ContentType);

                dynamic itemShape = CreateItemShape("Content_Edit");
                itemShape.ContentItem = content;

                if (context is BuildDisplayContext)
                {
                    var newContext = new BuildDisplayContext(itemShape, content, "Detail", "", context.New);
                    BindPlacement(newContext, "Detail", "Content");
                    contentShapeResult.Apply(newContext);
                }
                else
                {
                    var newContext = new BuildEditorContext(itemShape, content, "", context.New);
                    BindPlacement(newContext, null, "Content");
                    contentShapeResult.Apply(newContext);
                }


                yield return(new DriverResultPlacement {
                    Shape = itemShape.Content,
                    ShapeResult = contentShapeResult,
                    PlacementSettings = new PlacementSettings {
                        ShapeType = contentShapeResult.GetShapeType(),
                        Zone = zone,
                        Position = position,
                        Differentiator = contentShapeResult.GetDifferentiator() ?? String.Empty
                    }
                });
            }
        }
예제 #27
0
 // Creates local functions to be given as a parameter to get the sum of the targeted value
 static int winSelect(DriverResult a) => a.Position == 1 ? 1 : 0;
예제 #28
0
 static int poleSelect(DriverResult a) => a.Grid == 1 ? 1 : 0;
예제 #29
0
 static int nonFinishSelect(DriverResult a) => a.Status == Status.DNF || a.Status == Status.DSQ ? 1 : 0;
예제 #30
0
 static int podiumSelect(DriverResult a) => a.Position <= 3 ? 1 : 0;