private void CompileNxBrePolicySet(IPolicySetVersionCache version, IPolicySet policySet, string target)
        {
            if ((null == version) || (null == policySet) || (string.IsNullOrEmpty(target)))
                return;

            NxPolicyStore nxBreStore = new NxPolicyStore();
            nxBreStore.ResourceManager = ResourcesCache.GetResources();
            policySet.Export(nxBreStore);

            CompiledPolicySetExtractor cpse = new CompiledPolicySetExtractor(nxBreStore.XMLRepresentation);
            List<string> channels = cpse.GetChannelNames();

            foreach (string channel in channels)
            {
                string objects = cpse.GetObjects(channel);
                string rules = cpse.GetRules(channel);

                ICompiledPolicySetCache cps = version.GetCompiledPolicySet(channel, target);
                if (cps == null)
                {
                    cps = version.NewCompiledPolicySet(channel, target, rules, objects);
                }
                else
                {
                    cps.Content = rules;
                    cps.ObjectReferences = objects;
                }
                    
                SaveLanguages(cpse.GetLanguages(), cps);
            }
        }
		public void WriteChildCollection(IPolicySet policySet, IPolicyObject parent, string name, IPolicyObjectCollection<IPolicyObject> collection)
		{
			if (parent == null)
				return;

			IPolicy policy = parent as IPolicy;
			if (policy == null)
				return;

			string ruleXpath = string.Format(CultureInfo.InvariantCulture, "PolicySet[@id='{0}']/Policies/Policy[@id='{1}']",
				XmlHelpers.GetPolicyObjectIdString(policySet),
				XmlHelpers.GetPolicyObjectIdString(parent));

			XmlNode xmlRuleNode = m_policieSetsNode.SelectSingleNode(ruleXpath);
			if (xmlRuleNode == null)
			{
				new XmlCataloguePolicyWriter(m_xmlRootNode, policy).Write();
				xmlRuleNode = m_xmlRootNode.SelectSingleNode(ruleXpath);
			}

			if (collection.Count == 0)
				return;

			IPolicyChannel channel = collection[0] as IPolicyChannel;
			if (channel == null)
			{
				new XmlConditionsWriter(xmlRuleNode, collection).Write();
			}
			else
			{
				new XmlPolicyChannelsWriter(xmlRuleNode, collection).Write();
			}
		}
        public void SaveCompiledStreams(IPolicySetVersionCache version, IPolicySet policySet)
        {
            if ((null == version) || (null == policySet))
                return;

            CompileNxBrePolicySet(version, policySet, "Client");
        }
Exemple #4
0
 public Context(MDIChildForm parent, IPolicyStore policyStore)
 {
     m_parent = parent;
     m_policyStore = policyStore;
     //TODO: this will be refactored when IPolicy layer is removed
     m_policySet = m_policyStore.Reader.PolicySets[0];
 }
		public PolicySetSummary(IPolicySet set)
		{
			m_set = set;

			foreach (IPolicy policy in m_set.Policies)
			{
				m_policySummaryList.Add(new PolicySummary(policy));
			}
		}
        private void ReadPolicySet(string filename, out IPolicySet policySet)
        {
            PolicySetItem policySetItem = PolicySuites.Instance.LoadPolicySet("localhost", filename);

            policySet = new Policy.ObjectModel.PolicySet(policySetItem.Data.Identifier, policySetItem.Data.Name, null, policySetItem.Data.MasterCatalogue, false);
            AddPoliciesToPolicySet(policySet, policySetItem.Data.Policies);
            
            PolicySuites.Instance.ClosePolicySet(policySetItem.Data);
        }
Exemple #7
0
 public ExplicitRegistration(IPolicySet validators, Type mappedTo, LifetimeManager lifetimeManager, InjectionMember[] injectionMembers = null)
 {
     Type  = mappedTo;
     Key   = typeof(LifetimeManager);
     Value = lifetimeManager;
     LifetimeManager.InUse = true;
     InjectionMembers      = injectionMembers;
     Next = (PolicyEntry)validators;
 }
		private static bool ValidateInterPolicyConflicts(IPolicySet policyset, PolicySetValidator.AddViolationMessageHandler AddMessage)
		{
			bool retVal = true;

			for (int i = 0; i < policyset.Policies.Count; i++)
			{
				for (int j = i + 1; j < policyset.Policies.Count; j++)
				{
					IPolicy policy1 = policyset.Policies[i];
					IPolicy policy2 = policyset.Policies[j];

					List<FileType> checkTypes1 = GetFileTypesForPolicy(policy1.Conditions);
					List<CellActionsCollection> checkActions1 = GetActionsForPolicy(policy1.Channels, policyset, true);

					List<FileType> checkTypes2 = GetFileTypesForPolicy(policy2.Conditions);
					List<CellActionsCollection> checkActions2 = GetActionsForPolicy(policy2.Channels, policyset, true);

					FileType foundType = FileType.Unknown;
					foreach (FileType filetype in checkTypes1)
					{
						if (checkTypes2.Contains(filetype))
						{
							foundType = filetype;
							break;
						}
					}

					if (foundType == FileType.Unknown)
						continue;

					foreach (CellActionsCollection collection in checkActions1)
					{
						IAction foundAction = null;
						foreach (IAction action in collection.Actions)
						{
							m_actionPredicate = action.Name.Value;
							if (!checkActions2.Exists(FindActionPredicate))
								continue;

							foundAction = action;
							break;
						}

						if (null == foundAction)
							continue;

						retVal = false;
						if (null != AddMessage)
							AddMessage(policy2.Name.Value, string.Format(CultureInfo.CurrentCulture, Properties.Resources.VALIDATION_INTERPOLICY_FILETYPEACTION_CONFLICT,
													foundType, policy1.Name.Value, foundAction.Name.Value), false);
					}
				}
			}

			return retVal;
		}
Exemple #9
0
        public virtual void Add(IPolicySet set)
        {
            var node = (PolicyEntry)this;

            while (null != node.Next)
            {
                node = node.Next;
            }
            node.Next = (PolicyEntry)set;
        }
Exemple #10
0
 public HookrRepository(HookrContext context,
                        IPolicySet policySet,
                        ITelegramUserIdProvider telegramUserIdProvider,
                        ILoaderProvider loaderProvider)
 {
     PolicySet = policySet;
     this.telegramUserIdProvider = telegramUserIdProvider;
     this.loaderProvider         = loaderProvider;
     Context = context;
 }
Exemple #11
0
        public override ResolveDelegate <BuilderContext> GetResolver(Type type, IPolicySet registration, ResolveDelegate <BuilderContext> seed)
        {
            // Select ConstructorInfo
            var selector  = GetOrDefault(registration);
            var selection = selector.Select(type, registration)
                            .FirstOrDefault();

            // Select constructor for the Type
            ConstructorInfo info;

            object[] resolvers = null;

            switch (selection)
            {
            case ConstructorInfo memberInfo:
                info = memberInfo;
                break;

            case MethodBase <ConstructorInfo> injectionMember:
                info      = injectionMember.MemberInfo(type);
                resolvers = injectionMember.Data;
                break;

            case Exception exception:
                return((ref BuilderContext c) =>
                {
                    if (null == c.Existing)
                    {
                        throw exception;
                    }

                    return c.Existing;
                });

            default:
                return((ref BuilderContext c) =>
                {
                    if (null == c.Existing)
                    {
                        throw new InvalidOperationException($"No public constructor is available for type {c.Type}.",
                                                            new InvalidRegistrationException());
                    }

                    return c.Existing;
                });
            }

            // Get lifetime manager
            var lifetimeManager = (LifetimeManager)registration.Get(typeof(LifetimeManager));

            return(lifetimeManager is PerResolveLifetimeManager
                ? GetPerResolveDelegate(info, resolvers)
                : GetResolverDelegate(info, resolvers));
        }
        private void AddPoliciesToPolicySet(IPolicySet policySet, IPolicyObjectCollection<IPolicy> policies)
        {
            foreach (IPolicy policy in policies)
            {
                // This will force the policy to read the conditions from the test file if the policy has any.
                if (null == policy.Conditions)
                    continue;
            }

            (policySet as PolicySet).Policies = policies;
        }
Exemple #13
0
 public NxPolicySet(IPolicySet policySet, ChannelType channelType)
 {
     m_ChannelType = channelType;
     NxSet policies = new NxSet("Policies");            
     List<NxParameter> parameters = NxUtils.GetAttributes(policySet);
     parameters.Add(new NxParameter("Name", policySet));            
     policies.Append(new NxEvaluate("BeforePolicy", parameters));
     policies.Append(new NxInvokeSet("C1C0D5EA-5B82-4607-AE41-D52739AA6AB1"));
     policies.Append(new NxEvaluate("AfterPolicy", parameters));
     AppendSet(policies);
 }
Exemple #14
0
 public TelegramHookrRepository(HookrContext context,
                                IPolicySet policySet,
                                ITelegramUserIdProvider telegramUserIdProvider,
                                IMemoryCache memoryCache,
                                ILoaderProvider loaderProvider)
     : base(context,
            policySet,
            telegramUserIdProvider,
            loaderProvider)
 {
     this.memoryCache = memoryCache;
 }
Exemple #15
0
        /// <summary>
        /// Checks if a policy object exists in a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set whose master catalogue we will be looking in</param>
        /// <param name="policyObject">The policy object we are looking up in the catalogue</param>
        /// <returns>True if the policy object exists in the policy set master catalogue, otherwise false</returns>
        public static bool IsInMyMasterCatalogue(IPolicySet policySet, IPolicyObject policyObject)
        {
            if (policyObject is IActionGroup)
            {
                return policySet.MasterCatalogue.ActionGroups.Contains(policyObject);
            }
            else if (policyObject is IAction)
            {
                return policySet.MasterCatalogue.Actions.Contains(policyObject);
            }
            else if (policyObject is IRoutingItem)
            {
                return policySet.MasterCatalogue.Locations.Contains(policyObject);
            }
            else if (policyObject is IRoutingItemCollections)
            {
                return policySet.MasterCatalogue.LocationsCollection.Contains(policyObject);
            }
            else if (policyObject is ICataloguePolicy)
            {
                return policySet.MasterCatalogue.CataloguePolicies.Contains(policyObject);
            }
            else if (policyObject is IChannel)
            {
                return policySet.MasterCatalogue.Channels.Contains(policyObject);
            }
            else if (policyObject is IConditionGroup)
            {
                return policySet.MasterCatalogue.ConditionGroups.Contains(policyObject);
            }
            else if (policyObject is ICondition)
            {
                return policySet.MasterCatalogue.Conditions.Contains(policyObject);
            }
            else if (policyObject is IDataElement)
            {
                return policySet.MasterCatalogue.DataElements.Contains(policyObject);
            }
            else if (policyObject is IRoutingTable)
            {
                return policySet.MasterCatalogue.RoutingTables.Contains(policyObject);
            }
            else
            {
				Logger.LogError("Unsupported IPolicyObject");
                throw new ArgumentException("Unsupported IPolicyObject");
            }
        }
        internal static void Set(this Registry <IPolicySet> registry, Type type, IPolicySet set)
        {
            var hashCode     = type.GetHashCode();
            var targetBucket = (hashCode & UnityContainer.HashMask) % registry.Buckets.Length;

            for (var i = registry.Buckets[targetBucket]; i >= 0; i = registry.Entries[i].Next)
            {
                ref var candidate = ref registry.Entries[i];
                if (candidate.HashCode != hashCode || candidate.Type != type || candidate.Value is ImplicitRegistration)
                {
                    continue;
                }

                candidate.Value = set;
                return;
            }
        public void SetUpTest()
        {

            m_stateMachine = new DynamicMock(typeof(IStateMachine));

            XmlPolicyLanguageStore languageStore = XmlPolicyLanguageStore.Instance;
            languageStore.Reset();
            IPolicyLanguage language = new PolicyLanguage(new Guid("{E8B22533-98EB-4D00-BDE4-406DC3E1858B}"), "en");
            languageStore.AddLanguage(language);
            PolicyLanguageCache.Instance.ActiveLanguageId = language.Identifier;
            XMLPolicyCatalogueStore catalogueStore = XMLPolicyCatalogueStore.Instance;
            catalogueStore.Reset();
            PolicyCatalogue policyCatalogue = new PolicyCatalogue(new Guid("{AB5E2A43-01FB-4AA6-98FC-8F74BB0621CA}"), language.Identifier, new TranslateableLanguageItem("{B5C31A66-1B39-4CA7-BF02-AF271B5864F7}"), catalogueStore);
            catalogueStore.AddPolicyCatalogue(policyCatalogue);
            IPolicyStore policyStore = new XmlStore();
            m_policySet = new PolicySet(Guid.NewGuid(), new TranslateableLanguageItem("TestPolicySet"), policyStore, policyCatalogue, false);
        }
        private void FilterPolicies(IPolicySet policySet)
        {
            if (null == policySet)
                return;

            IPolicyObjectCollection<IPolicy> policies = new PolicyObjectCollection<IPolicy>();

            foreach (IPolicy policy in policySet.Policies)
            {
                IPolicy reducedPolicy = FilterPolicy(policy);
                if (null == reducedPolicy)
                    continue;

                policies.Add(reducedPolicy);
            }
            
            m_reducedPolicySet.Policies = policies;
        }
Exemple #19
0
        /// <summary>
        /// Creates a new policy object with default AuditLevel and ConditionGroup values. The IPolicy
        /// is created with a new GUID.
        /// </summary>
        /// <param name="policyName">The name of the policy</param>
        /// <param name="policySet">The policy set to which this policy belongs</param>
        /// <param name="policyStatus">The status of the policy</param>
        /// <param name="auditLevel">The audit level of the policy</param>
        /// <returns>The IPolicy object</returns>
        public static IPolicy CreatePolicy(string policyName, IPolicySet policySet, PolicyStatus policyStatus, string auditLevel)
        {
            IPolicy policy = new P5Policy(policySet, System.Guid.NewGuid(), new TranslateableLanguageItem(policyName), policyStatus);
            policy["AuditLevel"] = new NonTranslateableLanguageItem(auditLevel);
            policy["blockOnException"] = new NonTranslateableLanguageItem(bool.TrueString);
            policy[PolicyConstants.SkipVerifiedMessages] = new NonTranslateableLanguageItem(bool.FalseString);

            //create root condition group on the policy
        	ChannelType[] channelTypes = PolicyTypeInfoManager.Instance.GetInfo(policySet.PolicyType).ChannelTypes;
			IPolicyChannel[] channels = ChannelFactory.CreateChannels(channelTypes);
            policy.Conditions.Add(new ConditionGroup(Guid.NewGuid(), new TranslateableLanguageItem("Default Condition Group"), ConditionLogic.AND, false));

            foreach (IPolicyChannel channel in channels)
            {
                policy.Channels.Add(channel);
            }
            return policy;
        }
Exemple #20
0
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            HashSet <object> memberSet = new HashSet <object>();

            // Select Injected Members
            if (null != ((ImplicitRegistration)registration).InjectionMembers)
            {
                foreach (var injectionMember in ((ImplicitRegistration)registration).InjectionMembers)
                {
                    if (injectionMember is InjectionMember <MethodInfo, object[]> && memberSet.Add(injectionMember))
                    {
                        yield return(injectionMember);
                    }
                }
            }

            // Select Attributed members
            IEnumerable <MethodInfo> members = DeclaredMembers(type);

            if (null == members)
            {
                yield break;
            }
            foreach (var member in members)
            {
                foreach (var attribute in Markers)
                {
#if NET40
                    if (!member.IsDefined(attribute, true) ||
#else
                    if (!member.IsDefined(attribute) ||
#endif
                        !memberSet.Add(member))
                    {
                        continue;
                    }

                    yield return(member);

                    break;
                }
            }
        }
            public IEnumerable <object> Select(Type type, IPolicySet registration)
            {
                object originalConstructor =
                    OriginalConstructorSelectorPolicy.Select(type, registration)
                    .First();

                switch (originalConstructor)
                {
                case ConstructorInfo info:
                    return(new [] { FromConstructorInfo(info, InterceptingType) });

                case SelectedConstructor selectedConstructor:
                    return(new [] { FromSelectedConstructor(selectedConstructor, InterceptingType) });

                case MethodBase <ConstructorInfo> methodBaseMember:
                    return(new [] { FromMethodBaseMember(methodBaseMember, InterceptingType) });
                }

                throw new InvalidOperationException("Unknown type");
            }
        public MDIChildForm AddPolicySetWindow(IPolicySet policySet, PolicySetVersionStatus status, string version)
        {
            Guid childFormId = Guid.NewGuid();
            string nodeName;
            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "en")
                nodeName = string.Format(CultureInfo.CurrentCulture, "{0} - v{1} [{2}]", policySet.Name.Value, version, Workshare.Policy.PolicySuites.Instance.GetStatusText(status));
            else
                nodeName = string.Format(CultureInfo.CurrentCulture, "{0} - [{1}]", policySet.Name.Value, Workshare.Policy.PolicySuites.Instance.GetStatusText(status));

            TreeObject treeObject = new TreeObject(childFormId, (int)TreeViewControllerPolicyOriented.NodeType.PolicySet, nodeName, policySet);
            policySetTreeView.Nodes.Add(treeObject);

            MDIChildForm childForm = new MDIChildForm(childFormId, policySet, policySetTreeView, treeObject);
            ChildFormData childFormData = new ChildFormData(childFormId, childForm, status, policySet);
            treeObject.Tag = childFormData;

            policySetTreeView.SelectedNode = treeObject;

            return childForm;
        }
        public override IEnumerable <Expression> GetExpressions(Type type, IPolicySet registration)
        {
            // Select ConstructorInfo
            var selector  = GetOrDefault(registration);
            var selection = selector.Select(type, registration)
                            .FirstOrDefault();

            // Select constructor for the Type
            object[]                 resolvers = null;
            ConstructorInfo          info      = null;
            IEnumerable <Expression> parametersExpr;

            switch (selection)
            {
            case ConstructorInfo memberInfo:
                info           = memberInfo;
                parametersExpr = CreateParameterExpressions(info.GetParameters());
                break;

            case MethodBase <ConstructorInfo> injectionMember:
                info           = injectionMember.MemberInfo(type);
                resolvers      = injectionMember.Data;
                parametersExpr = CreateParameterExpressions(info.GetParameters(), resolvers);
                break;

            case Exception exception:
                return(new[] { Expression.IfThen(
                                   Expression.Equal(Expression.Constant(null), BuilderContextExpression.Existing),
                                   Expression.Throw(Expression.Constant(exception))) });

            default:
                return(NoConstructorExpr);
            }

            // Get lifetime manager
            var lifetimeManager = (LifetimeManager)registration.Get(typeof(LifetimeManager));

            return(lifetimeManager is PerResolveLifetimeManager
                ? new[] { GetResolverExpression(info, resolvers), SetPerBuildSingletonExpr }
                : new Expression[] { GetResolverExpression(info, resolvers) });
        }
        public static List<Guid> GetCategories(IPolicySet policySet)
        {
            if (policySet == null ||
                 policySet.Policies == null ||
                 policySet.Policies.Count == 0)
            {
                return new List<Guid>();
            }

            Dictionary<Guid, bool> categoryIDs = new Dictionary<Guid, bool>();

            foreach (IPolicy policy in policySet.Policies)
            {
                if (policy == null ||
                    policy.Conditions == null)
                {
                    continue;
                }

                foreach (IPolicyObject conditionObj in policy.Conditions)
                {
                    if (conditionObj is IConditionGroup)
                    {
                        AddForensicCategoryIDs(conditionObj as IConditionGroup, categoryIDs);
                    }
                    else if (conditionObj is ICondition)
                    {
                        AddForensicCategoryIDs(conditionObj as ICondition, categoryIDs);
                    }
                }
            }

            List<Guid> result = new List<Guid>();

            foreach (Guid guid in categoryIDs.Keys)
            {
                result.Add(guid);
            }

            return result;
        }
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            // Select Injected Members
            if (null != ((InternalRegistration)registration).InjectionMembers)
            {
                foreach (var injectionMember in ((InternalRegistration)registration).InjectionMembers)
                {
                    if (injectionMember is InjectionMember <ConstructorInfo, object[]> )
                    {
                        return(new[] { injectionMember });
                    }
                }
            }

            // Enumerate to array
            var constructors = DeclaredMembers(type).ToArray();

            if (1 >= constructors.Length)
            {
                return(constructors);
            }

            // Select Attributed constructors
            foreach (var constructor in constructors)
            {
                for (var i = 0; i < AttributeFactories.Length; i++)
                {
#if NET40
                    if (!constructor.IsDefined(AttributeFactories[i].Type, true))
#else
                    if (!constructor.IsDefined(AttributeFactories[i].Type))
#endif
                    { continue; }

                    return(new[] { constructor });
                }
            }

            // Select default
            return(new[] { SelectMethod(type, constructors) });
        }
Exemple #26
0
        public virtual IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            HashSet <object> memberSet = new HashSet <object>();

            // Select Injected Members
            foreach (var injectionMember in ((ImplicitRegistration)registration).InjectionMembers ?? EmptyCollection)
            {
                if (injectionMember is InjectionMember <TMemberInfo, TData> && memberSet.Add(injectionMember))
                {
                    yield return(injectionMember);
                }
            }

            // Select Attributed members
            IEnumerable <TMemberInfo> members = DeclaredMembers(type);

            if (null == members)
            {
                yield break;
            }
            foreach (var member in members)
            {
                foreach (var node in AttributeFactories)
                {
#if NET40
                    if (!member.IsDefined(node.Type, true) ||
#else
                    if (!member.IsDefined(node.Type) ||
#endif
                        !memberSet.Add(member))
                    {
                        continue;
                    }

                    yield return(member);

                    break;
                }
            }
        }
        public IPolicySet ApplyFilter(IPolicySet policySet)
        {
            if (null == policySet)
                return null;

            // Lets create a dummy catalgue store.
            Store.XMLPolicyCatalogueStore catalogueStore = new Store.XMLPolicyCatalogueStore();
            IPolicyCatalogue reducedCatalogue = new PolicyCatalogue(Guid.NewGuid(), policySet.MasterCatalogue.LanguageId, catalogueStore);

            Store.XmlStore store = new Store.XmlStore();

            m_reducedPolicySet = new PolicySet(policySet.Identifier, policySet.Name, store, reducedCatalogue, policySet.ReadOnly);

            Dictionary<string, IPolicyLanguageItem>.Enumerator enumerator = policySet.GetAttributeEnumerator();
            while (enumerator.MoveNext())
            {
                m_reducedPolicySet[enumerator.Current.Key] = enumerator.Current.Value;
            }

            FilterPolicies(policySet);
            return m_reducedPolicySet;
        }
Exemple #28
0
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            // Select Injected Members
            foreach (var injectionMember in ((ImplicitRegistration)registration).InjectionMembers ?? EmptyCollection)
            {
                if (injectionMember is InjectionMember <ConstructorInfo, object[]> )
                {
                    return(new[] { injectionMember });
                }
            }

            // Enumerate to array
            var constructors = DeclaredMembers(type).ToArray();

            if (1 >= constructors.Length)
            {
                return(constructors);
            }

            // Select Attributed constructors
            foreach (var constructor in constructors)
            {
                foreach (var attribute in Markers)
                {
#if NET40
                    if (!constructor.IsDefined(attribute, true))
#else
                    if (!constructor.IsDefined(attribute))
#endif
                    { continue; }

                    return(new[] { constructor });
                }
            }

            // Select default
            return(new[] { SelectMethod(type, constructors) });
        }
Exemple #29
0
        public UIStateMachine(IPolicySet policyset, MDIChildForm childform)
        {
            PolicyLanguageCache.Instance.ActiveLanguageId = policyset.MasterCatalogue.LanguageId;
            m_policySet = policyset;
            m_ChildForm = childform;

            m_InitState.PolicySet = m_policySet;
            m_InitState.SetParent(childform);
            
            AddState(m_CloseState);
            AddState(m_InitState);
            AddState(m_ShowConditionsState);
            AddState(m_ShowPoliciesState);
            AddState(m_AddPolicyState);
            AddState(m_CopyPolicyState);
            AddState(m_ShowPolicyState);
            AddState(m_ShowActionsState);
            AddState(m_deletePolicyState);
            AddState(m_DeleteAllPoliciesState);
            AddState(m_deletePolicySetState);
            AddState(m_EditConditionState);
            AddState(m_NewConditionState);
            AddState(m_addAddressCollectionState);
            AddState(m_editRoutingDetailState);
            AddState(m_deleteAddressCollectionState);
            AddState(m_savePolicySetState);
            AddState(m_addActionState);
            AddState(m_addActionConditionGroupState);
            AddState(m_editCustomActionGroupState);
            AddState(m_editActionState);
            AddState(m_deleteActionState);
            AddState(m_activatePolicyState);
            AddState(m_exportState);
            AddState(m_importState);
            AddState(m_deleteConditionState);
            AddState(m_changeRoutingTypeState);
        }
Exemple #30
0
		public void WritePolicySet(IPolicySet policySet)
		{
			XmlNode xmlPolicyNode = m_xmlDocument.CreateElement("PolicySet");
			m_policieSetsNode.AppendChild(xmlPolicyNode);

			string id = XmlHelpers.GetPolicyObjectIdString(policySet);
			XmlHelpers.AddAttribute(xmlPolicyNode, "id", id);
			XmlHelpers.AddLanguageItemAttribute(xmlPolicyNode, "name", policySet.Name);
			XmlHelpers.AddLanguageItemAttribute(xmlPolicyNode, "Description", policySet.Description);
			XmlHelpers.AddAttribute(xmlPolicyNode, "mastercatalogueId", policySet.MasterCatalogue.Identifier);
			XmlHelpers.AddReadOnlyAttribute(xmlPolicyNode, policySet.ReadOnly);

			//	TODO: AP: Remove condition
			//	(it's a bit lazy because it saves me having to rewrite all the unit tests that check legacy policy XML
			//	formats. It works because policy sets without the policyType attribute default to the legacy policy type)
			if (policySet.PolicyType != PolicyType.Legacy)
			{
				XmlHelpers.AddAttribute(xmlPolicyNode, "policyType", policySet.PolicyType.ToString());
			}

			XmlHelpers.AddCustomAttributes(xmlPolicyNode, policySet);
			XmlNode xmlPoliciesNode = m_xmlDocument.CreateElement("Policies");
			xmlPolicyNode.AppendChild(xmlPoliciesNode);
		}
 /// <summary>
 ///
 /// </summary>
 /// <remarks>
 /// Call hierarchy:
 /// <see cref="GetExpressions"/>
 /// + <see cref="SelectMembers"/>
 ///   + <see cref="ExpressionsFromSelected"/>
 ///     + <see cref="BuildMemberExpression"/>
 ///       + <see cref="GetResolverExpression"/>
 /// </remarks>
 /// <param name="type"></param>
 /// <param name="registration"></param>
 /// <returns></returns>
 public abstract IEnumerable <Expression> GetExpressions(Type type, IPolicySet registration);
 public ConstructorDiagnostic(IPolicySet policySet, UnityContainer container)
     : base(policySet, container)
 {
 }
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            HashSet <object> memberSet = new HashSet <object>();

            // Select Injected Members
            if (null != ((InternalRegistration)registration).InjectionMembers)
            {
                foreach (var injectionMember in ((InternalRegistration)registration).InjectionMembers)
                {
                    if (injectionMember is InjectionMember <MethodInfo, object[]> && memberSet.Add(injectionMember))
                    {
                        yield return(injectionMember);
                    }
                }
            }

            // Select Attributed members
            foreach (var member in type.GetDeclaredMethods())
            {
                for (var i = 0; i < AttributeFactories.Length; i++)
                {
#if NET40
                    if (!member.IsDefined(AttributeFactories[i].Type, true) ||
#else
                    if (!member.IsDefined(AttributeFactories[i].Type) ||
#endif
                        !memberSet.Add(member))
                    {
                        continue;
                    }

                    // Validate
                    if (member.IsStatic)
                    {
                        throw new ArgumentException(
                                  $"Static method {member.Name} on type '{member.DeclaringType.Name}' is marked for injection. Static methods cannot be injected");
                    }

                    if (member.IsPrivate)
                    {
                        throw new InvalidOperationException(
                                  $"Private method '{member.Name}' on type '{member.DeclaringType.Name}' is marked for injection. Private methods cannot be injected");
                    }

                    if (member.IsFamily)
                    {
                        throw new InvalidOperationException(
                                  $"Protected method '{member.Name}' on type '{member.DeclaringType.Name}' is marked for injection. Protected methods cannot be injected");
                    }

                    if (member.IsGenericMethodDefinition)
                    {
                        throw new ArgumentException(
                                  $"Open generic method {member.Name} on type '{member.DeclaringType.Name}' is marked for injection. Open generic methods cannot be injected.");
                    }

                    var parameters = member.GetParameters();
                    if (parameters.Any(param => param.IsOut))
                    {
                        throw new ArgumentException(
                                  $"Method {member.Name} on type '{member.DeclaringType.Name}' is marked for injection. Methods with 'out' parameters cannot be injected.");
                    }

                    if (parameters.Any(param => param.ParameterType.IsByRef))
                    {
                        throw new ArgumentException(
                                  $"Method {member.Name} on type '{member.DeclaringType.Name}' is marked for injection. Methods with 'ref' parameters cannot be injected.");
                    }

                    yield return(member);

                    break;
                }
            }
        }
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            HashSet <object> memberSet = new HashSet <object>();

            // Select Injected Members
            if (null != ((InternalRegistration)registration).InjectionMembers)
            {
                foreach (var injectionMember in ((InternalRegistration)registration).InjectionMembers)
                {
                    if (injectionMember is InjectionMember <FieldInfo, object> && memberSet.Add(injectionMember))
                    {
                        yield return(injectionMember);
                    }
                }
            }

            // Select Attributed members
            foreach (var member in type.GetDeclaredFields())
            {
                for (var i = 0; i < AttributeFactories.Length; i++)
                {
#if NET40
                    if (!member.IsDefined(AttributeFactories[i].Type, true) ||
#else
                    if (!member.IsDefined(AttributeFactories[i].Type) ||
#endif
                        !memberSet.Add(member))
                    {
                        continue;
                    }

                    if (member.IsStatic)
                    {
                        throw new InvalidOperationException(
                                  $"Static field '{member.Name}' on type '{type?.Name}' is marked for injection. Static fields cannot be injected");
                    }

                    if (member.IsInitOnly)
                    {
                        throw new InvalidOperationException(
                                  $"Readonly field '{member.Name}' on type '{type?.Name}' is marked for injection. Readonly fields cannot be injected");
                    }

                    if (member.IsPrivate)
                    {
                        throw new InvalidOperationException(
                                  $"Private field '{member.Name}' on type '{type?.Name}' is marked for injection. Private fields cannot be injected");
                    }

                    if (member.IsFamily)
                    {
                        throw new InvalidOperationException(
                                  $"Protected field '{member.Name}' on type '{type?.Name}' is marked for injection. Protected fields cannot be injected");
                    }

                    yield return(member);

                    break;
                }
            }
        }
        /// <param name="set">the IPolicySet to summarise</param>
		public BasicTextSummaryWriter( IPolicySet set )
		{
			m_pss = new PolicySetSummary(set);
		}
        /// <summary>
        /// Removes a RoutingTable from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the RoutingTable</param>
        /// <param name="routingTable">The Routingtable to remove</param>
        private static void RemoveRoutingTable(IPolicySet policySet, IRoutingTable routingTable)
        {
            if (null == policySet || null == routingTable)
            {
                return;
            }

            IRoutingItemCollections addressGroup = routingTable.Sources;
            foreach (IRoutingItemCollection addressCollection in addressGroup)
            {
                RemoveAddressCollection(policySet, addressCollection);
            }
            addressGroup = routingTable.Destinations;
            foreach (IRoutingItemCollection addressCollection in addressGroup)
            {
                RemoveAddressCollection(policySet, addressCollection);
            }

            policySet.MasterCatalogue.RoutingTables.Remove(routingTable);
        }
Exemple #37
0
        private ResolveDelegate <PipelineContext> PipelineFromTypeFactory(ref HashKey key, UnityContainer container, IPolicySet set)
        {
            Debug.Assert(null != _registry);
            Debug.Assert(null != key.Type);

            LifetimeManager?manager = null;
            ResolveDelegate <PipelineContext>?pipeline = null;
            var typeFactory = (TypeFactoryDelegate)set.Get(typeof(TypeFactoryDelegate));

            // Add Pipeline to the Registry
            lock (_syncRegistry)
            {
                bool adding       = true;
                var  collisions   = 0;
                var  targetBucket = key.HashCode % _registry.Buckets.Length;
                for (var i = _registry.Buckets[targetBucket]; i >= 0; i = _registry.Entries[i].Next)
                {
                    ref var candidate = ref _registry.Entries[i];
                    if (candidate.Key != key)
                    {
                        collisions++;
                        continue;
                    }

                    // Pipeline already been created
                    if (null != candidate.Pipeline)
                    {
                        return(candidate.Pipeline);
                    }

                    // Lifetime Manager
                    manager = (LifetimeManager)set.Get(typeof(LifetimeManager)) ??
                              Context.TypeLifetimeManager.CreateLifetimePolicy();
                    manager.PipelineDelegate = (ResolveDelegate <PipelineContext>)SpinWait;

                    // Type has not been registered
                    if (null == candidate.Registration)
                    {
                        candidate.Pipeline = manager.Pipeline;
                    }

                    adding = false;
                    break;
                }

                if (adding)
                {
                    // Expand if required
                    if (_registry.RequireToGrow || CollisionsCutPoint < collisions)
                    {
                        _registry    = new Registry(_registry);
                        targetBucket = key.HashCode % _registry.Buckets.Length;
                    }

                    // Lifetime Manager
                    manager = (LifetimeManager)set.Get(typeof(LifetimeManager)) ??
                              Context.TypeLifetimeManager.CreateLifetimePolicy();
                    manager.PipelineDelegate = (ResolveDelegate <PipelineContext>)SpinWait;

                    // Create new entry
                    ref var entry = ref _registry.Entries[_registry.Count];
                    entry.Key      = key;
                    entry.Pipeline = manager.Pipeline;
                    entry.Next     = _registry.Buckets[targetBucket];
                    _registry.Buckets[targetBucket] = _registry.Count++;
                }
        /// <summary>
        /// Removes a DataElement from a policy set's master catalogue. 
        /// 
        /// This should only be called for DataElements that are part of a collection, ie
        /// Action.DataElements and DataElements that are method parameters
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the DataElement</param>
        /// <param name="dataElement">The DataElement to remove</param>
        private static void RemoveDataElement(IPolicySet policySet, IDataElement dataElement)
        {
            if (null == policySet || null == dataElement)
            {
                return;
            }

            if (dataElement.Data is IDataSource)
            {
                IDataSource source = dataElement.Data as IDataSource;
                foreach (IParameter parameter in source.Method.Parameters)
                {
                    RemoveDataElement(policySet, parameter.Value);
                }
            }

            policySet.MasterCatalogue.DataElements.Remove(dataElement);
        }
        /// <summary>
        /// Removes a Channel from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the Channel</param>
        /// <param name="channel">The Channel to remove</param>
        private static void RemoveChannel(IPolicySet policySet, IPolicyChannel channel)
        {
            if (null == policySet || null == channel)
            {
                return;
            }

            IRoutingTable routingTable = channel.Routing;
            foreach(IRoutingItemCollection sender in routingTable.Sources)
            {
                foreach (IRoutingItemCollection recipient in routingTable.Destinations)
                {
                    if (channel.Actions.HasCell(sender, recipient))
                    {
                        IActionMatrixCell cell = channel.Actions[sender, recipient];
                        foreach (IActionConditionGroup actionConditionGroup in cell.ActionConditionGroups)
                        {
                            RemoveConditionGroup(policySet, actionConditionGroup);
                        }
                    }
                }
            }

            //remove routing table
            RemoveRoutingTable(policySet, channel.Routing);

            IChannel channelInCatalogue = policySet.MasterCatalogue.Channels[channel.Identifier];
            policySet.MasterCatalogue.Channels.Remove(channelInCatalogue);
        }
        /// <summary>
        /// Removes a ConditionGroup from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the ConditionGroup</param>
        /// <param name="conditionGroup">The ConditionGroup to remove</param>
        private static void RemoveConditionGroup(IPolicySet policySet, IConditionGroup conditionGroup)
        {
            if ((null == policySet) || (null == conditionGroup))
            {
                return;
            }

            foreach(IPolicyObject conditionOrGroup in conditionGroup.Conditions)
            {
                if (conditionOrGroup is ICondition)
                {
                    RemoveCondition(policySet, conditionOrGroup as ICondition);
                }
                else if (conditionOrGroup is IConditionGroup)
                {
                    RemoveConditionGroup(policySet, conditionOrGroup as IConditionGroup);
                }
            }

            //do extra processing on the IActionConditionGroup specialization
            if (conditionGroup is IActionConditionGroup)
            {
                RemoveActionGroup(policySet, ((IActionConditionGroup)conditionGroup).ActionGroup);
            }

            policySet.MasterCatalogue.ConditionGroups.Remove(conditionGroup);
        }
        /// <summary>
        /// Removes a condition from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the condition</param>
        /// <param name="condition">The condition to remove</param>
        private static void RemoveCondition(IPolicySet policySet, ICondition condition)
        {
            if ((null == policySet) || (null == condition))
            {
                return;
            }

            RemoveDataElement(policySet, condition.DataLeft);
            RemoveDataElement(policySet, condition.DataRight);

            policySet.MasterCatalogue.Conditions.Remove(condition);
        }
        /// <summary>
        /// Removes a policy from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the policy</param>
        /// <param name="policy">The policy to remove</param>
        private static void RemovePolicy(IPolicySet policySet, IPolicy policy)
        {
            if (null == policySet || null == policy)
            {
                return;
            }

            foreach(IPolicyObject conditionOrGroup in policy.Conditions)
            {
                if (conditionOrGroup is ICondition)
                {
                    RemoveCondition(policySet, conditionOrGroup as ICondition);
                }
                else
                {
                    RemoveConditionGroup(policySet, conditionOrGroup as IConditionGroup);
                }
            }

            foreach(IPolicyChannel channel in policy.Channels)
            {
                RemoveChannel(policySet, channel);
            }

            policySet.MasterCatalogue.CataloguePolicies.Remove(policy);
        }
 public PropertyDiagnostic(IPolicySet policySet)
     : base(policySet)
 {
 }
        /// <summary>
        /// Removes an ActionGroup from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the ActionGroup</param>
        /// <param name="actionGroup">The ActionGroup to remove</param>
        private static void RemoveActionGroup(IPolicySet policySet, IActionGroup actionGroup)
        {
            if (null == policySet || null == actionGroup)
            {
                return;
            }

            foreach (IActionGroup childActionGroup in actionGroup.ActionGroups)
            {
                RemoveActionGroup(policySet, childActionGroup);
            }

            foreach (IAction childAction in actionGroup.Actions)
            {
                RemoveAction(policySet, childAction);
            }

            policySet.MasterCatalogue.ActionGroups.Remove(actionGroup);
        }
Exemple #45
0
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            HashSet <object> memberSet = new HashSet <object>();

            // Select Injected Members
            foreach (var injectionMember in ((ImplicitRegistration)registration).InjectionMembers ?? EmptyCollection)
            {
                if (injectionMember is InjectionMember <PropertyInfo, object> && memberSet.Add(injectionMember))
                {
                    yield return(injectionMember);
                }
            }

            // Select Attributed members
            foreach (var member in type.GetDeclaredProperties())
            {
                foreach (var node in AttributeFactories)
                {
#if NET40
                    if (!member.IsDefined(node.Type, true) ||
#else
                    if (!member.IsDefined(node.Type) ||
#endif
                        !memberSet.Add(member))
                    {
                        continue;
                    }

                    var setter = member.GetSetMethod(true);
                    if (!member.CanWrite || null == setter)
                    {
                        yield return(new InvalidRegistrationException(
                                         $"Readonly property '{member.Name}' on type '{type?.Name}' is marked for injection. Readonly properties cannot be injected"));
                    }

                    if (0 != member.GetIndexParameters().Length)
                    {
                        yield return(new InvalidRegistrationException(
                                         $"Indexer '{member.Name}' on type '{type?.Name}' is marked for injection. Indexers cannot be injected"));
                    }

                    if (setter.IsStatic)
                    {
                        yield return(new InvalidRegistrationException(
                                         $"Static property '{member.Name}' on type '{type?.Name}' is marked for injection. Static properties cannot be injected"));
                    }

                    if (setter.IsPrivate)
                    {
                        yield return(new InvalidRegistrationException(
                                         $"Private property '{member.Name}' on type '{type?.Name}' is marked for injection. Private properties cannot be injected"));
                    }

                    if (setter.IsFamily)
                    {
                        yield return(new InvalidRegistrationException(
                                         $"Protected property '{member.Name}' on type '{type?.Name}' is marked for injection. Protected properties cannot be injected"));
                    }

                    yield return(member);

                    break;
                }
            }
        }
        /// <summary>
        /// Removes an Action from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the Action</param>
        /// <param name="action">The Action to remove</param>
        private static void RemoveAction(IPolicySet policySet, IAction action)
        {
            if (null == policySet || null == action)
            {
                return;
            }

            foreach (IDataElement dataElement in action.DataElements)
            {
                RemoveDataElement(policySet, dataElement);
            }

            policySet.MasterCatalogue.Actions.Remove(action);
        }
 public FieldDiagnostic(IPolicySet policySet) : base(policySet)
 {
 }
        /// <summary>
        /// Removes an RoutingItemCollection from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the RoutingItemCollection</param>
        /// <param name="locationCollection">The RoutingItemCollection to remove</param>
        private static void RemoveAddressCollection(IPolicySet policySet, IRoutingItemCollection addressCollection)
        {
            if (null == policySet || null == addressCollection)
            {
                return;
            }

            foreach (IRoutingItem address in addressCollection)
            {
                RemoveAddress(policySet, address);
            }

            policySet.MasterCatalogue.LocationsCollection.Remove(addressCollection);
        }
 public ConstructorProcessor(IPolicySet policySet, Func <Type, bool> isTypeRegistered)
     : base(policySet, typeof(InjectionConstructorAttribute))
 {
     _isTypeRegistered = isTypeRegistered;
     SelectMethod      = SmartSelector;
 }
        /// <summary>
        /// Removes an RoutingItem from a policy set's master catalogue
        /// </summary>
        /// <param name="policySet">The policy set from whose catalogue we will remove the RoutingItem</param>
        /// <param name="location">The Channel to remove</param>
        private static void RemoveAddress(IPolicySet policySet, IRoutingItem address)
        {
            if (null == policySet || null == address)
            {
                return;
            }

            policySet.MasterCatalogue.Locations.Remove(address);
        }
 public MethodDiagnostic(IPolicySet policySet, UnityContainer container)
     : base(policySet, container)
 {
 }
        /// <summary>
        /// Removes a policy object from a policy set's master catalogue. This method assumes that there is no sharing of
        /// objects within the object model; when a policy object is removed from the catalogue, all children of this
        /// policy object are also removed.
        /// 
        /// Be careful when using this method; in general, the object model dictates that it is only logical to explicitly
        /// remove those objects that are stored within a collection. You should also ensure you remove the policy object from
        /// the parent expression *before* calling this method.
        /// 
        /// Example 1: a policy, stored in policySet.Policies, is safe to remove from the catalogue explicitly, so long as you 
        /// remove it from policySet.Policies before calling this method.
        /// 
        /// Example 2: a DataElement, stored in Condition.DataLeft, should not be removed explicitly via this method. Note that if 
        /// you decide to remove the parent Condition from the catalogue, the DataElement will be implicitly removed for you. 
        /// 
        /// Ignoring this advice is not dangerous per se; the only problem you should see is that the policy object will 
        /// reappear in the catalogue the next time you inspect the parent object. 
        /// 
        /// Note: At the time of writing, because of problems with the object model not deleting action matrix cells when an location 
        /// collection is removed, explicit removal of LocationsCollection and Locations has been disabled. These can still be
        /// removed implicitly if you remove a PolicyChannel (or another object even higher up the object model).
        /// </summary>
        /// <param name="policySet">The policy set from whose master catalogue we should remove the policy object</param>
        /// <param name="policyObject">The policy object to remove</param>
        public static void RemovePolicyObjectFromCatalogue(IPolicySet policySet, IPolicyObject policyObject)
        {
            if (policyObject is IPolicy)
            {
                RemovePolicy(policySet, policyObject as IPolicy);
                return;
            }

            if (policyObject is ICondition)
            {
                RemoveCondition(policySet, policyObject as ICondition);
                return;
            }

            if (policyObject is IConditionGroup)
            {
                RemoveConditionGroup(policySet, policyObject as IConditionGroup);
                return;
            }

            if (policyObject is IDataElement)
            {
                //use this with care. If the DataElement is condition.DataLeft or condition.DataRight,
                //the dataelement will be added back into the catalogue the next time the parent condition is
                //inspected. Only use this if removing a DataElement from an action or from a parameter in a
                //method.
                RemoveDataElement(policySet, policyObject as IDataElement);
                return;
            }

            if (policyObject is IPolicyChannel)
            {
                RemoveChannel(policySet, policyObject as IPolicyChannel);
                return;
            }

            if (policyObject is IAction)
            {
                RemoveAction(policySet, policyObject as IAction);
                return;
            }

            //for now, don't support removal of individual location collections, as the object model doesn't delete
            //action matrix cells for us and so the location collection is automatically re-added into the catalogue.
            //however, location groups can be removed as part of a channel removal.
            //TODO: refactor object model to correctly remove action matrix cells
            //if (policyObject is IRoutingItemCollection)
            //{
            //    RemoveAddressCollection(policySet, policyObject as IRoutingItemCollection);
            //    return;
            //}

            //for now, don't support removal of individual locations, as the object model doesn't delete
            //action matrix cells for us and so the location is automatically re-added into the catalogue.
            //however, locations can be removed as part of a channel removal.
            //TODO: refactor object model to correctly remove action matrix cells
            //if (policyObject is IRoutingItem)
            //{
            //    RemoveAddress(policySet, policyObject as IRoutingItem);
            //    return;
            //}

            //It is illogical to attempt to remove the following objects in isolation; these should only
            //ever be removed from the catalogue because their parent object is being removed
            //
            //- remove a routing table only when removing an entire channel
            //- remove an action group only when removing an action condition group

            Utilities.ErrorMessage errorMessage = new Utilities.ErrorMessage(
                "POLICY_UNSUPPORTED_TYPE",
                "Workshare.PolicyDesigner.Properties.Resources",
                System.Reflection.Assembly.GetExecutingAssembly(), policyObject.ToString());
			Logger.LogError(errorMessage.LogString);
			throw new ArgumentException(errorMessage.DisplayString);
        }
Exemple #53
0
 public MethodProcessor(IPolicySet policySet, UnityContainer container)
     : base(policySet, typeof(InjectionMethodAttribute), container)
 {
 }
Exemple #54
0
 public override MemberSelector <ConstructorInfo> GetOrDefault(IPolicySet registration) =>
 registration.Get <MemberSelector <ConstructorInfo> >() ??
 Defaults.SelectConstructor;
        public override ResolveDelegate <BuilderContext> GetResolver(Type type, IPolicySet registration, ResolveDelegate <BuilderContext> seed)
        {
#if NETSTANDARD1_0 || NETCOREAPP1_0
            var typeInfo = type.GetTypeInfo();
#else
            var typeInfo = type;
#endif
            // Validate if Type could be created
            if (typeInfo.IsInterface)
            {
                return((ref BuilderContext c) =>
                {
                    if (null == c.Existing)
                    {
                        throw new InvalidOperationException(string.Format(CannotConstructInterface, c.Type),
                                                            new InvalidRegistrationException());
                    }

                    return c.Existing;
                });
            }

            if (typeInfo.IsAbstract)
            {
                return((ref BuilderContext c) =>
                {
                    if (null == c.Existing)
                    {
                        throw new InvalidOperationException(string.Format(CannotConstructAbstractClass, c.Type),
                                                            new InvalidRegistrationException());
                    }

                    return c.Existing;
                });
            }

            if (typeInfo.IsSubclassOf(typeof(Delegate)))
            {
                return((ref BuilderContext c) =>
                {
                    if (null == c.Existing)
                    {
                        throw new InvalidOperationException(string.Format(CannotConstructDelegate, c.Type),
                                                            new InvalidRegistrationException());
                    }

                    return c.Existing;
                });
            }

            if (type == typeof(string))
            {
                return((ref BuilderContext c) =>
                {
                    if (null == c.Existing)
                    {
                        throw new InvalidOperationException(string.Format(TypeIsNotConstructable, c.Type),
                                                            new InvalidRegistrationException());
                    }

                    return c.Existing;
                });
            }


            return(base.GetResolver(type, registration, seed));
        }
Exemple #56
0
 public override MemberSelector <FieldInfo> GetOrDefault(IPolicySet registration) =>
 registration.Get <MemberSelector <FieldInfo> >() ?? Defaults.SelectField;
        public override IEnumerable <object> Select(Type type, IPolicySet registration)
        {
            var members = new List <InjectionMember>();

            // Select Injected Members
            if (null != ((InternalRegistration)registration).InjectionMembers)
            {
                foreach (var injectionMember in ((InternalRegistration)registration).InjectionMembers)
                {
                    if (injectionMember is InjectionMember <ConstructorInfo, object[]> )
                    {
                        members.Add(injectionMember);
                    }
                }
            }

            switch (members.Count)
            {
            case 1:
                return(members.ToArray());

            case 0:
                break;

            default:
                return(new[] { new InvalidOperationException($"Multiple Injection Constructors are registered for Type {type.FullName}",
                                                             new InvalidRegistrationException()) });
            }

            // Enumerate to array
            var constructors = DeclaredMembers(type).ToArray();

            if (1 >= constructors.Length)
            {
                return(constructors);
            }

            var selection = new HashSet <ConstructorInfo>();

            // Select Attributed constructors
            foreach (var constructor in constructors)
            {
                for (var i = 0; i < AttributeFactories.Length; i++)
                {
#if NET40
                    if (!constructor.IsDefined(AttributeFactories[i].Type, true))
#else
                    if (!constructor.IsDefined(AttributeFactories[i].Type))
#endif
                    { continue; }

                    selection.Add(constructor);
                }
            }

            switch (selection.Count)
            {
            case 1:
                return(selection.ToArray());

            case 0:
                break;

            default:
                return(new[] { new InvalidOperationException($"Multiple Constructors are annotated for injection on Type {type.FullName}",
                                                             new InvalidRegistrationException()) });
            }

            // Select default
            return(new[] { SelectMethod(type, constructors) });
        }
 public override ISelect <FieldInfo> GetOrDefault(IPolicySet registration) =>
 registration.Get <ISelect <FieldInfo> >() ?? Defaults.FieldsSelector;
 /// <summary>
 ///
 /// </summary>
 /// <remarks>
 /// Call hierarchy:
 /// <see cref="GetResolver"/>
 /// + <see cref="SelectMembers"/>
 ///   + <see cref="ResolversFromSelected"/>
 ///     + <see cref="BuildMemberResolver"/>
 ///       + <see cref="GetResolverDelegate"/>
 /// </remarks>
 /// <param name="type"></param>
 /// <param name="registration"></param>
 /// <param name="seed"></param>
 /// <returns></returns>
 public abstract ResolveDelegate <BuilderContext> GetResolver(Type type, IPolicySet registration, ResolveDelegate <BuilderContext> seed);
 public ConstructorProcessor(IPolicySet policySet, UnityContainer container)
     : base(policySet, typeof(InjectionConstructorAttribute), container)
 {
     SelectMethod = SmartSelector;
 }