public static IComparableBeConstraints<Double> RoughlyEqualTo(this IComparableBeConstraints<Double> constraint, Double expected, Double tolerance) { var assertion = new Assertion<Double, IComparable>("Be roughly equal to", expected, a => Math.Abs(a - expected) <= tolerance); constraint.AssertionInfo.AssertUsing<Double>(assertion); return constraint; }
/// <summary> /// Creates a new instance of the <see cref="SchematronValidationEventArgs"/>. /// </summary> /// <param name="schematron">The <see cref="SchematronDocument"/> that detected the event.</param> /// <param name="queryEngine">The <see cref="IQueryLanguage"/> that detected the event.</param> /// <param name="pattern">The active <see cref="Pattern"/>.</param> /// <param name="rule">The <see cref="Sepia.Schematron.Rule"/> that caused the event to be raised.</param> /// <param name="assertion">The <see cref="Sepia.Schematron.Assertion"/> that caused the event to be raised.</param> /// <param name="context">An <see cref="object"/> that provides the context for the <paramref name="rule"/> and <paramref name="assertion"/>.</param> /// <param name="instance">An <see cref="XPathNavigator"/> to the document node that cause the event to be raised.</param> public SchematronValidationEventArgs(SchematronDocument schematron, IQueryLanguage queryEngine, Pattern pattern, Rule rule, Assertion assertion, object context, XPathNavigator instance) { this.schematron = schematron; this.queryEngine = queryEngine; this.pattern = pattern; this.rule = rule; this.assertion = assertion; this.instance = instance.Clone(); if (assertion == null) { message = "A schematron validation event occured."; } else { message = assertion.Message.ToString(instance, context); } List<string> diagnostics = new List<string>(); if (assertion != null && !string.IsNullOrEmpty(assertion.Diagnostics)) { foreach (string id in assertion.Diagnostics.Split(' ')) { Diagnostic diagnostic = schematron.Diagnostics[id]; diagnostics.Add(diagnostic.Message.ToString(instance, context)); } } this.diagnostics = diagnostics.ToArray(); }
public AssertSpecial(StateSystem statesystem, String label, TextSection textsection) : base(statesystem, label, textsection) { m_assert1 = textsection.GetAttribute<Assertion>("flag", Assertion.None); m_assert2 = textsection.GetAttribute<Assertion>("flag2", Assertion.None); m_assert3 = textsection.GetAttribute<Assertion>("flag3", Assertion.None); }
/// <summary> /// Ensures that a "subject" is present in the saml20Assertion, and validates the subject. /// </summary> private void ValidateSubject(Assertion assertion) { if (assertion.Subject == null) throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that a \"Subject\" element is present in the saml20Assertion."); SubjectValidator.ValidateSubject(assertion.Subject); }
public virtual void ValidateAssertion(Assertion assertion) { if (assertion == null) throw new ArgumentNullException("assertion"); ValidateAssertionAttributes(assertion); ValidateSubject(assertion); ValidateConditions(assertion); ValidateStatements(assertion); }
/// <summary> /// Validates the saml20Assertion to make sure it conforms to the DK-Saml 2.0 profile. /// </summary> /// <param name="assertion">The assertion to validate.</param> public override void ValidateAssertion(Assertion assertion) { base.ValidateAssertion(assertion); ValidateIssuerElement(assertion); ValidateStatements(assertion); ValidateSubject(assertion); ValidateConditions(assertion); }
/// <summary> /// Validates the time restrictions. /// </summary> /// <param name="assertion">The assertion.</param> /// <param name="allowedClockSkew">The allowed clock skew.</param> public void ValidateTimeRestrictions(Assertion assertion, TimeSpan allowedClockSkew) { // Conditions are not required if (assertion.Conditions == null) { return; } var conditions = assertion.Conditions; var now = DateTime.UtcNow; // Negative allowed clock skew does not make sense - we are trying to relax the restriction interval, not restrict it any further if (allowedClockSkew < TimeSpan.Zero) { allowedClockSkew = allowedClockSkew.Negate(); } // NotBefore must not be in the future if (!ValidateNotBefore(conditions.NotBefore, now, allowedClockSkew)) { throw new Saml20FormatException("Conditions.NotBefore must not be in the future"); } // NotOnOrAfter must not be in the past if (!ValidateNotOnOrAfter(conditions.NotOnOrAfter, now, allowedClockSkew)) { throw new Saml20FormatException("Conditions.NotOnOrAfter must not be in the past"); } foreach (var statement in assertion.GetAuthnStatements()) { if (statement.SessionNotOnOrAfter != null && statement.SessionNotOnOrAfter <= now) { throw new Saml20FormatException("AuthnStatement attribute SessionNotOnOrAfter MUST be in the future"); } // TODO: Consider validating that authnStatement.AuthnInstant is in the past } if (assertion.Subject != null) { foreach (var subjectConfirmation in assertion.Subject.Items.OfType<SubjectConfirmation>().Where(subjectConfirmation => subjectConfirmation.SubjectConfirmationData != null)) { if (!ValidateNotBefore(subjectConfirmation.SubjectConfirmationData.NotBefore, now, allowedClockSkew)) { throw new Saml20FormatException("SubjectConfirmationData.NotBefore must not be in the future"); } if (!ValidateNotOnOrAfter(subjectConfirmation.SubjectConfirmationData.NotOnOrAfter, now, allowedClockSkew)) { throw new Saml20FormatException("SubjectConfirmationData.NotOnOrAfter must not be in the past"); } } } }
/// <summary> /// Converts a <see cref="Report"/> to an <see cref="Assertion"/>. /// </summary> /// <param name="negatedTest"> /// The negated <see cref="Assertion.Test"/> for the <see cref="Assertion"/>. /// </param> /// <returns> /// A new <see cref="Assertion"/> that is equivalent to this <see cref="Report"/>. /// </returns> /// <remarks> /// <b>ToAssertion</b> is used to convert a <see cref="Report"/> to an <see cref="Assertion"/>. The <paramref name="negatedTest"/> /// must be negatation of the report's <see cref="Assertion.Test"/>. For the XPath query language, the <c>not()</c> function can /// be used. /// </remarks> public Assertion ToAssertion(string negatedTest) { Assertion a = new Assertion(); a.Diagnostics = this.Diagnostics; a.Fpi = this.Fpi; a.Icon = this.Icon; a.ID = this.ID; a.Message = this.Message; a.Role = this.Role; a.See = this.See; a.Subject = this.Subject; a.Test = negatedTest; return a; }
public void Letting_Assert_String() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<foo>bar</foo>"); XPathNavigator nav = doc.DocumentElement.CreateNavigator(); XPathQueryLanguage query = new XPathQueryLanguage(); object context = query.CreateMatchContext(null, doc); query.Let(context, "x", "'bar'"); Assertion assert = new Assertion(); assert.Test = ". = $x"; Assert.IsTrue(query.Assert(assert, context, nav)); context = query.CreateMatchContext(null, doc); query.Let(context, "x", "'foo'"); Assert.IsFalse(query.Assert(assert, context, nav)); }
public void NumberCompare() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<foo a='3'/>"); XPathNavigator nav = doc.DocumentElement.CreateNavigator(); var query = QueryLanguage; var context = query.CreateMatchContext(null, doc); var assert = new Assertion { Test = "/foo[@a < 20]" }; Assert.IsTrue(query.Assert(assert, context, nav), assert.Test, "a < 20"); assert = new Assertion { Test = "/foo[@a < -1]" }; Assert.IsFalse(query.Assert(assert, context, nav), assert.Test, "a < -1"); assert = new Assertion { Test = "/foo[-1 < @a]" }; Assert.IsTrue(query.Assert(assert, context, nav), assert.Test, "-1 < @a"); }
/// <summary> /// Validates the saml20Assertion's list of conditions. /// </summary> private void ValidateConditions(Assertion saml20Assertion) { bool audienceRestrictionPresent = false; foreach (ConditionAbstract condition in saml20Assertion.Conditions.Items) { if (condition is AudienceRestriction) { audienceRestrictionPresent = true; AudienceRestriction audienceRestriction = (AudienceRestriction)condition; if (audienceRestriction.Audience == null || audienceRestriction.Audience.Count == 0) throw new DKSaml20FormatException( "The DK-SAML 2.0 profile requires that an \"AudienceRestriction\" element contains the service provider's unique identifier in an \"Audience\" element."); } } if (!audienceRestrictionPresent) throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that an \"AudienceRestriction\" element is present on the saml20Assertion."); }
public void AddAssertion(string userName, int categoryId, string tagName) { Check.Require(!userName.IsNullOrEmpty(), "userName must be provided."); Check.Require(categoryId > 0, "categoryId must be greater than 0."); Check.Require(!tagName.IsNullOrEmpty(), "tagName must be provided."); // TODO: Ideally we want a transaction here as we are potentially doing two updates. var profile = this.GetProfileByUserName(userName); var tag = this.tagRepository.FindOne(new TagByNameSpecification(tagName)); if (tag == null) { tag = new Tag { Name = tagName }; this.tagRepository.Save(tag); } // See if there's already an assertion for this tag/category combination var existingAssertion = profile.Assertions.FirstOrDefault( a => (a.Tag == tag) && (a.Category.Id == categoryId)); // If not add it. If there is, do nothing further - there's no point returning an error, since the user has what they wanted if (existingAssertion == null) { var category = this.GetCategory(categoryId); var newAssertion = new Assertion { Profile = profile, Category = category, Tag = tag }; profile.Assertions.Add(newAssertion); this.profileRepository.Save(profile); } }
public void Exists() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<foo><a/></foo>"); XPathNavigator nav = doc.DocumentElement.CreateNavigator(); var query = QueryLanguage; var context = query.CreateMatchContext(null, doc); var assert = new Assertion { Test = "exists(/foo)" }; Assert.IsTrue(query.Assert(assert, context, nav), assert.Test); assert = new Assertion { Test = "exists(/foo/a)" }; Assert.IsTrue(query.Assert(assert, context, nav), assert.Test); assert = new Assertion { Test = "exists(/foo/b, /foo/a, /foo)" }; Assert.IsTrue(query.Assert(assert, context, nav), assert.Test); assert = new Assertion { Test = "exists(/bar)" }; Assert.IsFalse(query.Assert(assert, context, nav), assert.Test); }
public void AddAssertion(AddAssertionDetails addAssertionDetails) { addAssertionDetails.Validate(); // TODO: Ideally we want a transaction here as we are potentially doing two updates. var profile = this.GetProfileByUserName(addAssertionDetails.UserName); var tag = this.tagRepository.FindOne(new TagByNameSpecification(addAssertionDetails.TagName)); if (tag == null) { tag = new Tag { Name = addAssertionDetails.TagName }; this.tagRepository.Save(tag); } // See if there's already an assertion for this tag/category combination var existingAssertion = profile.Assertions.FirstOrDefault( a => (a.Tag == tag) && (a.Category.Id == addAssertionDetails.CategoryId)); // If not add it. If there is, do nothing further - there's no point returning an error, since the user has what they wanted if (existingAssertion == null) { var category = this.GetCategory(addAssertionDetails.CategoryId); var newAssertion = new Assertion { Profile = profile, Category = category, Tag = tag }; profile.Assertions.Add(newAssertion); this.profileRepository.Save(profile); } }
public void TestAddUserToSPSite() { SPSite site = new SPSite(_newSPSiteUrl); // verify that this user is not already part of the site. try { SPUser user1 = site.RootWeb.AllUsers[_newUserLogin]; Assertion.Fail("The user should not be found in the new site"); } catch (Exception ignored) { // this is the exptected response } string result = result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _newSPSiteUrl, "true", _newUserLogin, _validRole)); // Verify that the user was added. SPUser user2 = site.RootWeb.AllUsers[_newUserLogin]; Assertion.AssertNotNull(user2); }
public static MutableEventInfo CreateWithAccessors( MutableType declaringType = null, string name = "UnspecifiedEvent", EventAttributes attributes = EventAttributes.None, Type handlerType = null, bool createRaiseMethod = false) { declaringType = declaringType ?? MutableTypeObjectMother.Create(); handlerType = handlerType ?? typeof(Func <,>).MakeGenericType(ReflectionObjectMother.GetSomeType(), ReflectionObjectMother.GetSomeOtherType()); Assertion.IsTrue(handlerType.IsSubclassOf(typeof(Delegate))); var invokeMethod = handlerType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var raiseParameterTypes = invokeMethod.GetParameters().Select(p => p.ParameterType).ToArray(); var addRemoveParameterTypes = new[] { handlerType }; var addMethod = CreateMethod(declaringType, "Adder", addRemoveParameterTypes); var removeMethod = CreateMethod(declaringType, "Remover", addRemoveParameterTypes); var raiseMethod = createRaiseMethod ? CreateMethod(declaringType, "Raiser", raiseParameterTypes, invokeMethod.ReturnType) : null; return(new MutableEventInfo(declaringType, name, attributes, addMethod, removeMethod, raiseMethod)); }
/// <summary> /// Gets or sets the delegate to handle updates of game-specific /// data like configs and overrides. It is used asynchronously. /// If update is successful, result should be set to true. /// Do not commit resolution (it is provided by the parameter). /// </summary> /// <value> /// The delegate. /// </value> // public static List<ICustomDynamicContent> CustomDynamicContent // { // set { m_customDynamicContent = value; } // get { return m_customDynamicContent; } // } public static void Init(params string[] baseUrls) { Debug.Log("Init - Started"); Assertion.Check((baseUrls != null) && (baseUrls.Length > 0), "No URL has been specified!"); if ((baseUrls != null) && (baseUrls.Length > 0)) { for (int idx = 0; idx < baseUrls.Length; ++idx) { while (baseUrls[idx].EndsWith("/")) { baseUrls[idx] = baseUrls[idx].Remove(baseUrls[idx].Length - 1); } } m_baseUrls = baseUrls; } else { m_baseUrls = new string[0]; } Debug.Log("Init - Finished"); }
public static void StartContentUpdate(DynamicContentParam param) { Debug.Log("StartContentUpdate - Started"); Assertion.Check(!m_isLoadingInProgress); if (m_isLoadingInProgress) { Debug.Log("StartContentUpdate - Stopping update-in-progress"); m_isLoadingInProgress = false; Instance.StopCoroutine("DoContentUpdate"); } if (m_isCheckingInProgress) { Debug.Log("StartContentUpdate - Stopping check-in-progress"); m_isCheckingInProgress = false; Instance.StopCoroutine("DoCheckForUpdates"); } Reset(true); m_isLoadingInProgress = true; Instance.StartCoroutine("DoContentUpdate", param); Debug.Log("StartContentUpdate - Finished"); }
public void CatchDollarSignInOutputPropertyName() { string projectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`t` > <CreateProperty Value=`x`> <Output TaskParameter=`Value` PropertyName=`$(x)`/> </CreateProperty> </Target> </Project> "; Project p = ObjectModelHelpers.CreateInMemoryProject(projectContents); MockLogger l = new MockLogger(); p.ParentEngine.RegisterLogger(l); p.Build(new string[] { "t" }, null); string warning = String.Format(MockLogger.GetString("DollarSignInTaskOutputPropertyName"), "$(x)"); Assertion.Assert(-1 != l.FullLog.IndexOf(warning)); }
private void OpenChameleon() { Assertion.Assert(!myOpened, "!myOpened"); Assertion.Assert(firstChild == lastChild && firstChild is IClosedChameleonBody, "One ChameleonElement child but found also {0}", lastChild.NodeType); var node = ((IClosedChameleonBody)firstChild).Parse(parser => ((IFSharpParser)parser).ParseExpression(this, FSharpFile.StandaloneDocument)); var oldLength = firstChild.GetTextLength(); var newLength = node.GetTextLength(); Assertion.Assert(oldLength == newLength, "Chameleon length is different after opening; old: {0}, new: {1}", oldLength, newLength); DeleteChildRange(firstChild, lastChild); AppendNewChild((TreeElement)node); myOpened = true; SynExpr = null; }
private LengthValidator CreateLengthValidator(IResourceManager resourceManager) { var maxLength = TextBoxStyle.MaxLength; Assertion.IsTrue(maxLength.HasValue); LengthValidator lengthValidator = new LengthValidator(); lengthValidator.ID = ID + "_ValidatorMaxLength"; lengthValidator.ControlToValidate = TargetControl.ID; lengthValidator.MaximumLength = maxLength.Value; if (string.IsNullOrEmpty(ErrorMessage)) { lengthValidator.ErrorMessage = string.Format(resourceManager.GetString(ResourceIdentifier.MaxLengthValidationMessage), maxLength.Value); } else { lengthValidator.ErrorMessage = ErrorMessage; } return(lengthValidator); }
private IExpressionNode ParseNonQueryOperatorExpression(Expression expression, string associatedIdentifier) { var preprocessedExpression = SubQueryFindingExpressionVisitor.Process(expression, _nodeTypeProvider); try { // Assertions to ensure the argument exception can only happen because of an unsupported type in expression. Assertion.IsNotNull(expression); Assertion.IsFalse(string.IsNullOrEmpty(associatedIdentifier)); return(new MainSourceExpressionNode(associatedIdentifier, preprocessedExpression)); } catch (ArgumentException ex) { var message = string.Format( "Cannot parse expression '{0}' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) " + "and query operators can be parsed.", preprocessedExpression.BuildString()); throw new NotSupportedException(message, ex); } }
protected override void DoTest(IProject testProject) { testProject.GetSolution().GetPsiServices().Files.CommitAllDocuments(); var textControl = OpenTextControl(TestLifetime); var document = textControl.Document; var psiSourceFile = document.GetPsiSourceFile(Solution); Assert.IsNotNull(psiSourceFile, "sourceFile == null"); using (ReadLockCookie.Create()) { var highlightingFinder = new IdentifierHighlightingFinder(psiSourceFile, new DocumentRange(document, new TextRange(textControl.Caret.Offset()))); highlightingFinder.DoHighlighting(DaemonProcessKind.VISIBLE_DOCUMENT); var highlightingInfo = highlightingFinder.HighlightingInfo; Assertion.AssertNotNull(highlightingInfo, "Highlighting not found"); var markupModel = Solution.GetComponent <IDocumentMarkupManager>().GetMarkupModel(document); var highlighterTooltipProvider = DaemonUtil.GetHighlighterTooltipProvider(highlightingInfo.Highlighting, Solution); var attributeId = HighlightingSettingsManager.Instance.GetAttributeId(highlightingInfo.Highlighting, psiSourceFile, Solution, psiSourceFile.GetSettingsStore(Solution)).NotNull(); var highlighter = markupModel.AddHighlighter("test", highlightingInfo.Range.TextRange, AreaType.EXACT_RANGE, 0, attributeId, new ErrorStripeAttributes(), highlighterTooltipProvider); ExecuteWithGold(writer => writer.WriteLine(highlighter.ToolTip)); } }
public string GetJoins() { string ret = String.Empty; if (Count > 0) { List <string> joins = new List <string>(); var joinAliases = GetJoinAliases(); this.ForEachWithIndex((j, idx) => { // Use the override if it exists, otherwise the default is the "with" table name + ID var tableFieldName = j.TableField ?? $"_{j.WithTable}ID"; var alias = joinAliases[idx].alias; var joinType = joinTemplate[j.Type]; // Find the join table alias. // Currently this functionality is limited to one table with which we join other tables. // To fix this, the dictionary needs to have some "key" (such as the qualifier) that determines which of multiple joins // to continue joining with. Too complicated to set up right now. var joinTableAliases = joinAliases.Where(a => a.Value.table == j.Table).ToList(); var joinTableAlias = j.Table; Assertion.IsTrue(joinTableAliases.Count <= 1, $"Unsupported: Cannot join multiple instances of {j.Table} with other joins."); if (joinTableAliases.Count == 1) { joinTableAlias = joinTableAliases[0].Value.alias; } var join = $"{joinType} {j.WithTable} {alias} on {alias}.{Constants.ID} = {joinTableAlias}.{tableFieldName} and {alias}.{Constants.DELETED} = 0"; joins.Add(join); }); ret = String.Join(Constants.CRLF, joins); } return(ret); }
public void TestLineLine1() { // test when the point being tested in a node on the line Coordinate coordLine1 = new Coordinate(5.0, 5.0); Coordinate coordLine2 = new Coordinate(10.0, 10.0); Coordinate coordLine3 = new Coordinate(5.0, 10.0); Coordinate coordLine4 = new Coordinate(10.0, 5.0); Coordinates coordinates1 = new Coordinates(); coordinates1.Add(coordLine1); coordinates1.Add(coordLine2); Coordinates coordinates2 = new Coordinates(); coordinates2.Add(coordLine3); coordinates2.Add(coordLine4); LineString linestring1 = _factory.CreateLineString(coordinates1); LineString linestring2 = _factory.CreateLineString(coordinates2); Geometry pt = linestring1.Intersection(linestring2); Assertion.AssertEquals("intersects", true, linestring1.Intersects(linestring2)); Assertion.AssertEquals("disjoint", false, linestring1.Disjoint(linestring2)); Assertion.AssertEquals("contains", false, linestring1.Contains(linestring2)); Assertion.AssertEquals("within", false, linestring1.Within(linestring2)); Assertion.AssertEquals("crosses", true, linestring1.Crosses(linestring2)); Assertion.AssertEquals("touches", false, linestring1.Touches(linestring2)); // always returns false when a point is involved Assertion.AssertEquals("overlaps", false, linestring1.Overlaps(linestring2)); }
void Validation() { int type0Count = CountTypes(qbt_File.Type0); int type1Count = CountTypes(qbt_File.Type1); int type2Count = CountTypes(qbt_File.Type2); for (int i = 0; i < type0Count; i++) { Assertion.AssertArraySize(qbt_File.Type0[i].I_00, 30, "Normal_Dialogue", "Table"); if (qbt_File.Type0[i].DialogueEntries != null) { for (int a = 0; a < qbt_File.Type0[i].DialogueEntries.Count(); a++) { Assertion.AssertStringSize(qbt_File.Type0[i].DialogueEntries[a].Str_18, 32, "Normal_Dialogue", "MSG"); } } } for (int i = 0; i < type1Count; i++) { Assertion.AssertArraySize(qbt_File.Type1[i].I_00, 30, "Interactive_Dialogue", "Table"); if (qbt_File.Type1[i].DialogueEntries != null) { for (int a = 0; a < qbt_File.Type1[i].DialogueEntries.Count(); a++) { Assertion.AssertStringSize(qbt_File.Type1[i].DialogueEntries[a].Str_18, 32, "Interactive_Dialogue", "MSG"); } } } for (int i = 0; i < type2Count; i++) { Assertion.AssertArraySize(qbt_File.Type2[i].I_00, 30, "Type2_Unknown", "Table"); if (qbt_File.Type2[i].DialogueEntries != null) { for (int a = 0; a < qbt_File.Type2[i].DialogueEntries.Count(); a++) { Assertion.AssertStringSize(qbt_File.Type2[i].DialogueEntries[a].Str_18, 32, "Type2_Unknown", "MSG"); } } } }
private T GetOrCreateExtension <T>([NotNull] string name, bool highPriorityExtension, [NotNull] Func <T> create) where T : class { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (create == null) { throw new ArgumentNullException(nameof(create)); } lock (myExtensions) { object existing; T res; if (myExtensions.TryGetValue(name, out existing)) { res = existing.NotNull("Found null value for key: '{0}'", name) as T; Assertion.Require(res != null, "Found bad value for key '{0}'. Expected type: '{1}', actual:'{2}", name, typeof(T).FullName, existing.GetType().FullName); } else { res = create().NotNull("'Create' result must not be null"); myExtensions[name] = res; if (res is IRdBindable) { var bindable = res as IRdBindable; BindableChildren.Insert(highPriorityExtension ? 0 : BindableChildren.Count, new KeyValuePair <string, object>(name, bindable)); if (myBindLifetime != Lifetime.Terminated) { bindable.Identify(Proto.Identities, RdId.Mix("." + name)); bindable.Bind(myBindLifetime, this, name); } } } return(res); } }
public CommandBarActionDef(VsShortcutFinder vsShortcutFinder, DTE dte, string actionId, CommandID commandId, CommandBarControl control, CommandBarPopup[] parentPopups) { ActionId = actionId; // Lazily initialise. Talking to the command bar objects is SLOOOOOOOWWWWWW. backingFields = Lazy.Of(() => { Assertion.AssertNotNull(control, "control != null"); var sb = new StringBuilder(); foreach (var popup in parentPopups) { sb.AppendFormat("{0} \u2192 ", popup.Caption); } var fields = new BackingFields { Text = MnemonicStore.RemoveMnemonicMark(control.Caption), Path = MnemonicStore.RemoveMnemonicMark(sb.ToString()) }; var command = VsCommandHelpers.TryGetVsCommandAutomationObject(commandId, dte); var vsShortcut = vsShortcutFinder.GetVsShortcut(command); if (vsShortcut != null) { var details = new ShortcutDetails[vsShortcut.KeyboardShortcuts.Length]; for (int i = 0; i < vsShortcut.KeyboardShortcuts.Length; i++) { var keyboardShortcut = vsShortcut.KeyboardShortcuts[i]; details[i] = new ShortcutDetails(KeyConverter.Convert(keyboardShortcut.Key), keyboardShortcut.Modifiers); } fields.VsShortcut = new ShortcutSequence(details); } return(fields); }, true); }
public void ExecuteTemplate() { IDeclaration newDeclaration = myDeclaration; newDeclaration.AssertIsValid(); ISolution solution = newDeclaration.GetPsiModule().GetSolution(); Debug.Assert(Shell.Instance.Invocator != null, "Shell.Instance.Invocator != null"); Shell.Instance.Invocator.Dispatcher.AssertAccess(); solution.GetComponent <SolutionDocumentTransactionManager>().AssertNotUnderTransaction(); IFile file = myAnchor.GetContainingFile(); Assertion.Assert(file != null, "fileFullName!= null"); var item = file.GetSourceFile().ToProjectFile(); var infos = GetFieldInfos(newDeclaration, myHolders); var textControl = EditorManager.GetInstance(solution).OpenProjectFile(item, true); if (textControl == null) { if (Shell.Instance.IsInInternalMode || Shell.Instance.IsTestShell) { Logger.Fail("textControl != null"); } return; } if (infos.Length > 0) { HotspotSession hotspotSession = LiveTemplatesManager.Instance.CreateHotspotSessionAtopExistingText(solution, TextRange.InvalidRange, textControl, LiveTemplatesManager.EscapeAction.LeaveTextAndCaret, infos); hotspotSession.Execute(); } Shell.Instance.GetComponent <PsiIntentionResultBehavior>().OnHotspotSessionExecutionStarted(this, textControl); }
public void test_removeLjava_lang_Object() { EnumMap <Size, Int32> enumSizeMap = new EnumMap <Size, Int32>(typeof(Size)); Assertion.AssertEquals("Remove of non-mapped key returned non-null", enumSizeMap //$NON-NLS-1$ .Remove(Size.Big), 0); enumSizeMap.Put(Size.Big, 3); enumSizeMap.Put(Size.Middle, 2); Assertion.AssertEquals("Get returned non-null for non mapped key", enumSizeMap //$NON-NLS-1$ .Get(Size.Small), 0); Assertion.AssertEquals("Remove returned incorrect value", 3, enumSizeMap //$NON-NLS-1$ .Remove(Size.Big)); Assertion.AssertEquals("Get returned non-null for non mapped key", enumSizeMap //$NON-NLS-1$ .Get(Size.Big), 0); Assertion.AssertEquals("Remove of non-mapped key returned non-null", enumSizeMap //$NON-NLS-1$ .Remove(Size.Big), 0); /*Assertion.AssertNull("Remove of non-existent key returned non-null", enumSizeMap //$NON-NLS-1$ * .Remove(Color.Red)); * Assertion.AssertNull("Remove of non-existent key returned non-null", enumSizeMap //$NON-NLS-1$ * .Remove(4)); * Assertion.AssertNull("Remove of non-existent key returned non-null", enumSizeMap //$NON-NLS-1$ * .Remove(null));*/ EnumMap <Color, Double> enumColorMap = new EnumMap <Color, Double>(typeof(Color)); Assertion.AssertEquals("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$ .Get(Color.Green), 0); enumColorMap.Put(Color.Green, 4); Assertion.AssertEquals("Remove returned incorrect value", 4, //$NON-NLS-1$ enumColorMap.Remove(Color.Green)); Assertion.AssertEquals("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$ .Get(Color.Green), 0); enumColorMap.Put(Color.Green, 0); Assertion.AssertEquals("Can not handle null value", enumColorMap //$NON-NLS-1$ .Remove(Color.Green), 0); Assertion.AssertEquals("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$ .Get(Color.Green), 0); }
/// <summary> /// Adds membership to a group if the membership is not already known. /// </summary> /// <param name="groupID">The group ID.</param> /// <param name="fixTimeUtc">The fix time.</param> /// <remarks> /// <note> /// This implementation assumes that entities will be members of only a handfull /// of groups (something like 10 or less), /// </note> /// </remarks> private void AddGroup(string groupID, DateTime fixTimeUtc) { Assertion.Test(groupID != null); if (groups == null) { groups = new GroupMembership[] { new GroupMembership() { GroupID = groupID, FixTimeUtc = fixTimeUtc } }; return; } if (IsMemberOf(groupID)) { return; } var newGroups = new GroupMembership[groups.Length + 1]; // I'm putting the new group at the front of the list since // under many circumstances fixes for older groups will tend not // to be seen anymore and will eventually be flushed from the // cache. This will improve IsMemberOf() performance for many // real world cases. newGroups[0] = new GroupMembership() { GroupID = groupID, FixTimeUtc = fixTimeUtc }; Array.Copy(groups, 0, newGroups, 1, groups.Length); groups = newGroups; }
public void test_CompareTo() { //create a coordinate (the z value is not used so there is no need to create it) Coordinate coord = new Coordinate(testX, testY); //create an equal coordinate Coordinate coord2 = new Coordinate(1.0, 2.0); //create a coordinate where X is greater & Y is equal Coordinate coord3 = new Coordinate(2.0, 2.0); //create a coordinate where Y is greater & x is equal Coordinate coord4 = new Coordinate(1.0, 3.0); //create a coordinate where both X & Y are greater Coordinate coord5 = new Coordinate(2.0, 3.0); //create a coordinate where X is less & Y is equal Coordinate coord6 = new Coordinate(0.0, 2.0); //create a coordinate where Y is less & X is equal Coordinate coord7 = new Coordinate(1.0, 1.0); //create a coordinate where both are less Coordinate coord8 = new Coordinate(0.0, 0.0); //create a point to send to throw the exception _gf = new GeometryFactory(_pm, _srid); Point point = _gf.CreatePoint(coord); Assertion.AssertEquals("CompareTo1: ", 0, coord.CompareTo(coord2)); Assertion.AssertEquals("CompareTo2: ", -1, coord.CompareTo(coord3)); Assertion.AssertEquals("CompareTo3: ", -1, coord.CompareTo(coord4)); Assertion.AssertEquals("CompareTo4: ", -1, coord.CompareTo(coord5)); Assertion.AssertEquals("CompareTo5: ", 1, coord.CompareTo(coord6)); Assertion.AssertEquals("CompareTo6: ", 1, coord.CompareTo(coord7)); Assertion.AssertEquals("CompareTo7: ", 1, coord.CompareTo(coord8)); try { coord.CompareTo(point); Assertion.Fail("ArgumentException should have been thrown"); } catch (ArgumentException) { } }
private bool IsHandlerExists(Lifetime lifetime, int projectId, string className, string methodName) { using (TryReadLockCookie.Create(NullProgressIndicator.Create(), _locks, () => !lifetime.IsAlive || _locks.ContentModelLocks.IsWriteLockRequested)) { var project = _projectModelViewHost.GetItemById <IProject>(projectId); Assertion.AssertNotNull(project, "project instance shoud not be null"); _logger.Verbose($"Searching handler with name '{className}.{methodName}' in the project {project}..."); var psiModules = project.GetPsiModules(); foreach (var psiModule in psiModules) { using (CompilationContextCookie.OverrideOrCreate(psiModule.GetContextFromModule())) { var scope = _symbolCache.GetSymbolScope(psiModule, false, true); var typeElements = scope.GetElementsByQualifiedName(className).OfType <IClass>(); foreach (var typeElement in typeElements) { InterruptableActivityCookie.CheckAndThrow(); foreach (var method in typeElement.Methods) { if (method.ShortName != methodName) { continue; } if (!LambdaFinder.IsSuitableLambdaMethod(method)) { continue; } return(true); } } } } } return(false); }
private void RenderTitleCellSortingButton( BocColumnRenderingContext <TBocColumnDefinition> renderingContext, SortingDirection sortingDirection, int orderIndex) { if (sortingDirection == SortingDirection.None) { return; } // WhiteSpace before icon renderingContext.Writer.Write(c_whiteSpace); renderingContext.Writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClasses.SortingOrder); renderingContext.Writer.RenderBeginTag(HtmlTextWriterTag.Span); BocList.ResourceIdentifier alternateTextID; if (sortingDirection == SortingDirection.Ascending) { alternateTextID = BocList.ResourceIdentifier.SortAscendingAlternateText; } else { alternateTextID = BocList.ResourceIdentifier.SortDescendingAlternateText; } var imageUrl = GetImageUrl(sortingDirection); Assertion.IsNotNull(imageUrl); var icon = new IconInfo(imageUrl.GetUrl()); icon.AlternateText = renderingContext.Control.GetResourceManager().GetString(alternateTextID); icon.Render(renderingContext.Writer, renderingContext.Control); if (renderingContext.Control.IsShowSortingOrderEnabled && orderIndex >= 0) { renderingContext.Writer.Write(c_whiteSpace + (orderIndex + 1)); } renderingContext.Writer.RenderEndTag(); }
public void ModifyItemThatWasAddedInSameScope() { Hashtable table1 = new Hashtable(StringComparer.OrdinalIgnoreCase); Lookup lookup = LookupHelpers.CreateLookup(table1); lookup.EnterScope(); // Add an item with m=m1 BuildItem item1 = new BuildItem("i1", "a2"); item1.SetMetadata("m", "m1"); lookup.AddNewItem(item1); // Change the item to be m=m2 Dictionary <string, string> newMetadata = new Dictionary <string, string>(); newMetadata.Add("m", "m2"); BuildItemGroup group = new BuildItemGroup(); group.AddItem(item1); lookup.ModifyItems(item1.Name, group, newMetadata); // Now it has m=m2 group = lookup.GetItems("i1"); Assertion.AssertEquals(1, group.Count); Assertion.AssertEquals("m2", group[0].GetMetadata("m")); // But the original item hasn't changed yet Assertion.AssertEquals("m1", item1.GetMetadata("m")); lookup.LeaveScope(); // It still has m=m2 group = lookup.GetItems("i1"); Assertion.AssertEquals(1, group.Count); Assertion.AssertEquals("m2", group[0].GetMetadata("m")); // But now the original item has changed as well Assertion.AssertEquals("m2", item1.GetMetadata("m")); }
private object ActivateRd(Type type) { #if JET_MODE_ASSERT Assertion.Assert(!myCurrentActivationChain.Contains(type), $"Unable to activate {type.FullName}: circular dependency detected: {string.Join(" -> ", myCurrentActivationChain.Select(t => t.FullName).ToArray())}"); myCurrentActivationChain.Enqueue(type); #endif var typeInfo = type.GetTypeInfo(); ReflectionSerializerVerifier.AssertValidRdExt(typeInfo); var implementingType = ReflectionSerializerVerifier.GetImplementingType(typeInfo); Assertion.Assert(typeof(IRdBindable).GetTypeInfo().IsAssignableFrom(implementingType), $"Unable to activate {type.FullName}: type should be {nameof(IRdBindable)}"); var instance = Activator.CreateInstance(implementingType); var implementingTypeInfo = implementingType.GetTypeInfo(); foreach (var mi in ReflectionSerializers.GetBindableMembers(implementingTypeInfo)) { ReflectionSerializerVerifier.AssertMemberDeclaration(mi); var currentValue = ReflectionUtil.GetGetter(mi)(instance); if (currentValue == null) { currentValue = ActivateRdExtMember(mi); var memberSetter = ReflectionUtil.GetSetter(mi); memberSetter(instance, currentValue); } } #if JET_MODE_ASSERT myCurrentActivationChain.Dequeue(); #endif // Allow initialize to setup bindings to composite properties. if (instance is RdReflectionBindableBase reflectionBindable) { reflectionBindable.OnActivated(); } return(instance); }
public Pattern AddDocumentLevelTemplateConstraints(ImplementationGuide aImplementationGuide, Phase aPhase) { Pattern newPattern = null; string test = GenerateDocumentLevelTemplateConstraints(aImplementationGuide, aPhase); if (!string.IsNullOrEmpty(test)) { string templateContext = string.Format("{0}:ClinicalDocument", this.ig.ImplementationGuideType.SchemaPrefix); newPattern = new Pattern() { ID = "p-DOCUMENT-TEMPLATE", Name = "p-DOCUMENT-TEMPLATE" }; Rule newRule = new Rule() { Id = "r-errors-DOC", Context = templateContext }; Assertion newAssertion = new Assertion() { Id = "IG-" + aImplementationGuide.Id.ToString(), IdPostFix = "-DOC", AssertionMessage = "The document must contain at least 1 of the document level templates for this schematron to be applicable.", Test = test }; newRule.Assertions.Add(newAssertion); newPattern.Rules.Add(newRule); if (newPattern.Rules.Count > 0) { aPhase.ActivePatterns.Add(newPattern); } } return(newPattern); }
public object Load(IProgressIndicator progress, bool enablePersistence) { if (!enablePersistence) { return(null); } Assertion.Assert(myPersistentCache == null, "myPersistentCache == null"); using (ReadLockCookie.Create()) { myPersistentCache = new PsiPersistentCache <CachePair>(myShellLocks, VERSION, "PsiCache", myPsiConfiguration); } var data = new Dictionary <IPsiSourceFile, CachePair>(); if (myPersistentCache.Load(progress, myPersistentIdIndex, (file, reader) => { using (ReadLockCookie.Create()) { return(PsiCacheBuilder.Read(reader, file)); } }, (projectFile, psiSymbols) => { if (projectFile != null) { data[projectFile] = psiSymbols; } }) != LoadResult.OK) { // clear all... ((ICache)this).Release(); return(null); } return(data); }
protected override Expression VisitBinary(BinaryExpression expression) { ArgumentUtility.CheckNotNull("expression", expression); var childContext = BooleanUtility.IsBooleanType(expression.Type) ? GetChildSemanticsForBinaryBoolExpression(expression.NodeType) : SqlExpressionContext.SingleValueRequired; var left = ApplySqlExpressionContext(expression.Left, childContext); var right = ApplySqlExpressionContext(expression.Right, childContext); if (BooleanUtility.IsBooleanType(expression.Type) && expression.NodeType == ExpressionType.Coalesce) { // In predicate context, we can ignore coalesces towards false, treat like a conversion to bool instead. (SQL treats NULL values in a falsey // way in predicate contexts.) if (_currentContext == SqlExpressionContext.PredicateRequired && expression.Right is ConstantExpression && Equals(((ConstantExpression)expression.Right).Value, false)) { return(Visit(Expression.Convert(expression.Left, expression.Type))); } // We'll pull out the bool conversion marker from the operands of the Coalesce expression and instead put it around the whole expression. // That way, HandleValueSemantics will not try to convert us back to a value; this avoids double CASE WHENs. // We know that left and right must be ConvertedBooleanExpressions because Coalesce has single value semantics for its operands, and boolean // Coalesces must have booleans operands. Applying value semantics to boolean operands results in ConvertedBooleanExpression values. Assertion.DebugAssert(childContext == SqlExpressionContext.SingleValueRequired); Assertion.DebugAssert(left is SqlConvertedBooleanExpression); Assertion.DebugAssert(right is SqlConvertedBooleanExpression); var newCoalesceExpression = Expression.Coalesce(((SqlConvertedBooleanExpression)left).Expression, ((SqlConvertedBooleanExpression)right).Expression); return(new SqlConvertedBooleanExpression(newCoalesceExpression)); } if (left != expression.Left || right != expression.Right) { return(Expression.MakeBinary(expression.NodeType, left, right, expression.IsLiftedToNull, expression.Method)); } return(expression); }
public Type SubstituteGenericParameters(Type type, IDictionary <Type, Type> parametersToArguments) { ArgumentUtility.CheckNotNull("type", type); ArgumentUtility.CheckNotNull("parametersToArguments", parametersToArguments); Type typeArgument; if (parametersToArguments.TryGetValue(type, out typeArgument)) { return(Assertion.IsNotNull(typeArgument, "Type-argument for type-parameter '{0}' was null.", type)); } if (type.IsArray) { return(SubstituteArrayElementType(type, parametersToArguments)); } if (type.IsByRef) { return(SubstituteByRefElementType(type, parametersToArguments)); } if (!type.IsGenericType) { return(type); } var oldTypeArguments = type.GetGenericArguments(); var newTypeArguments = oldTypeArguments.Select(t => SubstituteGenericParameters(t, parametersToArguments)).ToList(); // No substitution necessary (this is an optimization only). if (oldTypeArguments.SequenceEqual(newTypeArguments)) { return(type); } var genericTypeDefinition = type.GetGenericTypeDefinition(); var instantiationInfo = new TypeInstantiationInfo(genericTypeDefinition, newTypeArguments); return(Instantiate(instantiationInfo)); }
/// <summary> /// Extracts the list of attributes from the <AttributeStatement> of the assertion, and /// stores it in <code>_assertionAttributes</code>. /// </summary> private void ExtractAttributes() { _assertionAttributes = new List <SamlAttribute>(0); _encryptedAssertionAttributes = new List <EncryptedElement>(0); XmlNodeList list = _samlAssertion.GetElementsByTagName(AttributeStatement.ELEMENT_NAME, Saml20Constants.ASSERTION); if (list.Count == 0) { return; } // NOTE It would be nice to implement a better-performing solution where only the AttributeStatement is converted. // NOTE Namespace issues in the xml-schema "type"-attribute prevents this, though. Assertion assertion = Serialization.Deserialize <Assertion>(new XmlNodeReader(_samlAssertion)); List <AttributeStatement> attributeStatements = assertion.GetAttributeStatements(); if (attributeStatements.Count == 0 || attributeStatements[0].Items == null) { return; } AttributeStatement attributeStatement = attributeStatements[0]; foreach (object item in attributeStatement.Items) { if (item is SamlAttribute) { _assertionAttributes.Add((SamlAttribute)item); } if (item is EncryptedElement) { _encryptedAssertionAttributes.Add((EncryptedElement)item); } } }
public void EmptyTar() { MemoryStream ms = new MemoryStream(); TarArchive tarOut = TarArchive.CreateOutputTarArchive(ms); tarOut.CloseArchive(); Assertion.Assert("Archive size must be > zero", ms.GetBuffer().Length > 0); Assertion.AssertEquals("Archive size must be a multiple of record size", ms.GetBuffer().Length % tarOut.RecordSize, 0); MemoryStream ms2 = new MemoryStream(); ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); TarArchive tarIn = TarArchive.CreateInputTarArchive(ms2); entryCount = 0; tarIn.ProgressMessageEvent += new ProgressMessageHandler(EntryCounter); tarIn.ListContents(); Assertion.AssertEquals("Expected 0 tar entries", 0, entryCount); }
public void VerifyWarningForOrder() { // Create a project file that has an expression MockLogger ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@" <Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`expression 1 is true ` Condition=`$(a) == 1 and $(b) == 2 or $(c) == 3`/> </Target> </Project> ", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath)); // Make sure the log contains the correct strings. Assertion.Assert("Need to warn for this expression - (a) == 1 and $(b) == 2 or $(c) == 3.", ml.FullLog.Contains("MSB4130:")); ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@" <Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`expression 1 is true ` Condition=`$(a) == 1 or $(b) == 2 and $(c) == 3`/> </Target> </Project> ", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath)); // Make sure the log contains the correct strings. Assertion.Assert("Need to warn for this expression - (a) == 1 or $(b) == 2 and $(c) == 3.", ml.FullLog.Contains("MSB4130:")); ml = ObjectModelHelpers.BuildProjectExpectSuccess(String.Format(@" <Project ToolsVersion=`3.5` xmlns=`msbuildnamespace`> <Target Name=`Build`> <Message Text=`expression 1 is true ` Condition=`($(a) == 1 or $(b) == 2 and $(c) == 3) or $(d) == 4`/> </Target> </Project> ", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath)); // Make sure the log contains the correct strings. Assertion.Assert("Need to warn for this expression - ($(a) == 1 or $(b) == 2 and $(c) == 3) or $(d) == 4.", ml.FullLog.Contains("MSB4130:")); }
/// <summary> /// Test dzia³ania dla przypadku, gdy nie ma iloœci widzów, ale jest /// cena od osoby. Iloœæ widzów powinna byæ co najmniej równa minimalnej /// i na tyle du¿a, by gwarantowaæ minimalny przychód z pokazu. /// </summary> public void TestNoHeadcount() { String s = "Date, November 5, City, Springfield, " + "DollarsPerHead, 9.95, HasSite, false"; ForgivingBuilder b = new ForgivingBuilder(); ReservationParser p = new ReservationParser(b); p.Parse(s); Reservation r = b.Build(); // DateTime d = new DateTime(2000, 11, 5); d = ReservationBuilder.Futurize(d); // Assertion.AssertEquals(d, r.Date); Assertion.Assert(r.Headcount >= ReservationBuilder.MINHEAD); Assertion.Assert(r.Headcount * r.DollarsPerHead >= ReservationBuilder.MINTOTAL); Assertion.AssertEquals("Springfield", r.City); Assertion.AssertEquals(9.95, (double)r.DollarsPerHead, .01); Assertion.AssertEquals(false, r.HasSite); }
protected override object VisitAssertion(Assertion assertion, object arg) { return arg; }
public override bool Equals(Assertion other) => InvocationExpression.GetDocumentRange() == (other as InlineAssertion)?.InvocationExpression.GetDocumentRange();
public virtual Differences VisitAssertion(Assertion assertion1, Assertion assertion2){ Differences differences = new Differences(assertion1, assertion2); if (assertion1 == null || assertion2 == null){ if (assertion1 != assertion2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++; return differences; } Assertion changes = (Assertion)assertion2.Clone(); Assertion deletions = (Assertion)assertion2.Clone(); Assertion insertions = (Assertion)assertion2.Clone(); Differences diff = this.VisitExpression(assertion1.Condition, assertion2.Condition); if (diff == null){Debug.Assert(false); return differences;} changes.Condition = diff.Changes as Expression; deletions.Condition = diff.Deletions as Expression; insertions.Condition = diff.Insertions as Expression; Debug.Assert(diff.Changes == changes.Condition && diff.Deletions == deletions.Condition && diff.Insertions == insertions.Condition); differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; if (differences.NumberOfDifferences == 0){ differences.Changes = null; differences.Deletions = null; differences.Insertions = null; }else{ differences.Changes = changes; differences.Deletions = deletions; differences.Insertions = insertions; } return differences; }
public override Statement VisitAssertion(Assertion assertion){ bool savedInsideAssertion = this.insideAssertion; this.insideAssertion = true; try{ return base.VisitAssertion(assertion); }finally{ this.insideAssertion = savedInsideAssertion; } }
void WriteAssertion(Assertion a) { writer.WriteStartElement(a is Report ? report : assert, namespaceURI); if (!string.IsNullOrEmpty(a.Test)) writer.WriteAttributeString(test, a.Test); if (!string.IsNullOrEmpty(a.ID)) writer.WriteAttributeString(id, a.ID); if (!string.IsNullOrEmpty(a.Diagnostics)) writer.WriteAttributeString(diagnostics, a.Diagnostics); if (!string.IsNullOrEmpty(a.Flag)) writer.WriteAttributeString(flag, a.Flag); if (!string.IsNullOrEmpty(a.Role)) writer.WriteAttributeString(role, a.Role); if (a.Subject != ".") writer.WriteAttributeString(subject, a.Subject); if (!string.IsNullOrEmpty(a.Fpi)) writer.WriteAttributeString(fpi, a.Fpi); if (!string.IsNullOrEmpty(a.Icon)) writer.WriteAttributeString(icon, a.Icon); if (!string.IsNullOrEmpty(a.See)) writer.WriteAttributeString(see, a.See); WriteAnnotation(a.Message); writer.WriteEndElement(); }
public TestResult AssertFailure(Assertion assertion, IEnumerable<string> logs) { throw new NotImplementedException(); }
/// <summary> /// Validates the details of the Statements present in the assertion ([SAML2.0 standard] section 2.7) /// NOTE: the rules relating to the enforcement of a Subject element are handled during Subject validation /// </summary> /// <param name="assertion">The assertion.</param> private void ValidateStatements(Assertion assertion) { // Statements are not required if (assertion.Items == null) { return; } foreach (var o in assertion.Items) { _statementValidator.ValidateStatement(o); } }
public virtual Statement VisitAssertion(Assertion assertion, Assertion changes, Assertion deletions, Assertion insertions){ this.UpdateSourceContext(assertion, changes); if (assertion == null) return changes; if (changes != null){ if (deletions == null || insertions == null) Debug.Assert(false); else{ assertion.Condition = this.VisitExpression(assertion.Condition, changes.Condition, deletions.Condition, insertions.Condition); } }else if (deletions != null) return null; return assertion; }
public void StringCompare() { XmlDocument doc = new XmlDocument(); doc.LoadXml("<foo a='alpha' b='beta'/>"); XPathNavigator nav = doc.DocumentElement.CreateNavigator(); var query = QueryLanguage; var context = query.CreateMatchContext(null, doc); var assert = new Assertion { Test = "/foo[@a < @b]" }; Assert.IsTrue(query.Assert(assert, context, nav), assert.Test, "a < b"); }
/// <summary> /// Validates that all the required attributes are present on the assertion. /// Furthermore it validates validity of the Issuer element. /// </summary> /// <param name="assertion">The assertion.</param> private void ValidateAssertionAttributes(Assertion assertion) { // There must be a Version if (!Saml20Utils.ValidateRequiredString(assertion.Version)) { throw new Saml20FormatException("Assertion element must have the Version attribute set."); } // Version must be 2.0 if (assertion.Version != Saml20Constants.Version) { throw new Saml20FormatException("Wrong value of version attribute on Assertion element"); } // Assertion must have an ID if (!Saml20Utils.ValidateRequiredString(assertion.Id)) { throw new Saml20FormatException("Assertion element must have the ID attribute set."); } // Make sure that the ID elements is at least 128 bits in length (SAML2.0 std section 1.3.4) if (!Saml20Utils.ValidateIdString(assertion.Id)) { throw new Saml20FormatException("Assertion element must have an ID attribute with at least 16 characters (the equivalent of 128 bits)"); } // IssueInstant must be set. if (!assertion.IssueInstant.HasValue) { throw new Saml20FormatException("Assertion element must have the IssueInstant attribute set."); } // There must be an Issuer if (assertion.Issuer == null) { throw new Saml20FormatException("Assertion element must have an issuer element."); } // The Issuer element must be valid _nameIdValidator.ValidateNameId(assertion.Issuer); }
/// <summary> /// Validates the Assertion's conditions /// Audience restrictions processing rules are: /// - Within a single audience restriction condition in the assertion, the service must be configured /// with an audience-list that contains at least one of the restrictions in the assertion ("OR" filter) /// - When multiple audience restrictions are present within the same assertion, all individual audience /// restriction conditions must be met ("AND" filter) /// </summary> /// <param name="assertion">The assertion.</param> private void ValidateConditions(Assertion assertion) { // Conditions are not required if (assertion.Conditions == null) { return; } var oneTimeUseSeen = false; var proxyRestrictionsSeen = false; ValidateConditionsInterval(assertion.Conditions); foreach (var cat in assertion.Conditions.Items) { if (cat is OneTimeUse) { if (oneTimeUseSeen) { throw new Saml20FormatException("Assertion contained more than one condition of type OneTimeUse"); } oneTimeUseSeen = true; continue; } if (cat is ProxyRestriction) { if (proxyRestrictionsSeen) { throw new Saml20FormatException("Assertion contained more than one condition of type ProxyRestriction"); } proxyRestrictionsSeen = true; var proxyRestriction = (ProxyRestriction)cat; if (!string.IsNullOrEmpty(proxyRestriction.Count)) { uint res; if (!uint.TryParse(proxyRestriction.Count, out res)) { throw new Saml20FormatException("Count attribute of ProxyRestriction MUST BE a non-negative integer"); } } if (proxyRestriction.Audience != null) { foreach (var audience in proxyRestriction.Audience) { if (!Uri.IsWellFormedUriString(audience, UriKind.Absolute)) { throw new Saml20FormatException("ProxyRestriction Audience MUST BE a wellformed uri"); } } } } // AudienceRestriction processing goes here (section 2.5.1.4 of [SAML2.0 standard]) if (cat is AudienceRestriction) { // No audience restrictions? No problems... var audienceRestriction = (AudienceRestriction)cat; if (audienceRestriction.Audience == null || audienceRestriction.Audience.Count == 0) { continue; } // If there are no allowed audience uris configured for the service, the assertion is not // valid for this service if (_allowedAudienceUris == null || _allowedAudienceUris.Count < 1) { throw new Saml20FormatException("The service is not configured to meet any audience restrictions"); } string match = null; foreach (var audience in audienceRestriction.Audience) { // In QuirksMode this validation is omitted if (!_quirksMode) { // The given audience value MUST BE a valid URI if (!Uri.IsWellFormedUriString(audience, UriKind.Absolute)) { throw new Saml20FormatException("Audience element has value which is not a wellformed absolute uri"); } } match = _allowedAudienceUris.Find(allowedUri => allowedUri.Equals(audience)); if (match != null) { break; } } var logger = Logging.LoggerProvider.LoggerFor(GetType()); if (logger.IsDebugEnabled) { var intended = string.Join(", ", audienceRestriction.Audience.ToArray()); var allowed = string.Join(", ", _allowedAudienceUris.ToArray()); logger.DebugFormat(TraceMessages.AudienceRestrictionValidated, intended, allowed); } if (match == null) { throw new Saml20FormatException("The service is not configured to meet the given audience restrictions"); } } } }
public override Statement VisitAssertion(Assertion assertion) { if (assertion == null) return null; this.insideAssertOrAssume = true; assertion.Condition = this.VisitBooleanExpression(assertion.Condition); this.insideAssertOrAssume = false; return assertion; }
public virtual void VisitAssertion(Assertion assertion) { if (assertion == null) return; this.VisitExpression(assertion.Condition); }
public virtual Statement VisitAssertion(Assertion assertion){ if (assertion == null) return null; assertion.Condition = this.VisitExpression(assertion.Condition); return assertion; }
/// <summary> /// Signs the assertion with the given certificate. /// </summary> /// <param name="cert">The certificate to sign the assertion with.</param> public void Sign(X509Certificate2 cert) { CheckCertificateCanSign(cert); // Clear the strongly typed version of the assertion in preparation for a new source. _assertion = null; // Merge the modified attributes to the assertion. InsertAttributes(); // Remove existing signatures when resigning the assertion var signatureParentNode = XmlAssertion; // FIX.DocumentElement; XmlNode sigNode; while ((sigNode = signatureParentNode.GetElementsByTagName(Schema.XmlDSig.Signature.ElementName, Saml20Constants.Xmldsig)[0]) != null) { signatureParentNode.RemoveChild(sigNode); } var assertionDocument = new XmlDocument(); assertionDocument.Load(new StringReader(Serialization.SerializeToXmlString(XmlAssertion))); AddSignature(assertionDocument, cert); LoadXml(assertionDocument.DocumentElement, new List<AsymmetricAlgorithm>(new[] { cert.PublicKey.Key })); }
/// <summary> /// Validates the subject of an Assertion /// </summary> /// <param name="assertion">The assertion.</param> private void ValidateSubject(Assertion assertion) { if (assertion.Subject == null) { // If there is no statements there must be a subject // as specified in [SAML2.0 standard] section 2.3.3 if (assertion.Items == null || assertion.Items.Length == 0) { throw new Saml20FormatException("Assertion with no Statements must have a subject."); } foreach (var o in assertion.Items) { // If any of the below types are present there must be a subject. if (o is AuthnStatement || o is AuthzDecisionStatement || o is AttributeStatement) { throw new Saml20FormatException("AuthnStatement, AuthzDecisionStatement and AttributeStatement require a subject."); } } } else { // If a subject is present, validate it _subjectValidator.ValidateSubject(assertion.Subject); } }