/// <summary>
        /// Checks the child conditions for each child parameter delegate in the given parent.
        /// </summary>
        /// <param name="param">The contract parameter that we are called from.</param>
        /// <param name="values">The values to enumerator over.</param>
        /// <param name="checkOnly">Only perform a check, don't change values.</param>
        /// <returns></returns>
        protected static BitArray CheckChildConditions(ContractParameter param, IEnumerable <T> values, ref bool conditionMet, bool checkOnly = false)
        {
            int      count   = values.Count();
            BitArray current = null;

            int paramCount = param.ParameterCount;

            for (int i = 0; i < paramCount; i++)
            {
                ParameterDelegate <T> paramDelegate = param[i] as ParameterDelegate <T>;
                if (paramDelegate != null)
                {
                    LoggingUtil.LogVerbose(paramDelegate, "Checking condition for '" + paramDelegate.title + "', conditionMet = " + conditionMet);

                    paramDelegate.InitializeBitArrays(values, current);
                    paramDelegate.SetState(values, ref conditionMet, checkOnly);

                    LoggingUtil.LogVerbose(paramDelegate, "  after, conditionMet = " + conditionMet);

                    if (paramDelegate.matchType == ParameterDelegateMatchType.FILTER)
                    {
                        current = paramDelegate.dest;
                    }
                    int newCount = GetCount(values, paramDelegate.dest);
                    switch (paramDelegate.matchType)
                    {
                    case ParameterDelegateMatchType.FILTER:
                        count = newCount;
                        break;

                    case ParameterDelegateMatchType.VALIDATE:
                        conditionMet &= newCount > 0;
                        break;

                    case ParameterDelegateMatchType.VALIDATE_ALL:
                        conditionMet &= count == newCount;
                        break;

                    case ParameterDelegateMatchType.NONE:
                        conditionMet &= newCount == 0;
                        break;
                    }
                }
            }

            return(current);
        }
        public async Task <ActionResult> AddAccount(string email, string secondEmail,
                                                    string firstName, string lastName, string phoneNumber)
        {
            try
            {
                int result = 0;

                // Prepare data
                AccountModel model = new AccountModel();
                model.Email           = email;
                model.SecondaryEmail  = secondEmail;
                model.FirstName       = firstName;
                model.LastName        = lastName;
                model.PhoneNumber     = phoneNumber;
                model.ConfirmedPerson = Int32.Parse(
                    User.Identity.Name.Split(Char.Parse(Constants.Minus))[2]);

                // Return list of dictionary words
                using (LinqDBDataContext data = new LinqDBDataContext())
                {
                    result = await model.InsertHospitalUserAsync(model);
                }

                // Check returned result
                if (result == 1)
                {
                    return(Json(new
                    {
                        result = 1.ToString() +
                                 Constants.VerticalBar + model.Email
                    }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new
                    {
                        result = 0.ToString() +
                                 Constants.VerticalBar + model.Email
                    }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception exception)
            {
                LoggingUtil.LogException(exception);
                return(RedirectToAction(Constants.SystemFailureHomeAction, Constants.ErrorController));
            }
        }
        protected void DoAwarding()
        {
            IEnumerable <ProtoCrewMember> awardees = crew.Union(kerbals.Where(k => k.pcm != null).Select(k => k.pcm));

            LoggingUtil.LogDebug(this, "Awarding {0} points to {1} crew member(s)", experience, awardees.Count());

            // Set the homeworld
            if (homeworld == null)
            {
                homeworld = FlightGlobals.Bodies.Where(cb => cb.isHomeWorld).FirstOrDefault();
            }

            foreach (ProtoCrewMember pcm in awardees.Where(pcm => pcm != null))
            {
                LoggingUtil.LogVerbose(this, "    Awarding experience to {0}", pcm.name);

                // Find existing entries
                int currentValue = 2;
                foreach (FlightLog.Entry entry in pcm.careerLog.Entries.Concat(pcm.flightLog.Entries).Where(e => e.type.Contains(SPECIAL_XP)))
                {
                    // Get the entry with the largest value
                    int entryValue = Convert.ToInt32(entry.type.Substring(SPECIAL_XP.Length, entry.type.Length - SPECIAL_XP.Length));
                    currentValue = Math.Max(currentValue, entryValue);
                }

                // Can't go above 64 special experience
                int value = Math.Min(currentValue + experience, 64);

                // Increment the entry's experience value
                string type = SPECIAL_XP + value.ToString();

                // Do the awarding
                pcm.flightLog.AddEntry(type, homeworld.name);
                if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Assigned)
                {
                    pcm.ArchiveFlightLog();
                }
                else if (awardImmediately)
                {
                    pcm.experience     += experience;
                    pcm.experienceLevel = KerbalRoster.CalculateExperienceLevel(pcm.experience);
                }
            }

            // Prevent duplicate awards
            crew.Clear();
        }
        protected void CreateDelegates()
        {
            if (ParameterCount < 1)
            {
                LoggingUtil.LogDebug(this, "Adding EVA parameter...");
                evaParam = new ParameterDelegate <MonolithParameter>("Send a Kerbal on EVA", x => CheckParameters(MonolithState.STARTED));
                AddParameter(evaParam);

                LoggingUtil.LogDebug(this, "Adding approach parameter...");
                approachParam        = new ParameterDelegate <MonolithParameter>("", x => !approachParam.hidden && CheckParameters(MonolithState.EVA));
                approachParam.hidden = true;
                AddParameter(approachParam);

                LoggingUtil.LogDebug(this, "Adding 'full of stars' parameter...");
                fullofstarsParam        = new ParameterDelegate <MonolithParameter>("...it's full of stars!", x => !fullofstarsParam.hidden && CheckParameters(MonolithState.FULL_OF_STARS_FINAL));
                fullofstarsParam.hidden = true;
                AddParameter(fullofstarsParam);
            }

            bool changeMade = false;

            if (currentState >= MonolithState.EVA)
            {
                if (approachParam.hidden)
                {
                    LoggingUtil.LogDebug(this, "Unhiding approach parameter...");
                    approachParam.SetTitle("Approach the monolith with " + candidateName);
                    changeMade           = true;
                    approachParam.hidden = false;
                }
            }

            if (currentState >= MonolithState.FULL_OF_STARS1)
            {
                if (fullofstarsParam.hidden)
                {
                    LoggingUtil.LogDebug(this, "Unhiding 'full of stars' parameter...");
                    changeMade = true;
                    fullofstarsParam.hidden = false;
                }
            }

            if (changeMade)
            {
                ContractConfigurator.ContractConfigurator.OnParameterChange.Fire(Root, this);
            }
        }
        public IActionResult Logs(DateTime date = default(DateTime))
        {
            if (!RoleHelper.UserIsAdmin(_database, User))
            {
                return(RedirectToAction("Index", "Home"));
            }

            date = date != default(DateTime) ? date : DateTime.Now;

            var viewModel = new LogsViewModel
            {
                ViewingDate = date,
                Entries     = LoggingUtil.GetLogEntries(date)
            };

            return(View(viewModel));
        }
        public async Task <ActionResult> AddDisease()
        {
            try
            {
                //Load list of specialities
                specialityList = await SpecialityUtil.LoadSpecialityAsync();

                ViewBag.SpecialityList = new SelectList(specialityList, Constants.SpecialityID, Constants.SpecialityName);

                return(PartialView(Constants.AddDiseaseAction));
            }
            catch (Exception exception)
            {
                LoggingUtil.LogException(exception);
                return(RedirectToAction(Constants.SystemFailureHomeAction, Constants.ErrorController));
            }
        }
        public async Task <ActionResult> AddFacility()
        {
            try
            {
                // Load list of service type
                facilityTypeList = await ServiceFacilityUtil.LoadFacilityTypeAsync();

                ViewBag.FacilityTypeList = new SelectList(facilityTypeList, Constants.TypeID, Constants.TypeName);

                return(PartialView(Constants.AddFacilityAction));
            }
            catch (Exception exception)
            {
                LoggingUtil.LogException(exception);
                return(RedirectToAction(Constants.SystemFailureHomeAction, Constants.ErrorController));
            }
        }
        protected new void SetState(ParameterState newState)
        {
            if (state != newState)
            {
                LoggingUtil.LogVerbose(this, "Setting state for '" + title + "', state = " + newState);
                state = newState;

                IContractParameterHost     current   = this;
                ParameterDelegateContainer container = null;
                while (container == null)
                {
                    current   = current.Parent;
                    container = current as ParameterDelegateContainer;
                }
                container.ChildChanged = true;
            }
        }
Exemple #9
0
        /// <summary>
        /// Verify the loaded assembly meets a minimum version number.
        /// </summary>
        /// <param name="name">Assembly name</param>
        /// <param name="version">Minium version</param>
        /// <param name="silent">Silent mode</param>
        /// <returns>The assembly if the version check was successful.  If not, logs and error and returns null.</returns>
        public static Assembly VerifyAssemblyVersion(string name, string version, bool silent = false)
        {
            // Logic courtesy of DMagic
            var assembly = AssemblyLoader.loadedAssemblies.SingleOrDefault(a => a.assembly.GetName().Name == name);

            if (assembly != null)
            {
                string receivedStr;

                // First try the informational version
                var ainfoV = Attribute.GetCustomAttribute(assembly.assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
                if (ainfoV != null)
                {
                    receivedStr = ainfoV.InformationalVersion;
                }
                // If that fails, use the product version
                else
                {
                    receivedStr = FileVersionInfo.GetVersionInfo(assembly.assembly.Location).ProductVersion;
                }
                // If that still fails, fall back on AssemblyVersion
                if (string.IsNullOrEmpty(receivedStr) || receivedStr == " ")
                {
                    receivedStr = assembly.assembly.GetName().Version.ToString();
                }

                System.Version expected = ParseVersion(version);
                System.Version received = ParseVersion(receivedStr);

                if (received >= expected)
                {
                    LoggingUtil.LogVerbose(typeof(ContractConfigurator), "Version check for '" + name + "' passed.  Minimum required is " + version + ", version found was " + receivedStr);
                    return(assembly.assembly);
                }
                else
                {
                    LoggingUtil.Log(silent ? LoggingUtil.LogLevel.DEBUG : LoggingUtil.LogLevel.ERROR, typeof(Version), "Version check for '" + name + "' failed!  Minimum required is " + version + ", version found was " + receivedStr);
                    return(null);
                }
            }
            else
            {
                LoggingUtil.Log(silent ? LoggingUtil.LogLevel.VERBOSE : LoggingUtil.LogLevel.ERROR, typeof(Version), "Couldn't find assembly for '" + name + "'!");
                return(null);
            }
        }
        private async Task <ActionResult> UpdateFractionStatistics()
        {
            if (!await CheckIp())
            {
                return(Json(new NoPermissionFailure()));
            }
            var fractions = await _db.Fractions.ToListAsync();

            foreach (var fraction in fractions)
            {
                await UpdateFractionStatistic(fraction.Name);
            }
            await _db.SaveChangesAsync();

            LoggingUtil.Log("Fraction statistics have been updated.");
            return(Json(new { success = true }));
        }
        public override bool Load(ConfigNode configNode)
        {
            bool valid = base.Load(configNode);

            foreach (ConfigNode handler in configNode.GetNodes("PARTS"))
            {
                _partHandlers.Add(new ChangeInventoryPartsHandler(handler));
            }

            if (!_partHandlers.Any())
            {
                valid = false;
                LoggingUtil.LogWarning(this, "Must include at least one PART node!");
            }

            return(valid);
        }
Exemple #12
0
        public string GetResultsScore(Guid id)
        {
            try
            {
                var results = Results.FirstOrDefault(r => r.ID == id);

                var passed = results.GetTestResults().Where(r => r.Passed == true);

                return(Utils.GetPercentageString(passed.Count(), results.TotalTestCount));
            }
            catch (Exception ex)
            {
                LoggingUtil.AddException(ex);

                return("error");
            }
        }
Exemple #13
0
        protected void OnStageSeparation(EventReport er)
        {
            LoggingUtil.LogVerbose(this, "OnStageSeparation");

            // We have a valid stage seperation
            if (lastPartJointTime == UnityEngine.Time.fixedTime)
            {
                foreach (Vessel v in possibleStages)
                {
                    // Add to staged list
                    staged.Add(v);

                    // Force a vessel check
                    CheckVessel(v);
                }
            }
        }
Exemple #14
0
        private async Task <ActionResult> UpdateAbilityData(string data)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return(Json(new MissingArgumentFailure()));
            }
            if (!data.TryToJson(out JsonDocument parsedAbilityData))
            {
                return(Json(new InvalidRequestFailure()));
            }
            var abilityData = parsedAbilityData.RootElement;

            try
            {
                var strategy = _db.Database.CreateExecutionStrategy();
                await strategy.ExecuteAsync(async() =>
                {
                    using var transaction = await _db.Database.BeginTransactionAsync();
                    var properties        = abilityData.EnumerateObject().Where(p => !string.IsNullOrWhiteSpace(p.Name));
                    var abilities         = await _db.GetOrCreateAsync(properties.Select(p => p.Name), a => a.Name, CreateAbility);
                    foreach (var(values, ability) in properties.Select(p => p.Value).Zip(abilities))
                    {
                        ability.UpdateValues(values);
                    }
                    await _db.SaveChangesAsync();
                    lock (_dbLock)
                    {
                        transaction.Commit();
                    }
                });

                return(Json(new { Success = true }));
            }
            catch (Exception e)
            {
                LoggingUtil.Error("Updating ability data failed");
                LoggingUtil.Error(e.ToString());
                await _fileLogger.LogToFile("update_ability_data", new Dictionary <string, object> {
                    { "exception", e.ToString() },
                    { "errorSource", e.Source },
                    { "targetSite", e.TargetSite }
                });

                return(Json(new { Success = false }));
            }
        }
Exemple #15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            LoggingUtil.Initialize();

            try
            {
                using (var serviceScope = app.ApplicationServices.CreateScope())
                {
                    var context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                    context.Database.Migrate();

                    RoleHelper.SeedAppRoles(context);
                }

                LoggingUtil.AddEntry("APP", "Application started up and applied database migrations.");
            }
            catch (Exception ex)
            {
                LoggingUtil.AddEntry("APP", $"Exception occurred applying database migrations: {ex.Message}");
            }
        }
Exemple #16
0
        public void AddPassengersToActiveVessel()
        {
            LoggingUtil.LogVerbose(this, "AddPassengersToActiveVessel");

            // Check the active vessel
            Vessel v = FlightGlobals.ActiveVessel;

            if (v == null || !HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            foreach (ProtoCrewMember crewMember in passengers.Keys.ToList())
            {
                // Find a seat for the crew
                Part part = v.parts.Find(p => p.protoModuleCrew.Count < p.CrewCapacity);

                // Add the crew member
                bool success = false;
                if (part != null)
                {
                    // Add them to the part
                    success = part.AddCrewmember(crewMember);
                    if (success)
                    {
                        crewMember.type        = ProtoCrewMember.KerbalType.Tourist;
                        passengers[crewMember] = true;
                        GameEvents.onCrewBoardVessel.Fire(new GameEvents.FromToAction <Part, Part>(part, part));
                        GameEvents.onCrewTransferred.Fire(new GameEvents.HostedFromToAction <ProtoCrewMember, Part>(crewMember, part, part));
                    }
                }

                if (!success)
                {
                    LoggingUtil.LogError(this, "Unable to add crew to vessel named '" + v.name + "'.  Perhaps there's no room?");
                    break;
                }
            }

            // This will force the crew members to appear
            v.SpawnCrew();

            // Update the parameters and force a re-check to update their state
            onPassengersLoaded.Fire();
        }
Exemple #17
0
        private async void SignInImplementation(object obj)
        {
            LoaderManager.Instance.ShowLoader();
            var result = await Task.Run(() =>
            {
                Thread.Sleep(1000);
                User currentUser;
                try
                {
                    currentUser = StationManager.Client.GetUser(_login);
                }
                catch (Exception ex)
                {
                    LoggingUtil.WriteToLog($"Sign In failed for user {_login}. Reason:{Environment.NewLine}{ex.Message}");
                    MessageBox.Show($"Sign In failed for user {_login}. Reason:{Environment.NewLine}{ex.Message}");
                    return(false);
                }
                if (currentUser == null)
                {
                    LoggingUtil.WriteToLog($"Sign In failed for user {_login}. Reason:{Environment.NewLine}User does not exist.");
                    MessageBox.Show(
                        $"Sign In failed for user {_login}. Reason:{Environment.NewLine}User does not exist.");
                    return(false);
                }
                if (!currentUser.CheckPassword(_password))
                {
                    LoggingUtil.WriteToLog($"Sign In failed for user {_login}. Reason:{Environment.NewLine}Wrong Password.");
                    MessageBox.Show($"Sign In failed for user {_login}. Reason:{Environment.NewLine}Wrong Password.");
                    return(false);
                }
                StationManager.CurrentUser      = currentUser;
                StationManager.CurrentLocalUser = new UserLocal(_login, _password);
                LoggingUtil.WriteToLog($"Sign In successful for user {_login}.");
                MessageBox.Show($"Sign In successful for user {_login}.");
                return(true);
            });

            Login    = "";
            Password = "";
            LoaderManager.Instance.HideLoader();
            if (result)
            {
                NavigationManager.Instance.Navigate(ViewType.Main);
            }
        }
        /// <summary>
        /// Whether this vessel meets the parameter condition.
        /// </summary>
        /// <param name="vessel">The vessel to check</param>
        /// <returns>Whether the vessel meets the condition</returns>
        protected override bool VesselMeetsCondition(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "Checking VesselMeetsCondition: {0}", vessel.id);

            double delta = 0.0;

            if (RP1FixedResourceConsumptionChecker.CanCheckVessel(vessel))
            {
                delta = RP1FixedResourceConsumptionChecker.Instance.Consumption(resource);
            }
            else
            {
                return(false);
            }

            LoggingUtil.LogVerbose(this, "Delta for resource {0} is: {1}", resource.name, delta);
            return(delta - minRate >= -0.001 && maxRate - delta >= -0.001);
        }
        /// <summary>
        /// Whether this vessel meets the parameter condition.
        /// </summary>
        /// <param name="vessel">The vessel to check</param>
        /// <returns>Whether the vessel meets the condition</returns>
        protected override bool VesselMeetsCondition(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "Checking VesselMeetsCondition: {0}", vessel.id);
            double antennaPower = 0.0f;

            if (vessel.connection != null)
            {
                if (antennaType == AntennaType.RELAY)
                {
                    antennaPower = vessel.connection.Comm.antennaRelay.power;
                }
                else
                {
                    antennaPower = vessel.connection.Comm.antennaTransmit.power;
                }
            }
            return(antennaPower >= minAntennaPower && antennaPower <= maxAntennaPower);
        }
        /*
         * Whether this vessel meets the parameter condition.
         */
        protected override bool VesselMeetsCondition(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "Checking VesselMeetsCondition: " + vessel.id);
            // No linq for part modules. :(
            int count = 0;

            foreach (Part p in vessel.parts)
            {
                foreach (PartModule pm in p.Modules)
                {
                    if (pm.moduleName == partModule)
                    {
                        count++;
                    }
                }
            }
            return(count >= minCount && count <= maxCount);
        }
Exemple #21
0
        protected void OnFlightReady()
        {
            LoggingUtil.LogVerbose(this, "OnFlightReady");

            // Handle late adjustments to PQS City based waypoint positions (workaround for Kopernicus bug)
            foreach (WaypointData wpData in waypoints)
            {
                if (wpData.pqsCity != null)
                {
                    LoggingUtil.LogDebug(this, "Adjusting PQS City offset coordinates for waypoint {0}", wpData.waypoint.name);

                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                    GeneratePQSCityCoordinates(wpData, body);
                    SetAltitude(wpData, body);
                    wpData.pqsCity = null;
                }
            }
        }
        public override bool Load(ConfigNode configNode)
        {
            bool valid = base.Load(configNode);

            valid &= ConfigNodeUtil.ParseValue <RadiationFieldType>(configNode, "field", x => field = x, this, RadiationFieldType.UNDEFINED, ValidateField);
            valid &= ConfigNodeUtil.ParseValue <int>(configNode, "crossings_min", x => crossings_min = x, this, -1);
            valid &= ConfigNodeUtil.ParseValue <int>(configNode, "crossings_max", x => crossings_max = x, this, -1);

            valid &= ValidateTargetBody(configNode);

            if (crossings_max > 0 && crossings_min > crossings_max)
            {
                LoggingUtil.LogError(GetType(), ErrorPrefix() + ": crossings_min must be <= crossings_max");
                valid = false;
            }

            return(valid);
        }
Exemple #23
0
        /*
         * Whether this vessel meets the parameter condition.
         */
        protected override bool VesselMeetsCondition(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "Checking VesselMeetsCondition: " + vessel.id);
            if (vessel.mainBody == targetBody && vessel.situation != Vessel.Situations.LANDED)
            {
                double inclination = vessel.orbit.inclination;

                // Inclination can momentarily be in the [0.0, 360] range before KSP adjusts it
                if (inclination > 180.0)
                {
                    inclination = 360 - inclination;
                }

                return(inclination >= minInclination && inclination <= maxInclination);
            }

            return(false);
        }
Exemple #24
0
 private async Task <ActionResult> UpdateRankings()
 {
     if (!await CheckIp())
     {
         return(Json(new NoPermissionFailure()));
     }
     try
     {
         await UpdateRanking(RankingTypes.Rating, false);
     }
     catch (Exception e)
     {
         LoggingUtil.Error("Failed to update ranking");
         LoggingUtil.Error(e.StackTrace);
         return(Json(new { success = false }));
     }
     return(Json(new { success = true }));
 }
        protected void OnScienceReceived(float science, ScienceSubject subject, ProtoVessel protoVessel)
        {
            // TODO - see if it makes sense to change to use the protovessel
            Vessel vessel = FlightGlobals.ActiveVessel;

            if (vessel == null)
            {
                return;
            }
            LoggingUtil.LogVerbose(this, "OnScienceReceived: " + subject.id + ", " + vessel.id);

            // Is it in our list, and are we looking for a transmission
            if (vesselData.ContainsKey(vessel.id) && vesselData[vessel.id].subjects.ContainsKey(subject.id) && (recoveryMethod & RecoveryMethod.Transmit) != 0)
            {
                vesselData[vessel.id].recovery = true;
                CheckVessel(vessel);
            }
        }
Exemple #26
0
        protected void LogPaginationQuery(string queryst, string queryAlias, Stopwatch watch, params object[] parameters)
        {
            //            if (!HibernateLog.IsDebugEnabled) {
            //                return;
            //            }
            var module = ContextLookuper.LookupContext().Module;

            watch.Stop();
            var ellapsed = watch.ElapsedMilliseconds;

            Task.Run(() => {
                LogicalThreadContext.Properties["ellapsed"]  = ellapsed;
                LogicalThreadContext.Properties["qualifier"] = queryAlias;
                LogicalThreadContext.Properties["username"]  = SecurityFacade.CurrentUser(false, false).Login;
                LogicalThreadContext.Properties["module"]    = module;
                HibernateLog.Info(LoggingUtil.QueryStringForLogging(queryst, null, parameters));
            });
        }
Exemple #27
0
        /// <summary>
        /// Whether this vessel meets the parameter condition.
        /// </summary>
        /// <param name="vessel">Vessel to check</param>
        /// <returns>Whether the vessel meets the parameter condition(s).</returns>
        protected override bool VesselMeetsCondition(Vessel vessel)
        {
            LoggingUtil.LogVerbose(this, "Checking VesselMeetsCondition: " + vessel.id);

            // Get all the antennae
            VesselSatellite        sat      = RTCore.Instance.Satellites[vessel.id];
            IEnumerable <IAntenna> antennas = sat != null ? sat.Antennas : new List <IAntenna>();

            // If we're a VesselParameterGroup child, only do actual state change if we're the tracked vessel
            bool checkOnly = false;

            if (Parent is VesselParameterGroup)
            {
                checkOnly = ((VesselParameterGroup)Parent).TrackedVessel != vessel;
            }

            return(ParameterDelegate <IAntenna> .CheckChildConditions(this, antennas, checkOnly));
        }
        protected virtual void OnVesselCreate(Vessel vessel)
        {
            if (IsIgnoredVesselType(vessel.vesselType) || HighLogic.LoadedScene != GameScenes.FLIGHT)
            {
                return;
            }

            LoggingUtil.LogVerbose(this, "OnVesselCreate(" + vessel.id + ")");

            // Go through the hashes to try to set the parameters for this vessel
            KeyValuePair <ParamStrength, double>?dockedInfo = null;

            foreach (uint hash in vessel.GetHashes())
            {
                if (dockedVesselInfo.ContainsKey(hash))
                {
                    if (dockedInfo == null)
                    {
                        dockedInfo = dockedVesselInfo[hash];
                    }
                    else
                    {
                        dockedInfo = dockedVesselInfo[hash].Key > dockedInfo.Value.Key ? dockedVesselInfo[hash] : dockedInfo;
                    }
                }
            }

            // Found one
            if (dockedInfo != null)
            {
                VesselInfo v = new VesselInfo(vessel.id, vessel);
                v.strength            = dockedInfo.Value.Key;
                v.completionTime      = dockedInfo.Value.Value;
                v.state               = ParameterState.Complete;
                vesselInfo[vessel.id] = v;
                LoggingUtil.LogVerbose(this, "   set state to " + v.state + " and strength to " + v.strength);
            }
            else
            {
                LoggingUtil.LogVerbose(this, "   didn't find docked sub-vessel info");
            }

            CheckVessel(vessel);
        }
Exemple #29
0
        public Dictionary <string, EntityRepository.SearchEntityResult> ResolveCollections(SlicedEntityMetadata entityMetadata, IDictionary <string, ApplicationCompositionSchema> compositionSchemas,
                                                                                           IReadOnlyList <AttributeHolder> entitiesList, PaginatedSearchRequestDto paginatedSearch = null)
        {
            if (!compositionSchemas.Any())
            {
                return(new Dictionary <string, EntityRepository.SearchEntityResult>());
            }
            var before = Stopwatch.StartNew();

            _log.DebugFormat("Init Collection Resolving for {0} Collections", String.Join(",", compositionSchemas.Keys));

            var collectionAssociations = new List <EntityAssociation>();

            foreach (var entityListAssociation in entityMetadata.ListAssociations())
            {
                if (compositionSchemas.Keys.Contains(entityListAssociation.Qualifier))
                {
                    collectionAssociations.Add(entityListAssociation);
                }
            }

            var results = new Dictionary <string, EntityRepository.SearchEntityResult>();

            var tasks = new Task[collectionAssociations.Count];
            var i     = 0;
            var ctx   = ContextLookuper.LookupContext();

            foreach (var collectionAssociation in collectionAssociations)
            {
                var association              = collectionAssociation;
                var shouldPaginate           = ShouldPaginate(compositionSchemas[association.Qualifier], paginatedSearch) && paginatedSearch != null;
                var perThreadPaginatedSearch = shouldPaginate ? (PaginatedSearchRequestDto)paginatedSearch.ShallowCopy() : null;
                //this will avoid that one thread impacts any other
                var perThreadContext = ctx.ShallowCopy();
                tasks[i++] = Task.Factory.NewThread(() => FetchAsync(entityMetadata, association, compositionSchemas, entitiesList, perThreadContext, results, perThreadPaginatedSearch));
            }
            Task.WaitAll(tasks);
            _log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "Finish Collection Resolving for {0} Collections",
                                                             String.Join(",", compositionSchemas.Keys)));


            return(results);
        }
Exemple #30
0
        public void Dispatch <T>(T eventToDispatch) where T : class
        {
            var handlers = FindHandlers <T>(eventToDispatch);

            foreach (var item in handlers)
            {
                var before = Stopwatch.StartNew();
                if (item is MultiThreadedSWEventListener <T> )
                {
                    var item1 = item;
                    var task  = Task.Factory.NewThread(() => item1.HandleEvent(eventToDispatch));
                }
                else
                {
                    item.HandleEvent(eventToDispatch);
                }
                Log.Debug(LoggingUtil.BaseDurationMessage(item.GetType() + "runned in {0} ms", before));
            }
        }