/// <summary> /// Initializes a new instance of the <see cref="PolicyInjectionBehavior"/> with the given information /// about what's being intercepted and the current set of injection policies. /// </summary> /// <param name="interceptionRequest">Information about what will be injected.</param> /// <param name="policies">Current injection policies.</param> /// <param name="container">Unity container that can be used to resolve call handlers.</param> public PolicyInjectionBehavior(CurrentInterceptionRequest interceptionRequest, InjectionPolicy[] policies, IUnityContainer container) { var allPolicies = new PolicySet(policies); bool hasHandlers = false; var manager = new PipelineManager(); foreach (MethodImplementationInfo method in interceptionRequest.Interceptor.GetInterceptableMethods( interceptionRequest.TypeToIntercept, interceptionRequest.ImplementationType)) { bool hasNewHandlers = manager.InitializePipeline(method, allPolicies.GetHandlersFor(method, container)); hasHandlers = hasHandlers || hasNewHandlers; } pipelineManager = hasHandlers ? manager : null; }
public void HandlersOrderedProperly() { RuleDrivenPolicy policy = new RuleDrivenPolicy("MatchesInterfacePolicy", new IMatchingRule[] { new TypeMatchingRule("ITwo") }, new string[] { "Handler1", "Handler2", "Handler3", "Handler4" }); ICallHandler handler1 = new CallCountHandler(); handler1.Order = 3; ICallHandler handler2 = new CallCountHandler(); handler2.Order = 0; ICallHandler handler3 = new CallCountHandler(); handler3.Order = 2; ICallHandler handler4 = new CallCountHandler(); handler4.Order = 1; container .RegisterInstance <ICallHandler>("Handler1", handler1) .RegisterInstance <ICallHandler>("Handler2", handler2) .RegisterInstance <ICallHandler>("Handler3", handler3) .RegisterInstance <ICallHandler>("Handler4", handler4); PolicySet policies = new PolicySet(policy); MethodImplementationInfo twoInfo = new MethodImplementationInfo( typeof(ITwo).GetMethod("Two"), typeof(TwoType).GetMethod("Two")); List <ICallHandler> handlers = new List <ICallHandler>(policies.GetHandlersFor(twoInfo, container)); Assert.AreSame(handler4, handlers[0]); Assert.AreSame(handler3, handlers[1]); Assert.AreSame(handler1, handlers[2]); Assert.AreSame(handler2, handlers[3]); }
public void ShouldBeAbleToAddOnePolicy() { PolicySet policies = new PolicySet(); RuleDrivenPolicy p = new RuleDrivenPolicy("NameMatching"); p.RuleSet.Add(new MemberNameMatchingRule("ShouldBeAbleToAddOnePolicy")); p.Handlers.Add(new Handler1()); p.Handlers.Add(new Handler2()); policies.Add(p); MethodBase thisMember = GetType().GetMethod("ShouldBeAbleToAddOnePolicy"); List <ICallHandler> handlers = new List <ICallHandler>(policies.GetHandlersFor(thisMember)); Assert.IsTrue(policies.AppliesTo(GetType())); Assert.AreEqual(2, handlers.Count); Assert.IsTrue(typeof(Handler1) == handlers[0].GetType()); Assert.IsTrue(typeof(Handler2) == handlers[1].GetType()); }
public override void Initialize(MonoDevelop.Ide.Gui.Dialogs.OptionsDialog dialog, object dataObject) { base.Initialize(dialog, dataObject); panelData = (MimeTypePanelData)dataObject; if (panelData.DataObject is SolutionItem) { bag = ((SolutionItem)panelData.DataObject).Policies; } else if (panelData.DataObject is Solution) { bag = ((Solution)panelData.DataObject).Policies; } else if (panelData.DataObject is PolicySet) { polSet = ((PolicySet)panelData.DataObject); } mimeType = panelData.MimeType; panelData.SectionPanel = this; isRoot = polSet != null || bag.IsRoot; }
public void ShouldMatchPolicyByTypeName() { PolicySet policies = GetMultiplePolicySet(); Assert.IsTrue(policies.AppliesTo(typeof(MatchesByType))); MethodInfo nameDoesntMatchMember = typeof(MatchesByType).GetMethod("NameDoesntMatch"); MethodInfo nameMatchMember = typeof(MatchesByType).GetMethod("NameMatch"); List <ICallHandler> nameDoesntMatchHandlers = new List <ICallHandler>(policies.GetHandlersFor(nameDoesntMatchMember)); List <ICallHandler> nameMatchHandlers = new List <ICallHandler>(policies.GetHandlersFor(nameMatchMember)); Assert.AreEqual(1, nameDoesntMatchHandlers.Count); Assert.IsTrue(typeof(Handler1) == nameDoesntMatchHandlers[0].GetType()); Assert.AreEqual(2, nameMatchHandlers.Count); Assert.IsTrue(typeof(Handler1) == nameMatchHandlers[0].GetType()); Assert.IsTrue(typeof(Handler2) == nameMatchHandlers[1].GetType()); }
void OnPolicySelectionChanged(object s, ComboSelectionChangedArgs args) { Gtk.TreeIter iter; if (store.GetIter(out iter, new Gtk.TreePath(args.Path))) { MimeTypePanelData mt = (MimeTypePanelData)store.GetValue(iter, 0); if (args.Active != -1) { string sel = args.ActiveText; if (sel == (panel.IsCustomUserPolicy ? systemPolicyText : parentPolicyText)) { mt.UseParentPolicy = true; } else if (sel != customPolicyText) { PolicySet pset = PolicyService.GetPolicySet(sel); mt.AssignPolicies(pset); } } } }
void HandleFromProject(object sender, EventArgs e) { ImportProjectPolicyDialog dlg = new ImportProjectPolicyDialog(); try { if (MessageService.RunCustomDialog(dlg, this) == (int)Gtk.ResponseType.Ok) { PolicySet pset = new PolicySet(); pset.CopyFrom(dlg.SelectedItem.Policies); pset.Name = GetValidName(dlg.PolicyName); sets.Add(pset); FillPolicySets(); policiesCombo.Active = sets.IndexOf(pset); } } finally { dlg.Destroy(); } }
protected void OnButtonOkClicked(object sender, System.EventArgs e) { if (radioCustom.Active) { if (entryName.Text.Length == 0) { MessageService.ShowError(GettextCatalog.GetString("Policy name not specified")); return; } PolicySet pset = CreatePolicySet(); pset.Name = entryName.Text; PolicyService.AddUserPolicySet(pset); PolicyService.SavePolicies(); } else { if (fileEntry.Path == null || fileEntry.Path.Length == 0) { MessageService.ShowError(GettextCatalog.GetString("File name not specified")); return; } FilePath file = fileEntry.Path; if (file.Extension != ".mdpolicy") { file = file + ".mdpolicy"; } DefaultFileDialogPolicyDir = file.ParentDirectory; if (System.IO.File.Exists(file) && !MessageService.Confirm(GettextCatalog.GetString("The file {0} already exists. Do you want to replace it?", file), AlertButton.Replace)) { return; } PolicySet pset = CreatePolicySet(); pset.Name = file.FileName; pset.SaveToFile(file); } Respond(Gtk.ResponseType.Ok); }
public void CanCreatePolicyWithCustomCallHandler() { PolicyInjectionSettings settings = new PolicyInjectionSettings(); settings.Policies.Add(new PolicyData("Policy")); settings.Policies.Get(0).Handlers.Add(new CustomCallHandlerData("callCountHandler", typeof(CallCountHandler))); DictionaryConfigurationSource dictSource = new DictionaryConfigurationSource(); dictSource.Add(PolicyInjectionSettings.SectionName, settings); PolicySetFactory factory = new PolicySetFactory(dictSource); PolicySet policySet = factory.Create(); Assert.IsNotNull(policySet); RuleDrivenPolicy policy = (RuleDrivenPolicy)policySet[1]; Assert.IsNotNull(policy); Assert.AreEqual("Policy", policy.Name); Assert.AreEqual(1, policy.Handlers.Count); Assert.AreEqual(typeof(CallCountHandler), policy.Handlers[0].GetType()); }
public void CanCreatePolicyWithMemberNameMatchingRule() { PolicyInjectionSettings settings = new PolicyInjectionSettings(); settings.Policies.Add(new PolicyData("Policy")); settings.Policies.Get(0).MatchingRules.Add(new MemberNameMatchingRuleData("RuleName", "memberName")); DictionaryConfigurationSource dictSource = new DictionaryConfigurationSource(); dictSource.Add(PolicyInjectionSettings.SectionName, settings); PolicySetFactory factory = new PolicySetFactory(dictSource); PolicySet policySet = factory.Create(); Assert.IsNotNull(policySet); RuleDrivenPolicy policy = (RuleDrivenPolicy)policySet[1]; Assert.IsNotNull(policy); Assert.AreEqual("Policy", policy.Name); Assert.AreEqual(1, policy.RuleSet.Count); Assert.AreEqual(typeof(MemberNameMatchingRule), policy.RuleSet[0].GetType()); }
T GetSelectedPolicy() { int active = policyCombo.Active; if (active == 0 && !IsRoot) { return(bag.Owner.ParentFolder.Policies.Get <T> ()); } if (active == 0 && IsCustomUserPolicy) { return(null); } TreeIter iter; int i = 0; if (store.GetIterFirst(out iter)) { do { if (active == i) { PolicySet s = store.GetValue(iter, 1) as PolicySet; if (s != null) { return(s.Get <T> ()); } else { return(null); } } i++; } while (store.IterNext(ref iter)); } return(null); }
public override void Initialize(MonoDevelop.Ide.Gui.Dialogs.OptionsDialog dialog, object dataObject) { base.Initialize(dialog, dataObject); panelData = (MimeTypePanelData)dataObject; IPolicyProvider provider = panelData.DataObject as IPolicyProvider; if (provider == null) { provider = PolicyService.GetUserDefaultPolicySet(); isGlobalPolicy = true; } bag = provider.Policies as PolicyBag; polSet = provider.Policies as PolicySet; mimeType = panelData.MimeType; panelData.SectionPanel = this; isRoot = polSet != null || bag.IsRoot; if (IsCustomUserPolicy) { isRoot = false; } }
protected void OnButtonOkClicked(object sender, System.EventArgs e) { PolicySet pset = null; try { pset = GetPolicySet(true); policyProvider.Policies.Import(pset, false); } catch (Exception ex) { string msg; if (pset == null) { msg = GettextCatalog.GetString("The policy set could not be loaded"); } else { msg = GettextCatalog.GetString("The policy set could not be applied"); } MessageService.ShowException(ex, msg); Respond(Gtk.ResponseType.Cancel); return; } Respond(Gtk.ResponseType.Ok); }
public void ShouldReturnAllPoliciesInOrderThatApplyToTarget() { PolicySet policies = new PolicySet(); Policy p1 = new Policy("DALPolicy"); p1.RuleSet.Add(new TypeMatchingAssignmentRule(typeof(MockDal))); Policy p2 = new Policy("LoggingPolicy"); p2.RuleSet.Add(new TypeMatchingAssignmentRule(typeof(string))); Policy p3 = new Policy("ExceptionPolicy"); p3.RuleSet.Add(new TypeMatchingAssignmentRule(typeof(MockDal))); policies.Add(p1); policies.Add(p2); policies.Add(p3); PolicySet matchingPolicies = policies.GetPoliciesFor(typeof(MockDal)); Assert.AreEqual(2, matchingPolicies.Count); Assert.AreSame(p1, matchingPolicies[0]); Assert.AreSame(p3, matchingPolicies[1]); }
public PolicySet GetMatchingSet(IEnumerable <PolicySet> candidateSets) { // Find a policy set which is common to all policy types PolicySet matchedSet = null; bool firstMatch = true; foreach (IMimeTypePolicyOptionsPanel panel in Panels) { PolicySet s = panel.GetMatchingSet(candidateSets); if (firstMatch) { matchedSet = s; firstMatch = false; } else if (matchedSet != s) { matchedSet = null; break; } } return(matchedSet); }
void UpdateContentLabels() { PolicySet pset = null; try { pset = GetPolicySet(false); } catch (Exception ex) { LoggingService.LogError("Policy file could not be loaded", ex); } tree.SetPolicies(pset); if (tree.HasPolicies) { buttonOk.Sensitive = true; return; } if (pset != null) { tree.Message = GettextCatalog.GetString("The selected policy is empty"); } else if (radioFile.Active) { if (string.IsNullOrEmpty(fileEntry.Path) || !System.IO.File.Exists(fileEntry.Path)) { tree.Message = GettextCatalog.GetString("Please select a valid policy file"); } else { tree.Message = GettextCatalog.GetString("The selected file is not a valid policies file"); } } else { tree.Message = GettextCatalog.GetString("Please select a policy"); } buttonOk.Sensitive = false; }
public void UpdateSelectedNamedPolicy() { if (loading) { return; } // Find a policy set which is common to all policy types if (!isRoot && panelData.UseParentPolicy) { policyCombo.Active = 0; return; } PolicySet matchedSet = panelData.GetMatchingSet(); TreeIter iter; int i = 0; if (matchedSet != null && store.GetIterFirst(out iter)) { do { PolicySet s2 = store.GetValue(iter, 1) as PolicySet; if (s2 != null && s2.Id == matchedSet.Id) { policyCombo.Active = i; return; } i++; } while (store.IterNext(ref iter)); } policyCombo.Active = store.IterNChildren() - 1; }
public void ShouldClearCachesAfterChangesToPolicySet() { PolicySet policies = GetMultiplePolicySet(); List <ICallHandler> handlersBefore = new List <ICallHandler>( policies.GetHandlersFor(GetNameDoesntMatchMethod())); Assert.AreEqual(1, handlersBefore.Count); RuleDrivenPolicy newPolicy = new RuleDrivenPolicy("MatchesAnotherName"); newPolicy.RuleSet.Add(new MemberNameMatchingRule("NameDoesntMatch")); newPolicy.Handlers.Add(new Handler2()); policies.Add(newPolicy); List <ICallHandler> handlersAfter = new List <ICallHandler>( policies.GetHandlersFor(GetNameDoesntMatchMethod())); Assert.AreEqual(2, handlersAfter.Count); newPolicy.Handlers.Add(new Handler3()); }
void IMimeTypePolicyOptionsPanel.LoadSetPolicy(PolicySet pset) { object selected = pset.Get <T> (mimeTypeScopes); if (selected == null) { selected = PolicyService.GetDefaultPolicy <T> (mimeTypeScopes); } if (loaded) { if (defaultSettingsButton != null) { defaultSettingsButton.Active = false; panelWidget.Sensitive = true; } LoadFrom((T)selected); } else { cachedPolicy = selected; hasCachedPolicy = true; } }
/// <summary> /// Creates a new <see cref="InterceptingRealProxy"/> instance that applies /// the given policies to the given target object. /// </summary> /// <param name="target">Target object to intercept calls to.</param> /// <param name="classToProxy">Type to return as the type being proxied.</param> /// <param name="policies"><see cref="PolicySet"/> that determines which /// handlers are installed.</param> public InterceptingRealProxy(object target, Type classToProxy, PolicySet policies) : base(classToProxy) { this.target = target; this.typeName = target.GetType().FullName; Type targetType = target.GetType(); memberHandlers = new Dictionary <MethodBase, HandlerPipeline>(); AddHandlersForType(targetType, policies); Type baseTypeIter = targetType.BaseType; while (baseTypeIter != null && baseTypeIter != typeof(object)) { AddHandlersForType(baseTypeIter, policies); baseTypeIter = baseTypeIter.BaseType; } foreach (Type inter in targetType.GetInterfaces()) { AddHandlersForInterface(targetType, inter); } }
public void ShouldBeAbleToAddOnePolicy() { container .RegisterInstance <ICallHandler>("Handler1", new Handler1()) .RegisterInstance <ICallHandler>("Handler2", new Handler2()); PolicySet policies = new PolicySet(); RuleDrivenPolicy p = new RuleDrivenPolicy( "NameMatching", new IMatchingRule[] { new MemberNameMatchingRule("ShouldBeAbleToAddOnePolicy") }, new string[] { "Handler1", "Handler2" }); policies.Add(p); MethodImplementationInfo thisMember = GetMethodImplInfo <PolicySetFixture>("ShouldBeAbleToAddOnePolicy"); List <ICallHandler> handlers = new List <ICallHandler>(policies.GetHandlersFor(thisMember, container)); Assert.AreEqual(2, handlers.Count); Assert.IsTrue(typeof(Handler1) == handlers[0].GetType()); Assert.IsTrue(typeof(Handler2) == handlers[1].GetType()); }
void HandleNewButtonClicked(object sender, EventArgs e) { HashSet <PolicySet> esets = new HashSet <PolicySet> (PolicyService.GetPolicySets()); esets.ExceptWith(PolicyService.GetUserPolicySets()); esets.UnionWith(sets); esets.RemoveWhere(p => !p.Visible); NewPolicySetDialog dlg = new NewPolicySetDialog(new List <PolicySet> (esets)); try { if (MessageService.RunCustomDialog(dlg, this) == (int)Gtk.ResponseType.Ok) { PolicySet pset = new PolicySet(); pset.CopyFrom(dlg.SourceSet); pset.Name = dlg.PolicyName; sets.Add(pset); FillPolicySets(); policiesCombo.Active = sets.IndexOf(pset); } } finally { dlg.Destroy(); } }
public async Task EvaluateTest() { var mockPolicy = new Mock <IPolicy>(); var testSet = new PolicySet { mockPolicy.Object, mockPolicy.Object }; var loader = new Mock <IPolicySetLoader>(); loader.Setup(l => l.Load()).Returns(() => Task.FromResult((IEnumerable <IPolicy>)testSet)); var expected = new Manifest { new Kanyon.Kubernetes.Core.V1.Namespace(), new Kubernetes.Apps.V1.Deployment() }; var sut = new PolicySetEvaluator(loader.Object); await sut.Evaluate(expected, new Dictionary <string, string>()); mockPolicy.Verify(p => p.Evaluate(It.IsAny <IManifestObject>(), It.IsAny <Dictionary <string, string> >()), Times.Exactly(4)); }
private void ApplyPolicies(IInterceptor interceptor, IInterceptingProxy proxy, object target, PolicySet policies) { PipelineManager manager = new PipelineManager(); foreach (MethodImplementationInfo method in interceptor.GetInterceptableMethods(target.GetType(), target.GetType())) { HandlerPipeline pipeline = new HandlerPipeline(policies.GetHandlersFor(method, container)); manager.SetPipeline(method.ImplementationMethodInfo, pipeline); } proxy.AddInterceptionBehavior(new PolicyInjectionBehavior(manager)); }
public void ShouldBeCreateableWithHandlers() { PolicySet policies = GetPolicies(); HandlerPipeline pipeline = new HandlerPipeline(policies.GetHandlersFor(GetTargetMemberInfo())); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mainTree_BeforeSelect(object sender, TreeViewCancelEventArgs e) { // Check if the control have been modified if (_mainPanel.Controls.Count != 0) { if (!(_mainPanel.Controls[0] is ContextCustomControls.XmlViewer)) { var baseControl = _mainPanel.Controls[0] as CustomControls.BaseControl; _mainTree.SelectedNode.NodeFont = new Font(_mainTree.Font, FontStyle.Regular); NoBoldNode oNode = null; var policySet = baseControl as CustomControls.PolicySet; if (policySet != null) { oNode = new PolicySet(policySet.PolicySetElement); } else { var rule = baseControl as CustomControls.Rule; if (rule != null) { oNode = new Rule(rule.RuleElement); } else { var targetItem = baseControl as CustomControls.TargetItem; if (targetItem != null) { TargetItemBaseReadWrite element = targetItem.TargetItemBaseElement; oNode = new TargetItem(element); } else { var obligations = baseControl as CustomControls.Obligations; if (obligations != null) { oNode = new Obligations(obligations.ObligationsElement); } else { var attribute = baseControl as ContextCustomControls.Attribute; if (attribute != null) { oNode = new Attribute(attribute.AttributeElement); } else { var resource = baseControl as ContextCustomControls.Resource; if (resource != null) { oNode = new Resource(resource.ResourceElement); } } } } } } if (oNode != null) { _mainTree.SelectedNode = oNode; _mainTree.SelectedNode.Text = oNode.Text; } } } }
public DefaultPolicyOptionsDialog(Gtk.Window parentWindow) : base(parentWindow, new PolicySet(), "/MonoDevelop/ProjectModel/Gui/DefaultPolicyPanels") { this.Title = GettextCatalog.GetString("Custom Policies"); editingSet = (PolicySet)DataObject; HBox topBar = new HBox(); topBar.Spacing = 3; topBar.PackStart(new Label(GettextCatalog.GetString("Editing Policy:")), false, false, 0); policiesCombo = ComboBox.NewText(); topBar.PackStart(policiesCombo, false, false, 0); deleteButton = new Button(GettextCatalog.GetString("Delete Policy")); topBar.PackEnd(deleteButton, false, false, 0); exportButton = new MenuButton(); exportButton.Label = GettextCatalog.GetString("Export"); exportButton.MenuCreator = delegate { Gtk.Menu menu = new Gtk.Menu(); MenuItem mi = new MenuItem(GettextCatalog.GetString("To file...")); mi.Activated += HandleToFile; menu.Insert(mi, -1); mi = new MenuItem(GettextCatalog.GetString("To project or solution...")); mi.Activated += HandleToProject; if (!IdeApp.Workspace.IsOpen) { mi.Sensitive = false; } menu.Insert(mi, -1); menu.ShowAll(); return(menu); }; topBar.PackEnd(exportButton, false, false, 0); newButton = new MenuButton(); newButton.Label = GettextCatalog.GetString("Add Policy"); newButton.MenuCreator = delegate { Gtk.Menu menu = new Gtk.Menu(); MenuItem mi = new MenuItem(GettextCatalog.GetString("New policy...")); mi.Activated += HandleNewButtonClicked; menu.Insert(mi, -1); mi = new MenuItem(GettextCatalog.GetString("From file...")); mi.Activated += HandleFromFile; menu.Insert(mi, -1); mi = new MenuItem(GettextCatalog.GetString("From project or solution...")); mi.Activated += HandleFromProject; if (!IdeApp.Workspace.IsOpen) { mi.Sensitive = false; } menu.Insert(mi, -1); menu.ShowAll(); return(menu); }; topBar.PackEnd(newButton, false, false, 0); Alignment align = new Alignment(0f, 0f, 1f, 1f); align.LeftPadding = 9; align.TopPadding = 9; align.RightPadding = 9; align.BottomPadding = 9; align.Add(topBar); HeaderBox ebox = new HeaderBox(); ebox.GradientBackround = true; ebox.SetMargins(0, 1, 0, 0); ebox.Add(align); ebox.ShowAll(); VBox.PackStart(ebox, false, false, 0); VBox.BorderWidth = 0; Box.BoxChild c = (Box.BoxChild)VBox [ebox]; c.Position = 0; foreach (PolicySet ps in PolicyService.GetUserPolicySets()) { PolicySet copy = ps.Clone(); originalSets [copy] = ps; sets.Add(copy); } FillPolicySets(); policiesCombo.Changed += HandlePoliciesComboChanged; deleteButton.Clicked += HandleDeleteButtonClicked; }
private PolicySet GetPolicies() { PolicySet policies = new PolicySet(); RuleDrivenPolicy noParamsPolicy = new RuleDrivenPolicy( "noParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithNoParameters") }, new string[] { "Handler1" }); container.RegisterInstance <ICallHandler>("Handler1", new SignatureCheckingHandler(new Type[] { })); policies.Add(noParamsPolicy); RuleDrivenPolicy simpleInputsPolicy = new RuleDrivenPolicy( "simpleInputsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithSimpleInputs") }, new string[] { "Handler2" }); container.RegisterInstance <ICallHandler>( "Handler2", new SignatureCheckingHandler(new Type[] { typeof(int), typeof(string) })); policies.Add(simpleInputsPolicy); RuleDrivenPolicy outParamsPolicy = new RuleDrivenPolicy( "outParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithOutParams") }, new string[] { "Handler3" }); container.RegisterInstance <ICallHandler>( "Handler3", new SignatureCheckingHandler(new Type[] { typeof(int).MakeByRefType(), typeof(string).MakeByRefType() })); policies.Add(outParamsPolicy); RuleDrivenPolicy mixedParamsPolicy = new RuleDrivenPolicy( "mixedParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithInOutByrefParams") }, new string[] { "Handler4" }); container.RegisterInstance <ICallHandler>( "Handler4", new SignatureCheckingHandler( new Type[] { typeof(int), typeof(string).MakeByRefType(), typeof(float).MakeByRefType(), typeof(decimal) })); policies.Add(mixedParamsPolicy); RuleDrivenPolicy varargsParamsPolicy = new RuleDrivenPolicy( "varargsParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithVarArgs") }, new string[] { "Handler5" }); container.RegisterInstance <ICallHandler>( "Handler5", new SignatureCheckingHandler(new Type[] { typeof(int), typeof(string).MakeArrayType() })); policies.Add(varargsParamsPolicy); return(policies); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void CreatePolicySetFromDocument(object sender, EventArgs args) { var policyDocumentNode = (TreeNodes.PolicyDocument)_mainTree.SelectedNode; PolicyDocumentReadWrite policyDoc = policyDocumentNode.PolicyDocumentDefinition; // Create a new policy var newPolicySet = new pol.PolicySetElementReadWrite( "urn:newpolicy", "[TODO: add a description]", null, new ArrayList(), Consts.Schema1.PolicyCombiningAlgorithms.FirstApplicable, new ObligationReadWriteCollection(), null, XacmlVersion.Version11); //TODO: check version policyDoc.PolicySet = newPolicySet; // Create a new node. var newPolicySetNode = new PolicySet(newPolicySet); // Add the tree node. policyDocumentNode.Nodes.Add(newPolicySetNode); // Set the font so the user knows the item was changed newPolicySetNode.NodeFont = new Font(_mainTree.Font, FontStyle.Bold); }
/// <summary> /// Create a default <see cref="UnityContainer"/>. /// </summary> public UnityContainer(ModeFlags mode = ModeFlags.Optimized) { if (!mode.IsValid()) { throw new ArgumentException("'Activated' and 'Diagnostic' flags are mutually exclusive."); } ///////////////////////////////////////////////////////////// // Initialize Root _root = this; // Defaults and policies ModeFlags = mode; Defaults = new DefaultPolicies(this); LifetimeContainer = new LifetimeContainer(this); Register = AddOrReplace; // Create Registry and set Factory strategy _metadata = new Registry <int[]>(); _registry = new Registry <IPolicySet>(Defaults); ///////////////////////////////////////////////////////////// //Built-In Registrations // IUnityContainer, IUnityContainerAsync var container = new ImplicitRegistration(this, null) { Pipeline = (ref BuilderContext c) => c.Async ? (object)Task.FromResult <object>(c.Container) : c.Container }; _registry.Set(typeof(IUnityContainer), null, container); _registry.Set(typeof(IUnityContainerAsync), null, container); // Built-In Features var func = new PolicySet(this); _registry.Set(typeof(Func <>), func); func.Set(typeof(LifetimeManager), new PerResolveLifetimeManager()); func.Set(typeof(TypeFactoryDelegate), FuncResolver.Factory); // Func<> Factory _registry.Set(typeof(Lazy <>), new PolicySet(this, typeof(TypeFactoryDelegate), LazyResolver.Factory)); // Lazy<> _registry.Set(typeof(IEnumerable <>), new PolicySet(this, typeof(TypeFactoryDelegate), EnumerableResolver.Factory)); // Enumerable _registry.Set(typeof(IRegex <>), new PolicySet(this, typeof(TypeFactoryDelegate), RegExResolver.Factory)); // Regular Expression Enumerable ///////////////////////////////////////////////////////////// // Pipelines var factory = new FactoryPipeline(); var lifetime = new LifetimePipeline(); // Mode of operation if (ModeFlags.IsOptimized()) { ///////////////////////////////////////////////////////////// // Setup Optimized mode // Create Context Context = new ContainerContext(this, new StagedStrategyChain <Pipeline, Stage> // Type Build Pipeline { { lifetime, Stage.Lifetime }, { factory, Stage.Factory }, { new MappingPipeline(), Stage.TypeMapping }, { new ConstructorPipeline(this), Stage.Creation }, { new FieldPipeline(this), Stage.Fields }, { new PropertyPipeline(this), Stage.Properties }, { new MethodPipeline(this), Stage.Methods } }, new StagedStrategyChain <Pipeline, Stage> // Factory Resolve Pipeline { { lifetime, Stage.Lifetime }, { factory, Stage.Factory } }, new StagedStrategyChain <Pipeline, Stage> // Instance Resolve Pipeline { { lifetime, Stage.Lifetime }, }); } else { ///////////////////////////////////////////////////////////// // Setup Diagnostic mode var diagnostic = new DiagnosticPipeline(); // Create Context Context = new ContainerContext(this, new StagedStrategyChain <Pipeline, Stage> // Type Build Pipeline { { diagnostic, Stage.Diagnostic }, { lifetime, Stage.Lifetime }, { factory, Stage.Factory }, { new MappingDiagnostic(), Stage.TypeMapping }, { new ConstructorDiagnostic(this), Stage.Creation }, { new FieldDiagnostic(this), Stage.Fields }, { new PropertyDiagnostic(this), Stage.Properties }, { new MethodDiagnostic(this), Stage.Methods } }, new StagedStrategyChain <Pipeline, Stage> // Factory Resolve Pipeline { { diagnostic, Stage.Diagnostic }, { lifetime, Stage.Lifetime }, { factory, Stage.Factory } }, new StagedStrategyChain <Pipeline, Stage> // Instance Resolve Pipeline { { diagnostic, Stage.Diagnostic }, { lifetime, Stage.Lifetime }, }); // Build process DependencyResolvePipeline = ValidatingDependencyResolvePipeline; // Validators ValidateType = DiagnosticValidateType; ValidateTypes = DiagnosticValidateTypes; CreateMessage = CreateDiagnosticMessage; } }
/// <summary> /// Method called by the EvaluationEngine when the evaluation is executed without a policy document, this /// method search in the policy repository and return the first policy that matches its target with the /// context document specified. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <returns>The policy document ready to be used by the evaluation engine.</returns> public PolicyDocument Match(EvaluationContext context) { if (context == null) throw new ArgumentNullException("context"); PolicyDocument polEv = null; //Search if there is a policySet which target matches the context document foreach (PolicyDocument policy in _policySets.Values) { var tempPolicy = new PolicySet(context.Engine, (PolicySetElement)policy.PolicySet); var tempContext = new EvaluationContext(context.Engine, policy, context.ContextDocument); // Match the policy set target with the context document if (tempPolicy.Match(tempContext) == TargetEvaluationValue.Match) { if (polEv == null) { polEv = policy; } else { throw new EvaluationException(Properties.Resource.exc_duplicated_policy_in_repository); } } } //Search if there is a policy which target matches the context document foreach (PolicyDocument policy in _policies.Values) { var tempPolicy = new Policy((PolicyElement)policy.Policy); var tempContext = new EvaluationContext(context.Engine, policy, context.ContextDocument); // Match the policy target with the context document if (tempPolicy.Match(tempContext) == TargetEvaluationValue.Match) { if (polEv == null) { polEv = policy; } else { throw new EvaluationException(Properties.Resource.exc_duplicated_policy_in_repository); } } } return polEv; }
private static void AddRuleAndPolicy(PolicySet responsePolicySet, Policy responsePolicy, PolicyRule rule) { responsePolicy.Rules.Add(rule); responsePolicySet.Policies.Add(responsePolicy); }
/// <summary> /// Create a default <see cref="UnityContainer"/>. /// </summary> public UnityContainer(ModeFlags mode = ModeFlags.Optimized) { if (!mode.IsValid()) { throw new ArgumentException("'Activated' and 'Diagnostic' flags are mutually exclusive."); } ///////////////////////////////////////////////////////////// // Initialize Root _root = this; ExecutionMode = mode; LifetimeContainer = new LifetimeContainer(this); Register = AddOrReplace; //Built-In Registrations // Defaults Defaults = new DefaultPolicies(this); // IUnityContainer, IUnityContainerAsync var container = new ExplicitRegistration(this, null, typeof(UnityContainer), new ContainerLifetimeManager()) { Pipeline = (ref PipelineContext c) => c.Container }; Debug.Assert(null != container.LifetimeManager); // Create Registries _metadata = new Metadata(); _registry = new Registry(Defaults); _registry.Set(typeof(IUnityContainer), null, container); // TODO: Remove redundancy _registry.Set(typeof(IUnityContainerAsync), null, container); _registry.Set(typeof(IUnityContainer), null, container.LifetimeManager.Pipeline); _registry.Set(typeof(IUnityContainerAsync), null, container.LifetimeManager.Pipeline); ///////////////////////////////////////////////////////////// // Built-In Features var func = new PolicySet(this); _registry.Set(typeof(Func <>), func); func.Set(typeof(LifetimeManager), new PerResolveLifetimeManager()); func.Set(typeof(TypeFactoryDelegate), FuncResolver.Factory); // Func<> Factory _registry.Set(typeof(Lazy <>), new PolicySet(this, typeof(TypeFactoryDelegate), LazyResolver.Factory)); // Lazy<> _registry.Set(typeof(IEnumerable <>), new PolicySet(this, typeof(TypeFactoryDelegate), EnumerableResolver.Factory)); // Enumerable _registry.Set(typeof(IRegex <>), new PolicySet(this, typeof(TypeFactoryDelegate), RegExResolver.Factory)); // Regular Expression Enumerable ///////////////////////////////////////////////////////////// // Pipelines var typeFactory = new TypeFactoryPipeline(); var lifetime = new LifetimePipeline(); // Mode of operation if (ExecutionMode.IsDiagnostic()) { ///////////////////////////////////////////////////////////// // Setup Diagnostic mode var diagnostic = new DiagnosticPipeline(); // Create Context Context = new ContainerContext(this, new StagedStrategyChain <Pipeline, Stage> // Type Build Pipeline { { diagnostic, Stage.Diagnostic }, { typeFactory, Stage.Factory }, { new MappingDiagnostic(), Stage.TypeMapping }, { new ConstructorDiagnostic(this), Stage.Creation }, { new FieldDiagnostic(this), Stage.Fields }, { new PropertyDiagnostic(this), Stage.Properties }, { new MethodDiagnostic(this), Stage.Methods } }, new StagedStrategyChain <Pipeline, Stage> // Factory Resolve Pipeline { { diagnostic, Stage.Diagnostic }, { new FactoryPipeline(), Stage.Factory } }, new StagedStrategyChain <Pipeline, Stage> // Instance Resolve Pipeline { { diagnostic, Stage.Diagnostic }, { typeFactory, Stage.Factory } }); // Build process DependencyResolvePipeline = ValidatingDependencyResolvePipeline; // Validators ValidateType = DiagnosticValidateType; ValidateTypes = DiagnosticValidateTypes; CreateErrorMessage = CreateDiagnosticMessage; } else { // Create Context Context = new ContainerContext(this, new StagedStrategyChain <Pipeline, Stage> // Type Build Pipeline { { lifetime, Stage.Lifetime }, { typeFactory, Stage.Factory }, { new MappingPipeline(), Stage.TypeMapping }, { new ConstructorPipeline(this), Stage.Creation }, { new FieldPipeline(this), Stage.Fields }, { new PropertyPipeline(this), Stage.Properties }, { new MethodPipeline(this), Stage.Methods } }, new StagedStrategyChain <Pipeline, Stage> // Factory Resolve Pipeline { { lifetime, Stage.Lifetime }, { new FactoryPipeline(), Stage.Factory } }, new StagedStrategyChain <Pipeline, Stage> // Instance Resolve Pipeline { { typeFactory, Stage.Factory } }); } ///////////////////////////////////////////////////////////// // Build Mode var build = _root.ExecutionMode.BuildMode(); PipelineFromRegistration = build switch { ModeFlags.Activated => PipelineFromRegistrationActivated, ModeFlags.Compiled => PipelineFromRegistrationCompiled, _ => (FromRegistration)PipelineFromRegistrationOptimized }; PipelineFromUnregisteredType = build switch { ModeFlags.Activated => PipelineFromUnregisteredTypeActivated, ModeFlags.Compiled => PipelineFromUnregisteredTypeCompiled, _ => (FromUnregistered)PipelineFromUnregisteredTypeOptimized }; PipelineFromOpenGeneric = build switch { ModeFlags.Activated => PipelineFromOpenGenericActivated, ModeFlags.Compiled => PipelineFromOpenGenericCompiled, _ => (FromOpenGeneric)PipelineFromOpenGenericOptimized }; }
/// <summary> /// This method will initialise a message record from /// an URO object /// </summary> public static Message Initialise(Workshare.PolicyContent.Response response) { try { string senderDomain = ""; string subject = ""; Contact sender = null; if (string.Compare(response.PolicyType, PolicyType.ActiveContent.ToString(), true, System.Threading.Thread.CurrentThread.CurrentCulture) == 0) { senderDomain = "localhost"; StringBuilder from = new StringBuilder(); string name = ""; if (response.Contents.Length == 1) { subject = response.Contents[0].Name; name = WorkoutName(response.Contents[0].Name); } else { subject = ""; name = "File"; } from.AppendFormat("{0}@localhost", name); sender = new Contact(ContactType.Sender, "", "", from.ToString(), senderDomain, true); } else if (string.Compare(response.PolicyType, PolicyType.ClientRemovableMedia.ToString(), true, System.Threading.Thread.CurrentThread.CurrentCulture) == 0) { // Hack - for removable device channel populate the sender as the name part of the ldap path // If the ldap path doesn't exist, this will be blank Workshare.PolicyContent.RoutingEntity sourceRoutingEntity = GetRoutingEntity(response, RoutingTypes.Source); if (null == sourceRoutingEntity) throw new ArgumentNullException("sourceRoutingEntity", "Null source routing entity"); string source = GetProperty(sourceRoutingEntity.Items[0].Properties, SMTPItemPropertyKeys.DisplayName); if (string.IsNullOrEmpty(source)) { string ldapPath = sourceRoutingEntity.Items[0].Content; int startCn = ldapPath.IndexOf("CN="); if (startCn != -1) { int endCn = ldapPath.IndexOf(",", startCn); if (endCn != -1) { source = ldapPath.Substring(startCn + 3, endCn - (startCn + 3)); } } } sender = new Contact(ContactType.Sender, "", "", source, "", true); } else { string senderAlias = ""; Workshare.PolicyContent.RoutingEntity sourceRoutingEntity = GetRoutingEntity(response, RoutingTypes.Source); if (null == sourceRoutingEntity) throw new ArgumentNullException("sourceRoutingEntity", "Null source routing entity"); int iPosAmpersand = sourceRoutingEntity.Items[0].Content.IndexOf("@"); if (iPosAmpersand > -1) { senderDomain = sourceRoutingEntity.Items[0].Content.Substring(iPosAmpersand + 1); senderAlias = sourceRoutingEntity.Items[0].Content.Substring(0, iPosAmpersand); } else senderDomain = sourceRoutingEntity.Items[0].Content; subject = GetProperty(response.Properties, "Subject"); sender = new Contact(ContactType.Sender, GetProperty(sourceRoutingEntity.Items[0].Properties, Workshare.Policy.Routing.SMTPItemPropertyKeys.DisplayName), senderAlias, sourceRoutingEntity.Items[0].Content, senderDomain, true); } System.Diagnostics.Trace.WriteLine("Starting to add audit message to collection", "MessageCollection.Add Audit"); Message msg = new Message(subject, response.ResponseDate, response.PolicyType, "", sender); if (string.Compare(response.PolicyType, PolicyType.ActiveContent.ToString(), true, System.Threading.Thread.CurrentThread.CurrentCulture) == 0) { msg.Recipients.Add(new Contact(ContactType.Recipient, sender.Name, sender.Alias, sender.EmailAddress, sender.EmailDomain, sender.IsInternal)); msg.MachineName = GetProperty(response.Properties, "MachineName"); msg.UserName = GetProperty(response.Properties, "UserName"); msg.ApplicationName = GetProperty(response.Properties, "Application"); msg.ChannelType = "ActiveContent"; } else if (string.Compare(response.PolicyType, PolicyType.ClientRemovableMedia.ToString(), true, System.Threading.Thread.CurrentThread.CurrentCulture) == 0) { Workshare.PolicyContent.RoutingEntity destinationRoutingEntity = GetRoutingEntity(response, RoutingTypes.Destination); if (null == destinationRoutingEntity) throw new ArgumentNullException("destinationRoutingEntity", "Null destination routing entity"); // Hack - for the removable device channel populate the recipient with the destination // routing items delimited with a ';'. May need to think a bit more about how this information // should be displayed in the report. If the particular routing item is UNDEFINED then // don't add it (this is the case, currently, for device id and name) msg.ChannelType = response.PolicyType; StringBuilder destinationInfo = new StringBuilder(); foreach (Workshare.PolicyContent.RoutingItem routingItem in destinationRoutingEntity.Items) { if (String.Compare(routingItem.Content, "UNDEFINED", true, System.Globalization.CultureInfo.InvariantCulture) != 0) { destinationInfo.Append(routingItem.Content + "; "); } } msg.Recipients.Add(new Contact(ContactType.Recipient, destinationInfo.ToString(), destinationInfo.ToString(), destinationInfo.ToString(), destinationInfo.ToString(), true)); } else { msg.ChannelType = "SMTP"; Workshare.PolicyContent.RoutingEntity destinationRoutingEntity = GetRoutingEntity(response, RoutingTypes.Destination); if (null == destinationRoutingEntity) throw new ArgumentNullException("destinationRoutingEntity", "Null destination routing entity"); foreach (Workshare.PolicyContent.RoutingItem recipient in destinationRoutingEntity.Items) { string recipAlias = ""; string recipDomain = ""; int iPosAmpersand = recipient.Content.IndexOf("@"); if (iPosAmpersand > -1) { recipDomain = recipient.Content.Substring(iPosAmpersand + 1); recipAlias = recipient.Content.Substring(0, iPosAmpersand); } ContactType contactType = ContactType.Recipient; if (GetProperty(recipient.Properties, SMTPItemPropertyKeys.AddressType) == AddressType.CC) contactType = ContactType.Copied; else if (GetProperty(recipient.Properties, SMTPItemPropertyKeys.AddressType) == AddressType.BCC) contactType = ContactType.BlindCopied; msg.Recipients.Add(new Contact(msg.MessageId, contactType, GetProperty(recipient.Properties, SMTPItemPropertyKeys.DisplayName), recipAlias, recipient.Content, recipDomain, false, senderDomain)); } } if (msg.Recipients.IsExternal || msg.Copied.IsExternal || msg.BlindCopied.IsExternal) msg.SentExternally = true; foreach (Workshare.PolicyContent.ContentItem contentItem in response.Contents) { // Create the document Document doc = new Document(msg.MessageId, contentItem.Name, contentItem.ContentType, "", contentItem.Name, (long)contentItem.Size, false); foreach (Workshare.PolicyContent.PolicySet policySet in contentItem.PolicySets) { // Process the policies PolicySet tp = new PolicySet(msg.MessageId, policySet.Name, policySet.Date); foreach (Workshare.PolicyContent.Policy policy in policySet.Policies) { // Check if we need to do this if (policy.Triggered == false) { System.Diagnostics.Trace.WriteLine("TracePolicy Passed so will not record it!", "MessageCollection.Add Audit"); continue; } // These are failed TracePolicys! TracePolicy r = new TracePolicy(msg.MessageId, policy.Name, policy.Triggered); r.Description = policy.Description; CreateExpressions(msg, r, policy); // Check to see if we have anything to save if (r.Conditions.Count > 0) tp.TracePolicies.Add(r); } if (tp.TracePolicies.Count > 0) doc.Policies.Add(tp); } if (doc.Policies.Count > 0) msg.Documents.Add(doc); } StringBuilder sb = new StringBuilder(); if (msg.Documents.Count > 0) { return msg; } else { sb.AppendFormat(Properties.Resources.AUDIT_ITEMPASSED, msg.Subject); System.Diagnostics.Trace.WriteLine(sb.ToString(), "AuditInfo"); System.Diagnostics.Trace.WriteLine("Completed - Everything passed or nothing assigned so will not record message", "MessageCollection.Add Audit"); } } catch (ArgumentNullException) { //Ignore as we are not a failed message System.Diagnostics.Trace.WriteLine("Audit message has passed policy", "MessageCollection.Add Audit"); } return null; }
private static PolicySet GetResponsePolicySet(DelegationRequestPolicySet maskPolicySet, PolicySet evidencePolicySet) { var responsePolicySet = new PolicySet { MaxDelegationDepth = evidencePolicySet.MaxDelegationDepth, Target = evidencePolicySet.Target, Policies = new List <Policy>() }; foreach (var maskPolicy in maskPolicySet.Policies) { var matchingPolicies = evidencePolicySet.Policies.Where(e => IsMatchingPolicy(maskPolicy, e)); var responsePolicy = new Policy { Target = maskPolicy.Target, Rules = new List <PolicyRule>() }; var rule = PolicyRule.Permit(); if (!matchingPolicies.Any() || matchingPolicies.Any(e => AccessDeniedToContainers(maskPolicy, e))) { rule = PolicyRule.Deny(); } AddRuleAndPolicy(responsePolicySet, responsePolicy, rule); } return(responsePolicySet); }
PolicySet GetPolicies() { PolicySet policies = new PolicySet(); RuleDrivenPolicy noParamsPolicy = new RuleDrivenPolicy( "noParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithNoParameters") }, new string[] { "Handler1" }); container.RegisterInstance<ICallHandler>("Handler1", new SignatureCheckingHandler(new Type[] { })); policies.Add(noParamsPolicy); RuleDrivenPolicy simpleInputsPolicy = new RuleDrivenPolicy( "simpleInputsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithSimpleInputs") }, new string[] { "Handler2" }); container.RegisterInstance<ICallHandler>( "Handler2", new SignatureCheckingHandler(new Type[] { typeof(int), typeof(string) })); policies.Add(simpleInputsPolicy); RuleDrivenPolicy outParamsPolicy = new RuleDrivenPolicy( "outParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithOutParams") }, new string[] { "Handler3" }); container.RegisterInstance<ICallHandler>( "Handler3", new SignatureCheckingHandler(new Type[] { typeof(int).MakeByRefType(), typeof(string).MakeByRefType() })); policies.Add(outParamsPolicy); RuleDrivenPolicy mixedParamsPolicy = new RuleDrivenPolicy( "mixedParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithInOutByrefParams") }, new string[] { "Handler4" }); container.RegisterInstance<ICallHandler>( "Handler4", new SignatureCheckingHandler( new Type[] { typeof(int), typeof(string).MakeByRefType(), typeof(float).MakeByRefType(), typeof(decimal) })); policies.Add(mixedParamsPolicy); RuleDrivenPolicy varargsParamsPolicy = new RuleDrivenPolicy( "varargsParamsPolicy", new IMatchingRule[] { new MatchByNameRule("MethodWithVarArgs") }, new string[] { "Handler5" }); container.RegisterInstance<ICallHandler>( "Handler5", new SignatureCheckingHandler(new Type[] { typeof(int), typeof(string).MakeArrayType() })); policies.Add(varargsParamsPolicy); return policies; }