internal static ExportCardinalityCheckResult CheckCardinality(ImportDefinition definition, IEnumerable <Export> exports)
        {
            EnumerableCardinality actualCardinality = exports.GetCardinality();

            switch (actualCardinality)
            {
            case EnumerableCardinality.Zero:
                if (definition.Cardinality == ImportCardinality.ExactlyOne)
                {
                    return(ExportCardinalityCheckResult.NoExports);
                }
                break;

            case EnumerableCardinality.TwoOrMore:
                if (definition.Cardinality.IsAtMostOne())
                {
                    return(ExportCardinalityCheckResult.TooManyExports);
                }
                break;

            default:
                Assumes.IsTrue(actualCardinality == EnumerableCardinality.One);
                break;
            }

            return(ExportCardinalityCheckResult.Match);
        }
Exemplo n.º 2
0
        internal static string GetTypeIdentity(Type type, bool formatGenericName)
        {
            Assumes.NotNull(type);
            string typeIdentity = null;

            if (!TypeIdentityCache.TryGetValue(type, out typeIdentity))
            {
                if (!type.IsAbstract && type.HasBaseclassOf(typeof(Delegate)))
                {
                    MethodInfo method = type.GetMethod("Invoke");
                    typeIdentity = ContractNameServices.GetTypeIdentityFromMethod(method);
                }
                else if (type.IsGenericParameter)
                {
                    StringBuilder typeIdentityStringBuilder = new StringBuilder();
                    WriteTypeArgument(typeIdentityStringBuilder, false, type, formatGenericName);
                    typeIdentityStringBuilder.Remove(typeIdentityStringBuilder.Length - 1, 1);
                    typeIdentity = typeIdentityStringBuilder.ToString();
                }
                else
                {
                    StringBuilder typeIdentityStringBuilder = new StringBuilder();
                    WriteTypeWithNamespace(typeIdentityStringBuilder, type, formatGenericName);
                    typeIdentity = typeIdentityStringBuilder.ToString();
                }

                Assumes.IsTrue(!string.IsNullOrEmpty(typeIdentity));
                TypeIdentityCache.Add(type, typeIdentity);
            }

            return(typeIdentity);
        }
Exemplo n.º 3
0
        private object Activate(LifetimeContext context, CompositionOperation operation)
        {
            Assumes.IsTrue(_exportDescriptor.IsValueCreated, "Activation in progress before all descriptors fully initialized.");

            Debug.WriteLine("[System.Composition] Activating via cycle-breaking proxy.");
            return(_exportDescriptor.Value.Activator(context, operation));
        }
Exemplo n.º 4
0
        public static Type GenerateView(Type viewType)
        {
            Assumes.NotNull(viewType);
            Assumes.IsTrue(viewType.IsInterface);

            Type proxyType;
            bool foundProxy;

            using (new ReadLock(_lock))
            {
                foundProxy = _proxies.TryGetValue(viewType, out proxyType);
            }

            // No factory exists
            if (!foundProxy)
            {
                // Try again under a write lock if still none generate the proxy
                Type generatedProxyType = GenerateInterfaceViewProxyType(viewType);
                Assumes.NotNull(generatedProxyType);

                using (new WriteLock(_lock))
                {
                    if (!_proxies.TryGetValue(viewType, out proxyType))
                    {
                        proxyType = generatedProxyType;
                        _proxies.Add(viewType, proxyType);
                    }
                }
            }
            return(proxyType);
        }
Exemplo n.º 5
0
        private static void WriteHeader(StringBuilder writer, int errorsCount, int pathCount)
        {
            if (errorsCount > 1 && pathCount > 1)
            {
                // The composition produced multiple composition errors, with {0} root causes. The root causes are provided below.
                writer.AppendFormat(
                    CultureInfo.CurrentCulture,
                    SR.CompositionException_MultipleErrorsWithMultiplePaths,
                    pathCount);
            }
            else if (errorsCount == 1 && pathCount > 1)
            {
                // The composition produced a single composition error, with {0} root causes. The root causes are provided below.
                writer.AppendFormat(
                    CultureInfo.CurrentCulture,
                    SR.CompositionException_SingleErrorWithMultiplePaths,
                    pathCount);
            }
            else
            {
                Assumes.IsTrue(errorsCount == 1);
                Assumes.IsTrue(pathCount == 1);

                // The composition produced a single composition error. The root cause is provided below.
                writer.AppendFormat(
                    CultureInfo.CurrentCulture,
                    SR.CompositionException_SingleErrorWithSinglePath,
                    pathCount);
            }

            writer.Append(' ');
            writer.AppendLine(SR.CompositionException_ReviewErrorProperty);
        }
Exemplo n.º 6
0
        private static ExportCardinalityCheckResult MatchCardinality(EnumerableCardinality actualCardinality, ImportCardinality importCardinality)
        {
            switch (actualCardinality)
            {
            case EnumerableCardinality.Zero:
                if (importCardinality == ImportCardinality.ExactlyOne)
                {
                    return(ExportCardinalityCheckResult.NoExports);
                }
                break;

            case EnumerableCardinality.TwoOrMore:
                if (importCardinality.IsAtMostOne())
                {
                    return(ExportCardinalityCheckResult.TooManyExports);
                }
                break;

            default:
                Assumes.IsTrue(actualCardinality == EnumerableCardinality.One);
                break;
            }

            return(ExportCardinalityCheckResult.Match);
        }
Exemplo n.º 7
0
        public static MetadataViewFactory GetMetadataViewFactory(Type viewType)
        {
            Assumes.NotNull(viewType);
            Assumes.IsTrue(viewType.IsInterface);

            MetadataViewFactory metadataViewFactory;
            bool foundMetadataViewFactory;

            using (new ReadLock(_lock))
            {
                foundMetadataViewFactory = _metadataViewFactories.TryGetValue(viewType, out metadataViewFactory);
            }

            // No factory exists
            if (!foundMetadataViewFactory)
            {
                // Try again under a write lock if still none generate the proxy
                Type generatedProxyType = GenerateInterfaceViewProxyType(viewType);
                Assumes.NotNull(generatedProxyType);

                MetadataViewFactory generatedMetadataViewFactory = (MetadataViewFactory)Delegate.CreateDelegate(
                    typeof(MetadataViewFactory), generatedProxyType.GetMethod(MetadataViewGenerator.MetadataViewFactoryName, BindingFlags.Public | BindingFlags.Static));
                Assumes.NotNull(generatedMetadataViewFactory);

                using (new WriteLock(_lock))
                {
                    if (!_metadataViewFactories.TryGetValue(viewType, out metadataViewFactory))
                    {
                        metadataViewFactory = generatedMetadataViewFactory;
                        _metadataViewFactories.Add(viewType, metadataViewFactory);
                    }
                }
            }
            return(metadataViewFactory);
        }
Exemplo n.º 8
0
        internal static string GetTypeIdentity(Type type)
        {
            Assumes.NotNull(type);
            string typeIdentity = null;

            if (!TypeIdentityCache.TryGetValue(type, out typeIdentity))
            {
                if (!type.IsPublic && type.IsSubclassOf(typeof(Delegate)))
                {
                    MethodInfo method = type.GetMethod("Invoke");
                    typeIdentity = ContractNameServices.GetTypeIdentityFromMethod(method);
                }
                else
                {
                    StringBuilder typeIdentityStringBuilder = new StringBuilder();
                    WriteTypeWithNamespace(typeIdentityStringBuilder, type);
                    typeIdentity = typeIdentityStringBuilder.ToString();
                }

                Assumes.IsTrue(!string.IsNullOrEmpty(typeIdentity));
                TypeIdentityCache.Add(type, typeIdentity);
            }

            return(typeIdentity);
        }
Exemplo n.º 9
0
            private static bool ShouldUseSharedPart(CreationPolicy partPolicy, CreationPolicy importPolicy)
            {
                // Matrix that details which policy to use for a given part to satisfy a given import.
                //                   Part.Any   Part.Shared  Part.NonShared
                // Import.Any        Shared     Shared       NonShared
                // Import.Shared     Shared     Shared       N/A
                // Import.NonShared  NonShared  N/A          NonShared

                switch (partPolicy)
                {
                case CreationPolicy.Any:
                {
                    if (importPolicy == CreationPolicy.Any ||
                        importPolicy == CreationPolicy.Shared)
                    {
                        return(true);
                    }
                    return(false);
                }

                case CreationPolicy.NonShared:
                {
                    Assumes.IsTrue(importPolicy != CreationPolicy.Shared);
                    return(false);
                }

                default:
                {
                    Assumes.IsTrue(partPolicy == CreationPolicy.Shared);
                    Assumes.IsTrue(importPolicy != CreationPolicy.NonShared);
                    return(true);
                }
                }
            }
Exemplo n.º 10
0
        public static MemberInfo ResolveMember(Module module, int metadataToken)
        {
            Assumes.NotNull(module);
            Assumes.IsTrue(metadataToken != 0);

            return(module.ResolveMember(metadataToken));
        }
Exemplo n.º 11
0
        public ReflectionProperty(MethodInfo getMethod, MethodInfo setMethod)
        {
            Assumes.IsTrue(getMethod != null || setMethod != null);

            this._getMethod = getMethod;
            this._setMethod = setMethod;
        }
Exemplo n.º 12
0
        private CachingResult LoadStandardDictionaryFast(ILGenerator ilGenerator, IDictionary<string, object> dictionary)
        {
            Assumes.NotNull(ilGenerator);
            Assumes.NotNull(dictionary);
            Assumes.IsTrue(dictionary.Count < GenerationServices.StandardDictionaryGeneratorsCount);

            CachingResult result = CachingResult.SucceededResult;
            MethodInfo standardDictionaryGenerator = this._standardDictionaryGenerators[dictionary.Count];

            // all we need to do is load all keys and values on stack and then invoke the standard generator
            foreach (KeyValuePair<string, object> dictionaryItem in dictionary)
            {
                // load key - boxing is never required for strings
                result = result.MergeResult(this.LoadValue(ilGenerator, dictionaryItem.Key));
                // load value
                result = result.MergeResult(this.LoadValue(ilGenerator, dictionaryItem.Value));
                if (GenerationServices.IsBoxingRequiredForValue(dictionaryItem.Value))
                {
                    ilGenerator.Emit(OpCodes.Box, dictionaryItem.Value.GetType());
                }
            }

            // call the standard dictionary generator - this would load the value on stack
            ilGenerator.EmitCall(OpCodes.Call, standardDictionaryGenerator, null);

            return result;
        }
        protected override IEnumerable <ExportDescriptorPromise> GetPromises(CompositionContract contract)
        {
            Assumes.IsTrue(!_updateFinished, "Update is finished - dependencies should have been requested earlier.");

            ExportDescriptor[] definitions;
            if (_partDefinitions.TryGetValue(contract, out definitions))
            {
                return(definitions.Select(d => new ExportDescriptorPromise(contract, "Preexisting", false, s_noDependencies, _ => d)).ToArray());
            }

            UpdateResult updateResult;

            if (!_updateResults.TryGetValue(contract, out updateResult))
            {
                updateResult = new UpdateResult(_exportDescriptorProviders);
                _updateResults.Add(contract, updateResult);
            }

            ExportDescriptorProvider nextProvider;

            while (updateResult.TryDequeueNextProvider(out nextProvider))
            {
                var newDefinitions = nextProvider.GetExportDescriptors(contract, this);
                foreach (var definition in newDefinitions)
                {
                    updateResult.AddPromise(definition);
                }
            }

            return(updateResult.GetResults());
        }
        private Type CheckForLazyAndPartCreator(Type type)
        {
            if (type.IsGenericType)
            {
                Type   genericType = type.GetGenericTypeDefinition();
                Type[] arguments   = type.GetGenericArguments();

                if (genericType == LazyOfTType)
                {
                    this._castSingleValue = ExportServices.CreateStronglyTypedLazyFactory(arguments[0], null);
                    return(arguments[0]);
                }

                if (genericType == LazyOfTMType)
                {
                    this.MetadataViewType = arguments[1];
                    this._castSingleValue = ExportServices.CreateStronglyTypedLazyFactory(arguments[0], arguments[1]);
                    return(arguments[0]);
                }

                if (
                    type.FullName.StartsWith(ExportFactoryTypeName, StringComparison.Ordinal) &&
                    ((arguments.Length == 1) || (arguments.Length == 2)))
                {
                    // Func<Tuple<T, Action>>
                    Type            exportLifetimeContextCreatorType = typeof(Func <>).MakeGenericType(typeof(Tuple <,>).MakeGenericType(arguments[0], typeof(Action)));
                    ConstructorInfo constructor = null;

                    if (arguments.Length == 1)
                    {
                        constructor = type.GetConstructor(new Type[] { exportLifetimeContextCreatorType });
                    }
                    else
                    {
                        Assumes.IsTrue(arguments.Length == 2);
                        constructor = type.GetConstructor(new Type[] { exportLifetimeContextCreatorType, arguments[1] });
                    }

                    if (constructor != null)
                    {
                        this.IsPartCreator = true;
                        if (arguments.Length == 1)
                        {
                            this._castSingleValue = ExportServices.CreateStronglyTypedExportFactoryFactory(arguments[0], null, constructor);
                        }
                        else
                        {
                            Assumes.IsTrue(arguments.Length == 2);
                            this._castSingleValue = ExportServices.CreateStronglyTypedExportFactoryFactory(arguments[0], arguments[1], constructor);
                            this.MetadataViewType = arguments[1];
                        }

                        return(arguments[0]);
                    }
                }
            }

            return(type);
        }
Exemplo n.º 15
0
        public SerializableCompositionElement(string displayName, ICompositionElement origin)
        {
#if !SILVERLIGHT
            Assumes.IsTrue(origin == null || origin.GetType().IsSerializable);
#endif
            this._displayName = displayName ?? string.Empty;
            this._origin      = origin;
        }
Exemplo n.º 16
0
        public void IsTrue()
        {
            ExceptionAssert.Throws <AssumptionException>(() => { Assumes.IsTrue(false); }).WithMessage("Assumption failed.");
            ExceptionAssert.Throws <AssumptionException>(() => { Assumes.IsTrue(false, "test."); }).WithMessage("Assumption failed. test.");

            Assumes.IsTrue(true);
            Assumes.IsTrue(true, "test");
        }
Exemplo n.º 17
0
        private T GetExportedValueCore <T>(string contractName, ImportCardinality cardinality)
        {
            Assumes.IsTrue(cardinality.IsAtMostOne());

            Export export = GetExportsCore(typeof(T), (Type)null, contractName, cardinality).SingleOrDefault();

            return((export != null) ? ExportServices.GetCastedExportedValue <T>(export) : default(T));
        }
        public SerializableCompositionElement(string displayName, ICompositionElement origin)
        {
#if FEATURE_SERIALIZATION
            Assumes.IsTrue(origin == null || origin.GetType().IsSerializable);
#endif
            _displayName = displayName ?? string.Empty;
            _origin      = origin;
        }
Exemplo n.º 19
0
        public void IsTrue()
        {
            ExceptionAssert.Throws(debugAssertException, () => { Assumes.IsTrue(false); }).WithMessage("Assumption failed.", ExceptionMessageComparison.StartsWith);
            ExceptionAssert.Throws(debugAssertException, () => { Assumes.IsTrue(false, "test."); }).WithMessage("Assumption failed. test.", ExceptionMessageComparison.StartsWith);

            Assumes.IsTrue(true);
            Assumes.IsTrue(true, "test");
        }
Exemplo n.º 20
0
        public static ReflectionWritableMember ToReflectionWriteableMember(this LazyMemberInfo lazyMember)
        {
            Assumes.IsTrue((lazyMember.MemberType == MemberTypes.Field) || (lazyMember.MemberType == MemberTypes.Property));

            ReflectionWritableMember reflectionMember = lazyMember.ToReflectionMember() as ReflectionWritableMember;

            Assumes.NotNull(reflectionMember);

            return(reflectionMember);
        }
Exemplo n.º 21
0
        static string FormatClosedGeneric(Type closedGenericType)
        {
            Assumes.NotNull(closedGenericType);
            Assumes.IsTrue(closedGenericType.IsConstructedGenericType);

            var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf("`"));
            var args = closedGenericType.GenericTypeArguments.Select(t => Format(t));

            return(string.Format("{0}<{1}>", name, string.Join(", ", args)));
        }
Exemplo n.º 22
0
        private object CastExportsToSingleImportType(Export[] exports)
        {
            Assumes.NotNull(exports);
            Assumes.IsTrue(exports.Length < 2);

            if (exports.Length == 0)
            {
                return(null);
            }

            return(CastSingleExportToImportType(this.ImportType.Type, exports[0]));
        }
Exemplo n.º 23
0
        internal void EnterSharingLock(object sharingLock)
        {
            Assumes.NotNull(sharingLock, "Sharing lock is required");

            if (_sharingLock == null)
            {
                _sharingLock = sharingLock;
                Monitor.Enter(sharingLock);
            }

            Assumes.IsTrue(_sharingLock == sharingLock, "Sharing lock already taken in this operation.");
        }
Exemplo n.º 24
0
        private static void WriteGenericTypeName(StringBuilder typeName, Type type, bool isDefinition, Queue <Type> genericTypeArguments, bool formatGenericName)
        {
            //
            // Writes generic type name, e.g. generic name and generic arguments
            //
            Assumes.IsTrue(type.IsGenericType, "Expecting type to be a generic type");
            int    genericArity    = GetGenericArity(type);
            string genericTypeName = FindGenericTypeName(type.GetGenericTypeDefinition().Name);

            typeName.Append(genericTypeName);
            WriteTypeArgumentsString(typeName, genericArity, isDefinition, genericTypeArguments, formatGenericName);
        }
Exemplo n.º 25
0
        //internal for testability
        internal static void WriteCustomModifiers(StringBuilder typeName, string customKeyword, Type[] types, bool formatGenericName)
        {
            //
            // Writes custom modifiers in the format: customKeyword(<contract_name>,<contract_name>,...)
            //
            typeName.Append(CustomModifiersSeparator);
            typeName.Append(customKeyword);
            Queue <Type> typeArguments = new Queue <Type>(types);

            WriteTypeArgumentsString(typeName, types.Length, false, typeArguments, formatGenericName);
            Assumes.IsTrue(typeArguments.Count == 0, "Expecting genericTypeArguments queue to be empty.");
        }
Exemplo n.º 26
0
        internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, out Type targetClosedInterfaceType)
        {
            // The interface must be open
            Assumes.IsTrue(targetOpenInterfaceType.IsInterface && targetOpenInterfaceType.IsGenericTypeDefinition);
            Assumes.IsTrue(!instanceType.IsGenericTypeDefinition);

            // if instanceType is an interface, we must first check it directly
            if (instanceType.IsInterface &&
                instanceType.IsGenericType &&
                instanceType.GetGenericTypeDefinition() == targetOpenInterfaceType)
            {
                targetClosedInterfaceType = instanceType;
                return true;
            }

            try
            {
                // Purposefully not using FullName here because it results in a significantly
                //  more expensive implementation of GetInterface, this does mean that we're
                //  takign the chance that there aren't too many types which implement multiple
                //  interfaces by the same name...
                Type targetInterface = instanceType.GetInterface(targetOpenInterfaceType.Name, false);
                if (targetInterface != null &&
                    targetInterface.GetGenericTypeDefinition() == targetOpenInterfaceType)
                {
                    targetClosedInterfaceType = targetInterface;
                    return true;
                }
            }
            catch (AmbiguousMatchException)
            {
                // On the off chance that the type has >1 interfaces that it implements 
                //  with the same name, we can use this to disambiguate... 
                //
                // However, maybe this isn't great because it means that we can end up with 
                //  situations where we implement the same interface over two different types 
                //  and will always hit the slow path through an exception... 

                foreach (Type type in instanceType.GetInterfaces())
                {
                    if (type.IsGenericType &&
                        type.GetGenericTypeDefinition() == targetOpenInterfaceType)
                    {
                        targetClosedInterfaceType = type;
                        return true;
                    }
                }
            }

            targetClosedInterfaceType = null;
            return false;
        }
Exemplo n.º 27
0
        private bool IsRejected(ComposablePartDefinition definition, AtomicComposition atomicComposition)
        {
            // Check to see if we're currently working on the definition in question.
            // Recursive queries always answer optimistically, as if the definition hasn't
            // been rejected - because if it is we can discard all decisions that were based
            // on the faulty assumption in the first place.
            var forceRejectionTest = false;

            if (atomicComposition != null)
            {
                var atomicCompositionQuery        = GetAtomicCompositionQuery(atomicComposition);
                AtomicCompositionQueryState state = atomicCompositionQuery(definition);
                switch (state)
                {
                case AtomicCompositionQueryState.TreatAsRejected:
                    return(true);

                case AtomicCompositionQueryState.TreatAsValidated:
                    return(false);

                case AtomicCompositionQueryState.NeedsTesting:
                    forceRejectionTest = true;
                    break;

                default:
                    Assumes.IsTrue(state == AtomicCompositionQueryState.Unknown);
                    // Need to do the work to determine the state
                    break;
                }
            }

            if (!forceRejectionTest)
            {
                // Next, anything that has been activated is not rejected
                using (new ReadLock(this._lock))
                {
                    if (this._activatedParts.ContainsKey(definition))
                    {
                        return(false);
                    }

                    // Last stop before doing the hard work: check a specific registry of rejected parts
                    if (this._rejectedParts.Contains(definition))
                    {
                        return(true);
                    }
                }
            }

            // Determine whether or not the definition's imports can be satisfied
            return(DetermineRejection(definition, atomicComposition));
        }
Exemplo n.º 28
0
        private static ParameterInfo ReadParameterCore(IDictionary <string, object> cache, Lazy <Type> defaultType)
        {
            int             parameterPosition = cache.ReadValue <int>(AttributedCacheServices.CacheKeys.ParameterPosition);
            ConstructorInfo constructor       = cache.ReadMember <ConstructorInfo>(AttributedCacheServices.CacheKeys.ParameterConstructor, defaultType.Value);

            Assumes.IsTrue(parameterPosition >= 0);

            ParameterInfo[] parameters = constructor.GetParameters();

            Assumes.IsTrue(parameterPosition < parameters.Length);

            return(parameters[parameterPosition]);
        }
Exemplo n.º 29
0
        internal void DescribeError(StringBuilder message)
        {
            Assumes.IsTrue(IsError, "Dependency is not in an error state.");

            if (_oversuppliedTargets != null)
            {
                var list = Formatters.ReadableList(_oversuppliedTargets.Select(t => string.Format(System.Composition.Properties.Resources.Dependency_QuoteParameter, t.Origin)));
                message.AppendFormat(System.Composition.Properties.Resources.Dependency_TooManyExports, Contract, list);
            }
            else
            {
                message.AppendFormat(System.Composition.Properties.Resources.Dependency_ExportNotFound, Contract);
            }
        }
        private static Expression CreateCreationPolicyContraint(CreationPolicy policy, ParameterExpression parameter)
        {
            Assumes.IsTrue(policy != CreationPolicy.Any);
            Assumes.NotNull(parameter);

            //    !definition.Metadata.ContainsKey(CompositionConstants.PartCreationPolicyMetadataName) ||
            //        CreationPolicy.Any.Equals(definition.Metadata[CompositionConstants.PartCreationPolicyMetadataName]) ||
            //        policy.Equals(definition.Metadata[CompositionConstants.PartCreationPolicyMetadataName]);

            return(Expression.MakeBinary(ExpressionType.OrElse,
                                         Expression.MakeBinary(ExpressionType.OrElse,
                                                               Expression.Not(CreateMetadataContainsKeyExpression(parameter, CompositionConstants.PartCreationPolicyMetadataName)),
                                                               CreateMetadataValueEqualsExpression(parameter, CreationPolicy.Any, CompositionConstants.PartCreationPolicyMetadataName)),
                                         CreateMetadataValueEqualsExpression(parameter, policy, CompositionConstants.PartCreationPolicyMetadataName)));
        }