public void DoesUserAgentMatchesTheRegularExpressionValueCondition(string userAgent, string regularExpressionValue, bool expectedResult, Db database) { SetupDb(database); RuleContext ruleContext = new RuleContext(); PoorMansDeviceDetectorCondition<RuleContext> customUserAgentCondition = new PoorMansDeviceDetectorCondition<RuleContext>() { OperatorId = Constants.StringOperations.MatchesTheRegularExpression.ItemID.ToString(), Value = regularExpressionValue, UserAgent = userAgent }; var ruleStack = new RuleStack(); // act customUserAgentCondition.Evaluate(ruleContext, ruleStack); // assert ruleStack.Should().HaveCount(1); object value = ruleStack.Pop(); value.Should().Be(expectedResult); }
private void AddButton(GetChromeDataArgs args, Item libraryItem, RuleContext ruleContext, string click) { foreach (var scriptItem in libraryItem.Children.ToList()) { if (!RulesUtils.EvaluateRules(scriptItem["ShowRule"], ruleContext)) { continue; } if (scriptItem.IsPowerShellLibrary()) { AddButton(args,scriptItem,ruleContext,click); continue; } if (scriptItem.IsPowerShellScript()) { AddButtonsToChromeData(new[] { new WebEditButton { Click = string.Format(click, scriptItem.ID, scriptItem.Database.Name), Icon = scriptItem.Appearance.Icon, Tooltip = scriptItem.Name, Header = scriptItem.Name, Type = "sticky", // sticky keeps it from being hidden in the 'more' dropdown } }, args); } } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var target = (FieldGenericStepEdit)context.Target; if (!target.IsNew) { var originalFieldType = (FieldTypeInfo)context.InputPropertyValues[FieldGenericStepEdit.OriginalFieldTypeProperty]; var newFieldType = (FieldTypeInfo)context.InputPropertyValues[PrimaryProperty]; //if process published already and current type is changed then check for data loss if (originalFieldType.ColumnType != newFieldType.ColumnType) { // no data loss should be if (newFieldType.ColumnType == ColumnTypes.String && (originalFieldType.ColumnType.IsValueType() || originalFieldType.ColumnType == ColumnTypes.DateTime)) return; if ((originalFieldType.ColumnType == ColumnTypes.Reference && newFieldType.ColumnType == ColumnTypes.MultiReference) || (originalFieldType.ColumnType == ColumnTypes.MultiReference && newFieldType.ColumnType == ColumnTypes.Reference) || (originalFieldType.ColumnType == ColumnTypes.ReverseReference && newFieldType.ColumnType == ColumnTypes.ReverseMultiReference) || (originalFieldType.ColumnType == ColumnTypes.ReverseMultiReference && newFieldType.ColumnType == ColumnTypes.ReverseReference)) return; context.AddWarningResult(PrimaryProperty, string.Format("Existing data in \"{0}\" fields will be lost during conversion.", target.Name)); } } }
/// <summary> /// Invoke global device resolution rules. /// </summary> /// <returns>True if a global device resolution rule applied.</returns> protected bool RunModuleRules() { Item moduleRuleItem = Context.Database.GetItem("{143624D2-7C7F-460A-B97E-068283D646B9}"); if (moduleRuleItem == null) return false; string ruleXml = moduleRuleItem["Rule"]; if (String.IsNullOrEmpty(ruleXml) || moduleRuleItem["Disable"] == "1") return false; // parse the rule XML RuleList<RuleContext> rules = new RuleList<RuleContext> {Name = moduleRuleItem.Paths.Path}; RuleList<RuleContext> parsed = RuleFactory.ParseRules<RuleContext>( Context.Database, ruleXml); rules.AddRange(parsed.Rules); if (rules.Count < 1) return false; // invoke the rule RuleContext ruleContext = new RuleContext {Item = Context.Item}; rules.Run(ruleContext); // rule applied return ruleContext.IsAborted; }
protected override void Execute(RuleContext context) { var activityIdValue = (int)context.InputPropertyValues[PrimaryProperty]; var activityStatusProperty = this.InputProperties.Single(p => p.Name == this.StatusName); var activtyStatusValue = (ActivitySubmissionStatus)context.InputPropertyValues[activityStatusProperty]; var approvedByIdProperty = this.InputProperties.Single(p => p.Name == this.ApprovedByIdName); var approvedByIdValue = (ActivitySubmissionStatus)context.InputPropertyValues[approvedByIdProperty]; if (approvedByIdValue == 0 && (activtyStatusValue == ActivitySubmissionStatus.Unset || activtyStatusValue == ActivitySubmissionStatus.AwaitingApproval || activtyStatusValue == ActivitySubmissionStatus.Approved)) { try { var activityTask = Task.Run(() => IoC.Container.Resolve<IObjectFactory<IActivityEdit>>().FetchAsync(activityIdValue)); var activity = activityTask.Result; context.AddOutValue(activityStatusProperty, activity.RequiresApproval ? ActivitySubmissionStatus.AwaitingApproval : ActivitySubmissionStatus.Approved); } catch (Exception) { context.AddErrorResult(PrimaryProperty, string.Format(CultureInfo.CurrentCulture, "Activity id {0} was not able to be retrieved.", activityIdValue)); } } }
public void MinHourDifferenceIsAtLeastAnHour() { var startTimeProperty = new Mock<IPropertyInfo>(); startTimeProperty.Setup(s => s.Name).Returns("StartTime"); startTimeProperty.Setup(s => s.Type).Returns(typeof(DateTime)); var endTimeProperty = new Mock<IPropertyInfo>(); endTimeProperty.Setup(s => s.Name).Returns("endTime"); endTimeProperty.Setup(s => s.Type).Returns(typeof(DateTime)); var wsMock = new Mock<IWorkSchedule>(); wsMock.SetupProperty<DateTime>(ws => ws.StartTime, new DateTime(2014, 4, 1, 10, 0, 0)); wsMock.SetupProperty<DateTime>(ws => ws.EndTime, new DateTime(2014, 4, 1, 10, 30, 0)); var newRule = new MinHourDifferenceRule(startTimeProperty.Object, endTimeProperty.Object); var ruleContext = new RuleContext(null, newRule, wsMock.Object, new Dictionary<IPropertyInfo, object>() { { startTimeProperty.Object, wsMock.Object.StartTime }, { endTimeProperty.Object, wsMock.Object.EndTime } }); var ruleInterface = (IBusinessRule)newRule; ruleInterface.Execute(ruleContext); Assert.IsTrue(ruleContext.Results.Count > 0); wsMock.SetupProperty<DateTime>(ws => ws.StartTime, new DateTime(2014, 4, 1, 8, 0, 0)); wsMock.SetupProperty<DateTime>(ws => ws.EndTime, new DateTime(2014, 4, 1, 9, 30, 0)); ruleContext = new RuleContext(null, newRule, wsMock.Object, new Dictionary<IPropertyInfo, object>() { { startTimeProperty.Object, wsMock.Object.StartTime }, { endTimeProperty.Object, wsMock.Object.EndTime } }); ruleInterface = (IBusinessRule)newRule; ruleInterface.Execute(ruleContext); Assert.IsTrue(ruleContext.Results.Count == 0); }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { foreach (var item in context.InputPropertyValues.Where(x => (int)x.Value < 10)) { context.AddErrorResult(item.Key, LanguageService.Translate("Rule_PictureSize")); } }
public void OnItemAdded(object sender, EventArgs args) { var addedItem = ExtractItem(args); if (addedItem == null) { return; } var rulesFolderId = ID.Parse(ItemAddedRulesConstants.ItemAddedRules.ItemId); var itemAddedRules = addedItem.Database.GetItem(rulesFolderId); if (itemAddedRules == null) { return; } var ruleContext = new RuleContext(); ruleContext.Item = addedItem; RuleList<RuleContext> rules = RuleFactory.GetRules<RuleContext>(itemAddedRules, "Rule"); if (rules.Count > 0) { rules.Run(ruleContext); } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var sections = (ProcessSections)context.InputPropertyValues[PrimaryProperty]; if (sections == null || sections.Count == 0) return; //ignore parent var localSections = sections.Where(s => !s.IsBase).ToList(); //duplicate section name check var duplicateSections = localSections.Where(x => localSections.Count(y => y.Name == x.Name) > 1); foreach (var section in duplicateSections) context.AddErrorResult(string.Format(LanguageService.Translate("Rule_UniqueSectionName"), section.Name)); //duplicate field's system name check var fields = new Dictionary<string, string>(); foreach (var section in sections.Where(s => s.FieldList != null)) foreach (var field in section.FieldList.Where(f => !string.IsNullOrEmpty(f.SystemName))) if (fields.Keys.Any(key => key.ToUpperInvariant().Equals(field.SystemName.ToUpperInvariant()))) { var duplicate = fields.First(f => f.Key.Equals(field.SystemName, StringComparison.OrdinalIgnoreCase)); context.AddErrorResult(string.Format(LanguageService.Translate("Rule_UniqueFieldSystemNames"), field.SystemName, section.Name, duplicate.Value)); } else fields.Add(field.SystemName, section.Name); }
public override void Render(HtmlTextWriter output, Ribbon ribbon, Item button, CommandContext context) { var contextChunks = context.CustomData as List<Item>; if (contextChunks != null) { var chunk = contextChunks[0]; contextChunks.RemoveAt(0); var psButtons = chunk.Children; var contextItem = context.Items.Length > 0 ? context.Items[0] : null; var ruleContext = new RuleContext { Item = contextItem }; foreach (var parameter in context.Parameters.AllKeys) { ruleContext.Parameters[parameter] = context.Parameters[parameter]; } foreach (Item psButton in psButtons) { if (!RulesUtils.EvaluateRules(psButton["ShowRule"], ruleContext)) { continue; } RenderLargeButton(output, ribbon, Control.GetUniqueID("script"), Translate.Text(psButton.DisplayName), psButton["__Icon"], string.Empty, $"ise:runplugin(scriptDb={psButton.Database.Name},scriptId={psButton.ID})", context.Parameters["ScriptRunning"] == "0" && RulesUtils.EvaluateRules(psButton["EnableRule"], ruleContext), false, context); } } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if (string.IsNullOrEmpty((string)context.InputPropertyValues[ProcessScheduleEdit.ScheduleDisplayDateFieldProperty])) { context.AddErrorResult(PrimaryProperty, LanguageService.Translate("Rule_ScheduleDate")); } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var sections = (ProcessSections)context.InputPropertyValues[ProcessEdit.SectionListProperty]; if (sections == null || sections.Count == 0) return; if ((bool)context.InputPropertyValues[ProcessEdit.IsSystemProperty]) return; var layoutList = (IProcessLayoutList)context.InputPropertyValues[PrimaryProperty]; var defaultLayout = layoutList.GetDefaultLayout(); if (defaultLayout == null) context.AddErrorResult(LanguageService.Translate("Rule_ProcessDefaultLayout")); foreach (var layout in layoutList) { if (string.IsNullOrEmpty(layout.Name)) context.AddErrorResult(PrimaryProperty, LanguageService.Translate("Rule_ProcessLayoutName")); if (string.IsNullOrEmpty(layout.LayoutInfo)) context.AddErrorResult(PrimaryProperty, LanguageService.Translate("Rule_ProcessSearchMustHaveAtLeastOneField")); } context.Complete(); }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if ((int)context.InputPropertyValues[ProcessScheduleEdit.ScheduleFrequencyPatternIdProperty] == 0) { context.AddErrorResult(PrimaryProperty, LanguageService.Translate("Rule_ScheduleFrequencyPattern")); } }
/// <summary> /// Calls inner rule if PrimaryProperty has value. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if (context.InputPropertyValues.ContainsKey(PrimaryProperty)) { context.ExecuteRule(InnerRule); } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if (context == null) return; var selectedFrequency = (int?)context.InputPropertyValues[PrimaryProperty]; var frequencyTypeString = (string)context.InputPropertyValues[_frequencyTypeProperty]; var frequencyName = (string)context.InputPropertyValues[_frequencyName]; FrequencyEventEnum frequencyType; if (string.IsNullOrEmpty(frequencyTypeString)) frequencyTypeString = FrequencyEventEnum.Time.ToString(); if (!Enum.TryParse(frequencyTypeString, true, out frequencyType)) return; if (frequencyType == FrequencyEventEnum.Event) { if (!selectedFrequency.HasValue || selectedFrequency.Value == 0) { context.AddErrorResult(PrimaryProperty, string.Format(CultureInfo.InvariantCulture, "Frequency event for field \"{0}\" is required.", _frequencyFieldName)); } if (string.IsNullOrEmpty(frequencyName)) { context.AddErrorResult(PrimaryProperty, string.Format(CultureInfo.InvariantCulture, "Frequency event for field \"{0}\" is required.", _frequencyFieldName)); } } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if (string.IsNullOrWhiteSpace((string)context.InputPropertyValues[PrimaryProperty]) && (((SummaryTypes)context.InputPropertyValues[InputProperties[2]]) != SummaryTypes.Count)) { context.AddErrorResult(ProcessMetricEdit.MetricFieldSystemNameRuleHighlightProperty, LanguageService.Translate("Rule_MetricFieldIsRequired")); } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var isSimpleProcess = (bool)context.InputPropertyValues[PrimaryProperty]; if (!isSimpleProcess) return; var sectionsProperty = InputProperties.First(x => x.Name.Equals(ProcessEdit.SectionListProperty.Name)); var sections = (ProcessSections)context.InputPropertyValues[sectionsProperty]; if (sections == null || sections.Count == 0) return; var invalidFieldTypes = string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", ColumnTypes.Approval, ColumnTypes.Checklist, ColumnTypes.DisplayList, ColumnTypes.Result, ColumnTypes.Sample, ColumnTypes.SampleType, ColumnTypes.SamplingTechnique, ColumnTypes.SPCChart); foreach (var section in sections.Where(s => s.FieldList != null)) foreach (var field in section.FieldList.Where(f => !string.IsNullOrEmpty(f.SystemName)).Where(field => field.FieldType != null && invalidFieldTypes.Contains(field.FieldType.DataType))) context.AddErrorResult(string.Format(LanguageService.Translate("Rule_SympleProcessFields"), field.Name, section.Name)); }
/// <summary> /// Rule implementation. /// </summary> /// <param name="context">Rule context.</param> protected override void Execute(RuleContext context) { var value = (string) context.InputPropertyValues[PrimaryProperty]; if (MaxCharsPerLineProperty != null) { MaxCharsPerLine = (int) context.InputPropertyValues[MaxCharsPerLineProperty]; } if (value != null) { string[] valueArray = value.Split(new string[1] {Environment.NewLine}, StringSplitOptions.None); bool maxExceeded = false; if (valueArray != null) { foreach (string line in valueArray) { if (line.Length > MaxCharsPerLine) { maxExceeded = true; break; } } } if (!String.IsNullOrEmpty(value) && (maxExceeded)) { string message = string.Format(ResourcesValidation.StringMaxCharsPerLine, PrimaryProperty.FriendlyName, MaxCharsPerLine.ToString()); context.Results.Add(new RuleResult(RuleName, PrimaryProperty, message) {Severity = Severity}); } } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if ((Guid)context.InputPropertyValues[ProcessScheduleEdit.ScheduleStartStateGuidProperty] == Guid.Empty) { context.AddErrorResult(PrimaryProperty, LanguageService.Translate("Rule_ScheduleState")); } }
protected override void Execute(RuleContext context) { //modify property value, to upper var val1 = (string)context.InputPropertyValues[PrimaryProperty]; if (!string.IsNullOrEmpty(val1)) context.AddOutValue(PrimaryProperty, val1.ToUpper()); }
public bool Include(object item) { var visit = (item as IVisitAggregationContext).TryGet(v => v.Visit); if (visit != null) { var tracker = _trackerFactory(visit); TrackerSwitcher.Enter(tracker); try { var rulesContext = new RuleContext(); rulesContext.Item = RuleContextItem; _rules.Run(rulesContext); object addToSegment; var include = !rulesContext.IsAborted && rulesContext.Parameters.TryGetValue("addVisit", out addToSegment) && (bool) addToSegment; return include; } finally { if (Tracker.Current == tracker) { TrackerSwitcher.Exit(); } } } return false; }
public override void Process(StartTrackingArgs args) { if (!Tracker.IsActive || String.IsNullOrEmpty(RulesItemId)) return; VisitorDataSet.VisitsRow currentVisit = Tracker.Visitor.GetCurrentVisit(); if (currentVisit == null || currentVisit.HasGeoIpData) return; Item rulesItem = Sitecore.Context.Database.GetItem(RulesItemId); if (rulesItem == null) return; RuleList<RuleContext> ruleList = RuleFactory.GetRules<RuleContext>(rulesItem, "Rule"); if (ruleList == null) return; RuleContext ruleContext = new RuleContext(); if (SatisfiesConditions(ruleList, ruleContext)) currentVisit.UpdateGeoIpData(); ruleContext.Abort(); }
public bool RunRule(Item outcomeItem) { if (outcomeItem == null) return false; string ruleXml = outcomeItem[RulesField]; if (String.IsNullOrEmpty(ruleXml)) return false; RuleList<RuleContext> rules = new RuleList<RuleContext> { Name = outcomeItem.Paths.Path }; RuleList<RuleContext> parsed = RuleFactory.ParseRules<RuleContext>( Context.Database, ruleXml); rules.AddRange(parsed.Rules); if (rules.Count < 1) return false; RuleContext ruleContext = new RuleContext { Item = Context.Item }; ruleContext.Parameters.Add("DefinitionItem",outcomeItem); rules.Run(ruleContext); return ruleContext.IsAborted; }
/// <summary> /// Applies the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public RuleFlagProcessorResponse Apply(RuleContext context) { Manager.SetServerVariable(context.HttpContext, Name, Value, Replace); Manager.LogIf(context.LogLevel >= 2, "Set Server Variable: " + Name, "Rewrite"); return RuleFlagProcessorResponse.ContinueToNextFlag; }
protected override void Execute(RuleContext context) { if (context == null) { throw new ArgumentException("Context cannot be null"); } var imageArray = (byte[])context.InputPropertyValues[this.ImageProptery]; if (imageArray != null && imageArray.Length > 0) { try { using (var ms = new MemoryStream(imageArray)) { var image = System.Drawing.Image.FromStream(ms); if (image.Height != ImageConstants.AllowedHeight || image.Width != ImageConstants.AllowedWidth) { context.AddErrorResult(string.Format(CultureInfo.CurrentCulture, "The supplied image must have a height of {0} px and a width of {1} px.", ImageConstants.AllowedHeight, ImageConstants.AllowedWidth)); } } } catch (ArgumentException) { context.AddErrorResult("Image must be set with a valid image type."); } } }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { if (context == null) return; var value = context.InputPropertyValues[InputProperties[0]]; if (value == null) { return; } var s = value as string; if (s != null && string.IsNullOrEmpty(s)) return; if (value is int) { return; } if (value is decimal) { if ((decimal)value < int.MaxValue && (decimal)value > int.MinValue) return; } context.AddErrorResult("Value must be between -2 147 483 648 and +2 147 483 647"); }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var commands = (ProcessCommandEditList)context.InputPropertyValues[PrimaryProperty]; if (commands == null) return; foreach (var command in commands) { var foundConfigurations = new HashSet<ProcessCommandSecurityConfigurationEdit>(); var command1 = command; foreach (var configuration in command.SecurityConfigurationList.Where(configuration => !foundConfigurations.Any(f => f.RoleId == configuration.RoleId && f.StateGuid == configuration.StateGuid && f.BusinessUnitId == configuration.BusinessUnitId && f.PersonFieldSystemName == configuration.PersonFieldSystemName) && command1.SecurityConfigurationList.Any(x => !x.Equals(configuration) && x.RoleId == configuration.RoleId && x.StateGuid == configuration.StateGuid && x.BusinessUnitId == configuration.BusinessUnitId && x.PersonFieldSystemName == configuration.PersonFieldSystemName)) ) { foundConfigurations.Add(configuration); context.AddErrorResult(PrimaryProperty, string.Format(LanguageService.Translate("Rule_UniqueSecurityConfiguration"), command.CommandName)); } } }
public override void Render(HtmlTextWriter output, Ribbon ribbon, Item button, CommandContext context) { var typeName = context.Parameters["type"]; var viewName = context.Parameters["viewName"]; var ruleContext = new RuleContext { Item = context.CustomData as Item }; ruleContext.Parameters["ViewName"] = viewName; if (!string.IsNullOrEmpty(typeName)) { foreach ( Item scriptItem in ModuleManager.GetFeatureRoots(IntegrationPoints.ListViewRibbonFeature) .Select(parent => parent.Paths.GetSubItem(typeName)) .Where(scriptLibrary => scriptLibrary != null) .SelectMany(scriptLibrary => scriptLibrary.Children, (scriptLibrary, scriptItem) => new {scriptLibrary, scriptItem}) .Where( @t => RulesUtils.EvaluateRules(@t.scriptItem["ShowRule"], ruleContext) ) .Select(@t => @t.scriptItem)) { RenderSmallButton(output, ribbon, Control.GetUniqueID("export"), Translate.Text(scriptItem.DisplayName), scriptItem["__Icon"], string.Empty, string.Format("listview:action(scriptDb={0},scriptID={1})", scriptItem.Database.Name, scriptItem.ID), RulesUtils.EvaluateRules(scriptItem["EnableRule"], ruleContext) && context.Parameters["ScriptRunning"] == "0", false); } } }
protected override void Execute(RuleContext context) { if (((IAppointmentRequest)context.Target).TimeEntries == null || ((IAppointmentRequest)context.Target).TimeEntries.Count < 1) { context.AddErrorResult(ValidationMessages.NoTimeEntries); } }
/// <summary> /// Runs the specified context. /// </summary> /// <param name="context">The rule context.</param> public override void Run(RuleContext context) { context.Message = ErrorMessage; context.Success = true; if (!CanRun(context.TrackedObject)) return; object value = GetPropertyValue(context.TrackedObject.Current); if (value is string && value != null) { context.Success = ((string)value).Trim().Length > 0; } else if (value is Guid) { context.Success = (Guid)value != Guid.Empty; } else if (value is DateTime) { context.Success = (DateTime)value > (DateTime)SqlDateTime.MinValue; } else { context.Success = value != null; } }
public static Antlr4.Runtime.Atn.PredictionContext FromRuleContext(ATN atn, RuleContext outerContext) { return(FromRuleContext(atn, outerContext, true)); }
public MarketRulesRequestType7(int counter, Guid existingDiscountId, string functionName, string username, Guid storeId, RuleContext discountType, double precent, string category, Guid productId, Guid originDiscountId) { this.Id = counter; this.ExistingDiscountId = existingDiscountId; this.FunctionName = functionName; this.Username = username; this.StoreId = storeId; this.DiscountType = discountType; this.Precent = precent; this.Category = category; this.ProductId = productId; this.OriginDiscountId = originDiscountId; }
private void TestRuleAction(RuleContext context) { context.AddErrorResult("test rule broken"); }
/// <summary> /// This rule passes if the parameters section contains both subscriptionId and api-version parameters /// </summary> /// <param name="paths"></param> /// <returns></returns> public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, SwaggerParameter> ParametersMap, RuleContext context) { var serviceDefinition = (ServiceDefinition)context.Root; // Check if subscriptionId is used but not defined in global parameters bool isSubscriptionIdReferenced = serviceDefinition.Paths.Keys.Any(key => key.ToLower().Contains("{" + SubscriptionId.ToLower() + "}")); if (isSubscriptionIdReferenced && (ParametersMap?.Values.Any(parameter => parameter.Name?.ToLower().Equals(SubscriptionId) == true)) == false) { yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path), this, SubscriptionId)); } // For ARM specs, api version is almost always required, call it out if it isn't defined in the global params // We are not distinguishing between ARM and non-ARM specs currently, so let's apply this for all specs regardless // and make appropriate changes in the future so this gets applied only for ARM specs if (ParametersMap?.Values.Any(parameter => parameter.Name?.ToLower().Equals(ApiVersion) == true) == false) { yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path), this, ApiVersion)); } }
public async IAsyncEnumerable <EnrichedEvent> CreateEnrichedEventsAsync(Envelope <AppEvent> @event, RuleContext context, [EnumeratorCancellation] CancellationToken ct) { var usageEvent = (AppUsageExceeded)@event.Payload; var result = new EnrichedUsageExceededEvent { CallsCurrent = usageEvent.CallsCurrent, CallsLimit = usageEvent.CallsLimit, Name = EventName }; await Task.Yield(); yield return(result); }
/// <inheritdoc/> public override Task RunAsync(RuleContext context) { return(this.transactionChecker.RunAsync(context, this.internalRules)); }
/// <summary> /// This rule fails if the description is null and the reference is null (since the reference could have a description) /// </summary> /// <param name="entity">Entity being validated</param> /// <param name="context">Rule context</param> /// <param name="formatParameters">formatted parameters</param> /// <returns><c>true</c> if entity contains description, <c>false</c> otherwise</returns> public override bool IsValid(SwaggerParameter entity, RuleContext context, out object[] formatParameters) { formatParameters = new string[] { string.Format(ParameterTypeFormatter, entity.Name) }; return(!string.IsNullOrWhiteSpace(entity.Description) || !string.IsNullOrWhiteSpace(entity.Reference)); }
/// <inheritdoc /> public override async Task RunAsync(RuleContext context) { this.Logger.LogTrace("()"); Block block = context.BlockValidationContext.Block; ChainedHeader index = context.BlockValidationContext.ChainedHeader; DeploymentFlags flags = context.Flags; UnspentOutputSet view = context.Set; this.Parent.PerformanceCounter.AddProcessedBlocks(1); long sigOpsCost = 0; Money fees = Money.Zero; var checkInputs = new List <Task <bool> >(); for (int txIndex = 0; txIndex < block.Transactions.Count; txIndex++) { this.Parent.PerformanceCounter.AddProcessedTransactions(1); Transaction tx = block.Transactions[txIndex]; if (!context.SkipValidation) { // TODO: Simplify this condition. if (!tx.IsCoinBase && (!context.IsPoS || (context.IsPoS && !tx.IsCoinStake))) { if (!view.HaveInputs(tx)) { this.Logger.LogTrace("(-)[BAD_TX_NO_INPUT]"); ConsensusErrors.BadTransactionMissingInput.Throw(); } var prevheights = new int[tx.Inputs.Count]; // Check that transaction is BIP68 final. // BIP68 lock checks (as opposed to nLockTime checks) must // be in ConnectBlock because they require the UTXO set. for (int j = 0; j < tx.Inputs.Count; j++) { prevheights[j] = (int)view.AccessCoins(tx.Inputs[j].PrevOut.Hash).Height; } if (!tx.CheckSequenceLocks(prevheights, index, flags.LockTimeFlags)) { this.Logger.LogTrace("(-)[BAD_TX_NON_FINAL]"); ConsensusErrors.BadTransactionNonFinal.Throw(); } } // GetTransactionSignatureOperationCost counts 3 types of sigops: // * legacy (always), // * p2sh (when P2SH enabled in flags and excludes coinbase), // * witness (when witness enabled in flags and excludes coinbase). sigOpsCost += this.GetTransactionSignatureOperationCost(tx, view, flags); if (sigOpsCost > this.consensusOptions.MaxBlockSigopsCost) { this.Logger.LogTrace("(-)[BAD_BLOCK_SIG_OPS]"); ConsensusErrors.BadBlockSigOps.Throw(); } // TODO: Simplify this condition. if (!tx.IsCoinBase && (!context.IsPoS || (context.IsPoS && !tx.IsCoinStake))) { this.CheckInputs(tx, view, index.Height); fees += view.GetValueIn(tx) - tx.TotalOut; var txData = new PrecomputedTransactionData(tx); for (int inputIndex = 0; inputIndex < tx.Inputs.Count; inputIndex++) { this.Parent.PerformanceCounter.AddProcessedInputs(1); TxIn input = tx.Inputs[inputIndex]; int inputIndexCopy = inputIndex; TxOut txout = view.GetOutputFor(input); var checkInput = new Task <bool>(() => { var checker = new TransactionChecker(tx, inputIndexCopy, txout.Value, txData); var ctx = new ScriptEvaluationContext(this.Parent.Network); ctx.ScriptVerify = flags.ScriptFlags; return(ctx.VerifyScript(input.ScriptSig, txout.ScriptPubKey, checker)); }); checkInput.Start(); checkInputs.Add(checkInput); } } } this.UpdateCoinView(context, tx); } if (!context.SkipValidation) { this.CheckBlockReward(context, fees, index.Height, block); foreach (Task <bool> checkInput in checkInputs) { if (await checkInput.ConfigureAwait(false)) { continue; } this.Logger.LogTrace("(-)[BAD_TX_SCRIPT]"); ConsensusErrors.BadTransactionScriptError.Throw(); } } else { this.Logger.LogTrace("BIP68, SigOp cost, and block reward validation skipped for block at height {0}.", index.Height); } this.Logger.LogTrace("(-)"); }
public virtual string GetText(RuleContext ctx) => this.GetText(ctx.SourceInterval);
/// <summary> /// Checks and computes stake. /// </summary> /// <param name="context">Context that contains variety of information regarding blocks validation and execution.</param> /// <exception cref="ConsensusErrors.PrevStakeNull">Thrown if previous stake is not found.</exception> /// <exception cref="ConsensusErrors.SetStakeEntropyBitFailed">Thrown if failed to set stake entropy bit.</exception> private void CheckAndComputeStake(RuleContext context) { ChainedHeader chainedHeader = context.ValidationContext.ChainedHeaderToValidate; Block block = context.ValidationContext.BlockToValidate; var posRuleContext = context as PosRuleContext; if (posRuleContext.BlockStake == null) { posRuleContext.BlockStake = BlockStake.Load(context.ValidationContext.BlockToValidate); } BlockStake blockStake = posRuleContext.BlockStake; // Verify hash target and signature of coinstake tx. if (BlockStake.IsProofOfStake(block)) { ChainedHeader prevChainedHeader = chainedHeader.Previous; BlockStake prevBlockStake = this.stakeChain.Get(prevChainedHeader.HashBlock); if (prevBlockStake == null) { ConsensusErrors.PrevStakeNull.Throw(); } // Only do proof of stake validation for blocks that are after the assumevalid block or after the last checkpoint. if (!context.SkipValidation) { this.stakeValidator.CheckProofOfStake(posRuleContext, prevChainedHeader, prevBlockStake, block.Transactions[1], chainedHeader.Header.Bits.ToCompact()); } else { this.Logger.LogTrace("POS validation skipped for block at height {0}.", chainedHeader.Height); } } // PoW is checked in CheckBlock(). if (BlockStake.IsProofOfWork(block)) { posRuleContext.HashProofOfStake = chainedHeader.Header.GetPoWHash(); } // Compute stake entropy bit for stake modifier. if (!blockStake.SetStakeEntropyBit(blockStake.GetStakeEntropyBit())) { this.Logger.LogTrace("(-)[STAKE_ENTROPY_BIT_FAIL]"); ConsensusErrors.SetStakeEntropyBitFailed.Throw(); } // Record proof hash value. blockStake.HashProof = posRuleContext.HashProofOfStake; int lastCheckpointHeight = this.Parent.Checkpoints.GetLastCheckpointHeight(); if (chainedHeader.Height > lastCheckpointHeight) { // Compute stake modifier. ChainedHeader prevChainedHeader = chainedHeader.Previous; BlockStake blockStakePrev = prevChainedHeader == null ? null : this.stakeChain.Get(prevChainedHeader.HashBlock); blockStake.StakeModifierV2 = this.stakeValidator.ComputeStakeModifierV2(prevChainedHeader, blockStakePrev?.StakeModifierV2, blockStake.IsProofOfWork() ? chainedHeader.HashBlock : blockStake.PrevoutStake.Hash); } else if (chainedHeader.Height == lastCheckpointHeight) { // Copy checkpointed stake modifier. CheckpointInfo checkpoint = this.Parent.Checkpoints.GetCheckpoint(lastCheckpointHeight); blockStake.StakeModifierV2 = checkpoint.StakeModifierV2; this.Logger.LogTrace("Last checkpoint stake modifier V2 loaded: '{0}'.", blockStake.StakeModifierV2); } else { this.Logger.LogTrace("POS stake modifier computation skipped for block at height {0} because it is not above last checkpoint block height {1}.", chainedHeader.Height, lastCheckpointHeight); } }
/// <summary> /// Validates whether property names are camelCase in body parameters. /// </summary> public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Operation> path, RuleContext context) { foreach (string operation in path.Keys) { if (path[operation]?.Parameters != null) { for (var i = 0; i < path[operation].Parameters.Count; ++i) { if (path[operation].Parameters[i].In == ParameterLocation.Body && path[operation].Parameters[i].Schema?.Properties != null) { foreach (KeyValuePair <string, Schema> prop in path[operation].Parameters[i].Schema?.Properties) { if (!ValidationUtilities.IsODataProperty(prop.Key) && !ValidationUtilities.IsNameCamelCase(prop.Key)) { yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(operation).AppendProperty("parameters").AppendIndex(i).AppendProperty("schema").AppendProperty("properties").AppendProperty(prop.Key)), this, prop.Key, ValidationUtilities.GetCamelCasedSuggestion(prop.Key))); } } } } } } }
public Expression Get(RuleContext context, MethodCallExpression node) { var entityType = node.Method.GetGenericArguments()[0]; return(SpQueryable.MakeFetch(entityType, context.ListItemsProvider, context.Query)); }
public static string GetTextSanitized(this RuleContext context) { string text = context.GetText(); return(text.Trim('"').ToLowerInvariant()); }
public async IAsyncEnumerable <EnrichedEvent> CreateEnrichedEventsAsync(Envelope <AppEvent> @event, RuleContext context, [EnumeratorCancellation] CancellationToken ct) { var contentEvent = (ContentEvent)@event.Payload; var result = new EnrichedContentEvent(); var content = await contentLoader.GetAsync( contentEvent.AppId.Id, contentEvent.ContentId, @event.Headers.EventStreamNumber()); if (content != null) { SimpleMapper.Map(content, result); } switch (@event.Payload) { case ContentCreated: result.Type = EnrichedContentEventType.Created; break; case ContentDeleted: result.Type = EnrichedContentEventType.Deleted; break; case ContentStatusChanged e when e.Change == StatusChange.Published: result.Type = EnrichedContentEventType.Published; break; case ContentStatusChanged e when e.Change == StatusChange.Unpublished: result.Type = EnrichedContentEventType.Unpublished; break; case ContentStatusChanged e when e.Change == StatusChange.Change: result.Type = EnrichedContentEventType.StatusChanged; break; case ContentUpdated: { result.Type = EnrichedContentEventType.Updated; if (content != null) { var previousContent = await contentLoader.GetAsync( content.AppId.Id, content.Id, content.Version - 1); if (previousContent != null) { result.DataOld = previousContent.Data; } } break; } } yield return(result); }
/// <inheritdoc /> public override void Run(RuleContext context) { // TODO POA implement rule }
private void PrintBoolean(RuleContext left, string op, RuleContext right) { left.Accept(this); _output.AppendFormat(" {0} ", op); right.Accept(this); }
public MarketRulesRequestType2(int counter, string functionName, string username, Guid storeId, PolicyRuleRelation policyRuleRelation, RuleContext ruleContext, RuleType ruleType, string category, Guid productId, double valueLessThan, double valueGreaterEQThan, DateTime d1, DateTime d2) { this.id = counter; this.functionName = functionName; this.username = username; this.storeId = storeId; this.policyRuleRelation = policyRuleRelation; this.ruleContext = ruleContext; this.ruleType = ruleType; this.category = category; this.productId = productId; this.valueLessThan = valueLessThan; this.valueGreaterEQThan = valueGreaterEQThan; this.d1 = d1; this.d2 = d2; }
/// <inheritdoc/> public override void UpdateCoinView(RuleContext context, Transaction transaction) { base.UpdateUTXOSet(context, transaction); }
/// <inheritdoc /> public override async Task RunAsync(RuleContext context) { await this.logic.RunAsync(base.RunAsync, context); }
// Verifies if a tracked resource has a corresponding get operation public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Schema> definitions, RuleContext context) { ServiceDefinition serviceDefinition = (ServiceDefinition)context.Root; IEnumerable <Operation> getOperations = ValidationUtilities.GetOperationsByRequestMethod("get", serviceDefinition); // filter out the model definitions that are not being returned as a response var respDefinitions = ValidationUtilities.GetResponseModelDefinitions(serviceDefinition); foreach (KeyValuePair <string, Schema> definition in definitions) { if (respDefinitions.Contains(definition.Key) && ValidationUtilities.IsTrackedResource(definition.Value, definitions)) { // check for 200 status response models since they correspond to a successful get operation if (!getOperations.Any(op => op.Responses.ContainsKey("200") && (op.Responses["200"]?.Schema?.Reference?.StripDefinitionPath()) == definition.Key)) { // if no GET operation returns current tracked resource as a response, // the tracked resource does not have a corresponding get operation yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path), this, definition.Key.StripDefinitionPath())); } } } }
protected virtual void TrimItemVersions(Item item) { var pruneMe = new List <PruneAction>(); // Get the latest valid version for this item var latestValidVersion = item.Publishing.GetValidVersion(DateTime.Now, true, false); if (latestValidVersion == null) { Log.Warn(string.Format("Item does not have a published version. This item will NOT be pruned. [{0}]", item.Paths.Path), this); return; } // Get an array of all possible versions that can be removed var versions = item.Versions.GetVersions() .Where(x => x.Version.Number < latestValidVersion.Version.Number) .OrderBy(x => x.Version.Number) .ToArray(); Log.Debug(string.Format("[{0}][latest published version #: {1}][# of pruning candidates: {2}]", item.Paths.Path, latestValidVersion, versions.Length), this); // Process each item version against the Version Filter rules foreach (var v in versions) { var ruleContext = new RuleContext(); ruleContext.Parameters["currentversion"] = latestValidVersion; ruleContext.Item = v; this.VersionFilterRules.Run(ruleContext); var a = new PruneAction { ItemVersion = v }; a.Archive = ruleContext.Parameters.ContainsKey("ArchiveThisVersion"); a.Serialize = ruleContext.Parameters.ContainsKey("SerializeThisVersion"); if (a.Archive || a.Serialize) { // Passed all rules. Add to "deleteMe" list pruneMe.Add(a); } } if (pruneMe.Count > 0) { if (pruneMe.Any(x => x.Serialize)) { // Serialize versions.. var serializeMe = pruneMe.Where(x => x.Serialize); this.Serializer.SerializeItemVersions(item, serializeMe.Select(x => x.ItemVersion.Version.Number).ToArray()); } if (pruneMe.Any(x => x.Archive)) { // Copy the to-be-deleted item versions to the Archive database.. this.Archiver.ArchiveItemVersions(pruneMe.Where(x => x.Archive).Select(x => x.ItemVersion).ToArray()); } if (pruneMe.Any(x => !x.Archive)) { foreach (var v in pruneMe.Where(x => !x.Archive)) { var msg = String.Format("Delete version: [{0}][{1}][vers# {2}]", item.Language.Name, item.Paths.FullPath, v.ItemVersion.Version.Number); Log.Audit(msg, this); v.ItemVersion.Versions.RemoveVersion(); } } } }
/// <summary> /// Executes contracts as necessary and updates the coinview / UTXOset after execution. /// </summary> /// <inheritdoc/> public override void UpdateCoinView(RuleContext context, Transaction transaction) { this.logic.UpdateCoinView(base.UpdateUTXOSet, context, transaction); }
/// <summary> /// Called when [executing]. /// </summary> /// <param name="context">The context.</param> protected virtual void OnExecuting(RuleContext context) { }
#pragma warning restore CS0649 public override async Task Run(RuleContext context) { // There is a lot of drama here around whether the Launcher is running or not. This is because the launcher // launcher creates its own MemoryContentDirectory, so the only message that we can use to do this is used // for two different reasons. var query = $@" let end = now(); let start = end - {CslTimeSpanLiteral.AsCslString(_configuration.LookbackPeriod)}; table('{_configuration.CacheTableName}') | where PreciseTimeStamp between (start .. end) | summarize Total=dcount(Machine), Reimaged=dcountif(Machine, Message has 'MemoryContentDirectory starting with 0 entries from no file'), Machines=make_set_if(Machine, Message has 'MemoryContentDirectory starting with 0 entries from no file') by Stamp, Service | extend Machines=tostring(Machines) | where not(isnull(Total))"; var results = (await QueryKustoAsync <Result>(context, query)).ToList(); GroupByStampAndCallHelper(results, result => result.Stamp, rule); void rule(string stamp, List <Result> results) { if (results.Count == 0) { return; } // We skip stamps with the Launcher because things get really weird. This should be removed in the near future. var isLauncherRunning = results.Any(r => r.Service.Equals(Constants.CacheService, StringComparison.InvariantCultureIgnoreCase)); if (isLauncherRunning) { return; } var result = results.Where(r => r.Service.Equals(Constants.ContentAddressableStoreService, StringComparison.InvariantCultureIgnoreCase)).First(); if (result.Reimaged == 0) { return; } var reimageRate = result.Reimaged / (double)result.Total; _configuration.ReimageRateThresholds.Check( reimageRate, (severity, cut) => { var examples = string.Empty; if (!string.IsNullOrEmpty(result.Machines)) { var machines = JsonSerializer.Deserialize <List <string> >(result.Machines) !; examples = ". Examples: " + string.Join(", ", machines.Take(_configuration.MaximumExamplesOnAlert).Select(m => $"`{m}`")); } Emit( context, "ReimageRate", severity, $"Detected `{Math.Round(reimageRate * 100.0, 4, MidpointRounding.AwayFromZero)}%` ({result.Reimaged} / {result.Total}) of the stamp has been reimaged in over the last `{_configuration.LookbackPeriod}` period{examples}", stamp); }); } }
/// <summary> /// Applies the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public RuleFlagProcessorResponse Apply(RuleContext context) { return(RuleFlagProcessorResponse.ContinueToNextFlag); }
// Verifies if a tracked resource has a corresponding PATCH operation public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Dictionary <string, Operation> > paths, RuleContext context) { var serviceDefinition = (ServiceDefinition)context.Root; var ops = ValidationUtilities.GetOperationsByRequestMethod("put", serviceDefinition); var putRespModels = ops.Select(op => (op.Responses?.ContainsKey("200") != true) ? null : op.Responses["200"].Schema?.Reference?.StripDefinitionPath()); putRespModels = putRespModels.Where(modelName => !string.IsNullOrEmpty(modelName)); var xmsResModels = ValidationUtilities.GetXmsAzureResourceModels(serviceDefinition.Definitions); var violatingModels = putRespModels.Where(respModel => !ValidationUtilities.EnumerateModelHierarchy(respModel, serviceDefinition.Definitions).Intersect(xmsResModels).Any()); foreach (var model in violatingModels) { var violatingOp = ops.Where(op => (op.Responses?.ContainsKey("200") == true) && op.Responses["200"].Schema.Reference.StripDefinitionPath() == model).First(); var violatingPath = paths.Where(pathObj => pathObj.Value.Values.Where(op => op.OperationId == violatingOp.OperationId).Any()).First(); var violatingOpVerb = violatingPath.Value.Keys.Where(key => key.EqualsIgnoreCase("put")).First(); yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path.AppendProperty(violatingPath.Key).AppendProperty(violatingOpVerb).AppendProperty("operationId")), this, violatingOp.OperationId, model)); } }
public override IEnumerable <ValidationMessage> GetValidationMessages(Schema schema, RuleContext context) { if (schema != null && string.IsNullOrEmpty(schema.Reference) && schema.RepresentsCompositeType()) { if (schema.Description == null) { yield return(new ValidationMessage(this, "description")); } } }
public override void Run(RuleContext context) { var header = context.ValidationContext.ChainedHeaderToValidate.Header as PoABlockHeader; PubKey pubKey = this.slotsManager.GetPubKeyForTimestamp(header.Time); if (!this.validator.VerifySignature(pubKey, header)) { // In case voting is enabled it is possible that federation was modified and another fed member signed // the header. Since voting changes are applied after max reorg blocks are passed we can tell exactly // how federation will look like max reorg blocks ahead. Code below tries to construct federation that is // expected to exist at the moment block that corresponds to header being validated was produced. Then // this federation is used to estimate who was expected to sign a block and then the signature is verified. if (this.votingEnabled) { ChainedHeader currentHeader = context.ValidationContext.ChainedHeaderToValidate; bool mightBeInsufficient = currentHeader.Height - this.chainState.ConsensusTip.Height > this.maxReorg; List <IFederationMember> modifiedFederation = this.federationManager.GetFederationMembers(); foreach (Poll poll in this.votingManager.GetFinishedPolls().Where(x => !x.IsExecuted && ((x.VotingData.Key == VoteKey.AddFederationMember) || (x.VotingData.Key == VoteKey.KickFederationMember)))) { if (currentHeader.Height - poll.PollVotedInFavorBlockData.Height <= this.maxReorg) { // Not applied yet. continue; } IFederationMember federationMember = this.consensusFactory.CreateFederationMemberFromBytes(poll.VotingData.Data); if (poll.VotingData.Key == VoteKey.AddFederationMember) { modifiedFederation.Add(federationMember); } else if (poll.VotingData.Key == VoteKey.KickFederationMember) { modifiedFederation.Remove(federationMember); } } pubKey = this.slotsManager.GetPubKeyForTimestamp(header.Time, modifiedFederation); if (this.validator.VerifySignature(pubKey, header)) { this.Logger.LogDebug("Signature verified using updated federation."); return; } if (mightBeInsufficient) { // Mark header as insufficient to avoid banning the peer that presented it. // When we advance consensus we will be able to validate it. context.ValidationContext.InsufficientHeaderInformation = true; } } this.Logger.LogTrace("(-)[INVALID_SIGNATURE]"); PoAConsensusErrors.InvalidHeaderSignature.Throw(); } }
public override bool IsValid(Dictionary <string, Operation> xmsPath, RuleContext context) { return(context?.GetServiceDefinition()?.Paths?.ContainsKey(GetBasePath(context.Key)) ?? false); }
///// <summary> ///// Validates whether property names are camelCase for definitions. ///// </summary> public override IEnumerable <ValidationMessage> GetValidationMessages(Dictionary <string, Schema> definitions, RuleContext context) { foreach (KeyValuePair <string, Schema> definition in definitions) { if (definition.Value.Properties != null) { foreach (KeyValuePair <string, Schema> prop in definition.Value.Properties) { if (!ValidationUtilities.isNameCamelCase(prop.Key)) { yield return(new ValidationMessage(new FileObjectPath(context.File, context.Path), this, prop.Key, definition.Key, ValidationUtilities.ToCamelCase(prop.Key))); } } } } }