Beispiel #1
0
    public void Bind(object model_, string propertyOnModel_, Validators.IValidator validator_, bool colourNegRed_)
    {
      System.Windows.Forms.Binding binding;

      binding = new System.Windows.Forms.Binding("Text", model_, propertyOnModel_, validator_ != null, DataSourceUpdateMode.OnPropertyChanged);

      if (validator_ != null)
      {
        binding.Parse += new ConvertEventHandler(validator_.Parse);
        binding.Format += new ConvertEventHandler(validator_.Format);

        if (colourNegRed_ && validator_ is Validators.ISignChanged)
        {
          UseAppStyling = false;
          m_validator = validator_;
          ForeColor = System.Drawing.Color.Red;
          ((Validators.ISignChanged)validator_).SignChanged += handleSignChanged;
          ((Validators.ISignChanged)validator_).FireOnSignChanged();
        }
      }

      if (DataBindings["Text"] != null)
        DataBindings.Remove(DataBindings["Text"]);

      DataBindings.Add(binding);
    }
Beispiel #2
0
 private void handleSignChanged(object sender, Validators.SignChangedEventArgs e_)
 {
   if (IsDisposed)
     return;
     
   ForeColor = (e_.Sign == Sign.Negative) ? System.Drawing.Color.Red : System.Drawing.Color.Black;
 }
Beispiel #3
0
    public void Bind(object model_, string propertyOnModel_, Validators.IValidator validator_, DataSourceUpdateMode mode_=DataSourceUpdateMode.OnPropertyChanged)
    {
      var binding = new System.Windows.Forms.Binding("Text", model_, propertyOnModel_, validator_ != null,
        mode_);

      if (validator_ != null)
      {
        binding.Parse+=new ConvertEventHandler(validator_.Parse);
        binding.Format+=new ConvertEventHandler(validator_.Format);
      }

      if (DataBindings["Text"] != null)
        DataBindings.Remove(DataBindings["Text"]);
      DataBindings.Add(binding);
    }
    public void Bind(string propertyOnControl_, object model_, string propertyOnModel_, Validators.IValidator validator_)
    {
      System.Windows.Forms.Binding binding;

      binding = new System.Windows.Forms.Binding(propertyOnControl_, model_, propertyOnModel_, validator_ != null, DataSourceUpdateMode.OnPropertyChanged);

      if (validator_ != null)
      {
        binding.Parse += new ConvertEventHandler(validator_.Parse);
        binding.Format += new ConvertEventHandler(validator_.Format);
      }

      if (DataBindings[propertyOnControl_] != null)
        DataBindings.Remove(DataBindings[propertyOnControl_]);

      DataBindings.Add(binding);
    }
Beispiel #5
0
        private void PrepareSettingsHandles()
        {
            bool DevModeVisible() => Prefs.DevMode;

            PaidRerollsSetting = Settings.GetHandle("paidRerolls", "setting_paidRerolls_label".Translate(), "setting_paidRerolls_desc".Translate(), true);

            DeterministicRerollsSetting = Settings.GetHandle("deterministicRerolls", "setting_deterministicRerolls_label".Translate(), "setting_deterministicRerolls_desc".Translate(), true);

            AntiCheeseSetting = Settings.GetHandle("antiCheese", "setting_antiCheese_label".Translate(), "setting_antiCheese_desc".Translate(), true);
            AntiCheeseSetting.VisibilityPredicate = DevModeVisible;

            LogConsumedResourcesSetting = Settings.GetHandle("logConsumption", "setting_logConsumption_label".Translate(), "setting_logConsumption_desc".Translate(), false);
            LogConsumedResourcesSetting.VisibilityPredicate = DevModeVisible;

            NoVomitingSetting = Settings.GetHandle("noVomiting", "setting_noVomiting_label".Translate(), "setting_noVomiting_desc".Translate(), false);
            NoVomitingSetting.VisibilityPredicate = DevModeVisible;

            LoadingMessagesSetting = Settings.GetHandle("loadingMessages", "setting_loadingMessages_label".Translate(), "setting_loadingMessages_desc".Translate(), true);

            GeyserArrowsSetting = Settings.GetHandle("geyserArrows", "setting_geyserArrows_label".Translate(), "setting_geyserArrows_desc".Translate(), true);

            PreviewCavesSetting = Settings.GetHandle("previewCaves", "setting_previewCaves_label".Translate(), "setting_previewCaves_desc".Translate(), true);

            WidgetSizeSetting = Settings.GetHandle("widgetSize", "setting_widgetSize_label".Translate(), "setting_widgetSize_desc".Translate(), MapRerollUIController.DefaultWidgetSize, Validators.IntRangeValidator(MapRerollUIController.MinWidgetSize, MapRerollUIController.MaxWidgetSize));
            WidgetSizeSetting.SpinnerIncrement = 8;

            MapGeneratorModeSetting = Settings.GetHandle("mapGeneratorMode", "setting_mapGeneratorMode_label".Translate(), "setting_mapGeneratorMode_desc".Translate(), MapGeneratorMode.AccuratePreviews, null, "setting_mapGeneratorMode_");

            var changeSize = Settings.GetHandle <bool>("changeMapSize", "setting_changeMapSize_label".Translate(), "setting_changeMapSize_desc".Translate());

            changeSize.Unsaved      = true;
            changeSize.CustomDrawer = ChangeSizeCustomDrawer;
        }
		public Validation(Validators op, string arg, string error)
		{
			this.Operation = op;
			this.Arg = arg;
			this.ErrorMessage = error;
		}
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="validators">The validators collection to use.</param>
 /// <param name="testConfigLimits">The test configuration limits to modify.</param>
 public Visitor(Validators validators, TestConfigurationLimits testConfigLimits)
 {
     this.validators = validators;
     this.testConfigLimits = testConfigLimits;
 }
 /// <summary>
 /// Copy constructor.
 /// </summary>
 /// <param name="other">The validators collection to clone.</param>
 public Validators(Validators other)
     : this()
 {
     foreach (var m in other.map)
     {
         this.map.Add(m.Key, new List<ConfigurationValidator>(m.Value));
     }
 }
Beispiel #9
0
        public override void DefsLoaded()
        {
            base.DefsLoaded();
            Predicate <ThingDef>   isMech           = (ThingDef d) => d.race != null && d.race.IsMechanoid;
            Predicate <FactionDef> isHackingFaction = (FactionDef d) => !d.isPlayer && d != FactionDefOf.Mechanoid && d != FactionDefOf.Insect;

            allMechs        = (from td in DefDatabase <ThingDef> .AllDefs where isMech(td) select td).ToList();
            allFactionNames = (from td  in DefDatabase <FactionDef> .AllDefs
                               where isHackingFaction(td)
                               select td.defName).ToList();
            tabsHandler = Settings.GetHandle <String>("tabs", "WTH_FactionRestrictions_Label".Translate(), "WTH_FactionRestrictions_Description".Translate(), allFactionNames.First());
            tabsHandler.CustomDrawer         = rect => { return(false); };
            factionRestrictions              = Settings.GetHandle <Dict2DRecordHandler>("factionRestrictions", "", "", null);
            factionRestrictions.CustomDrawer = rect => { return(GUIDrawUtility.CustomDrawer_MatchingPawns_active(rect, factionRestrictions, allMechs, allFactionNames, tabsHandler, "WTH_FactionRestrictions_OK".Translate(), "WTH_FactionRestrictions_NOK".Translate())); };


            hackedMechChance    = Settings.GetHandle <int>("hackedMechChance", "WTH_HackedMechChance_Title".Translate(), "WTH_HackedMechChance_Description".Translate(), 60, Validators.IntRangeValidator(0, 100));
            maxHackedMechPoints = Settings.GetHandle <int>("maxHackedMechPoints", "WTH_MaxHackedMechPoints_Title".Translate(), "WTH_MaxHackedMechPoints_Description".Translate(), 50, Validators.IntRangeValidator(0, 500));
            minHackedMechPoints = Settings.GetHandle <int>("minHackedMechPoints", "WTH_MinHackedMechPoints_Title".Translate(), "WTH_MinHackedMechPoints_Description".Translate(), 0, Validators.IntRangeValidator(0, 500));

            failureChanceNothing              = Settings.GetHandle <int>("failureChanceNothing", "WTH_FailureChance_Nothing_Title".Translate(), "WTH_FailureChance_Nothing_Description".Translate(), 70);
            failureChanceCauseRaid            = Settings.GetHandle <int>("failureChanceCauseRaid", "WTH_FailureChance_CauseRaid_Title".Translate(), "WTH_FailureChance_CauseRaid_Description".Translate(), 5);
            failureChanceShootRandomDirection = Settings.GetHandle <int>("failureChanceShootRandomDirection", "WTH_FailureChance_ShootRandomDirection_Title".Translate(), "WTH_FailureChance_ShootRandomDirection_Description".Translate(), 10);
            failureChanceHealToStanding       = Settings.GetHandle <int>("failureChanceHealToStanding", "WTH_FailureChance_HealToStanding_Title".Translate(), "WTH_FailureChance_HealToStanding_Description".Translate(), 5);
            failureChanceHackPoorly           = Settings.GetHandle <int>("failureChanceHackPoorly", "WTH_FailureChance_HackPoorly_Title".Translate(), "WTH_FailureChance_HackPoorly_Description".Translate(), 10);
            maintenanceDecayEnabled           = Settings.GetHandle <bool>("maintenanceDecayEnabled", "WTH_MaintenanceDedayEnabled_Title".Translate(), "WTH_MaintenanceDedayEnabled_Description".Translate(), true);

            factionRestrictions = GetDefaultForFactionRestrictions(factionRestrictions, allMechs, allFactionNames);
            GenerateImpliedRecipeDefs();
            DefDatabase <ThingDef> .ResolveAllReferences(true);

            SetMechMarketValue();
        }
 public NegateExpression(Expression value)
     : base(DetermineResultType(Validators.NullCheck(value, "value")))
 {
     _value = value;
 }
Beispiel #11
0
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var requestType = requestDto.GetType();
            await Validators.AssertTypeValidatorsAsync(req, requestDto, requestType);

            var validator = ValidatorCache.GetValidator(req, requestType);

            if (validator == null)
            {
                return;
            }

            using (validator as IDisposable)
            {
                if (validator is IHasTypeValidators hasTypeValidators && hasTypeValidators.TypeValidators.Count > 0)
                {
                    foreach (var scriptValidator in hasTypeValidators.TypeValidators)
                    {
                        await scriptValidator.ThrowIfNotValidAsync(requestDto, req);
                    }
                }

                try
                {
                    if (req.Verb == HttpMethods.Patch)
                    {
                        // Ignore property rules for AutoCrud Patch operations with default values (which are ignored)
                        if (validator is IServiceStackValidator ssValidator && requestDto is ICrud && requestType.IsOrHasGenericInterfaceTypeOf(typeof(IPatchDb <>)))
                        {
                            var typeProperties         = TypeProperties.Get(requestType);
                            var propsWithDefaultValues = new HashSet <string>();
                            foreach (var entry in typeProperties.PropertyMap)
                            {
                                if (entry.Value.PublicGetter == null)
                                {
                                    continue;
                                }
                                var defaultValue = entry.Value.PropertyInfo.PropertyType.GetDefaultValue();
                                var propValue    = entry.Value.PublicGetter(requestDto);
                                if (propValue == null || propValue.Equals(defaultValue))
                                {
                                    propsWithDefaultValues.Add(entry.Key);
                                }
                            }
                            if (propsWithDefaultValues.Count > 0)
                            {
                                ssValidator.RemovePropertyRules(rule => propsWithDefaultValues.Contains(rule.PropertyName));
                            }
                        }
                    }

                    var validationResult = await validator.ValidateAsync(req, requestDto);

                    if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                    {
                        return;
                    }

                    if (!treatInfoAndWarningsAsErrors &&
                        (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                    {
                        return;
                    }

                    var errorResponse =
                        await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                    if (autoBatchIndex != null)
                    {
                        var responseStatus = errorResponse.GetResponseStatus();
                        if (responseStatus != null)
                        {
                            if (responseStatus.Meta == null)
                            {
                                responseStatus.Meta = new Dictionary <string, string>();
                            }
                            responseStatus.Meta[Keywords.AutoBatchIndex] = autoBatchIndex;
                        }
                    }

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(req, validationResult, errorResponse);
                    }

                    await res.WriteToResponse(req, errorResponse);
                }
                catch (Exception ex)
                {
                    var validationEx = ex.UnwrapIfSingleException();

                    var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    await res.WriteToResponse(req, errorResponse);
                }
            }
        }
Beispiel #12
0
        public CSPrice GetPrice(long dateTime)
        {
            Validators.CheckDateTime(dateTime);

            int day = DateToDay.ToDay((int)(dateTime / 1000000));
            SortedList <CSPrice> prices = GetDayPrices(day);

            CSPrice[] matched = prices.GetMatchWithEdge(prices.GetFerret(new CSPrice()
            {
                DateTime = dateTime
            })).ToArray();

            if (matched.Length == 3)
            {
                return(matched[1]);
            }

            if (matched.Length != 2)
            {
                throw null;                 // 2bs -- 同じ日時のデータは無いはず!
            }
            if (matched[0] == null)
            {
                for (int c = 1; c <= Consts.MARGIN_DAY_MAX; c++)
                {
                    prices = GetDayPrices(day - c);

                    if (1 <= prices.Count)
                    {
                        matched[0] = prices.Get(prices.Count - 1);
                        break;
                    }
                }
            }
            if (matched[1] == null)
            {
                for (int c = 1; c <= Consts.MARGIN_DAY_MAX; c++)
                {
                    prices = GetDayPrices(day + c);

                    if (1 <= prices.Count)
                    {
                        matched[0] = prices.Get(0);
                        break;
                    }
                }
            }
            matched = matched.Where(v => v != null).ToArray();

            if (matched.Length == 0)
            {
                return new CSPrice()
                       {
                           DateTime = dateTime
                       }
            }
            ;

            if (matched.Length == 1)
            {
                return(matched[0]);
            }

            long sec1 = DateTimeToSec.ToSec(matched[0].DateTime);
            long sec2 = DateTimeToSec.ToSec(dateTime);
            long sec3 = DateTimeToSec.ToSec(matched[1].DateTime);

            double rate = (sec2 - sec1) * 1.0 / (sec3 - sec1);

            return(new CSPrice()
            {
                DateTime = dateTime,
                Hig = matched[0].Hig + rate * (matched[1].Hig - matched[0].Hig),
                Low = matched[0].Low + rate * (matched[1].Low - matched[0].Low),
                Ask = matched[0].Ask + rate * (matched[1].Ask - matched[0].Ask),
                Bid = matched[0].Bid + rate * (matched[1].Bid - matched[0].Bid),
            });
        }
    }
Beispiel #13
0
        public override void OnBlockProcessingStart(Block block, ProcessingOptions options = ProcessingOptions.None)
        {
            if (block.IsGenesis)
            {
                return;
            }

            var isProducingBlock     = options.IsProducingBlock();
            var isProcessingBlock    = !isProducingBlock;
            var isInitBlock          = InitBlockNumber == block.Number;
            var notConsecutiveBlock  = block.Number - 1 > _lastProcessedBlockNumber || _lastProcessedBlockNumber == 0;
            var shouldLoadValidators = Validators == null || notConsecutiveBlock || isProducingBlock;
            var mainChainProcessing  = !ForSealing && isProcessingBlock;

            if (shouldLoadValidators)
            {
                Validators = isInitBlock || notConsecutiveBlock
                    ? LoadValidatorsFromContract(BlockTree.FindParentHeader(block.Header, BlockTreeLookupOptions.None))
                    : ValidatorStore.GetValidators();

                if (mainChainProcessing)
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info($"{(isInitBlock ? "Initial" : "Current")} contract validators ({Validators.Length}): [{string.Join<Address>(", ", Validators)}].");
                    }
                }
            }

            if (isInitBlock)
            {
                if (mainChainProcessing)
                {
                    ValidatorStore.SetValidators(InitBlockNumber, Validators);
                }

                InitiateChange(block, Validators.ToArray(), isProcessingBlock, true);
            }
            else
            {
                if (mainChainProcessing && notConsecutiveBlock)
                {
                    bool loadedValidatorsAreSameInStore = (ValidatorStore.GetValidators()?.SequenceEqual(Validators) == true);
                    if (!loadedValidatorsAreSameInStore)
                    {
                        ValidatorStore.SetValidators(_blockFinalizationManager.GetLastLevelFinalizedBy(block.ParentHash), Validators);
                    }
                }

                if (isProcessingBlock)
                {
                    bool reorganisationHappened = block.Number <= _lastProcessedBlockNumber;
                    if (reorganisationHappened)
                    {
                        var reorganisationToBlockBeforePendingValidatorsInitChange = block.Number <= CurrentPendingValidators?.BlockNumber;
                        SetPendingValidators(reorganisationToBlockBeforePendingValidatorsInitChange ? null : LoadPendingValidators(), reorganisationToBlockBeforePendingValidatorsInitChange);
                    }
                    else if (block.Number > _lastProcessedBlockNumber + 1) // blocks skipped, like fast sync
                    {
                        SetPendingValidators(TryGetInitChangeFromPastBlocks(block.ParentHash), true);
                    }
                }
                else
                {
                    // if we are not processing blocks we are not on consecutive blocks.
                    // We need to initialize pending validators from db on each block being produced.
                    SetPendingValidators(LoadPendingValidators());
                }
            }

            base.OnBlockProcessingStart(block, options);

            FinalizePendingValidatorsIfNeeded(block.Header, isProcessingBlock);

            _lastProcessedBlockNumber = block.Number;
        }
 protected override Validators.Rule InnerConfigure(Validators.Rule rule)
 {
     return rule.MaxLength(MaxLenght);
 }
 public Validators.Rule Configure(Type resourceType, Validators.Rule rule)
 {
     return rule.Required(null);
 }
 public virtual IValidationCollection AddWebsite()
 {
     Validators.Add(new PatternValidator(@"^([a-zA-Z]{3,9}:(\/){2})?([a-zA-Z0-9\.]*){1}(?::[a-zA-Z0-9]{1,4})?(?:\/[_\,\$#~\?\-\+=&;%@\.\w%]+)*(?:\/)?$"));
     return(this);
 }
 public bool Has <TValidator>() where TValidator : IValidator
 {
     return(Validators.Any(d => d is TValidator));
 }
Beispiel #18
0
 public ValidatorPredicate(Validators id, PredicatePriority priority, Func <Rule, string, bool> eval)
 {
     _id        = id;
     _evaluator = eval;
     Priority   = priority;
 }
Beispiel #19
0
 /// <summary>
 /// Adds the validator.
 /// </summary>
 /// <param name="validator">The validator.</param>
 public void AddValidator(Validators.IValidator validator)
 {
     if (validator != null) {
         this.validators.Add(validator);
     }
 }
Beispiel #20
0
 public bool IsA(Validators identifier)
 {
     return((identifier & _id) == _id);
 }
        /// <summary>
        /// Empties and refreshes the validator library. Reloads configuration from the xml file.
        /// </summary>
        public static void Refresh()
        {
            // Clear lists and set to null.
            _validators.Clear();
            _validators = null;

            _validatorLib = null;
        }
 protected virtual void ValidateLifetime(DateTime?notBefore, DateTime?expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
 => Validators.ValidateLifetime(notBefore, expires, securityToken, validationParameters);
 /// <summary>
 /// For a given payload element determines its test configuration limits.
 /// </summary>
 /// <param name="payloadElement">The payload element to check.</param>
 /// <param name="validators">The collection of validators to use.</param>
 /// <returns>The test configuration limits computed.</returns>
 public static TestConfigurationLimits GetTestConfigurationLimits(ODataPayloadElement payloadElement, Validators validators)
 {
     TestConfigurationLimits testConfigLimits = new TestConfigurationLimits();
     new Visitor(validators, testConfigLimits).Visit(payloadElement);
     return testConfigLimits;
 }
 protected virtual void ValidateAudience(IEnumerable <string> audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
 => Validators.ValidateAudience(audiences, securityToken, validationParameters);
		/// <summary>
		/// Determines whether the specified identifier is a.
		/// </summary>
		/// <param name="identifier">The identifier.</param>
		/// <returns><c>true</c> if the specified identifier is a; otherwise, <c>false</c>.</returns>
		public bool IsA(Validators identifier) { return (identifier & _id) == _id; }
 protected virtual string ValidateIssuer(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
 => Validators.ValidateIssuer(issuer, securityToken, validationParameters);
Beispiel #27
0
        private static void RunPasswordSample()
        {
            var secret = Prompt.Password("Type new password", new[] { Validators.Required(), Validators.MinLength(8) });

            Console.WriteLine("Password OK");
        }
 protected virtual void ValidateTokenReplay(DateTime?expirationTime, string securityToken, TokenValidationParameters validationParameters)
 => Validators.ValidateTokenReplay(expirationTime, securityToken, validationParameters);
Beispiel #29
0
        //
        // Main loop. This will be called each 60s and also when the settings are reloaded
        //
        private async void LoadGlucoseValue()
        {
            if (!Validators.IsUrl(this.nsURL, Default.AllowFileURIScheme))
            {
                this.showErrorMessage("The nightscout_site setting is not specifed or invalid. Please update it from the settings!");
                return;
            }

            PebbleData data = null;

            var alarmManger     = SoundAlarm.Instance;
            var now             = DateTime.Now;
            var alarmsPostponed = alarmManger.GetPostponedUntil();

            //cleanup context menu
            if (alarmsPostponed != null && alarmsPostponed < now)
            {
                this.postponedUntilFooToolStripMenuItem.Visible  =
                    this.reenableAlarmsToolStripMenuItem.Visible = false;
            }


            try
            {
                WriteDebug("Trying to refresh data");

                data = await PebbleData.GetNightscoutPebbleDataAsync(this.nsURL);


                var glucoseDate = data.LocalDate;


                this.lblLastUpdate.Text = glucoseDate.ToTimeAgo();

                //
                // even if we have glucose data, don't display them if it's considered stale
                //
                if (Default.EnableAlarms)
                {
                    var urgentTime  = now.AddMinutes(-Default.AlarmStaleDataUrgent);
                    var warningTime = now.AddMinutes(-Default.AlarmStaleDataWarning);
                    var isUrgent    = glucoseDate <= urgentTime;
                    var isWarning   = glucoseDate <= warningTime;
                    if (isUrgent || isWarning)
                    {
                        this.lblGlucoseValue.Text = "Stale";
                        this.lblDelta.Text        = "data";
                        this.notifyIcon1.Text     = "Stale data";

                        alarmManger.PlayStaleAlarm();

                        if (isUrgent)
                        {
                            setLabelsColor(Color.Red);
                        }
                        else
                        {
                            setLabelsColor(Color.Yellow);
                        }

                        return;
                    }
                }

                string arrow = data.DirectionArrow;

                //mgdl values are always reported in whole numbers
                this.lblGlucoseValue.Text = Default.GlucoseUnits == "mmol" ?
                                            $"{data.Glucose:N1} {arrow}" : $"{data.Glucose:N0} {arrow}";

                this.notifyIcon1.Text = "BG: " + this.lblGlucoseValue.Text;
                var status = GlucoseStatus.GetGlucoseStatus((decimal)data.Glucose);


                this.lblDelta.Text = data.FormattedDelta + " " + (Default.GlucoseUnits == "mmol" ? "mmol/L" : "mg/dL");



                if (Default.EnableRawGlucoseDisplay)
                {
                    this.lblRawBG.Text = $"{data.RawGlucose:N1}";
                }

                this.SetSuccessState();


                switch (status)
                {
                case GlucoseStatusEnum.UrgentHigh:
                case GlucoseStatusEnum.UrgentLow:
                    setLabelsColor(Color.Red);
                    alarmManger.PlayGlucoseAlarm();
                    break;

                case GlucoseStatusEnum.Low:
                case GlucoseStatusEnum.High:
                    setLabelsColor(Color.Yellow);
                    alarmManger.PlayGlucoseAlarm();
                    break;

                case GlucoseStatusEnum.Unknown:
                case GlucoseStatusEnum.Normal:
                default:
                    alarmManger.StopAlarm();
                    setLabelsColor(Color.Green);
                    break;
                }
            }
            catch (FileNotFoundException ex)
            {
                //will only happen during debugging, when the allow file:/// scheme is set
                this.showErrorMessage($"Could not find file '{ex.FileName}'!");
                this.SetErrorState(ex);
                return;
            }
            catch (IOException ex)
            {
                this.SetErrorState(ex);
            }
            catch (HttpRequestException ex)
            {
                this.SetErrorState(ex);
            }
            catch (JsonReaderException ex)
            {
                this.SetErrorState(ex);
            }
            catch (MissingDataException ex)
            {
                //typically happens during azure site restarts
                this.SetErrorState(ex);
            }
            catch (JsonSerializationException ex)
            {
                //typically happens during azure site restarts
                this.SetErrorState(ex);
            }
            catch (InvalidJsonDataException ex)
            {
                this.SetErrorState(ex);
                this.showErrorMessage(ex.Message);
                AppShared.SettingsFormShouldFocusAdvancedSettings = true;
                this.settingsForm.Visible = false;
                this.settingsForm.ShowDialog();
            }

            catch (Exception ex)
            {
                var msg = "An unknown error occured of type " + ex.GetType().ToString() + ": " + ex.Message;
                this.showErrorMessage(msg);
                Application.Exit();
            }

            try {
                if (Default.EnableRawGlucoseDisplay && data != null)
                {
                    this.lblRawDelta.Text = data.FormattedRawDelta;
                }
            }
            catch (InvalidJsonDataException) {
                // No data available.
                // This can happen even if raw glucose is enabled
                // as it required two data points to be available
                this.lblRawDelta.Text = "-";
            }

            //these are just for layout tests
            //this.lblGlucoseValue.Text = "+500.0";
            //this.lblRawBG.Text = "+489.5";
            //this.lblRawDelta.Text = "+50.0";
            //this.lblDelta.Text = "-50.0";
        }
 protected virtual void ValidateIssuerSecurityKey(SecurityKey securityKey, SecurityToken securityToken, TokenValidationParameters validationParameters)
 => Validators.ValidateIssuerSecurityKey(securityKey, securityToken, validationParameters);
 public virtual IValidationCollection AddRequired(string reqCondition = null)
 {
     Validators.Add(new RequiredValidator(reqCondition));
     return(this);
 }
 /// <summary>
 /// Ввалидация ввода на цифры
 /// </summary>
 internal void Validinput(KeyEventArgs e, object s)
 {
     Validators.Validinput(e, s);
 }
 public bool HasRequired()
 {
     return(Validators.Any(d => d is RequiredValidator));
 }
Beispiel #34
0
        public override void DefsLoaded()
        {
            // No need to do anything if the mod is disabled
            if (!ModIsActive)
            {
                return;
            }

            // Basic capacity values
            pawnMassCapacity = Settings.GetHandle <float>("pawnMassCapacity", "WobCapacityLimits.PawnMassCapacity.Title".Translate(), "WobCapacityLimits.PawnMassCapacity.Desc".Translate(), 35f, Validators.FloatRangeValidator(1, float.MaxValue));
            podMassCapacity  = Settings.GetHandle <float>("podMassCapacity", "WobCapacityLimits.PodMassCapacity.Title".Translate(), "WobCapacityLimits.PodMassCapacity.Desc".Translate(), 150f, Validators.FloatRangeValidator(1, float.MaxValue));
            podFuelPerTile   = Settings.GetHandle <float>("podFuelPerTile", "WobCapacityLimits.PodFuelPerTile.Title".Translate(), "WobCapacityLimits.PodFuelPerTile.Desc".Translate(), 2.25f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));

            // Stack maximum size multipliers
            mealsStack        = Settings.GetHandle <float>("mealsStack", "WobCapacityLimits.Stack.Meals.Title".Translate(), "WobCapacityLimits.Stack.Meals.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            foodStack         = Settings.GetHandle <float>("foodStack", "WobCapacityLimits.Stack.Food.Title".Translate(), "WobCapacityLimits.Stack.Food.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            animalfeedStack   = Settings.GetHandle <float>("animalfeedStack", "WobCapacityLimits.Stack.AnimalFeed.Title".Translate(), "WobCapacityLimits.Stack.AnimalFeed.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            textilesStack     = Settings.GetHandle <float>("textilesStack", "WobCapacityLimits.Stack.Textiles.Title".Translate(), "WobCapacityLimits.Stack.Textiles.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            medicineStack     = Settings.GetHandle <float>("medicineStack", "WobCapacityLimits.Stack.Medicine.Title".Translate(), "WobCapacityLimits.Stack.Medicine.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            drugsStack        = Settings.GetHandle <float>("drugsStack", "WobCapacityLimits.Stack.Drugs.Title".Translate(), "WobCapacityLimits.Stack.Drugs.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            manufacturedStack = Settings.GetHandle <float>("manufacturedStack", "WobCapacityLimits.Stack.Manufactured.Title".Translate(), "WobCapacityLimits.Stack.Manufactured.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            silverStack       = Settings.GetHandle <float>("silverStack", "WobCapacityLimits.Stack.Silver.Title".Translate(), "WobCapacityLimits.Stack.Silver.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            resourcesStack    = Settings.GetHandle <float>("resourcesStack", "WobCapacityLimits.Stack.Resources.Title".Translate(), "WobCapacityLimits.Stack.Resources.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            chunksStack       = Settings.GetHandle <float>("chunksStack", "WobCapacityLimits.Stack.Chunks.Title".Translate(), "WobCapacityLimits.Stack.Chunks.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            artifactsStack    = Settings.GetHandle <float>("artifactsStack", "WobCapacityLimits.Stack.Artifacts.Title".Translate(), "WobCapacityLimits.Stack.Artifacts.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            bodypartsStack    = Settings.GetHandle <float>("bodypartsStack", "WobCapacityLimits.Stack.BodyParts.Title".Translate(), "WobCapacityLimits.Stack.BodyParts.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));
            miscStack         = Settings.GetHandle <float>("miscStack", "WobCapacityLimits.Stack.Misc.Title".Translate(), "WobCapacityLimits.Stack.Misc.Desc".Translate(), 1.0f, Validators.FloatRangeValidator(float.Epsilon, float.MaxValue));

            // Verbose logging for debugging
            debugMode = Settings.GetHandle <bool>("debugMode", "WobCapacityLimits.DebugMode.Title".Translate(), "WobCapacityLimits.DebugMode.Desc".Translate(), false);

            stackSizes = new Dictionary <string, int>();

            // Set static values used in harmony patches
            SettingsContainer.pawnMassCapacityValue = pawnMassCapacity.Value;
            SettingsContainer.podFuelPerTileValue   = podFuelPerTile.Value;
            // Edit the pod capacity property
            EditPodMassCapacity(podMassCapacity.Value);
            // Modify stack sizes, and return the maximum stack size
            int maxStack = EditStackLimits(true);

            // Edit the pawn carry capacity to the maximum stack size
            EditPawnStackCapacity(maxStack);

            // All initialised, note on log
            Logger.Message("Loaded");
        }
Beispiel #35
0
 public void Bind(object model_, string propertyOnModel_, Validators.IValidator validator_)
 {
   Bind(model_, propertyOnModel_, validator_, false);
 }
        /// <summary>
        /// internal construct subscriber object
        /// </summary>
        /// <param name="logger">ILogger instance</param>
        /// <param name="hostConfig">rabbitMQ configuration</param>
        public RabbitMQSubscriberWorker(
            IServiceProvider serviceProvider,
            ILoggerFactory logger,
            RabbitMQConfiguration hostConfig,
            Action <Func <byte[]> > callback) : base(serviceProvider)
        {
            _logger = logger?
                      .AddConsole()
                      .AddDebug()
                      .CreateLogger <RabbitMQPublisher>()
                      ?? throw new ArgumentNullException("Logger reference is required");
            try
            {
                Validators.EnsureHostConfig(hostConfig);
                _hostConfig   = hostConfig;
                exchange      = _hostConfig.exchange;
                route         = _hostConfig.routes.FirstOrDefault() ?? throw new ArgumentNullException("route queue is missing.");
                this.callback = callback ?? throw new ArgumentNullException("Callback reference is invalid");
                var host = Helper.ExtractHostStructure(_hostConfig.hostName);
                connectionFactory = new ConnectionFactory()
                {
                    HostName            = host.hostName,
                    Port                = host.port ?? defaultMiddlewarePort,
                    UserName            = _hostConfig.userName,
                    Password            = _hostConfig.password,
                    ContinuationTimeout = TimeSpan.FromSeconds(DomainModels.System.Identifiers.TimeoutInSec)
                };
                new Function(_logger, DomainModels.System.Identifiers.RetryCount).Decorate(() =>
                {
                    connection = connectionFactory.CreateConnection();
                    channel    = connection.CreateModel();
                    channel.ExchangeDeclare(exchange: exchange, type: ExchangeType.Topic, durable: true);

                    channel.ExchangeDeclare(exchange: _hostConfig.exchange, type: ExchangeType.Topic, durable: true);
                    //TODO: in case scaling the middleware, running multiple workers simultaneously.
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
                    return(Task.CompletedTask);
                }, (ex) =>
                {
                    switch (ex)
                    {
                    case BrokerUnreachableException brokerEx:
                        return(true);

                    case ConnectFailureException connEx:
                        return(true);

                    case SocketException socketEx:
                        return(true);

                    default:
                        return(false);
                    }
                }).Wait();

                queueName = channel.QueueDeclare().QueueName;

                foreach (var bindingKey in _hostConfig.routes)
                {
                    channel.QueueBind(queue: queueName,
                                      exchange: _hostConfig.exchange,
                                      routingKey: bindingKey);
                }
                consumer = new EventingBasicConsumer(channel);

                consumer.Received += async(model, ea) =>
                {
                    await new Function(_logger, DomainModels.System.Identifiers.RetryCount).Decorate(() =>
                    {
                        if (ea.Body == null || ea.Body.Length == 0)
                        {
                            throw new TypeLoadException("Invalid message type");
                        }

                        // callback action feeding
                        callback(() => ea.Body);
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);

                        _logger.LogInformation($"[x] Event sourcing service receiving a messaged from exchange: {_hostConfig.exchange}, route :{ea.RoutingKey}.");
                        return(true);
                    }, (ex) =>
                    {
                        switch (ex)
                        {
                        case TypeLoadException typeEx:
                            return(true);

                        default:
                            return(false);
                        }
                    });
                };
                //bind event handler
                channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to initialize RabbitMQSubscriberWorker", ex);
                throw ex;
            }
        }
Beispiel #37
0
        private void ChangedSubnet(object sender, TextChangedEventArgs e)
        {
            string tag = ((TextBox)sender).Tag.ToString();

            if (oac.IsFree(tag))
            {
                string content = ((TextBox)sender).Text;
                string result  = "";
                subnetStatus = false;
                //
                if (tag == "B1")
                {
                    if (Validators.IsValidAddress(content, AddressType.SubnetmaskAddress, AddressStructure.IntegerAddress))
                    {
                        result = Converters.AddressIntToBin(content);
                        SetSlash(Converters.SubnetmaskToSlash(content));
                        subnetStatus = true;
                    }
                    else
                    {
                        result = "";
                        SetSlashEmpty();
                    }
                    if (txtSubnetmaskBinario.Text != result)
                    {
                        oac.Block("B2");
                        txtSubnetmaskBinario.Text = result;
                    }
                }
                else
                {
                    if (Validators.IsValidAddress(content, AddressType.SubnetmaskAddress, AddressStructure.BinaryAddress))
                    {
                        result = Converters.AddressBinToInt(content);
                        SetSlash(Converters.SubnetmaskToSlash(content));
                        subnetStatus = true;
                    }
                    else
                    {
                        result = "";
                        SetSlashEmpty();
                    }
                    if (txtSubnetmaskStandard.Text != result)
                    {
                        oac.Block("B1");
                        txtSubnetmaskStandard.Text = result;
                    }
                }
                SetErrorMessage();
            }

            // F
            void SetSlash(int slash)
            {
                if (comboBoxSlash.SelectedIndex != slash)
                {
                    oac.Block("B3"); comboBoxSlash.SelectedIndex = slash;
                }
            }

            void SetSlashEmpty()
            {
                SetSlash(0);
            }
        }
Beispiel #38
0
        private void SetErrorMessage()
        {
            string error = null;
            bool   fail  = false;

            try
            {
                fail = Validators.IsValidAddressNetwork(txtIndirizzoBinario.Text, txtSubnetmaskBinario.Text);
            }
            catch { }
            if (fail)
            {
            }
            else if (!addressStatus && !subnetStatus)
            {
                error = "Impostare un indirizzo di rete e una subnetmask validi";
            }
            else if (!addressStatus)
            {
                error = "L'indirizzo di rete inserito non è valido";
            }
            else if (!subnetStatus)
            {
                error = "La subnetmask inserita non è valida";
            }
            else
            {
                error = "L'indirizzo di rete non rispetta la subnetmask inserita";
            }

            //

            bool before = gridError2.Visibility == Visibility.Collapsed;

            if (error == null)
            {
                gridError2.Visibility = Visibility.Collapsed;
                if (button.Visibility == Visibility.Collapsed)
                {
                    button.Opacity    = 0.1;
                    button.Visibility = Visibility.Visible;
                    Storyboard sb = this.Resources["ButtonShow"] as Storyboard;
                    sb.Begin();
                }
            }
            else
            {
                button.Visibility     = Visibility.Collapsed;
                gridError2.Visibility = Visibility.Visible;
                //
                if (txtError.Text != error)
                {
                    txtError.Text = error;
                    Storyboard sb = this.Resources["Terremoto"] as Storyboard;
                    sb.Begin();
                }
                if (before)
                {
                    Storyboard sb = this.Resources["Terremoto"] as Storyboard;
                    sb.Begin();
                }
            }
        }
Beispiel #39
0
 public BindArgs(object model_, string propertyOnModel_, Validators.IValidator validator_)
 {
   m_model=model_;
   m_propertyOnModel_=propertyOnModel_;
   m_validator=validator_;
 }
Beispiel #40
0
        public override void DefsLoaded()
        {
            minMoodBonus = Settings.GetHandle <int>("minMoodBonus", "EasierExpectations.MinMoodBonus.Title".Translate(), "EasierExpectations.MinMoodBonus.Desc".Translate(), 0, Validators.IntRangeValidator(1, int.MaxValue));
            maxMoodBonus = Settings.GetHandle <int>("maxMoodBonus", "EasierExpectations.MaxMoodBonus.Title".Translate(), "EasierExpectations.MaxMoodBonus.Desc".Translate(), 30, Validators.IntRangeValidator(1, int.MaxValue));

            SetExpectationValues();
            LogExpectationValues();
            Logger.Message("Loaded");
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="ValidatorPredicate" /> class.
		/// </summary>
		/// <param name="id">The identifier.</param>
		/// <param name="priority">The priority.</param>
		/// <param name="eval">The eval.</param>
		public UserValidator(Validators id, PredicatePriority priority, Func<Rule, string, bool> eval) : base(id, priority, eval) {
		}
        public async Task Any(ModifyValidationRules request)
        {
            var appHost = HostContext.AssertAppHost();
            var feature = appHost.AssertPlugin <ValidationFeature>();
            await RequestUtils.AssertAccessRoleAsync(base.Request, accessRole : feature.AccessRole, authSecret : request.AuthSecret);

            var utcNow   = DateTime.UtcNow;
            var userName = (await base.GetSessionAsync()).GetUserAuthName();
            var rules    = request.SaveRules;

            if (!rules.IsEmpty())
            {
                foreach (var rule in rules)
                {
                    if (rule.Type == null)
                    {
                        throw new ArgumentNullException(nameof(rule.Type));
                    }

                    var existingType = appHost.Metadata.FindDtoType(rule.Type);
                    if (existingType == null)
                    {
                        throw new ArgumentException(@$ "{rule.Type} does not exist", nameof(rule.Type));
                    }

                    if (rule.Validator == "")
                    {
                        rule.Validator = null;
                    }
                    if (rule.Condition == "")
                    {
                        rule.Condition = null;
                    }
                    if (rule.Field == "")
                    {
                        rule.Field = null;
                    }
                    if (rule.ErrorCode == "")
                    {
                        rule.ErrorCode = null;
                    }
                    if (rule.Message == "")
                    {
                        rule.Message = null;
                    }
                    if (rule.Notes == "")
                    {
                        rule.Notes = null;
                    }

                    if (rule.Field != null && TypeProperties.Get(existingType).GetAccessor(rule.Field) == null)
                    {
                        throw new ArgumentException(@$ "{rule.Field} does not exist on {rule.Type}", nameof(rule.Field));
                    }

                    if (rule.Validator != null)
                    {
                        object validator;
                        try
                        {
                            validator = appHost.EvalExpression(rule.Validator);
                            if (validator == null)
                            {
                                throw new ArgumentException(@$ "Validator does not exist", nameof(rule.Validator));
                            }
                        }
                        catch (Exception e)
                        {
                            throw new ArgumentException(@$ "Invalid Validator: " + e.Message, nameof(rule.Validator));
                        }

                        var validators     = (validator as List <object>) ?? TypeConstants.EmptyObjectList;
                        var firstValidator = validator is IPropertyValidator pv
                            ? pv
                            : validator is ITypeValidator tv
                            ? tv
                            : validators?.FirstOrDefault() ?? validator;

                        if (rule.Field != null && !(firstValidator is IPropertyValidator && validators.All(v => v is IPropertyValidator)))
                        {
                            throw new ArgumentException(@$ "{nameof(IPropertyValidator)} is expected but was {(validators?.FirstOrDefault(v => !(v is IPropertyValidator)) ?? firstValidator).GetType().Name}", nameof(rule.Validator));
                        }

                        if (rule.Field == null && !(firstValidator is ITypeValidator && validators.All(v => v is ITypeValidator)))
                        {
                            throw new ArgumentException(@$ "{nameof(ITypeValidator)} is expected but was {(validators?.FirstOrDefault(v => !(v is IPropertyValidator)) ?? firstValidator).GetType().Name}", nameof(rule.Validator));
                        }

                        if (rule.Condition != null)
                        {
                            throw new ArgumentException(@$ "Only {nameof(rule.Validator)} or {nameof(rule.Condition)} can be specified, not both", nameof(rule.Condition));
                        }
                    }
                    else
                    {
                        if (rule.Condition == null)
                        {
                            throw new ArgumentNullException(nameof(rule.Validator), @$ "{nameof(rule.Validator)} or {nameof(rule.Condition)} is required");
                        }

                        try
                        {
                            var ast = Validators.ParseCondition(appHost.ScriptContext, rule.Condition);
                            await ast.Init().ConfigAwait();
                        }
                        catch (Exception e)
                        {
                            var useEx = e is ScriptException se ? se.InnerException ?? e : e;
                            throw new ArgumentException(useEx.Message, nameof(rule.Condition));
                        }
                    }

                    if (rule.CreatedBy == null)
                    {
                        rule.CreatedBy   = userName;
                        rule.CreatedDate = utcNow;
                    }
                    rule.ModifiedBy   = userName;
                    rule.ModifiedDate = utcNow;
                }

                await ValidationSource.SaveValidationRulesAsync(rules).ConfigAwait();
            }

            if (!request.SuspendRuleIds.IsEmpty())
            {
                var suspendRules = await ValidationSource.GetValidateRulesByIdsAsync(request.SuspendRuleIds).ConfigAwait();

                foreach (var suspendRule in suspendRules)
                {
                    suspendRule.SuspendedBy   = userName;
                    suspendRule.SuspendedDate = utcNow;
                }

                await ValidationSource.SaveValidationRulesAsync(suspendRules).ConfigAwait();
            }

            if (!request.UnsuspendRuleIds.IsEmpty())
            {
                var unsuspendRules = await ValidationSource.GetValidateRulesByIdsAsync(request.UnsuspendRuleIds).ConfigAwait();

                foreach (var unsuspendRule in unsuspendRules)
                {
                    unsuspendRule.SuspendedBy   = null;
                    unsuspendRule.SuspendedDate = null;
                }

                await ValidationSource.SaveValidationRulesAsync(unsuspendRules).ConfigAwait();
            }

            if (!request.DeleteRuleIds.IsEmpty())
            {
                await ValidationSource.DeleteValidationRulesAsync(request.DeleteRuleIds.ToArray()).ConfigAwait();
            }

            if (request.ClearCache.GetValueOrDefault())
            {
                await ValidationSource.ClearCacheAsync().ConfigAwait();
            }
        }
 protected override Validators.Rule InnerConfigure(Validators.Rule rule)
 {
     return rule.Required();
 }
Beispiel #44
0
        public override void DefsLoaded()
        {
            base.DefsLoaded();
            if (AssemblyExists("GiddyUpMechanoids"))
            {
                GiddyUpMechanoidsLoaded = true;
            }
            if (AssemblyExists("FacialStuff"))
            {
                facialStuffLoaded = true;
            }

            List <ThingDef> allAnimals = DefUtility.getAnimals();

            allAnimals = allAnimals.OrderBy(o => o.defName).ToList();

            handlingMovementImpact = Settings.GetHandle <float>("handlingMovementImpact", "GUC_HandlingMovementImpact_Title".Translate(), "GUC_HandlingMovementImpact_Description".Translate(), 1.5f, Validators.FloatRangeValidator(0f, 5f));
            accuracyPenalty        = Settings.GetHandle <int>("accuracyPenalty", "GUC_AccuracyPenalty_Title".Translate(), "GUC_AccuracyPenalty_Description".Translate(), 10, Validators.IntRangeValidator(minPercentage, maxPercentage));
            handlingAccuracyImpact = Settings.GetHandle <float>("handlingAccuracyImpact", "GUC_HandlingAccuracyImpact_Title".Translate(), "GUC_HandlingAccuracyImpact_Description".Translate(), 0.5f, Validators.FloatRangeValidator(0f, 2f));


            tabsHandler    = Settings.GetHandle <String>("tabs", "GUC_Tabs_Title".Translate(), "", "none");
            bodySizeFilter = Settings.GetHandle <float>("bodySizeFilter", "GUC_BodySizeFilter_Title".Translate(), "GUC_BodySizeFilter_Description".Translate(), 0.8f);
            animalSelecter = Settings.GetHandle <DictAnimalRecordHandler>("Animalselecter", "GUC_Animalselection_Title".Translate(), "GUC_Animalselection_Description".Translate(), null);
            drawSelecter   = Settings.GetHandle <DictAnimalRecordHandler>("drawSelecter", "GUC_Drawselection_Title".Translate(), "GUC_Drawselection_Description".Translate(), null);


            tabsHandler.CustomDrawer = rect => { return(DrawUtility.CustomDrawer_Tabs(rect, tabsHandler, tabNames)); };

            bodySizeFilter.CustomDrawer        = rect => { return(DrawUtility.CustomDrawer_Filter(rect, bodySizeFilter, false, 0, 5, highlight1)); };
            animalSelecter.CustomDrawer        = rect => { return(DrawUtility.CustomDrawer_MatchingAnimals_active(rect, animalSelecter, allAnimals, bodySizeFilter, "GUC_SizeOk".Translate(), "GUC_SizeNotOk".Translate())); };
            bodySizeFilter.VisibilityPredicate = delegate { return(tabsHandler.Value == tabNames[0]); };
            animalSelecter.VisibilityPredicate = delegate { return(tabsHandler.Value == tabNames[0]); };


            drawSelecter.CustomDrawer        = rect => { return(DrawUtility.CustomDrawer_MatchingAnimals_active(rect, drawSelecter, allAnimals, null, "GUC_DrawFront".Translate(), "GUC_DrawBack".Translate())); };
            drawSelecter.VisibilityPredicate = delegate { return(tabsHandler.Value == tabNames[1]); };


            DrawUtility.filterAnimals(ref animalSelecter, allAnimals, bodySizeFilter);
            DrawUtility.filterAnimals(ref drawSelecter, allAnimals, null);

            foreach (ThingDef td in allAnimals)
            {
                if (td.HasModExtension <DrawingOffsetPatch>())
                {
                    td.GetModExtension <DrawingOffsetPatch>().Init();
                }
            }

            foreach (BiomeDef biomeDef in DefDatabase <BiomeDef> .AllDefs)
            {
                foreach (PawnKindDef animalKind in biomeDef.AllWildAnimals)
                {
                    if (!animalsWithBiome.Contains(animalKind))
                    {
                        animalsWithBiome.Add(animalKind);
                    }
                }
            }
            foreach (PawnKindDef animalWithoutBiome in from d in DefDatabase <PawnKindDef> .AllDefs
                     where d.RaceProps.Animal && !animalsWithBiome.Contains(d)
                     select d)
            {
                animalsWithoutBiome.Add(animalWithoutBiome);
            }

            /*
             * foreach (PawnKindDef pd in DefDatabase<PawnKindDef>.AllDefs)
             * {
             *  if (pd.HasModExtension<CustomMountsPatch>())
             *  {
             *      pd.GetModExtension<CustomMountsPatch>().Init();
             *  }
             * }
             */
        }
 /// <summary>
 /// Initializes static members of the ODataPayloadElementConfigurationValidator type.
 /// </summary>
 static ODataPayloadElementConfigurationValidator()
 {
     AllValidators = new Validators();
     AllValidators.Add(NonEntityCollectionValidator, ODataPayloadElementType.PrimitiveMultiValue, ODataPayloadElementType.ComplexMultiValue);
     AllValidators.Add(StreamPropertyValidator, ODataPayloadElementType.NamedStreamInstance);
     AllValidators.Add(AssociationLinkValidator, ODataPayloadElementType.NavigationPropertyInstance);
     AllValidators.Add(SpatialValueValidator, ODataPayloadElementType.PrimitiveValue);
     AllValidators.Add(ActionAndFunctionValidator, ODataPayloadElementType.EntityInstance);
 }
Beispiel #46
0
        /// <summary>
        /// Get the reply to a question asked by end user.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="message">Text message.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        private async Task GetQuestionAnswerReplyAsync(
            ITurnContext <IMessageActivity> turnContext,
            IMessageActivity message)
        {
            string text = message.Text?.ToLower()?.Trim() ?? string.Empty;

            try
            {
                var queryResult = new QnASearchResultList();

                ResponseCardPayload payload = new ResponseCardPayload();

                if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null))
                {
                    payload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                }

                queryResult = await this.qnaServiceProvider.GenerateAnswerAsync(question : text, isTestKnowledgeBase : false, payload.PreviousQuestions?.First().Id.ToString(), payload.PreviousQuestions?.First().Questions.First()).ConfigureAwait(false);

                if (queryResult.Answers.First().Id != -1)
                {
                    var         answerData  = queryResult.Answers.First();
                    AnswerModel answerModel = new AnswerModel();

                    if (Validators.IsValidJSON(answerData.Answer))
                    {
                        answerModel = JsonConvert.DeserializeObject <AnswerModel>(answerData.Answer);
                    }

                    if (!string.IsNullOrEmpty(answerModel?.Title) || !string.IsNullOrEmpty(answerModel?.Subtitle) || !string.IsNullOrEmpty(answerModel?.ImageUrl) || !string.IsNullOrEmpty(answerModel?.RedirectionUrl))
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(MessagingExtensionQnaCard.GetEndUserRichCard(text, answerData))).ConfigureAwait(false);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, this.appBaseUri, payload))).ConfigureAwait(false);
                    }
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                // Check if knowledge base is empty and has not published yet when end user is asking a question to bot.
                if (((ErrorResponseException)ex).Response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var knowledgeBaseId = await this.configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false);

                    var hasPublished = await this.qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false);

                    // Check if knowledge base has not published yet.
                    if (!hasPublished)
                    {
                        this.logger.LogError(ex, "Error while fetching the qna pair: knowledge base may be empty or it has not published yet.");
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);

                        return;
                    }
                }

                // Throw the error at calling place, if there is any generic exception which is not caught.
                throw;
            }
        }
 /// <summary>
 /// For a given payload element returns a func which skips test configuration which are not allowed.
 /// </summary>
 /// <param name="payloadElement">The payload element to check.</param>
 /// <param name="validators">The collection of validators to use.</param>
 /// <returns>The func to use for skipping test configuration which are not allowed by that payload element.</returns>
 public static Func<TestConfiguration, bool> GetSkipTestConfiguration(ODataPayloadElement payloadElement, Validators validators)
 {
     return GetTestConfigurationLimits(payloadElement, validators).SkipTestConfiguration;
 }
Beispiel #48
0
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var requestType = requestDto.GetType();
            await Validators.AssertTypeValidatorsAsync(req, requestDto, requestType);

            var validator = ValidatorCache.GetValidator(req, requestType);

            if (validator == null)
            {
                return;
            }

            using (validator as IDisposable)
            {
                if (validator is IHasTypeValidators hasTypeValidators && hasTypeValidators.TypeValidators.Count > 0)
                {
                    foreach (var scriptValidator in hasTypeValidators.TypeValidators)
                    {
                        await scriptValidator.ThrowIfNotValidAsync(requestDto, req);
                    }
                }

                try
                {
                    var validationResult = await validator.ValidateAsync(req, requestDto);

                    if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                    {
                        return;
                    }

                    if (!treatInfoAndWarningsAsErrors &&
                        (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                    {
                        return;
                    }

                    var errorResponse =
                        await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                    if (autoBatchIndex != null)
                    {
                        var responseStatus = errorResponse.GetResponseStatus();
                        if (responseStatus != null)
                        {
                            if (responseStatus.Meta == null)
                            {
                                responseStatus.Meta = new Dictionary <string, string>();
                            }
                            responseStatus.Meta[Keywords.AutoBatchIndex] = autoBatchIndex;
                        }
                    }

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(req, validationResult, errorResponse);
                    }

                    await res.WriteToResponse(req, errorResponse);
                }
                catch (Exception ex)
                {
                    var validationEx = ex.UnwrapIfSingleException();

                    var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    await res.WriteToResponse(req, errorResponse);
                }
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="ValidatorPredicate"/> class.
		/// </summary>
		/// <param name="id">The identifier.</param>
		/// <param name="priority">The priority.</param>
		/// <param name="eval">The eval.</param>
		public ValidatorPredicate(Validators id, PredicatePriority priority, Func<Rule, string, bool> eval)
		{
			_id = id;
			_evaluator = eval;
			Priority = priority;
		}
Beispiel #50
0
        private static void RunInputSample()
        {
            var name = Prompt.Input <string>("What's your name?", validators: new[] { Validators.Required(), Validators.MinLength(3) });

            Console.WriteLine($"Hello, {name}!");
        }
 protected override Validators.Rule InnerConfigure(Validators.Rule rule)
 {
     return rule.IsInRange(Min, Max);
 }
Beispiel #52
0
 public void Bind(object model_, string propertyOnModel_, Validators.IValidator validator_)
 {
   Bind("Value",model_,propertyOnModel_,validator_);
 }