diff options
Diffstat (limited to 'mcs/class/System.ComponentModel.Composition/src/ComponentModel/System')
132 files changed, 0 insertions, 17999 deletions
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/.gitattributes deleted file mode 100644 index 8381eda809e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/.gitattributes +++ /dev/null @@ -1,3 +0,0 @@ -/Lazy.cs -crlf -/LazyOfTTMetadata.cs -crlf -/Tuple.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/.gitattributes deleted file mode 100644 index cd15fcf2076..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/.gitattributes +++ /dev/null @@ -1,38 +0,0 @@ -/AttributedModelServices.cs -crlf -/ChangeRejectedException.cs -crlf -/CompositionContractMismatchException.cs -crlf -/CompositionError.cs -crlf -/CompositionErrorDebuggerProxy.cs -crlf -/CompositionErrorId.cs -crlf -/CompositionException.cs -crlf -/CompositionResult.cs -crlf -/CompositionResultOfT.cs -crlf -/ConstraintServices.cs -crlf -/ContractNameServices.cs -crlf -/CreationPolicy.cs -crlf -/ErrorBuilder.cs -crlf -/ExceptionBuilder.cs -crlf -/ExportAttribute.cs -crlf -/ExportCardinalityCheckResult.cs -crlf -/ExportMetadataAttribute.cs -crlf -/ExportServices.DisposableLazy.cs -crlf -/ExportServices.cs -crlf -/IAttributedImport.cs -crlf -/ICompositionError.cs -crlf -/ICompositionService.cs -crlf -/IPartImportsSatisfiedNotification.cs -crlf -/ImportAttribute.cs -crlf -/ImportCardinalityMismatchException.cs -crlf -/ImportManyAttribute.cs -crlf -/ImportingConstructorAttribute.cs -crlf -/InheritedExportAttribute.cs -crlf -/MetadataAttributeAttribute.cs -crlf -/MetadataServices.cs -crlf -/MetadataViewGenerator.cs -crlf -/MetadataViewProvider.cs -crlf -/PartCreationPolicyAttribute.cs -crlf -/PartCreatorOfT.cs -crlf -/PartCreatorOfTTMetadata.cs -crlf -/PartLifetimeContextOfT.cs -crlf -/PartMetadataAttribute.cs -crlf -/PartNotDiscoverableAttribute.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/.gitattributes deleted file mode 100644 index 64069f9372e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/.gitattributes +++ /dev/null @@ -1,3 +0,0 @@ -/AttributedExportDefinition.cs -crlf -/AttributedModelDiscovery.cs -crlf -/AttributedPartCreationInfo.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs deleted file mode 100644 index c06732adf8a..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition;
-using System.ComponentModel.Composition.AttributedModel;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.AttributedModel
-{
- internal class AttributedExportDefinition : ExportDefinition
- {
- private readonly AttributedPartCreationInfo _partCreationInfo;
- private readonly MemberInfo _member;
- private readonly ExportAttribute _exportAttribute;
-
- private IDictionary<string, object> _metadata;
-
- public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute)
- : base(member.GetContractNameFromExport(exportAttribute), (IDictionary<string, object>)null)
- {
- Assumes.NotNull(partCreationInfo);
- Assumes.NotNull(member);
- Assumes.NotNull(exportAttribute);
-
- this._partCreationInfo = partCreationInfo;
- this._member = member;
- this._exportAttribute = exportAttribute;
- }
-
- public override IDictionary<string, object> Metadata
- {
- get
- {
- if (this._metadata == null)
- {
- IDictionary<string, object> metadata;
- this._member.TryExportMetadataForMember(out metadata);
-
- string typeIdentity = this._member.GetTypeIdentityFromExport(this._exportAttribute);
- metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity);
-
- var partMetadata = this._partCreationInfo.GetMetadata();
- if (partMetadata != null && partMetadata.ContainsKey(CompositionConstants.PartCreationPolicyMetadataName))
- {
- metadata.Add(CompositionConstants.PartCreationPolicyMetadataName, partMetadata[CompositionConstants.PartCreationPolicyMetadataName]);
- }
-
- this._metadata = metadata;
- }
- return this._metadata;
- }
- }
- }
-
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs deleted file mode 100644 index ed5fbb4b9bd..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs +++ /dev/null @@ -1,138 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Diagnostics;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.AttributedModel
-{
- internal static class AttributedModelDiscovery
- {
- public static ComposablePartDefinition CreatePartDefinitionIfDiscoverable(Type type, ICompositionElement origin)
- {
- AttributedPartCreationInfo creationInfo = new AttributedPartCreationInfo(type, null, false, origin);
- if (!creationInfo.IsPartDiscoverable())
- {
- return null;
- }
-
- return new ReflectionComposablePartDefinition(creationInfo);
- }
-
- public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin)
- {
- Assumes.NotNull(type);
-
- AttributedPartCreationInfo creationInfo = new AttributedPartCreationInfo(type, partCreationPolicy, ignoreConstructorImports, origin);
-
- return new ReflectionComposablePartDefinition(creationInfo);
- }
-
- public static ReflectionComposablePart CreatePart(object attributedPart)
- {
- Assumes.NotNull(attributedPart);
-
- // If given an instance then we want to pass the default composition options because we treat it as a shared part
- // TODO: ICompositionElement Give this def an origin indicating that it was added directly to the ComposablePartExportProvider.
-
- ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(attributedPart.GetType(), PartCreationPolicyAttribute.Shared, true, (ICompositionElement)null);
-
- return new ReflectionComposablePart(definition, attributedPart);
- }
-
- public static ReflectionParameterImportDefinition CreateParameterImportDefinition(ParameterInfo parameter, ICompositionElement origin)
- {
- Requires.NotNull(parameter, "parameter");
-
- ReflectionParameter reflectionParameter = parameter.ToReflectionParameter();
- IAttributedImport attributedImport = AttributedModelDiscovery.GetAttributedImport(reflectionParameter, parameter);
- ImportType importType = new ImportType(reflectionParameter.ReturnType, attributedImport.Cardinality);
-
- if (importType.IsPartCreator)
- {
- return new PartCreatorParameterImportDefinition(
- new Lazy<ParameterInfo>(() => parameter),
- origin,
- new ContractBasedImportDefinition(
- attributedImport.GetContractNameFromImport(importType),
- attributedImport.GetTypeIdentityFromImport(importType),
- CompositionServices.GetRequiredMetadata(importType.MetadataViewType),
- attributedImport.Cardinality,
- false,
- true,
- CreationPolicy.NonShared));
- }
- else
- {
- return new ReflectionParameterImportDefinition(
- new Lazy<ParameterInfo>(() => parameter),
- attributedImport.GetContractNameFromImport(importType),
- attributedImport.GetTypeIdentityFromImport(importType),
- CompositionServices.GetRequiredMetadata(importType.MetadataViewType),
- attributedImport.Cardinality,
- attributedImport.RequiredCreationPolicy,
- origin);
- }
- }
-
- public static ReflectionMemberImportDefinition CreateMemberImportDefinition(MemberInfo member, ICompositionElement origin)
- {
- Requires.NotNull(member, "member");
-
- ReflectionWritableMember reflectionMember = member.ToReflectionWritableMember();
- IAttributedImport attributedImport = AttributedModelDiscovery.GetAttributedImport(reflectionMember, member);
- ImportType importType = new ImportType(reflectionMember.ReturnType, attributedImport.Cardinality);
-
- if (importType.IsPartCreator)
- {
- return new PartCreatorMemberImportDefinition(
- new LazyMemberInfo(member),
- origin,
- new ContractBasedImportDefinition(
- attributedImport.GetContractNameFromImport(importType),
- attributedImport.GetTypeIdentityFromImport(importType),
- CompositionServices.GetRequiredMetadata(importType.MetadataViewType),
- attributedImport.Cardinality,
- attributedImport.AllowRecomposition,
- false,
- CreationPolicy.NonShared));
- }
- else
- {
- return new ReflectionMemberImportDefinition(
- new LazyMemberInfo(member),
- attributedImport.GetContractNameFromImport(importType),
- attributedImport.GetTypeIdentityFromImport(importType),
- CompositionServices.GetRequiredMetadata(importType.MetadataViewType),
- attributedImport.Cardinality,
- attributedImport.AllowRecomposition,
- attributedImport.RequiredCreationPolicy,
- origin);
- }
- }
-
- private static IAttributedImport GetAttributedImport(ReflectionItem item, ICustomAttributeProvider attributeProvider)
- {
- IAttributedImport[] imports = attributeProvider.GetAttributes<IAttributedImport>(false);
-
- // For constructor parameters they may not have an ImportAttribute
- if (imports.Length == 0)
- {
- return new ImportAttribute();
- }
-
- if (imports.Length > 1)
- {
- CompositionTrace.MemberMarkedWithMultipleImportAndImportMany(item);
- }
-
- // Regardless of how many imports, always return the first one
- return imports[0];
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs deleted file mode 100644 index 9bc3d2f705b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs +++ /dev/null @@ -1,446 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Diagnostics;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.AttributedModel
-{
- internal class AttributedPartCreationInfo : IReflectionPartCreationInfo
- {
- private readonly Type _type;
- private readonly bool _ignoreConstructorImports = false;
- private readonly ICompositionElement _origin;
- private PartCreationPolicyAttribute _partCreationPolicy = null;
- private ConstructorInfo _constructor;
- private IEnumerable<ExportDefinition> _exports;
- private IEnumerable<ImportDefinition> _imports;
- private HashSet<string> _contractNamesOnNonInterfaces;
-
- public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin)
- {
- Assumes.NotNull(type);
- this._type = type;
- this._ignoreConstructorImports = ignoreConstructorImports;
- this._partCreationPolicy = partCreationPolicy;
- this._origin = origin;
- }
-
- public Type GetPartType()
- {
- return this._type;
- }
-
- public Lazy<Type> GetLazyPartType()
- {
- return new Lazy<Type>(this.GetPartType, false);
- }
-
- public ConstructorInfo GetConstructor()
- {
- if (this._constructor == null && !this._ignoreConstructorImports)
- {
- this._constructor = SelectPartConstructor(this._type);
- }
- return this._constructor;
- }
-
- public IDictionary<string, object> GetMetadata()
- {
- return this._type.GetPartMetadataForType(this.CreationPolicy);
- }
-
- public IEnumerable<ExportDefinition> GetExports()
- {
- DiscoverExportsAndImports();
- return this._exports;
- }
-
- public IEnumerable<ImportDefinition> GetImports()
- {
- DiscoverExportsAndImports();
- return this._imports;
- }
-
- public bool IsDisposalRequired
- {
- get
- {
- return typeof(IDisposable).IsAssignableFrom(this.GetPartType());
- }
- }
-
- public bool IsPartDiscoverable()
- {
- if (this._type.IsAttributeDefined<PartNotDiscoverableAttribute>())
- {
- CompositionTrace.DefinitionMarkedWithPartNotDiscoverableAttribute(this._type);
- return false;
- }
-
- if (this._type.ContainsGenericParameters)
- {
- CompositionTrace.DefinitionContainsGenericsParameters(this._type);
- return false;
- }
-
- if (!HasExports())
- {
- CompositionTrace.DefinitionContainsNoExports(this._type);
- return false;
- }
-
- return true;
- }
-
- private bool HasExports()
- {
- return GetExportMembers(this._type).Any() ||
- GetInheritedExports(this._type).Any();
- }
-
- string ICompositionElement.DisplayName
- {
- get { return this.GetDisplayName(); }
- }
-
- ICompositionElement ICompositionElement.Origin
- {
- get { return this._origin; }
- }
-
- public override string ToString()
- {
- return GetDisplayName();
- }
-
- private string GetDisplayName()
- {
- return this.GetPartType().GetDisplayName();
- }
-
- private CreationPolicy CreationPolicy
- {
- get
- {
- if (this._partCreationPolicy == null)
- {
- this._partCreationPolicy = this._type.GetFirstAttribute<PartCreationPolicyAttribute>() ?? PartCreationPolicyAttribute.Default;
- }
- return this._partCreationPolicy.CreationPolicy;
- }
- }
-
- private static ConstructorInfo SelectPartConstructor(Type type)
- {
- Assumes.NotNull(type);
-
- if (type.IsAbstract)
- {
- return null;
- }
-
- // Only deal with non-static constructors
- BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
-
- ConstructorInfo[] constructors = type.GetConstructors(flags);
-
- // Should likely only happen for static or abstract types
- if (constructors.Length == 0)
- {
- return null;
- }
-
- // Optimize single default constructor.
- if (constructors.Length == 1 && constructors[0].GetParameters().Length == 0)
- {
- return constructors[0];
- }
-
- // Select the marked constructor if there is exactly one marked
- IEnumerable<ConstructorInfo> importingConstructors = constructors.Where(
- ctor => ctor.IsAttributeDefined<ImportingConstructorAttribute>());
-
- switch (importingConstructors.GetCardinality())
- {
- case EnumerableCardinality.One:
- {
- return importingConstructors.First();
- }
-
- case EnumerableCardinality.TwoOrMore:
- {
- // Return null, the part will error on instantiation.
- return null;
- }
- }
-
- // If there are no marked constructors then select the default constructor
- IEnumerable<ConstructorInfo> defaultConstructors = constructors.Where(
- ctor => ctor.GetParameters().Length == 0);
-
- // There should only ever be zero or one default constructors
- return defaultConstructors.SingleOrDefault();
- }
-
- private void DiscoverExportsAndImports()
- {
- // NOTE : in most cases both of these will be null or not null at the same time
- // the only situation when that is not the case is when there was a failure during the previous discovery
- // and one of them ended up not being set. In that case we will force the discovery again so that the same exception is thrown.
- if ((this._exports != null) && (this._imports != null))
- {
- return;
- }
-
- this._exports = GetExportDefinitions();
- this._imports = GetImportDefinitions();
- }
-
- private IEnumerable<ExportDefinition> GetExportDefinitions()
- {
- List<ExportDefinition> exports = new List<ExportDefinition>();
-
- this._contractNamesOnNonInterfaces = new HashSet<string>();
-
- // GetExportMembers should only contain the type itself along with the members declared on it,
- // it should not contain any base types, members on base types or interfaces on the type.
- foreach (MemberInfo member in GetExportMembers(this._type))
- {
- foreach (ExportAttribute exportAttribute in member.GetAttributes<ExportAttribute>())
- {
- var attributedExportDefinition = new AttributedExportDefinition(this, member, exportAttribute);
-
- if (exportAttribute.GetType() == CompositionServices.InheritedExportAttributeType)
- {
- // Any InheritedExports on the type itself are contributed during this pass
- // and we need to do the book keeping for those.
- if (!this._contractNamesOnNonInterfaces.Contains(attributedExportDefinition.ContractName))
- {
- exports.Add(new ReflectionMemberExportDefinition(member.ToLazyMember(), attributedExportDefinition, this));
- this._contractNamesOnNonInterfaces.Add(attributedExportDefinition.ContractName);
- }
- }
- else
- {
- exports.Add(new ReflectionMemberExportDefinition(member.ToLazyMember(), attributedExportDefinition, this));
- }
- }
- }
-
- // GetInheritedExports should only contain InheritedExports on base types or interfaces.
- // The order of types returned here is important because it is used as a
- // priority list of which InhertedExport to choose if multiple exists with
- // the same contract name. Therefore ensure that we always return the types
- // in the hiearchy from most derived to the lowest base type, followed
- // by all the interfaces that this type implements.
- foreach (Type type in GetInheritedExports(this._type))
- {
- foreach (InheritedExportAttribute exportAttribute in type.GetAttributes<InheritedExportAttribute>())
- {
- var attributedExportDefinition = new AttributedExportDefinition(this, type, exportAttribute);
-
- if (!this._contractNamesOnNonInterfaces.Contains(attributedExportDefinition.ContractName))
- {
- exports.Add(new ReflectionMemberExportDefinition(type.ToLazyMember(), attributedExportDefinition, this));
-
- if (!type.IsInterface)
- {
- this._contractNamesOnNonInterfaces.Add(attributedExportDefinition.ContractName);
- }
- }
- }
- }
-
- this._contractNamesOnNonInterfaces = null; // No need to hold this state around any longer
-
- return exports;
- }
-
- private IEnumerable<MemberInfo> GetExportMembers(Type type)
- {
- BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public |
- BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
-
- // If the type is abstract only find local static exports
- if (type.IsAbstract)
- {
- flags &= ~BindingFlags.Instance;
- }
- else if (IsExport(type))
- {
- yield return type;
- }
-
- // Walk the fields
- foreach (var member in type.GetFields(flags))
- {
- if (IsExport(member))
- {
- yield return member;
- }
- }
-
- // Walk the properties
- foreach (var member in type.GetProperties(flags))
- {
- if (IsExport(member))
- {
- yield return member;
- }
- }
-
- // Walk the methods
- foreach (var member in type.GetMethods(flags))
- {
- if (IsExport(member))
- {
- yield return member;
- }
- }
- }
-
- private IEnumerable<Type> GetInheritedExports(Type type)
- {
- // If the type is abstract we aren't interested in type level exports
- if (type.IsAbstract)
- {
- yield break;
- }
-
- // The order of types returned here is important because it is used as a
- // priority list of which InhertedExport to choose if multiple exists with
- // the same contract name. Therefore ensure that we always return the types
- // in the hiearchy from most derived to the lowest base type, followed
- // by all the interfaces that this type implements.
-
- Type currentType = type.BaseType;
-
- if (currentType == null)
- {
- yield break;
- }
-
- // Stopping at object instead of null to help with performance. It is a noticable performance
- // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object.
- // We also need the null check in case we're passed a type that doesn't live in the runtime context.
- while (currentType != null && currentType != CompositionServices.ObjectType)
- {
- if (IsInheritedExport(currentType))
- {
- yield return currentType;
- }
- currentType = currentType.BaseType;
- }
-
- foreach (Type iface in type.GetInterfaces())
- {
- if (IsInheritedExport(iface))
- {
- yield return iface;
- }
- }
- }
-
- private static bool IsExport(ICustomAttributeProvider attributeProvider)
- {
- return attributeProvider.IsAttributeDefined<ExportAttribute>(false);
- }
-
- private static bool IsInheritedExport(ICustomAttributeProvider attributedProvider)
- {
- return attributedProvider.IsAttributeDefined<InheritedExportAttribute>(false);
- }
-
- private IEnumerable<ImportDefinition> GetImportDefinitions()
- {
- List<ImportDefinition> imports = new List<ImportDefinition>();
-
- foreach (MemberInfo member in GetImportMembers(this._type))
- {
- ReflectionMemberImportDefinition importDefinition = AttributedModelDiscovery.CreateMemberImportDefinition(member, this);
- imports.Add(importDefinition);
- }
-
- var constructor = this.GetConstructor();
-
- if (constructor != null)
- {
- foreach (ParameterInfo parameter in constructor.GetParameters())
- {
- ReflectionParameterImportDefinition importDefinition = AttributedModelDiscovery.CreateParameterImportDefinition(parameter, this);
- imports.Add(importDefinition);
- }
- }
-
- return imports;
- }
-
- private IEnumerable<MemberInfo> GetImportMembers(Type type)
- {
- if (type.IsAbstract)
- {
- yield break;
- }
-
- foreach (MemberInfo member in GetDeclaredOnlyImportMembers(type))
- {
- yield return member;
- }
-
- // Walk up the type chain until you hit object.
- if (type.BaseType != null)
- {
- Type baseType = type.BaseType;
-
- // Stopping at object instead of null to help with performance. It is a noticable performance
- // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object.
- // We also need the null check in case we're passed a type that doesn't live in the runtime context.
- while (baseType != null && baseType != CompositionServices.ObjectType)
- {
- foreach (MemberInfo member in GetDeclaredOnlyImportMembers(baseType))
- {
- yield return member;
- }
- baseType = baseType.BaseType;
- }
- }
- }
-
- private IEnumerable<MemberInfo> GetDeclaredOnlyImportMembers(Type type)
- {
- BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
-
- // Walk the fields
- foreach (var member in type.GetFields(flags))
- {
- if (IsImport(member))
- {
- yield return member;
- }
- }
-
- // Walk the properties
- foreach (var member in type.GetProperties(flags))
- {
- if (IsImport(member))
- {
- yield return member;
- }
- }
- }
-
- private static bool IsImport(ICustomAttributeProvider attributeProvider)
- {
- return attributeProvider.IsAttributeDefined<IAttributedImport>(false);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModelServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModelServices.cs deleted file mode 100644 index b2be75773a2..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/AttributedModelServices.cs +++ /dev/null @@ -1,161 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Runtime.Serialization;
-using System.ComponentModel.Composition.AttributedModel;
-using System.Reflection;
-using System.Linq;
-using Microsoft.Internal;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- public static class AttributedModelServices
- {
- [SuppressMessage("Microsoft.Design", "CA1004")]
- public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
- {
- Requires.NotNull(metadata, "metadata");
-
- return MetadataViewProvider.GetMetadataView<TMetadataView>(metadata);
- }
-
- public static ComposablePart CreatePart(object attributedPart)
- {
- Requires.NotNull(attributedPart, "attributedPart");
- return AttributedModelDiscovery.CreatePart(attributedPart);
- }
-
- public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin)
- {
- Requires.NotNull(type, "type");
- return AttributedModelServices.CreatePartDefinition(type, origin, false);
- }
-
- public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin, bool ensureIsDiscoverable)
- {
- Requires.NotNull(type, "type");
- if (ensureIsDiscoverable)
- {
- return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin);
- }
- else
- {
- return AttributedModelDiscovery.CreatePartDefinition(type, null, false, origin);
- }
- }
-
- public static string GetTypeIdentity(Type type)
- {
- Requires.NotNull(type, "type");
-
- return ContractNameServices.GetTypeIdentity(type);
- }
-
- public static string GetTypeIdentity(MethodInfo method)
- {
- Requires.NotNull(method, "method");
-
- return ContractNameServices.GetTypeIdentityFromMethod(method);
- }
-
- public static string GetContractName(Type type)
- {
- return AttributedModelServices.GetTypeIdentity(type);
- }
-
- public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, T exportedValue)
- {
- Requires.NotNull(batch, "batch");
- string contractName = AttributedModelServices.GetContractName(typeof(T));
-
- return batch.AddExportedValue<T>(contractName, exportedValue);
- }
-
- public static void ComposeExportedValue<T>(this CompositionContainer container, T exportedValue)
- {
- Requires.NotNull(container, "container");
-
- CompositionBatch batch = new CompositionBatch();
- batch.AddExportedValue<T>(exportedValue);
- container.Compose(batch);
- }
-
- public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, string contractName, T exportedValue)
- {
- Requires.NotNull(batch, "batch");
-
- string typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T));
-
- IDictionary<string, object> metadata = new Dictionary<string, object>();
- metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity);
-
- return batch.AddExport(new Export(contractName, metadata, () => exportedValue));
- }
-
- public static void ComposeExportedValue<T>(this CompositionContainer container, string contractName, T exportedValue)
- {
- Requires.NotNull(container, "container");
-
- CompositionBatch batch = new CompositionBatch();
- batch.AddExportedValue<T>(contractName, exportedValue);
- container.Compose(batch);
- }
-
- public static ComposablePart AddPart(this CompositionBatch batch, object attributedPart)
- {
- Requires.NotNull(batch, "batch");
- Requires.NotNull(attributedPart, "attributedPart");
-
- ComposablePart part = AttributedModelServices.CreatePart(attributedPart);
-
- batch.AddPart(part);
-
- return part;
- }
-
- public static void ComposeParts(this CompositionContainer container, params object[] attributedParts)
- {
- Requires.NotNull(container, "container");
- Requires.NotNullOrNullElements(attributedParts, "attributedParts");
-
- CompositionBatch batch = new CompositionBatch(
- attributedParts.Select(attributedPart => AttributedModelServices.CreatePart(attributedPart)).ToArray(),
- Enumerable.Empty<ComposablePart>());
-
- container.Compose(batch);
- }
-
- /// <summary>
- /// Satisfies the imports of the specified attributed object exactly once and they will not
- /// ever be recomposed.
- /// </summary>
- /// <param name="part">
- /// The attributed object to set the imports.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="attributedPart"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ICompositionService"/> has been disposed of.
- /// </exception>
- public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart)
- {
- Requires.NotNull(compositionService, "compositionService");
- Requires.NotNull(attributedPart, "attributedPart");
-
- ComposablePart part = AttributedModelServices.CreatePart(attributedPart);
- compositionService.SatisfyImportsOnce(part);
-
- return part;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ChangeRejectedException.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ChangeRejectedException.cs deleted file mode 100644 index db81e13fbd4..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ChangeRejectedException.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Security.Permissions;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// The exception that is thrown when one or more recoverable errors occur during
- /// composition which results in those changes being rejected.
- /// </summary>
- [Serializable]
- public class ChangeRejectedException : CompositionException
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
- /// </summary>
- public ChangeRejectedException()
- : this((string)null, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
- /// </summary>
- public ChangeRejectedException(string message)
- : this(message, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
- /// </summary>
- public ChangeRejectedException(string message, Exception innerException)
- : base(message, innerException, (IEnumerable<CompositionError>)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
- /// </summary>
- /// <param name="errors">List of errors that occured while applying the changes.</param>
- public ChangeRejectedException(IEnumerable<CompositionError> errors)
- : base((string)null, (Exception)null, errors)
- {
- }
-
- /// <summary>
- /// Gets a message that describes the exception.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ChangeRejectedException"/>.
- /// </value>
- public override string Message
- {
- get
- {
- return string.Format(CultureInfo.CurrentCulture,
- Strings.CompositionException_ChangesRejected,
- base.Message);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionContractMismatchException.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionContractMismatchException.cs deleted file mode 100644 index f1a5f4968b8..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionContractMismatchException.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Runtime.Serialization;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// The exception that is thrown when the underlying exported value or metadata of an
- /// <see cref="Lazy{T}"/> or <see cref="Lazy{T, TMetadataView}"/> object cannot be
- /// cast to <c>T</c> or <c>TMetadataView</c>, respectively.
- /// </summary>
- [Serializable]
- public class CompositionContractMismatchException : Exception
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class.
- /// </summary>
- public CompositionContractMismatchException()
- : this((string)null, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class
- /// with the specified error message.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- public CompositionContractMismatchException(string message)
- : this(message, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class
- /// with the specified error message and exception that is the cause of the
- /// exception.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- /// <param name="innerException">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
- /// </param>
- public CompositionContractMismatchException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
-
-#if !SILVERLIGHT
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class
- /// with the specified serialization data.
- /// </summary>
- /// <param name="info">
- /// The <see cref="SerializationInfo"/> that holds the serialized object data about the
- /// <see cref="CompositionContractMismatchException"/>.
- /// </param>
- /// <param name="context">
- /// The <see cref="StreamingContext"/> that contains contextual information about the
- /// source or destination.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="info"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="SerializationException">
- /// <paramref name="info"/> is missing a required value.
- /// </exception>
- /// <exception cref="InvalidCastException">
- /// <paramref name="info"/> contains a value that cannot be cast to the correct type.
- /// </exception>
- [System.Security.SecuritySafeCritical]
- protected CompositionContractMismatchException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
-
-#endif
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionError.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionError.cs deleted file mode 100644 index d5237502bc2..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionError.cs +++ /dev/null @@ -1,188 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Globalization;
-using System.Security.Permissions;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Represents an error that occurs during composition in a <see cref="CompositionContainer"/>.
- /// </summary>
- [Serializable]
- [DebuggerTypeProxy(typeof(CompositionErrorDebuggerProxy))]
- public class CompositionError : ICompositionError
- {
- private readonly CompositionErrorId _id;
- private readonly string _description;
- private readonly Exception _exception;
-
- private readonly ICompositionElement _element;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionError"/> class
- /// with the specified error message.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set the
- /// <see cref="Description"/> property to an empty string ("").
- /// </param>
- public CompositionError(string message)
- : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionError"/> class
- /// with the specified error message and composition element that is the
- /// cause of the composition error.
- /// </summary>
- /// <param name="element">
- /// The <see cref="ICompositionElement"/> that is the cause of the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set
- /// the <see cref="CompositionError.Element"/> property to
- /// <see langword="null"/>.
- /// </param>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set the
- /// <see cref="Description"/> property to an empty string ("").
- /// </param>
- public CompositionError(string message, ICompositionElement element)
- : this(CompositionErrorId.Unknown, message, element, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionError"/> class
- /// with the specified error message and exception that is the cause of the
- /// composition error.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set the
- /// <see cref="Description"/> property to an empty string ("").
- /// </param>
- /// <param name="exception">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set
- /// the <see cref="CompositionError.Exception"/> property to <see langword="null"/>.
- /// </param>
- public CompositionError(string message, Exception exception)
- : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, exception)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionError"/> class
- /// with the specified error message, and composition element and exception that
- /// is the cause of the composition error.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set the
- /// <see cref="Description"/> property to an empty string ("").
- /// </param>
- /// <param name="element">
- /// The <see cref="ICompositionElement"/> that is the cause of the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set
- /// the <see cref="CompositionError.Element"/> property to
- /// <see langword="null"/>.
- /// </param>
- /// <param name="exception">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="CompositionError"/>; or <see langword="null"/> to set
- /// the <see cref="CompositionError.Exception"/> property to <see langword="null"/>.
- /// </param>
- public CompositionError(string message, ICompositionElement element, Exception exception)
- : this(CompositionErrorId.Unknown, message, element, exception)
- {
- }
-
- internal CompositionError(CompositionErrorId id, string description, ICompositionElement element, Exception exception)
- {
- _id = id;
- _description = description ?? string.Empty;
- _element = element;
- _exception = exception;
- }
-
- /// <summary>
- /// Gets the composition element that is the cause of the error.
- /// </summary>
- /// <value>
- /// The <see cref="ICompositionElement"/> that is the cause of the
- /// <see cref="CompositionError"/>. The default is <see langword="null"/>.
- /// </value>
- public ICompositionElement Element
- {
- get { return _element; }
- }
-
- /// <summary>
- /// Gets the message that describes the composition error.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionError"/>.
- /// </value>
- public string Description
- {
- get { return _description; }
- }
-
- /// <summary>
- /// Gets the exception that is the underlying cause of the composition error.
- /// </summary>
- /// <value>
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="CompositionError"/>. The default is <see langword="null"/>.
- /// </value>
- public Exception Exception
- {
- get { return _exception; }
- }
-
- CompositionErrorId ICompositionError.Id
- {
- get { return _id; }
- }
-
- Exception ICompositionError.InnerException
- {
- get { return Exception; }
- }
-
- /// <summary>
- /// Returns a string representation of the composition error.
- /// </summary>
- /// <returns>
- /// A <see cref="String"/> containing the <see cref="Description"/> property.
- /// </returns>
- public override string ToString()
- {
- return this.Description;
- }
-
- internal static CompositionError Create(CompositionErrorId id, string format, params object[] parameters)
- {
- return Create(id, (ICompositionElement)null, (Exception)null, format, parameters);
- }
-
- internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object[] parameters)
- {
- return Create(id, element, (Exception)null, format, parameters);
- }
-
- internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, Exception exception, string format, params object[] parameters)
- {
- return new CompositionError(id, string.Format(CultureInfo.CurrentCulture, format, parameters), element, exception);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs deleted file mode 100644 index eafbc0c20ba..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- internal class CompositionErrorDebuggerProxy
- {
- private readonly CompositionError _error;
-
- public CompositionErrorDebuggerProxy(CompositionError error)
- {
- Requires.NotNull(error, "error");
-
- this._error = error;
- }
-
- public string Description
- {
- get { return this._error.Description; }
- }
-
- public Exception Exception
- {
- get { return this._error.Exception; }
- }
-
- public ICompositionElement Element
- {
- get { return this._error.Element; }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionErrorId.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionErrorId.cs deleted file mode 100644 index b9eb3b6d16e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionErrorId.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition
-{
- internal enum CompositionErrorId : int
- {
- Unknown = 0,
- InvalidExportMetadata,
- RequiredMetadataNotFound,
- UnsupportedExportType,
- ImportNotSetOnPart,
- ImportEngine_ComposeTookTooManyIterations,
- ImportEngine_ImportCardinalityMismatch,
- ImportEngine_PartCycle,
- ImportEngine_PartCannotSetImport,
- ImportEngine_PartCannotGetExportedValue,
- ImportEngine_PartCannotActivate,
- ImportEngine_PreventedByExistingImport,
- ImportEngine_InvalidStateForRecomposition,
- ReflectionModel_PartConstructorMissing,
- ReflectionModel_PartConstructorThrewException,
- ReflectionModel_PartOnImportsSatisfiedThrewException,
- ReflectionModel_ExportNotReadable,
- ReflectionModel_ExportThrewException,
- ReflectionModel_ExportMethodTooManyParameters,
- ReflectionModel_ImportNotWritable,
- ReflectionModel_ImportThrewException,
- ReflectionModel_ImportNotAssignableFromExport,
- ReflectionModel_ImportCollectionNull,
- ReflectionModel_ImportCollectionNotWritable,
- ReflectionModel_ImportCollectionConstructionThrewException,
- ReflectionModel_ImportCollectionGetThrewException,
- ReflectionModel_ImportCollectionIsReadOnlyThrewException,
- ReflectionModel_ImportCollectionClearThrewException,
- ReflectionModel_ImportCollectionAddThrewException,
- ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned,
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionException.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionException.cs deleted file mode 100644 index 39491ad433b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionException.cs +++ /dev/null @@ -1,340 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Linq;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Text;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition
-{
-
- /// <summary>
- /// The exception that is thrown when one or more errors occur during composition in
- /// a <see cref="CompositionContainer"/>.
- /// </summary>
- [Serializable]
- public class CompositionException : Exception
- {
- const string ErrorsKey = "Errors";
- private ReadOnlyCollection<CompositionError> _errors;
-
-#if CLR40 && !SILVERLIGHT
- [Serializable]
- private struct CompositionExceptionData : ISafeSerializationData
- {
- public CompositionError[] _errors;
-
- void ISafeSerializationData.CompleteDeserialization(object obj)
- {
- CompositionException exception = obj as CompositionException;
-
- exception._errors = new ReadOnlyCollection<CompositionError>(this._errors);
- }
- }
-#endif
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionException"/> class.
- /// </summary>
- public CompositionException()
- : this((string)null, (Exception)null, (IEnumerable<CompositionError>)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionException"/> class
- /// with the specified error message.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- public CompositionException(string message)
- : this(message, (Exception)null, (IEnumerable<CompositionError>)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionException"/> class
- /// with the specified error message and exception that is the cause of the
- /// exception.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- /// <param name="innerException">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
- /// </param>
- public CompositionException(string message, Exception innerException)
- : this(message, innerException, (IEnumerable<CompositionError>)null)
- {
- }
-
- internal CompositionException(CompositionError error)
- : this(new CompositionError[] { error })
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionException"/> class
- /// with the specified errors.
- /// </summary>
- /// <param name="errors">
- /// An <see cref="IEnumerable{T}"/> of <see cref="CompositionError"/> objects
- /// representing the errors that are the cause of the
- /// <see cref="CompositionException"/>; or <see langword="null"/> to set the
- /// <see cref="Errors"/> property to an empty <see cref="IEnumerable{T}"/>.
- /// </param>
- /// <exception cref="ArgumentException">
- /// <paramref name="errors"/> contains an element that is <see langword="null"/>.
- /// </exception>
- public CompositionException(IEnumerable<CompositionError> errors)
- : this((string)null, (Exception)null, errors)
- {
- }
-
- internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors)
- : base(message, innerException)
- {
- Requires.NullOrNotNullElements(errors, "errors");
-#if CLR40 && !SILVERLIGHT
- SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs)
- {
- var data = new CompositionExceptionData();
- if(this._errors != null)
- {
- data._errors = this._errors.Select(error => new CompositionError(
- ((ICompositionError)error).Id,
- error.Description,
- error.Element.ToSerializableElement(),
- error.Exception)).ToArray();
- }
- else
- {
- data._errors = new CompositionError[0];
- }
-
- eventArgs.AddSerializedState(data);
- };
-#endif
- _errors = new ReadOnlyCollection<CompositionError>(errors == null ? new CompositionError[0] : errors.ToArray<CompositionError>());
- }
-
- /// <summary>
- /// Gets the errors that are the cause of the exception.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="CompositionError"/> objects
- /// representing the errors that are the cause of the
- /// <see cref="CompositionException"/>.
- /// </value>
- public ReadOnlyCollection<CompositionError> Errors
- {
- get { return _errors; }
- }
-
- /// <summary>
- /// Gets a message that describes the exception.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="CompositionException"/>.
- /// </value>
- public override string Message
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- if (this.Errors.Count == 0)
- { // If there are no errors, then we simply return base.Message,
- // which will either use the default Exception message, or if
- // one was specified; the user supplied message.
-
- return base.Message;
- }
-
- return BuildDefaultMessage();
- }
- }
-
- private string BuildDefaultMessage()
- {
- IEnumerable<IEnumerable<CompositionError>> paths = CalculatePaths(this);
-
- StringBuilder writer = new StringBuilder();
-
- WriteHeader(writer, this.Errors.Count, paths.Count());
- WritePaths(writer, paths);
-
- return writer.ToString();
- }
-
- 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,
- Strings.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,
- Strings.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,
- Strings.CompositionException_SingleErrorWithSinglePath,
- pathCount);
- }
-
- writer.Append(' ');
- writer.AppendLine(Strings.CompositionException_ReviewErrorProperty);
- }
-
- private static void WritePaths(StringBuilder writer, IEnumerable<IEnumerable<CompositionError>> paths)
- {
- int ordinal = 0;
- foreach (IEnumerable<CompositionError> path in paths)
- {
- ordinal++;
- WritePath(writer, path, ordinal);
- }
- }
-
- private static void WritePath(StringBuilder writer, IEnumerable<CompositionError> path, int ordinal)
- {
- writer.AppendLine();
- writer.Append(ordinal.ToString(CultureInfo.CurrentCulture));
- writer.Append(Strings.CompositionException_PathsCountSeparator);
- writer.Append(' ');
-
- WriteError(writer, path.First());
-
- foreach (CompositionError error in path.Skip(1))
- {
- writer.AppendLine();
- writer.Append(Strings.CompositionException_ErrorPrefix);
- writer.Append(' ');
- WriteError(writer, error);
- }
- }
-
- private static void WriteError(StringBuilder writer, CompositionError error)
- {
- writer.AppendLine(error.Description);
-
- if (error.Element != null)
- {
- WriteElementGraph(writer, error.Element);
- }
- }
-
- private static void WriteElementGraph(StringBuilder writer, ICompositionElement element)
- {
- // Writes the composition element and its origins in the format:
- // Element: Export --> Part --> PartDefinition --> Catalog
-
- writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_ElementPrefix, element.DisplayName);
-
- while ((element = element.Origin) != null)
- {
- writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_OriginFormat, Strings.CompositionException_OriginSeparator, element.DisplayName);
- }
-
- writer.AppendLine();
- }
-
- private static IEnumerable<IEnumerable<CompositionError>> CalculatePaths(CompositionException exception)
- {
- List<IEnumerable<CompositionError>> paths = new List<IEnumerable<CompositionError>>();
-
- VisitContext context = new VisitContext();
- context.Path = new Stack<CompositionError>();
- context.LeafVisitor = path =>
- {
- // Take a snapshot of the path
- paths.Add(path.Copy());
- };
-
- VisitCompositionException(exception, context);
-
- return paths;
- }
-
- private static void VisitCompositionException(CompositionException exception, VisitContext context)
- {
- foreach (CompositionError error in exception.Errors)
- {
- VisitError(error, context);
- }
-
- if (exception.InnerException != null)
- {
- VisitException(exception.InnerException, context);
- }
- }
-
- private static void VisitError(CompositionError error, VisitContext context)
- {
- context.Path.Push(error);
-
- if (error.Exception == null)
- { // This error is a root cause, so write
- // out the stack from this point
-
- context.LeafVisitor(context.Path);
- }
- else
- {
- VisitException(error.Exception, context);
- }
-
- context.Path.Pop();
- }
-
- private static void VisitException(Exception exception, VisitContext context)
- {
- CompositionException composition = exception as CompositionException;
- if (composition != null)
- {
- VisitCompositionException(composition, context);
- }
- else
- {
- VisitError(new CompositionError(exception.Message, exception.InnerException), context);
- }
- }
-
- private struct VisitContext
- {
- public Stack<CompositionError> Path;
- public Action<Stack<CompositionError>> LeafVisitor;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionResult.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionResult.cs deleted file mode 100644 index 3cdda7123bf..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionResult.cs +++ /dev/null @@ -1,86 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using Microsoft.Internal.Collections;
-using System.ComponentModel.Composition.Hosting;
-
-namespace System.ComponentModel.Composition
-{
- internal struct CompositionResult
- {
- public static readonly CompositionResult SucceededResult = new CompositionResult();
- private readonly IEnumerable<CompositionError> _errors;
-
- public CompositionResult(params CompositionError[] errors)
- : this((IEnumerable<CompositionError>)errors)
- {
- }
-
- public CompositionResult(IEnumerable<CompositionError> errors)
- {
- this._errors = errors;
- }
-
- public bool Succeeded
- {
- get { return this._errors == null || !this._errors.FastAny(); }
- }
-
- public IEnumerable<CompositionError> Errors
- {
- get { return this._errors ?? Enumerable.Empty<CompositionError>(); }
- }
-
- public CompositionResult MergeResult(CompositionResult result)
- {
- if (this.Succeeded)
- {
- return result;
- }
- if (result.Succeeded)
- {
- return this;
- }
- return MergeErrors(result._errors);
- }
-
- public CompositionResult MergeError(CompositionError error)
- {
- return MergeErrors(new CompositionError[] { error });
- }
-
- public CompositionResult MergeErrors(IEnumerable<CompositionError> errors)
- {
- return new CompositionResult(this._errors.ConcatAllowingNull(errors));
- }
-
- public CompositionResult<T> ToResult<T>(T value)
- {
- return new CompositionResult<T>(value, this._errors);
- }
-
- public void ThrowOnErrors()
- {
- ThrowOnErrors(null);
- }
-
- public void ThrowOnErrors(AtomicComposition atomicComposition)
- {
- if (!this.Succeeded)
- {
- if (atomicComposition == null)
- {
- throw new CompositionException(this._errors);
- }
- else
- {
- throw new ChangeRejectedException(this._errors);
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionResultOfT.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionResultOfT.cs deleted file mode 100644 index a891a841360..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CompositionResultOfT.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition
-{
- internal struct CompositionResult<T>
- {
- private readonly IEnumerable<CompositionError> _errors;
- private readonly T _value;
-
- public CompositionResult(T value)
- : this(value, (CompositionError[])null)
- {
- }
-
- public CompositionResult(params CompositionError[] errors)
- : this(default(T), (IEnumerable<CompositionError>)errors)
- {
- }
-
- public CompositionResult(IEnumerable<CompositionError> errors)
- : this(default(T), errors)
- {
- }
-
- internal CompositionResult(T value, IEnumerable<CompositionError> errors)
- {
- this._errors = errors;
- this._value = value;
- }
-
- public bool Succeeded
- {
- get { return this._errors == null || !this._errors.FastAny(); }
- }
-
- public IEnumerable<CompositionError> Errors
- {
- get { return this._errors ?? Enumerable.Empty<CompositionError>(); }
- }
-
- /// <summary>
- /// Gets the value from the result, throwing a CompositionException if there are any errors.
- /// </summary>
- public T Value
- {
- get
- {
- ThrowOnErrors();
-
- return this._value;
- }
- }
-
- internal CompositionResult<TValue> ToResult<TValue>()
- {
- return new CompositionResult<TValue>(this._errors);
- }
-
- internal CompositionResult ToResult()
- {
- return new CompositionResult(this._errors);
- }
-
- private void ThrowOnErrors()
- {
- if (!this.Succeeded)
- {
- throw new CompositionException(this._errors);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ConstraintServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ConstraintServices.cs deleted file mode 100644 index 9f321e8bc64..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ConstraintServices.cs +++ /dev/null @@ -1,214 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- internal static class ConstraintServices
- {
- // NOTE : these are here as Reflection member search is pretty expensive, and we want that to be done once.
- // Also, making these static would cause this class to fail loading if we rename members of ExportDefinition.
- private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName");
- private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata");
- private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey");
- private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).GetMethod("get_Item");
- private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[] { typeof(object) });
- private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType");
-
- public static Expression<Func<ExportDefinition, bool>> CreateConstraint(IEnumerable<KeyValuePair<string, Type>> requiredMetadata)
- {
- ParameterExpression parameter = Expression.Parameter(typeof(ExportDefinition), "exportDefinition");
- Expression metadataConstraintBody = null;
-
- if (requiredMetadata != null)
- {
- metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter);
- }
-
- if (metadataConstraintBody != null)
- {
- return Expression.Lambda<Func<ExportDefinition, bool>>(metadataConstraintBody, parameter);
- }
-
- return null;
- }
-
- public static Expression<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, CreationPolicy requiredCreationPolicy)
- {
- ParameterExpression parameter = Expression.Parameter(typeof(ExportDefinition), "exportDefinition");
-
- Expression constraintBody = ConstraintServices.CreateContractConstraintBody(contractName, parameter);
-
- if (!string.IsNullOrEmpty(requiredTypeIdentity))
- {
- Expression typeIdentityConstraintBody = ConstraintServices.CreateTypeIdentityContraint(requiredTypeIdentity, parameter);
-
- constraintBody = Expression.AndAlso(constraintBody, typeIdentityConstraintBody);
- }
-
- if (requiredMetadata != null)
- {
- Expression metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter);
- if (metadataConstraintBody != null)
- {
- constraintBody = Expression.AndAlso(constraintBody, metadataConstraintBody);
- }
- }
-
- if (requiredCreationPolicy != CreationPolicy.Any)
- {
- Expression policyConstraintBody = ConstraintServices.CreateCreationPolicyContraint(requiredCreationPolicy, parameter);
-
- constraintBody = Expression.AndAlso(constraintBody, policyConstraintBody);
- }
-
- Expression<Func<ExportDefinition, bool>> constraint = Expression.Lambda<Func<ExportDefinition, bool>>(constraintBody, parameter);
- return constraint;
- }
-
- private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter)
- {
- Assumes.NotNull(parameter);
-
- // export.ContractName=<contract>;
- return Expression.Equal(
- Expression.Property(parameter, ConstraintServices._exportDefinitionContractNameProperty),
- Expression.Constant(contractName ?? string.Empty, typeof(string)));
- }
-
- private static Expression CreateMetadataConstraintBody(IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ParameterExpression parameter)
- {
- Assumes.NotNull(requiredMetadata);
- Assumes.NotNull(parameter);
-
- Expression body = null;
- foreach (KeyValuePair<string, Type> requiredMetadataItem in requiredMetadata)
- {
- // export.Metadata.ContainsKey(<metadataItem>)
- Expression metadataItemExpression = CreateMetadataContainsKeyExpression(parameter, requiredMetadataItem.Key);
-
- body = (body != null) ? Expression.AndAlso(body, metadataItemExpression) : metadataItemExpression;
- body = Expression.AndAlso(body, CreateMetadataOfTypeExpression(parameter, requiredMetadataItem.Key, requiredMetadataItem.Value));
- }
-
- return body;
- }
-
- 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));
- }
-
- private static Expression CreateTypeIdentityContraint(string requiredTypeIdentity, ParameterExpression parameter)
- {
- Assumes.NotNull(requiredTypeIdentity);
- Assumes.NotNull(parameter);
-
- // definition.Metadata.ContainsKey(CompositionServices.ExportTypeIdentity) &&
- // requiredTypeIdentity.Equals(definition.Metadata[CompositionConstants.ExportTypeIdentityMetadataName]);
-
- return Expression.MakeBinary(ExpressionType.AndAlso,
- CreateMetadataContainsKeyExpression(parameter, CompositionConstants.ExportTypeIdentityMetadataName),
- CreateMetadataValueEqualsExpression(parameter, requiredTypeIdentity, CompositionConstants.ExportTypeIdentityMetadataName));
- }
-
- private static Expression CreateMetadataContainsKeyExpression(ParameterExpression parameter, string constantKey)
- {
- Assumes.NotNull(parameter, constantKey);
-
- // definition.Metadata.ContainsKey(constantKey)
- return Expression.Call(
- Expression.Property(parameter, ConstraintServices._exportDefinitionMetadataProperty),
- ConstraintServices._metadataContainsKeyMethod,
- Expression.Constant(constantKey));
- }
-
- private static Expression CreateMetadataOfTypeExpression(ParameterExpression parameter, string constantKey, Type constantType)
- {
- Assumes.NotNull(parameter, constantKey);
- Assumes.NotNull(parameter, constantType);
-
- // constantType.IsInstanceOfType(definition.Metadata[constantKey])
- return Expression.Call(
- Expression.Constant(constantType, typeof(Type)),
- ConstraintServices._typeIsInstanceOfTypeMethod,
- Expression.Call(
- Expression.Property(parameter, ConstraintServices._exportDefinitionMetadataProperty),
- ConstraintServices._metadataItemMethod,
- Expression.Constant(constantKey))
- );
- }
-
- private static Expression CreateMetadataValueEqualsExpression(ParameterExpression parameter, object constantValue, string metadataName)
- {
- Assumes.NotNull(parameter, constantValue);
-
- // constantValue.Equals(definition.Metadata[CompositionServices.PartCreationPolicyMetadataName])
- return Expression.Call(
- Expression.Constant(constantValue),
- ConstraintServices._metadataEqualsMethod,
- Expression.Call(
- Expression.Property(parameter, ConstraintServices._exportDefinitionMetadataProperty),
- ConstraintServices._metadataItemMethod,
- Expression.Constant(metadataName)));
- }
-
- public static Expression<Func<ExportDefinition, bool>> CreatePartCreatorConstraint(Expression<Func<ExportDefinition, bool>> baseConstraint, ImportDefinition productImportDefinition)
- {
- ParameterExpression exportDefinitionParameter = baseConstraint.Parameters[0];
-
- // exportDefinition.Metadata
- Expression metadataExpression = Expression.Property(exportDefinitionParameter, ConstraintServices._exportDefinitionMetadataProperty);
-
- // exportDefinition.Metadata.ContainsKey("ProductDefinition")
- Expression containsProductExpression = Expression.Call(
- metadataExpression,
- ConstraintServices._metadataContainsKeyMethod,
- Expression.Constant(CompositionConstants.ProductDefinitionMetadataName));
-
- // exportDefinition.Metadata["ProductDefinition"]
- Expression productExportDefinitionExpression = Expression.Call(
- metadataExpression,
- ConstraintServices._metadataItemMethod,
- Expression.Constant(CompositionConstants.ProductDefinitionMetadataName));
-
- // ProductImportDefinition.Contraint((ExportDefinition)exportDefinition.Metadata["ProductDefinition"])
- Expression productMatchExpression =
- Expression.Invoke(productImportDefinition.Constraint,
- Expression.Convert(productExportDefinitionExpression, typeof(ExportDefinition)));
-
- // baseContraint(exportDefinition) &&
- // exportDefinition.Metadata.ContainsKey("ProductDefinition") &&
- // ProductImportDefinition.Contraint((ExportDefinition)exportDefinition.Metadata["ProductDefinition"])
- Expression<Func<ExportDefinition, bool>> constraint =
- Expression.Lambda<Func<ExportDefinition, bool>>(
- Expression.AndAlso(
- baseConstraint.Body,
- Expression.AndAlso(
- containsProductExpression,
- productMatchExpression)),
- exportDefinitionParameter);
-
- return constraint;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ContractNameServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ContractNameServices.cs deleted file mode 100644 index 4285722dec6..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ContractNameServices.cs +++ /dev/null @@ -1,310 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Reflection;
-using System.Text;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- internal static class ContractNameServices
- {
- const char NamespaceSeparator = '.';
- const char ArrayOpeningBracket = '[';
- const char ArrayClosingBracket = ']';
- const char ArraySeparator = ',';
- const char PointerSymbol = '*';
- const char ReferenceSymbol = '&';
- const char GenericArityBackQuote = '`';
- const char NestedClassSeparator = '+';
- const char ContractNameGenericOpeningBracket = '(';
- const char ContractNameGenericClosingBracket = ')';
- const char ContractNameGenericArgumentSeparator = ',';
- const char CustomModifiersSeparator = ' ';
-
- [ThreadStatic]
- private static Dictionary<Type, string> typeIdentityCache;
-
- private static Dictionary<Type, string> TypeIdentityCache
- {
- get
- {
- return typeIdentityCache = typeIdentityCache ?? new Dictionary<Type, string>();
- }
- }
-
- internal static string GetTypeIdentity(Type type)
- {
- Assumes.NotNull(type);
- string typeIdentity = null;
-
- if (!TypeIdentityCache.TryGetValue(type, out typeIdentity))
- {
- if (!type.IsAbstract && type.IsSubclassOf(typeof(Delegate)))
- {
- MethodInfo method = type.GetMethod("Invoke");
- typeIdentity = ContractNameServices.GetTypeIdentityFromMethod(method);
- }
- else
- {
- StringBuilder typeIdentityStringBuilder = new StringBuilder();
- WriteTypeWithNamespace(typeIdentityStringBuilder, type);
- typeIdentity = typeIdentityStringBuilder.ToString();
- }
-
- TypeIdentityCache.Add(type, typeIdentity);
- }
-
- return typeIdentity;
- }
-
- internal static string GetTypeIdentityFromMethod(MethodInfo method)
- {
- StringBuilder methodNameStringBuilder = new StringBuilder();
-
- WriteTypeWithNamespace(methodNameStringBuilder, method.ReturnType);
-
- methodNameStringBuilder.Append("(");
-
- ParameterInfo[] parameters = method.GetParameters();
-
- for (int i = 0; i < parameters.Length; i++)
- {
- if (i != 0)
- {
- methodNameStringBuilder.Append(",");
- }
-
- WriteTypeWithNamespace(methodNameStringBuilder, parameters[i].ParameterType);
- }
- methodNameStringBuilder.Append(")");
-
- return methodNameStringBuilder.ToString();
- }
-
- private static void WriteTypeWithNamespace(StringBuilder typeName, Type type)
- {
- // Writes type with namesapce
- if (!string.IsNullOrEmpty(type.Namespace))
- {
- typeName.Append(type.Namespace);
- typeName.Append(NamespaceSeparator);
- }
- WriteType(typeName, type);
- }
-
- private static void WriteType(StringBuilder typeName, Type type)
- {
- // Writes type name
- if (type.IsGenericType)
- {
- //
- // Reflection format stores all the generic arguments (including the ones for parent types) on the leaf type.
- // These arguments are placed in a queue and are written out based on generic arity (`X) of each type
- //
- Queue<Type> genericTypeArguments = new Queue<Type>(type.GetGenericArguments());
- WriteGenericType(typeName, type, type.IsGenericTypeDefinition, genericTypeArguments);
- Assumes.IsTrue(genericTypeArguments.Count == 0, "Expecting genericTypeArguments queue to be empty.");
- }
- else
- {
- WriteNonGenericType(typeName, type);
- }
- }
-
- private static void WriteNonGenericType(StringBuilder typeName, Type type)
- {
- //
- // Writes non-generic type
- //
- if (type.DeclaringType != null)
- {
- WriteType(typeName, type.DeclaringType);
- typeName.Append(NestedClassSeparator);
- }
- if (type.IsArray)
- {
- WriteArrayType(typeName, type);
- }
- else if (type.IsPointer)
- {
- WritePointerType(typeName, type);
- }
- else if (type.IsByRef)
- {
- WriteByRefType(typeName, type);
- }
- else
- {
- typeName.Append(type.Name);
- }
- }
-
- private static void WriteArrayType(StringBuilder typeName, Type type)
- {
- //
- // Writes array type e.g <TypeName>[]
- // Note that jagged arrays are stored in reverse order
- // e.g. C#: Int32[][,] Reflection: Int32[,][]
- // we are following C# order for arrays
- //
- Type rootElementType = FindArrayElementType(type);
- WriteType(typeName, rootElementType);
- Type elementType = type;
- do
- {
- WriteArrayTypeDimensions(typeName, elementType);
- }
- while ((elementType = elementType.GetElementType()) != null && elementType.IsArray);
- }
-
- private static void WritePointerType(StringBuilder typeName, Type type)
- {
- //
- // Writes pointer type e.g <TypeName>*
- //
- WriteType(typeName, type.GetElementType());
- typeName.Append(PointerSymbol);
- }
-
- private static void WriteByRefType(StringBuilder typeName, Type type)
- {
- //
- // Writes by ref type e.g <TypeName>&
- //
- WriteType(typeName, type.GetElementType());
- typeName.Append(ReferenceSymbol);
- }
-
- private static void WriteArrayTypeDimensions(StringBuilder typeName, Type type)
- {
- //
- // Writes array type dimensions e.g. [,,]
- //
- typeName.Append(ArrayOpeningBracket);
- int rank = type.GetArrayRank();
- for (int i = 1; i < rank; i++)
- {
- typeName.Append(ArraySeparator);
- }
- typeName.Append(ArrayClosingBracket);
- }
-
- private static void WriteGenericType(StringBuilder typeName, Type type, bool isDefinition, Queue<Type> genericTypeArguments)
- {
- //
- // Writes generic type including parent generic types
- // genericTypeArguments contains type arguments obtained from the most nested type
- // isDefinition parameter indicates if we are dealing with generic type definition
- //
- if (type.DeclaringType != null)
- {
- if (type.DeclaringType.IsGenericType)
- {
- WriteGenericType(typeName, type.DeclaringType, isDefinition, genericTypeArguments);
- }
- else
- {
- WriteNonGenericType(typeName, type.DeclaringType);
- }
- typeName.Append(NestedClassSeparator);
- }
- WriteGenericTypeName(typeName, type, isDefinition, genericTypeArguments);
- }
-
- private static void WriteGenericTypeName(StringBuilder typeName, Type type, bool isDefinition, Queue<Type> genericTypeArguments)
- {
- //
- // 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);
- }
-
- private static void WriteTypeArgumentsString(StringBuilder typeName, int argumentsCount, bool isDefinition, Queue<Type> genericTypeArguments)
- {
- //
- // Writes type arguments in brackets, e.g. (<contract_name1>, <contract_name2>, ...)
- //
- if (argumentsCount == 0)
- {
- return;
- }
- typeName.Append(ContractNameGenericOpeningBracket);
- for (int i = 0; i < argumentsCount; i++)
- {
- Assumes.IsTrue(genericTypeArguments.Count > 0, "Expecting genericTypeArguments to contain at least one Type");
- Type genericTypeArgument = genericTypeArguments.Dequeue();
- if (!isDefinition)
- {
- WriteTypeWithNamespace(typeName, genericTypeArgument);
- }
- typeName.Append(ContractNameGenericArgumentSeparator);
- }
- typeName.Remove(typeName.Length - 1, 1);
- typeName.Append(ContractNameGenericClosingBracket);
- }
-
- //internal for testability
- internal static void WriteCustomModifiers(StringBuilder typeName, string customKeyword, Type[] types)
- {
- //
- // 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);
- Assumes.IsTrue(typeArguments.Count == 0, "Expecting genericTypeArguments queue to be empty.");
- }
-
- private static Type FindArrayElementType(Type type)
- {
- //
- // Gets array element type by calling GetElementType() until the element is not an array
- //
- Type elementType = type;
- while ((elementType = elementType.GetElementType()) != null && elementType.IsArray) { }
- return elementType;
- }
-
- private static string FindGenericTypeName(string genericName)
- {
- //
- // Gets generic type name omitting the backquote and arity indicator
- // List`1 -> List
- // Arity indicator is returned as output parameter
- //
- int indexOfBackQuote = genericName.IndexOf(GenericArityBackQuote);
- if (indexOfBackQuote > -1)
- {
- genericName = genericName.Substring(0, indexOfBackQuote);
- }
- return genericName;
- }
-
- private static int GetGenericArity(Type type)
- {
- if (type.DeclaringType == null)
- {
- return type.GetGenericArguments().Length;
- }
-
- // The generic arity is equal to the difference in the number of generic arguments
- // from the type and the declaring type.
-
- int delclaringTypeGenericArguments = type.DeclaringType.GetGenericArguments().Length;
- int typeGenericArguments = type.GetGenericArguments().Length;
-
- Assumes.IsTrue(typeGenericArguments >= delclaringTypeGenericArguments);
-
- return typeGenericArguments - delclaringTypeGenericArguments;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CreationPolicy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CreationPolicy.cs deleted file mode 100644 index 5a8d4cb158b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/CreationPolicy.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Option placed on a type that controls when the <see cref="CompositionContainer"/> creates
- /// a new instance of a <see cref="ComposablePart"/>.
- /// </summary>
- public enum CreationPolicy : int
- {
- /// <summary>
- /// Let the <see cref="CompositionContainer"/> choose the most appropriate <see cref="CreationPolicy"/>
- /// for the part given the current context. This is the default <see cref="CreationPolicy"/>, with
- /// the <see cref="CompositionContainer"/> choosing <see cref="CreationPolicy.Shared"/> by default
- /// unless the <see cref="ComposablePart"/> or importer requests <see cref="CreationPolicy.NonShared"/>.
- /// </summary>
- Any = 0,
-
- /// <summary>
- /// A single shared instance of the associated <see cref="ComposablePart"/> will be created
- /// by the <see cref="CompositionContainer"/> and shared by all requestors.
- /// </summary>
- Shared = 1,
-
- /// <summary>
- /// A new non-shared instance of the associated <see cref="ComposablePart"/> will be created
- /// by the <see cref="CompositionContainer"/> for every requestor.
- /// </summary>
- NonShared = 2,
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/.gitattributes deleted file mode 100644 index 8ab95b78fe5..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/.gitattributes +++ /dev/null @@ -1,6 +0,0 @@ -/CompositionTrace.cs -crlf -/CompositionTraceId.cs -crlf -/CompositionTraceSource.cs -crlf -/SilverlightTraceWriter.cs -crlf -/TraceSourceTraceWriter.cs -crlf -/TraceWriter.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTrace.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTrace.cs deleted file mode 100644 index ed0cb4bcc51..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTrace.cs +++ /dev/null @@ -1,106 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Diagnostics
-{
- internal static class CompositionTrace
- {
- internal static void PartDefinitionResurrected(ComposablePartDefinition definition)
- {
- Assumes.NotNull(definition);
-
- if (CompositionTraceSource.CanWriteInformation)
- {
- CompositionTraceSource.WriteInformation(CompositionTraceId.Rejection_DefinitionResurrected,
- Strings.CompositionTrace_Rejection_DefinitionResurrected,
- definition.GetDisplayName());
- }
- }
-
- internal static void PartDefinitionRejected(ComposablePartDefinition definition, ChangeRejectedException exception)
- {
- Assumes.NotNull(definition, exception);
-
- if (CompositionTraceSource.CanWriteWarning)
- {
- CompositionTraceSource.WriteWarning(CompositionTraceId.Rejection_DefinitionRejected,
- Strings.CompositionTrace_Rejection_DefinitionRejected,
- definition.GetDisplayName(),
- exception.Message);
- }
- }
-
-#if !SILVERLIGHT
-
- internal static void AssemblyLoadFailed(DirectoryCatalog catalog, string fileName, Exception exception)
- {
- Assumes.NotNull(catalog, exception);
- Assumes.NotNullOrEmpty(fileName);
-
- if (CompositionTraceSource.CanWriteWarning)
- {
- CompositionTraceSource.WriteWarning(CompositionTraceId.Discovery_AssemblyLoadFailed,
- Strings.CompositionTrace_Discovery_AssemblyLoadFailed,
- catalog.GetDisplayName(),
- fileName,
- exception.Message);
- }
- }
-
-#endif
-
- internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type)
- {
- Assumes.NotNull(type);
-
- if (CompositionTraceSource.CanWriteInformation)
- {
- CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute,
- Strings.CompositionTrace_Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute,
- type.GetDisplayName());
- }
- }
-
- internal static void DefinitionContainsGenericsParameters(Type type)
- {
- Assumes.NotNull(type);
-
- if (CompositionTraceSource.CanWriteInformation)
- {
- CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionContainsGenericParameters,
- Strings.CompositionTrace_Discovery_DefinitionContainsGenericParameters,
- type.GetDisplayName());
- }
- }
-
- internal static void DefinitionContainsNoExports(Type type)
- {
- Assumes.NotNull(type);
-
- if (CompositionTraceSource.CanWriteInformation)
- {
- CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionContainsNoExports,
- Strings.CompositionTrace_Discovery_DefinitionContainsNoExports,
- type.GetDisplayName());
- }
- }
-
- internal static void MemberMarkedWithMultipleImportAndImportMany(ReflectionItem item)
- {
- Assumes.NotNull(item);
-
- if (CompositionTraceSource.CanWriteError)
- {
- CompositionTraceSource.WriteError(CompositionTraceId.Discovery_MemberMarkedWithMultipleImportAndImportMany,
- Strings.CompositionTrace_Discovery_MemberMarkedWithMultipleImportAndImportMany,
- item.GetDisplayName());
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTraceId.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTraceId.cs deleted file mode 100644 index 2fa8bcf45e8..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTraceId.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition.Diagnostics
-{
- // NOTE: Do not change the trace ids of values that have already shipped,
- // these leak out to TraceListerners which could take a dependency on them.
- // This enum is a ushort deliberately, the maximum value of a trace id is 65535.
- internal enum CompositionTraceId : ushort
- {
- // Rejection
-
- Rejection_DefinitionRejected = 1,
- Rejection_DefinitionResurrected = 2,
-
- Discovery_AssemblyLoadFailed = 3,
- Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute = 4,
- Discovery_DefinitionContainsGenericParameters = 5,
- Discovery_DefinitionContainsNoExports = 6,
- Discovery_MemberMarkedWithMultipleImportAndImportMany = 7,
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTraceSource.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTraceSource.cs deleted file mode 100644 index bf5ba23580b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/CompositionTraceSource.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Diagnostics
-{
- internal static class CompositionTraceSource
- {
-#if SILVERLIGHT
- private static readonly SilverlightTraceWriter Source = new SilverlightTraceWriter();
-#else
- private static readonly TraceSourceTraceWriter Source = new TraceSourceTraceWriter();
-#endif
-
- public static bool CanWriteInformation
- {
- get { return Source.CanWriteInformation; }
- }
-
- public static bool CanWriteWarning
- {
- get { return Source.CanWriteWarning; }
- }
-
- public static bool CanWriteError
- {
- get { return Source.CanWriteError; }
- }
-
- public static void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments)
- {
- EnsureEnabled(CanWriteInformation);
-
- Source.WriteInformation(traceId, format, arguments);
- }
-
- public static void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments)
- {
- EnsureEnabled(CanWriteWarning);
-
- Source.WriteWarning(traceId, format, arguments);
- }
-
- public static void WriteError(CompositionTraceId traceId, string format, params object[] arguments)
- {
- EnsureEnabled(CanWriteError);
-
- Source.WriteError(traceId, format, arguments);
- }
-
- private static void EnsureEnabled(bool condition)
- {
- Assumes.IsTrue(condition, "To avoid unnecessary work when a trace level has not been enabled, check CanWriteXXX before calling this method.");
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/SilverlightTraceWriter.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/SilverlightTraceWriter.cs deleted file mode 100644 index 11bfabd31e9..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/SilverlightTraceWriter.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#if SILVERLIGHT
-
-using System;
-using System.Diagnostics;
-using System.Globalization;
-using System.Text;
-
-namespace System.ComponentModel.Composition.Diagnostics
-{
- internal sealed class SilverlightTraceWriter : TraceWriter
- {
- private static readonly string SourceName = "System.ComponentModel.Composition";
-
- public override bool CanWriteInformation
- {
- get { return false; }
- }
-
- public override bool CanWriteWarning
- {
- get { return Debugger.IsLogging(); }
- }
-
- public override bool CanWriteError
- {
- get { return Debugger.IsLogging(); }
- }
-
- public override void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments)
- {
- WriteEvent(TraceEventType.Information, traceId, format, arguments);
- }
-
- public override void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments)
- {
- WriteEvent(TraceEventType.Warning, traceId, format, arguments);
- }
-
- public override void WriteError(CompositionTraceId traceId, string format, params object[] arguments)
- {
- WriteEvent(TraceEventType.Error, traceId, format, arguments);
- }
-
- private static void WriteEvent(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments)
- {
- if (!Debugger.IsLogging())
- {
- return;
- }
-
- string logMessage = CreateLogMessage(eventType, traceId, format, arguments);
- Debugger.Log(0, null, logMessage);
- }
-
- internal static string CreateLogMessage(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments)
- {
- StringBuilder messageBuilder = new StringBuilder();
-
- // Format taken from TraceListener.TraceEvent in full framework
- messageBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0} {1}: {2} : ",
- SourceName, eventType.ToString(), (int)traceId);
-
- if (arguments == null)
- {
- messageBuilder.Append(format);
- }
- else
- {
- messageBuilder.AppendFormat(CultureInfo.InvariantCulture, format, arguments);
- }
-
- messageBuilder.AppendLine();
-
- return messageBuilder.ToString();
- }
-
- // Copied from TraceEventType in full framework
- internal enum TraceEventType
- {
- Error = 2,
- Warning = 4,
- Information = 8,
- }
- }
-}
-
-#endif
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/TraceSourceTraceWriter.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/TraceSourceTraceWriter.cs deleted file mode 100644 index b9ada437c2e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/TraceSourceTraceWriter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#if !SILVERLIGHT
-
-using System;
-using System.Diagnostics;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Diagnostics
-{
- // Represents a trace writer that writes to a System.Diagnostics TraceSource
- internal sealed class TraceSourceTraceWriter : TraceWriter
- {
- internal static readonly TraceSource Source = new TraceSource("System.ComponentModel.Composition", SourceLevels.Warning);
-
- public override bool CanWriteInformation
- {
- get { return Source.Switch.ShouldTrace(TraceEventType.Information); }
- }
-
- public override bool CanWriteWarning
- {
- get { return Source.Switch.ShouldTrace(TraceEventType.Warning); }
- }
-
- public override bool CanWriteError
- {
- get { return Source.Switch.ShouldTrace(TraceEventType.Error); }
- }
-
- public override void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments)
- {
- WriteEvent(TraceEventType.Information, traceId, format, arguments);
- }
-
- public override void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments)
- {
- WriteEvent(TraceEventType.Warning, traceId, format, arguments);
- }
-
- public override void WriteError(CompositionTraceId traceId, string format, params object[] arguments)
- {
- WriteEvent(TraceEventType.Error, traceId, format, arguments);
- }
-
- private static void WriteEvent(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments)
- {
- Source.TraceEvent(eventType, (int)traceId, format, arguments);
- }
- }
-}
-
-#endif
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/TraceWriter.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/TraceWriter.cs deleted file mode 100644 index da3415f677d..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Diagnostics/TraceWriter.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-
-using System;
-
-namespace System.ComponentModel.Composition.Diagnostics
-{
- internal abstract class TraceWriter
- {
- public abstract bool CanWriteInformation
- {
- get;
- }
-
- public abstract bool CanWriteWarning
- {
- get;
- }
-
- public abstract bool CanWriteError
- {
- get;
- }
-
- public abstract void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments);
-
- public abstract void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments);
-
- public abstract void WriteError(CompositionTraceId traceId, string format, params object[] arguments);
- }
-}
-
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ErrorBuilder.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ErrorBuilder.cs deleted file mode 100644 index 14ca13364e7..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ErrorBuilder.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- internal static class ErrorBuilder
- {
- public static CompositionError PreventedByExistingImport(ComposablePart part, ImportDefinition import)
- {
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_PreventedByExistingImport,
- Strings.ImportEngine_PreventedByExistingImport,
- import.ToElement().DisplayName,
- part.ToElement().DisplayName);
- }
-
- public static CompositionError InvalidStateForRecompposition(ComposablePart part)
- {
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_InvalidStateForRecomposition,
- Strings.ImportEngine_InvalidStateForRecomposition,
- part.ToElement().DisplayName);
- }
-
- public static CompositionError ComposeTookTooManyIterations(int maximumNumberOfCompositionIterations)
- {
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_ComposeTookTooManyIterations,
- Strings.ImportEngine_ComposeTookTooManyIterations,
- maximumNumberOfCompositionIterations);
- }
-
- public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception, ImportDefinition definition)
- {
- Assumes.NotNull(exception, definition);
-
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_ImportCardinalityMismatch,
- exception.Message,
- definition.ToElement(),
- (Exception)null);
- }
-
- public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException)
- {
- Assumes.NotNull(part, innerException);
-
- ICompositionElement element = part.ToElement();
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_PartCannotActivate,
- element,
- innerException,
- Strings.ImportEngine_PartCannotActivate,
- element.DisplayName);
- }
-
- public static CompositionError CreatePartCannotSetImport(ComposablePart part, ImportDefinition definition, Exception innerException)
- {
- Assumes.NotNull(part, definition, innerException);
-
- ICompositionElement element = definition.ToElement();
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_PartCannotSetImport,
- element,
- innerException,
- Strings.ImportEngine_PartCannotSetImport,
- element.DisplayName,
- part.ToElement().DisplayName);
- }
-
- public static CompositionError CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException)
- {
- Assumes.NotNull(part, definition, innerException);
-
- ICompositionElement element = definition.ToElement();
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_PartCannotGetExportedValue,
- element,
- innerException,
- Strings.ImportEngine_PartCannotGetExportedValue,
- element.DisplayName,
- part.ToElement().DisplayName);
- }
-
- public static CompositionError CreatePartCycle(ComposablePart part)
- {
- Assumes.NotNull(part);
-
- ICompositionElement element = part.ToElement();
- return CompositionError.Create(
- CompositionErrorId.ImportEngine_PartCycle,
- element,
- Strings.ImportEngine_PartCycle,
- element.DisplayName);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExceptionBuilder.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExceptionBuilder.cs deleted file mode 100644 index ed42b30f5df..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExceptionBuilder.cs +++ /dev/null @@ -1,78 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition
-{
- internal static class ExceptionBuilder
- {
- public static Exception CreateDiscoveryException(string messageFormat, params string[] arguments)
- {
- // DiscoveryError (Dev10:602872): This should go through the discovery error reporting when
- // we add a way to report discovery errors properly.
- return new InvalidOperationException(Format(messageFormat, arguments));
- }
-
- public static ArgumentException CreateContainsNullElement(string parameterName)
- {
- Assumes.NotNull(parameterName);
-
- string message = Format(Strings.Argument_NullElement, parameterName);
-
- return new ArgumentException(message, parameterName);
- }
-
- public static ObjectDisposedException CreateObjectDisposed(object instance)
- {
- Assumes.NotNull(instance);
-
- return new ObjectDisposedException(instance.GetType().ToString());
- }
-
- public static NotImplementedException CreateNotOverriddenByDerived(string memberName)
- {
- Assumes.NotNullOrEmpty(memberName);
-
- string message = Format(Strings.NotImplemented_NotOverriddenByDerived, memberName);
-
- return new NotImplementedException(message);
- }
-
- public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName)
- {
- Assumes.NotNullOrEmpty(parameterName);
-
- string message = Format(Strings.ExportDefinitionNotOnThisComposablePart, parameterName);
-
- return new ArgumentException(message, parameterName);
- }
-
- public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName)
- {
- Assumes.NotNullOrEmpty(parameterName);
-
- string message = Format(Strings.ImportDefinitionNotOnThisComposablePart, parameterName);
-
- return new ArgumentException(message, parameterName);
- }
-
- public static CompositionException CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException)
- {
- Assumes.NotNull(part, definition, innerException);
-
- return new CompositionException(
- ErrorBuilder.CreateCannotGetExportedValue(part, definition, innerException));
- }
-
- private static string Format(string format, params string[] arguments)
- {
- return String.Format(CultureInfo.CurrentCulture, format, arguments);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportAttribute.cs deleted file mode 100644 index 6882f92a494..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportAttribute.cs +++ /dev/null @@ -1,144 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies that a type, property, field, or method provides a particular export.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method,
- AllowMultiple = true, Inherited = false)]
- public class ExportAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type or member marked with this attribute under the default contract name.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the type of the
- /// property or field, or the type itself, that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ExportAttribute()
- : this((string)null, (Type)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type or member marked with this attribute under a contract name derived from the
- /// specified type.
- /// </summary>
- /// <param name="contractType">
- /// A <see cref="Type"/> of which to derive the contract name to export the type or
- /// member marked with this attribute, under; or <see langword="null"/> to use the
- /// default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on
- /// <paramref name="contractType"/>.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the type of the
- /// property or field, or the type itself, that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ExportAttribute(Type contractType)
- : this((string)null, contractType)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type or member marked with this attribute under the specified contract name.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name to export the type or member
- /// marked with this attribute, under; or <see langword="null"/> or an empty string
- /// ("") to use the default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property or field
- /// type, or the type itself that this is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ExportAttribute(string contractName)
- : this(contractName, (Type)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type or member marked with this attribute under the specified contract name.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name to export the type or member
- /// marked with this attribute, under; or <see langword="null"/> or an empty string
- /// ("") to use the default contract name.
- /// </param>
- /// <param name="contractType">
- /// A <see cref="Type"/> of which to derive the contract name to export the type or
- /// member marked with this attribute, under; or <see langword="null"/> to use the
- /// default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property or field
- /// type, or the type itself that this is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ExportAttribute(string contractName, Type contractType)
- {
- this.ContractName = contractName;
- this.ContractType = contractType;
- }
-
- /// <summary>
- /// Gets the contract name to export the type or member under.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the contract name to export the type or member
- /// marked with this attribute, under. The default value is an empty string ("").
- /// </value>
- public string ContractName { get; private set; }
-
- /// <summary>
- /// Get the contract type that is exported by the member that this attribute is attached to.
- /// </summary>
- /// <value>
- /// A <see cref="Type"/> of the export that is be provided. The default value is
- /// <see langword="null"/> which means that the type will be obtained by looking at the type on
- /// the member that this export is attached to.
- /// </value>
- public Type ContractType { get; private set; }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportCardinalityCheckResult.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportCardinalityCheckResult.cs deleted file mode 100644 index 5786d48c5df..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportCardinalityCheckResult.cs +++ /dev/null @@ -1,14 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition
-{
- internal enum ExportCardinalityCheckResult : int
- {
- Match,
- NoExports,
- TooManyExports
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportMetadataAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportMetadataAttribute.cs deleted file mode 100644 index 67a38cbd8f2..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportMetadataAttribute.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies metadata for a type, property, field, or method marked with the
- /// <see cref="ExportAttribute"/>.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Field,
- AllowMultiple = true, Inherited = false)]
- public sealed class ExportMetadataAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportMetadataAttribute"/> with the
- /// specified name and metadata value.
- /// </summary>
- /// <param name="name">
- /// A <see cref="String"/> containing the name of the metadata value; or
- /// <see langword="null"/> to set the <see cref="Name"/> property to an empty
- /// string ("").
- /// </param>
- /// <param name="value">
- /// An <see cref="object"/> containing the metadata value. This can be
- /// <see langword="null"/>.
- /// </param>
- public ExportMetadataAttribute(string name, object value)
- {
- this.Name = name ?? string.Empty;
- this.Value = value;
- }
-
- /// <summary>
- /// Gets the name of the metadata value.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the name of the metadata value.
- /// </value>
- public string Name
- {
- get;
- private set;
- }
-
- /// <summary>
- /// Gets the metadata value.
- /// </summary>
- /// <value>
- /// An <see cref="object"/> containing the metadata value.
- /// </value>
- public object Value
- {
- get;
- private set;
- }
-
- public bool IsMultiple
- {
- get;
- set;
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs deleted file mode 100644 index af8dc0ff8e6..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using Microsoft.Internal;
-using System.Collections.Generic;
-
-namespace System.ComponentModel.Composition
-{
- partial class ExportServices
- {
- private sealed class DisposableLazy<T, TMetadataView> : Lazy<T, TMetadataView>, IDisposable
- {
- private IDisposable _disposable;
-
- public DisposableLazy(Func<T> valueFactory, TMetadataView metadataView, IDisposable disposable)
- : base(valueFactory, metadataView)
- {
- Assumes.NotNull(disposable);
-
- this._disposable = disposable;
- }
-
- void IDisposable.Dispose()
- {
- this._disposable.Dispose();
- }
- }
-
- private sealed class DisposableLazy<T> : Lazy<T>, IDisposable
- {
- private IDisposable _disposable;
-
- public DisposableLazy(Func<T> valueFactory, IDisposable disposable)
- : base(valueFactory)
- {
- Assumes.NotNull(disposable);
-
- this._disposable = disposable;
- }
-
- void IDisposable.Dispose()
- {
- this._disposable.Dispose();
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportServices.cs deleted file mode 100644 index 9aa11951d59..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ExportServices.cs +++ /dev/null @@ -1,249 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition
-{
- // Provides helpers for creating and dealing with Exports
- internal static partial class ExportServices
- {
- private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.NonPublic | BindingFlags.Static);
- private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.NonPublic | BindingFlags.Static);
- private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.NonPublic | BindingFlags.Static);
- private static readonly MethodInfo _createStronglyTypedExportFactoryOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedExportFactoryOfT", BindingFlags.NonPublic | BindingFlags.Static);
- private static readonly MethodInfo _createStronglyTypedExportFactoryOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedExportFactoryOfTM", BindingFlags.NonPublic | BindingFlags.Static);
-
- internal static readonly Type DefaultMetadataViewType = typeof(IDictionary<string, object>);
- internal static readonly Type DefaultExportedValueType = typeof(object);
-
- internal static bool IsDefaultMetadataViewType(Type metadataViewType)
- {
- Assumes.NotNull(metadataViewType);
-
- // Consider all types that IDictionary<string, object> derives from, such
- // as ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>
- // and IEnumerable, as default metadata view
- return metadataViewType.IsAssignableFrom(DefaultMetadataViewType);
- }
-
- internal static bool IsDictionaryConstructorViewType(Type metadataViewType)
- {
- Assumes.NotNull(metadataViewType);
-
- // Does the view type have a constructor that is a Dictionary<string, object>
- return metadataViewType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
- Type.DefaultBinder,
- new Type[] { typeof(IDictionary<string, object>) },
- new ParameterModifier[0]) != null;
- }
-
- internal static Func<Export, object> CreateStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
- {
- MethodInfo genericMethod = null;
- if (metadataViewType != null)
- {
- genericMethod = _createStronglyTypedLazyOfTM.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType, metadataViewType);
- }
- else
- {
- genericMethod = _createStronglyTypedLazyOfT.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType);
- }
- Assumes.NotNull(genericMethod);
- return (Func<Export, object>)Delegate.CreateDelegate(typeof(Func<Export, object>), genericMethod);
- }
-
- internal static Func<Export, Lazy<object, object>> CreateSemiStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
- {
- MethodInfo genericMethod = _createSemiStronglyTypedLazy.MakeGenericMethod(
- exportType ?? ExportServices.DefaultExportedValueType,
- metadataViewType ?? ExportServices.DefaultMetadataViewType);
- Assumes.NotNull(genericMethod);
- return (Func<Export, Lazy<object, object>>)Delegate.CreateDelegate(typeof(Func<Export, Lazy<object,object>>), genericMethod);
- }
-
- [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- internal static Lazy<T, M> CreateStronglyTypedLazyOfTM<T, M>(Export export)
- {
- IDisposable disposable = export as IDisposable;
- if (disposable != null)
- {
- return new DisposableLazy<T, M>(
- () => ExportServices.GetCastedExportedValue<T>(export),
- AttributedModelServices.GetMetadataView<M>(export.Metadata),
- disposable);
- }
- else
- {
- return new Lazy<T, M>(
- () => ExportServices.GetCastedExportedValue<T>(export),
- AttributedModelServices.GetMetadataView<M>(export.Metadata),
- false);
- }
- }
-
- [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- internal static Lazy<T> CreateStronglyTypedLazyOfT<T>(Export export)
- {
- IDisposable disposable = export as IDisposable;
- if (disposable != null)
- {
- return new DisposableLazy<T>(
- () => ExportServices.GetCastedExportedValue<T>(export),
- disposable);
- }
- else
- {
- return new Lazy<T>(() => ExportServices.GetCastedExportedValue<T>(export), false);
-
- }
- }
-
- [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- internal static Lazy<object, object> CreateSemiStronglyTypedLazy<T, M>(Export export)
- {
- IDisposable disposable = export as IDisposable;
- if (disposable != null)
- {
- return new DisposableLazy<object, object>(
- () => ExportServices.GetCastedExportedValue<T>(export),
- AttributedModelServices.GetMetadataView<M>(export.Metadata),
- disposable);
- }
- else
- {
- return new Lazy<object, object>(
- () => ExportServices.GetCastedExportedValue<T>(export),
- AttributedModelServices.GetMetadataView<M>(export.Metadata),
- false
- );
- }
- }
-
- internal static Func<Export, object> CreateStronglyTypedExportFactoryFactory(Type exportType, Type metadataType, ConstructorInfo constructor)
- {
- MethodInfo genericMethod = null;
- if (metadataType == null)
- {
- genericMethod = _createStronglyTypedExportFactoryOfT.MakeGenericMethod(exportType);
- }
- else
- {
- genericMethod = _createStronglyTypedExportFactoryOfTM.MakeGenericMethod(exportType, metadataType);
- }
-
- Assumes.NotNull(genericMethod);
- Func<Export, ConstructorInfo, object> exportFactoryFactory = (Func<Export, ConstructorInfo, object>)Delegate.CreateDelegate(typeof(Func<Export, ConstructorInfo, object>), genericMethod);
- return (e) => exportFactoryFactory.Invoke(e, constructor);
- }
-
- private static Tuple<T, Action> GetExportLifetimeContextFromExport<T>(Export export)
- {
- T exportedValue;
- Action disposeAction;
- IDisposable disposable = null;
-
- CatalogExportProvider.PartCreatorExport partCreatorExport = export as CatalogExportProvider.PartCreatorExport;
-
- if (partCreatorExport != null)
- {
- // PartCreatorExport is the more optimized route
- Export exportProduct = partCreatorExport.CreateExportProduct();
- exportedValue = GetCastedExportedValue<T>(exportProduct);
- disposable = exportProduct as IDisposable;
- }
- else
- {
- // If it comes from somewhere else we walk through the ComposablePartDefinition
- var factoryPartDefinition = GetCastedExportedValue<ComposablePartDefinition>(export);
- var part = factoryPartDefinition.CreatePart();
- var exportDef = factoryPartDefinition.ExportDefinitions.Single();
-
- exportedValue = CastExportedValue<T>(part.ToElement(), part.GetExportedValue(exportDef));
- disposable = part as IDisposable;
- }
-
- if (disposable != null)
- {
- disposeAction = () => disposable.Dispose();
- }
- else
- {
- disposeAction = () => { };
- }
-
- return new Tuple<T, Action>(exportedValue, disposeAction);
- }
-
- private static object CreateStronglyTypedExportFactoryOfT<T>(Export export, ConstructorInfo constructor)
- {
- Func<Tuple<T, Action>> exportLifetimeContextCreator = () => ExportServices.GetExportLifetimeContextFromExport<T>(export);
- return constructor.Invoke(new object[] { exportLifetimeContextCreator });
- }
-
- private static object CreateStronglyTypedExportFactoryOfTM<T, M>(Export export, ConstructorInfo constructor)
- {
- Func<Tuple<T, Action>> exportLifetimeContextCreator = () => ExportServices.GetExportLifetimeContextFromExport<T>(export);
- return constructor.Invoke(new object[] { exportLifetimeContextCreator, AttributedModelServices.GetMetadataView<M>(export.Metadata) });
- }
-
- internal static T GetCastedExportedValue<T>(Export export)
- {
- return CastExportedValue<T>(export.ToElement(), export.Value);
- }
-
- internal static T CastExportedValue<T>(ICompositionElement element, object exportedValue)
- {
- object typedExportedValue = null;
-
- bool succeeded = ContractServices.TryCast(typeof(T), exportedValue, out typedExportedValue);
- if (!succeeded)
- {
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
- Strings.ContractMismatch_ExportedValueCannotBeCastToT,
- element.DisplayName,
- typeof(T)));
- }
-
- return (T)typedExportedValue;
- }
-
- 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;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/.gitattributes deleted file mode 100644 index 3fab40e5ea1..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/.gitattributes +++ /dev/null @@ -1,30 +0,0 @@ -/AggregateCatalog.cs -crlf -/AggregateExportProvider.cs -crlf -/AssemblyCatalog.cs -crlf -/AssemblyCatalogDebuggerProxy.cs -crlf -/AtomicComposition.cs -crlf -/AtomicCompositionExtensions.cs -crlf -/CatalogExportProvider.CatalogChangeProxy.cs -crlf -/CatalogExportProvider.CatalogExport.cs -crlf -/CatalogExportProvider.PartCreatorExport.cs -crlf -/CatalogExportProvider.cs -crlf -/ComposablePartCatalogChangeEventArgs.cs -crlf -/ComposablePartCatalogCollection.cs -crlf -/ComposablePartExportProvider.cs -crlf -/CompositionBatch.SingleExportComposablePart.cs -crlf -/CompositionBatch.cs -crlf -/CompositionConstants.cs -crlf -/CompositionContainer.cs -crlf -/CompositionLock.cs -crlf -/CompositionServices.cs -crlf -/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs -crlf -/DirectoryCatalog.cs -crlf -/ExportProvider.GetExportOverrides.cs -crlf -/ExportProvider.cs -crlf -/ExportsChangeEventArgs.cs -crlf -/INotifyComposablePartCatalogChanged.cs -crlf -/ImportEngine.EngineContext.cs -crlf -/ImportEngine.PartManager.cs -crlf -/ImportEngine.RecompositionManager.cs -crlf -/ImportEngine.cs -crlf -/TypeCatalog.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs deleted file mode 100644 index aba950333da..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs +++ /dev/null @@ -1,230 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// A mutable collection of <see cref="ComposablePartCatalog"/>s.
- /// </summary>
- /// <remarks>
- /// This type is thread safe.
- /// </remarks>
- public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged
- {
- private ComposablePartCatalogCollection _catalogs = null;
- private volatile int _isDisposed = 0;
- private IQueryable<ComposablePartDefinition> _partsQuery;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AggregateCatalog"/> class.
- /// </summary>
- public AggregateCatalog()
- : this((IEnumerable<ComposablePartCatalog>)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AggregateCatalog"/> class
- /// with the specified catalogs.
- /// </summary>
- /// <param name="catalogs">
- /// An <see cref="Array"/> of <see cref="ComposablePartCatalog"/> objects to add to the
- /// <see cref="AggregateCatalog"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="catalogs"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
- /// </exception>
- public AggregateCatalog(params ComposablePartCatalog[] catalogs)
- : this((IEnumerable<ComposablePartCatalog>)catalogs)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AggregateCatalog"/> class
- /// with the specified catalogs.
- /// </summary>
- /// <param name="catalogs">
- /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartCatalog"/> objects to add
- /// to the <see cref="AggregateCatalog"/>; or <see langword="null"/> to
- /// create an <see cref="AggregateCatalog"/> that is empty.
- /// </param>
- /// <exception cref="ArgumentException">
- /// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
- /// </exception>
- public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs)
- {
- Requires.NullOrNotNullElements(catalogs, "catalogs");
-
- this._catalogs = new ComposablePartCatalogCollection(catalogs, this.OnChanged, this.OnChanging);
- this._partsQuery = this._catalogs.AsQueryable().SelectMany(catalog => catalog.Parts);
- }
-
- /// <summary>
- /// Notify when the contents of the Catalog has changed.
- /// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed
- {
- add
- {
- this._catalogs.Changed += value;
- }
- remove
- {
- this._catalogs.Changed -= value;
- }
- }
-
- /// <summary>
- /// Notify when the contents of the Catalog has changing.
- /// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing
- {
- add
- {
- this._catalogs.Changing += value;
- }
- remove
- {
- this._catalogs.Changing -= value;
- }
- }
-
- /// <summary>
- /// Gets the part definitions of the catalog.
- /// </summary>
- /// <value>
- /// A <see cref="IQueryable{T}"/> of <see cref="ComposablePartDefinition"/> objects of the
- /// <see cref="AggregateCatalog"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="AggregateCatalog"/> has been disposed of.
- /// </exception>
- public override IQueryable<ComposablePartDefinition> Parts
- {
- get
- {
- this.ThrowIfDisposed();
- return this._partsQuery;
- }
- }
-
- /// <summary>
- /// Returns the export definitions that match the constraint defined by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="ExportDefinition"/> objects to return.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
- /// <see cref="ExportDefinition"/> objects and their associated
- /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
- /// by <paramref name="definition"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="AggregateCatalog"/> has been disposed of.
- /// </exception>
- public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(definition, "definition");
-
- // delegate the query to each catalog and merge the results.
- var exports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
- foreach (var catalog in this._catalogs)
- {
- foreach (var export in catalog.GetExports(definition))
- {
- exports.Add(export);
- }
- }
- return exports;
- }
-
- /// <summary>
- /// Gets the underlying catalogs of the catalog.
- /// </summary>
- /// <value>
- /// An <see cref="ICollection{T}"/> of underlying <see cref="ComposablePartCatalog"/> objects
- /// of the <see cref="AggregateCatalog"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="AggregateCatalog"/> has been disposed of.
- /// </exception>
- public ICollection<ComposablePartCatalog> Catalogs
- {
- get
- {
- this.ThrowIfDisposed();
- return this._catalogs;
- }
- }
-
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (disposing)
- {
- // NOTE : According to http://msdn.microsoft.com/en-us/library/4bw5ewxy.aspx, the warning is bogus when used with Interlocked API.
-#pragma warning disable 420
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
-#pragma warning restore 420
- {
- this._catalogs.Dispose();
- }
- }
- }
- finally
- {
- base.Dispose(disposing);
- }
- }
-
- /// <summary>
- /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
- /// </summary>
- /// <param name="e">
- /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
- /// </param>
- protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
- {
- this._catalogs.OnChanged(this, e);
- }
-
- /// <summary>
- /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event.
- /// </summary>
- /// <param name="e">
- /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
- /// </param>
- protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
- {
- this._catalogs.OnChanging(this, e);
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed == 1)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs deleted file mode 100644 index 62bfe70ce79..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs +++ /dev/null @@ -1,219 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public class AggregateExportProvider : ExportProvider , IDisposable
- {
- private ReadOnlyCollection<ExportProvider> _providers;
- private volatile int _isDisposed = 0;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
- /// </summary>
- /// <param name="providers">The prioritized list of export providers.</param>
- /// <remarks>
- /// <para>
- /// The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when
- /// executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>.
- /// </para>
- /// <para>
- /// The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers.
- /// That is, it will not try to dispose of any of them when it gets disposed.
- /// </para>
- /// </remarks>
- public AggregateExportProvider(params ExportProvider[] providers)
- : this(providers.AsEnumerable())
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
- /// </summary>
- /// <param name="providers">The prioritized list of export providers. The providers are consulted in order in which they are supplied.</param>
- /// <remarks>
- /// <para>
- /// The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when
- /// executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>.
- /// </para>
- /// <para>
- /// The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers.
- /// That is, it will not try to dispose of any of them when it gets disposed.
- /// </para>
- /// </remarks>
- public AggregateExportProvider(IEnumerable<ExportProvider> providers)
- {
- List<ExportProvider> providerList = new List<ExportProvider>();
-
- if (providers != null)
- {
- // we are in the constructor, so there's no need to lock anything
- foreach (var provider in providers)
- {
- if (provider == null)
- {
- throw ExceptionBuilder.CreateContainsNullElement("providers");
- }
-
- providerList.Add(provider);
-
- provider.ExportsChanged += this.OnExportChangedInternal;
- provider.ExportsChanging += this.OnExportChangingInternal;
- }
- }
-
- // this will always fully copy the array
- this._providers = new ReadOnlyCollection<ExportProvider>(providerList);
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- // NOTE : According to http://msdn.microsoft.com/en-us/library/4bw5ewxy.aspx, the warning is bogus when used with Interlocked API.
-#pragma warning disable 420
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
-#pragma warning restore 420
- {
- this._providers.ForEach(provider =>
- {
- provider.ExportsChanged -= this.OnExportChangedInternal;
- provider.ExportsChanging -= this.OnExportChangingInternal;
- });
- }
- }
- }
-
- /// <summary>
- /// Gets the export providers which the aggregate export provider aggregates.
- /// </summary>
- /// <value>
- /// A <see cref="ReadOnlyCollection{T}"/> of <see cref="ExportProvider"/> objects
- /// which the <see cref="AggregateExportProvider"/> aggregates.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="AggregateExportProvider"/> has been disposed of.
- /// </exception>
- public ReadOnlyCollection<ExportProvider> Providers
- {
- get
- {
- this.ThrowIfDisposed();
-
- return this._providers;
- }
- }
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> to get.</param>
- /// <returns></returns>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <remarks>
- /// <note type="inheritinfo">
- /// The implementers should not treat the cardinality-related mismatches as errors, and are not
- /// expected to throw exceptions in those cases.
- /// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
- /// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
- /// </note>
- /// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
-
- if (definition.Cardinality == ImportCardinality.ZeroOrMore)
- {
- var exports = new List<Export>();
- foreach (var provider in this._providers)
- {
- foreach (var export in provider.GetExports(definition, atomicComposition))
- {
- exports.Add(export);
- }
- }
- return exports;
- }
- else
- {
- IEnumerable<Export> allExports = Enumerable.Empty<Export>();
-
- // if asked for "one or less", the prioriry is at play - the first provider that agrees to return the value
- // which best complies with the request, wins.
- foreach (ExportProvider provider in this._providers)
- {
- IEnumerable<Export> exports;
- bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out exports);
- bool anyExports = exports.FastAny();
- if (cardinalityCheckResult && anyExports)
- {
- // NOTE : if the provider returned nothing, we need to proceed, even if it indicated that the
- // cardinality is correct - when asked for "one or less", the provider might - correctly -
- // return an empty sequence, but we shouldn't be satisfied with that as providers down the list
- // might have a value we are interested in.
- return exports;
- }
- else
- {
- // TODO
- // This is a sneaky thing that we do - if in the end no provider returns the exports with the right cardinality
- // we simply return the aggregation of all exports they have restuned. This way the end result is still not waht we want
- // but no information is lost.
- // WE SHOULD fix this behavior, but this is ONLY possible if we can treat many exports as no exports for the sake of singles
- if (anyExports)
- {
- allExports = allExports.Concat(exports);
- }
- }
- }
-
- return allExports;
- }
- }
-
- private void OnExportChangedInternal(object sender, ExportsChangeEventArgs e)
- {
- this.OnExportsChanged(e);
- }
-
- private void OnExportChangingInternal(object sender, ExportsChangeEventArgs e)
- {
- this.OnExportsChanging(e);
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed == 1)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs deleted file mode 100644 index b1e079b0746..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs +++ /dev/null @@ -1,301 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Security;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// An immutable ComposablePartCatalog created from a managed code assembly.
- /// </summary>
- /// <remarks>
- /// This type is thread safe.
- /// </remarks>
- [DebuggerTypeProxy(typeof(AssemblyCatalogDebuggerProxy))]
- public class AssemblyCatalog : ComposablePartCatalog, ICompositionElement
- {
- private readonly object _thisLock = new object();
- private readonly ICompositionElement _definitionOrigin;
- private volatile Assembly _assembly = null;
- private volatile TypeCatalog _innerCatalog = null;
- private int _isDisposed = 0;
-
-#if !SILVERLIGHT
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class
- /// with the specified code base.
- /// </summary>
- /// <param name="codeBase">
- /// A <see cref="String"/> containing the code base of the assembly containing the
- /// attributed <see cref="Type"/> objects to add to the <see cref="AssemblyCatalog"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="codeBase"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="codeBase"/> is a zero-length string, contains only white space,
- /// or contains one or more invalid characters as defined by <see cref="Path.InvalidPathChars"/>.
- /// </exception>
- /// <exception cref="PathTooLongException">
- /// The specified path, file name, or both exceed the system-defined maximum length.
- /// </exception>
- /// <exception cref="SecurityException">
- /// The caller does not have path discovery permission.
- /// </exception>
- /// <exception cref="FileNotFoundException">
- /// <paramref name="codeBase"/> is not found.
- /// </exception>
- /// <exception cref="FileLoadException ">
- /// <paramref name="codeBase"/> could not be loaded.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="codeBase"/> specified a directory.
- /// </exception>
- /// <exception cref="BadImageFormatException">
- /// <paramref name="codeBase"/> is not a valid assembly
- /// -or-
- /// Version 2.0 or later of the common language runtime is currently loaded
- /// and <paramref name="codeBase"/> was compiled with a later version.
- /// </exception>
- /// <remarks>
- /// The assembly referenced by <paramref langword="codeBase"/> is loaded into the Load context.
- /// </remarks>
- public AssemblyCatalog(string codeBase)
- : this(codeBase, (ICompositionElement)null)
- {
- }
-
- internal AssemblyCatalog(string codeBase, ICompositionElement definitionOrigin)
- : this(LoadAssembly(codeBase), definitionOrigin)
- {
- }
-
-#endif
-
- /// <summary>
- /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class
- /// with the specified assembly.
- /// </summary>
- /// <param name="assembly">
- /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects to
- /// add to the <see cref="AssemblyCatalog"/>.
- /// </param>
- /// <exception cref="ArgumentException">
- /// <paramref name="assembly"/> is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="assembly"/> was loaded in the reflection-only context.
- /// </exception>
- public AssemblyCatalog(Assembly assembly)
- : this(assembly, (ICompositionElement)null)
- {
- }
-
- internal AssemblyCatalog(Assembly assembly, ICompositionElement definitionOrigin)
- {
- Requires.NotNull(assembly, "assembly");
-
-#if !SILVERLIGHT
- if (assembly.ReflectionOnly)
- {
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Argument_AssemblyReflectionOnly, "assembly"), "assembly");
- }
-#endif
- this._assembly = assembly;
- this._definitionOrigin = definitionOrigin ?? this;
- }
-
- /// <summary>
- /// Gets the part definitions of the assembly catalog.
- /// </summary>
- /// <value>
- /// A <see cref="IQueryable{T}"/> of <see cref="ComposablePartDefinition"/> objects of the
- /// <see cref="AssemblyCatalog"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="AssemblyCatalog"/> has been disposed of.
- /// </exception>
- public override IQueryable<ComposablePartDefinition> Parts
- {
- get
- {
- return this.InnerCatalog.Parts;
- }
- }
-
- /// <summary>
- /// Returns the export definitions that match the constraint defined by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="ExportDefinition"/> objects to return.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
- /// <see cref="ExportDefinition"/> objects and their associated
- /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
- /// by <paramref name="definition"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePartCatalog"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>, if no
- /// <see cref="ExportDefinition"/> match the conditions defined by
- /// <paramref name="definition"/>, return an empty <see cref="IEnumerable{T}"/>.
- /// </note>
- /// </remarks>
- public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
- {
- return this.InnerCatalog.GetExports(definition);
- }
-
- private TypeCatalog InnerCatalog
- {
- get
- {
- this.ThrowIfDisposed();
-
- if (this._innerCatalog == null)
- {
- lock (this._thisLock)
- {
- if (this._innerCatalog == null)
- {
- var catalog = new TypeCatalog(this._assembly.GetTypes(), _definitionOrigin);
- this._innerCatalog = catalog;
- }
- }
- }
- return this._innerCatalog;
- }
- }
-
- /// <summary>
- /// Gets the assembly containing the attributed types contained within the assembly
- /// catalog.
- /// </summary>
- /// <value>
- /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects
- /// contained within the <see cref="AssemblyCatalog"/>.
- /// </value>
- public Assembly Assembly
- {
- get { return this._assembly; }
- }
-
- /// <summary>
- /// Gets the display name of the assembly catalog.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a human-readable display name of the <see cref="AssemblyCatalog"/>.
- /// </value>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- string ICompositionElement.DisplayName
- {
- get { return this.GetDisplayName(); }
- }
-
- /// <summary>
- /// Gets the composition element from which the assembly catalog originated.
- /// </summary>
- /// <value>
- /// This property always returns <see langword="null"/>.
- /// </value>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
- {
- get { return null; }
- }
-
-
- /// <summary>
- /// Returns a string representation of the assembly catalog.
- /// </summary>
- /// <returns>
- /// A <see cref="String"/> containing the string representation of the <see cref="AssemblyCatalog"/>.
- /// </returns>
- public override string ToString()
- {
- return this.GetDisplayName();
- }
-
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
- {
- if (disposing)
- {
- if (this._innerCatalog != null)
- {
- this._innerCatalog.Dispose();
- }
- }
- }
- }
- finally
- {
- base.Dispose(disposing);
- }
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed == 1)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
-
- private string GetDisplayName()
- {
- return string.Format(CultureInfo.CurrentCulture,
- "{0} (Assembly=\"{1}\")", // NOLOC
- GetType().Name,
- this.Assembly.FullName);
- }
-
-#if !SILVERLIGHT
-
- private static Assembly LoadAssembly(string codeBase)
- {
- Requires.NotNullOrEmpty(codeBase, "codeBase");
-
- AssemblyName assemblyName;
-
- try
- {
- assemblyName = AssemblyName.GetAssemblyName(codeBase);
- }
- catch (ArgumentException)
- {
- assemblyName = new AssemblyName();
- assemblyName.CodeBase = codeBase;
- }
-
- return Assembly.Load(assemblyName);
- }
-#endif
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AssemblyCatalogDebuggerProxy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AssemblyCatalogDebuggerProxy.cs deleted file mode 100644 index 86aa5fad768..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AssemblyCatalogDebuggerProxy.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- internal class AssemblyCatalogDebuggerProxy
- {
- private readonly AssemblyCatalog _catalog;
-
- public AssemblyCatalogDebuggerProxy(AssemblyCatalog catalog)
- {
- Requires.NotNull(catalog, "catalog");
-
- this._catalog = catalog;
- }
-
- public Assembly Assembly
- {
- get { return this._catalog.Assembly; }
- }
-
- public ReadOnlyCollection<ComposablePartDefinition> Parts
- {
- // NOTE: This shouldn't be cached, so that on every query of
- // the current value of the underlying catalog is respected.
- // We use ReadOnlyCollection as arrays do not have the
- // appropriate debugger display attributes applied to them.
- get { return this._catalog.Parts.ToReadOnlyCollection(); }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AtomicComposition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AtomicComposition.cs deleted file mode 100644 index 4c027f73d3d..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AtomicComposition.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System;
-using System.Diagnostics;
-using System.Collections.Generic;
-using Microsoft.Internal;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// AtomicComposition provides lightweight atomicCompositional semantics to enable temporary
- /// state to be managed for a series of nested atomicCompositions. Each atomicComposition maintains
- /// queryable state along with a sequence of actions necessary to complete the state when
- /// the atomicComposition is no longer in danger of being rolled back. State is completed or
- /// rolled back when the atomicComposition is disposed, depending on the state of the
- /// CompleteOnDipose property which defaults to false. The using(...) pattern in C# is a
- /// convenient mechanism for defining atomicComposition scopes.
- ///
- /// The least obvious aspects of AtomicComposition deal with nesting.
- ///
- /// Firstly, no complete actions are actually performed until the outermost atomicComposition is
- /// completed. Completeting or rolling back nested atomicCompositions serves only to change which
- /// actions would be completed the outer atomicComposition.
- ///
- /// Secondly, state is added in the form of queries associated with an object key. The
- /// key represents a unique object the state is being held on behalf of. The quieries are
- /// accessed throught the Query methods which provide automatic chaining to execute queries
- /// across the target atomicComposition and its inner atomicComposition as appropriate.
- ///
- /// Lastly, when a nested atomicComposition is created for a given outer the outer atomicComposition is locked.
- /// It remains locked until the inner atomicComposition is disposed or completeed preventing the addition of
- /// state, actions or other inner atomicCompositions.
- /// </summary>
- public class AtomicComposition : IDisposable
- {
- private readonly AtomicComposition _outerAtomicComposition;
- private KeyValuePair<object, object>[] _values;
- private int _valueCount = 0;
- private List<Action> _completeActionList;
- private List<Action> _revertActionList;
- private bool _isDisposed = false;
- private bool _isCompleted = false;
- private bool _containsInnerAtomicComposition = false;
-
- public AtomicComposition()
- : this(null)
- {
- }
-
- public AtomicComposition(AtomicComposition outerAtomicComposition)
- {
- // Lock the inner atomicComposition so that we can assume nothing changes except on
- // the innermost scope, and thereby optimize the query path
- if (outerAtomicComposition != null)
- {
- this._outerAtomicComposition = outerAtomicComposition;
- this._outerAtomicComposition.ContainsInnerAtomicComposition = true;
- }
- }
-
- public void SetValue(object key, object value)
- {
- ThrowIfDisposed();
- ThrowIfCompleteed();
- ThrowIfContainsInnerAtomicComposition();
-
- Requires.NotNull(key, "key");
-
- SetValueInternal(key, value);
- }
-
- public bool TryGetValue<T>(object key, out T value)
- {
- return TryGetValue(key, false, out value);
- }
-
- [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")]
- public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value)
- {
- ThrowIfDisposed();
- ThrowIfCompleteed();
-
- Requires.NotNull(key, "key");
-
- return TryGetValueInternal(key, localAtomicCompositionOnly, out value);
- }
-
- public void AddCompleteAction(Action completeAction)
- {
- ThrowIfDisposed();
- ThrowIfCompleteed();
- ThrowIfContainsInnerAtomicComposition();
-
- Requires.NotNull(completeAction, "completeAction");
-
- if (this._completeActionList == null)
- {
- this._completeActionList = new List<Action>();
- }
- this._completeActionList.Add(completeAction);
- }
-
- public void AddRevertAction(Action revertAction)
- {
- ThrowIfDisposed();
- ThrowIfCompleteed();
- ThrowIfContainsInnerAtomicComposition();
-
- Requires.NotNull(revertAction, "revertAction");
-
- if (this._revertActionList == null)
- {
- this._revertActionList = new List<Action>();
- }
- this._revertActionList.Add(revertAction);
- }
-
- public void Complete()
- {
- ThrowIfDisposed();
- ThrowIfCompleteed();
-
- if (this._outerAtomicComposition == null)
- { // Execute all the complete actions
- FinalComplete();
- }
- else
- { // Copy the actions and state to the outer atomicComposition
- CopyComplete();
- }
-
- this._isCompleted = true;
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- ThrowIfDisposed();
- this._isDisposed = true;
-
- if (this._outerAtomicComposition != null)
- {
- this._outerAtomicComposition.ContainsInnerAtomicComposition = false;
- }
-
- // Revert is always immediate and involves forgetting information and
- // exceuting any appropriate revert actions
- if (!this._isCompleted)
- {
- if (this._revertActionList != null)
- {
- // Execute the revert actions in reverse order to ensure
- // everything incrementally rollsback its state.
- for (int i = this._revertActionList.Count - 1; i >= 0; i--)
- {
- Action action = this._revertActionList[i];
- action();
- }
- this._revertActionList = null;
- }
- }
- }
-
- private void FinalComplete()
- {
- // Completeting the outer most scope is easy, just execute all the actions
- if (this._completeActionList != null)
- {
- foreach (Action action in this._completeActionList)
- {
- action();
- }
- this._completeActionList = null;
- }
- }
-
- private void CopyComplete()
- {
- Assumes.NotNull(this._outerAtomicComposition);
-
- this._outerAtomicComposition.ContainsInnerAtomicComposition = false;
-
- // Inner scopes are much odder, because completeting them means coalescing them into the
- // outer scope - the complete or revert actions are deferred until the outermost scope completes
- // or any intermediate rolls back
- if (this._completeActionList != null)
- {
- foreach (Action action in this._completeActionList)
- {
- this._outerAtomicComposition.AddCompleteAction(action);
- }
- }
-
- if (this._revertActionList != null)
- {
- foreach (Action action in this._revertActionList)
- {
- this._outerAtomicComposition.AddRevertAction(action);
- }
- }
-
- // We can copy over existing atomicComposition entries because they're either already chained or
- // overwrite by design and can now be completed or rolled back together
- for (var index = 0; index < this._valueCount; index++)
- {
- this._outerAtomicComposition.SetValueInternal(
- this._values[index].Key, this._values[index].Value);
- }
- }
-
- private bool ContainsInnerAtomicComposition
- {
- set
- {
- if (value == true && this._containsInnerAtomicComposition == true)
- {
- throw new InvalidOperationException(Strings.AtomicComposition_AlreadyNested);
- }
- this._containsInnerAtomicComposition = value;
- }
- }
-
- private bool TryGetValueInternal<T>(object key, bool localAtomicCompositionOnly, out T value)
- {
- for (var index = 0; index < this._valueCount; index++)
- {
- if (this._values[index].Key == key)
- {
- value = (T)this._values[index].Value;
- return true;
- }
- }
-
- // If there's no atomicComposition available then recurse until we hit the outermost
- // scope, where upon we go ahead and return null
- if (!localAtomicCompositionOnly && this._outerAtomicComposition != null)
- {
- return this._outerAtomicComposition.TryGetValueInternal<T>(key, localAtomicCompositionOnly, out value);
- }
-
- value = default(T);
- return false;
- }
-
- private void SetValueInternal(object key, object value)
- {
- // Handle overwrites quickly
- for (var index = 0; index < this._valueCount; index++)
- {
- if (this._values[index].Key == key)
- {
- this._values[index] = new KeyValuePair<object,object>(key, value);
- return;
- }
- }
-
- // Expand storage when needed
- if (this._values == null || this._valueCount == this._values.Length)
- {
- var newQueries = new KeyValuePair<object, object>[this._valueCount == 0 ? 5 : this._valueCount * 2];
- if (this._values != null)
- {
- Array.Copy(this._values, newQueries, this._valueCount);
- }
- this._values = newQueries;
- }
-
- // Store a new entry
- this._values[_valueCount] = new KeyValuePair<object, object>(key, value);
- this._valueCount++;
- return;
- }
-
- [DebuggerStepThrough]
- private void ThrowIfContainsInnerAtomicComposition()
- {
- if (this._containsInnerAtomicComposition)
- {
- throw new InvalidOperationException(Strings.AtomicComposition_PartOfAnotherAtomicComposition);
- }
- }
-
- [DebuggerStepThrough]
- private void ThrowIfCompleteed()
- {
- if (this._isCompleted)
- {
- throw new InvalidOperationException(Strings.AtomicComposition_AlreadyCompleted);
- }
- }
-
- [DebuggerStepThrough]
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs deleted file mode 100644 index 5756a0f9fab..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System;
-using System.Diagnostics;
-using System.Collections.Generic;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- internal static class AtomicCompositionExtensions
- {
- internal static T GetValueAllowNull<T>(this AtomicComposition atomicComposition, T defaultResultAndKey) where T : class
- {
- Assumes.NotNull(defaultResultAndKey);
-
- return GetValueAllowNull<T>(atomicComposition, defaultResultAndKey, defaultResultAndKey);
- }
-
- internal static T GetValueAllowNull<T>(this AtomicComposition atomicComposition, object key, T defaultResult)
- {
- T result;
- if (atomicComposition != null && atomicComposition.TryGetValue(key, out result))
- {
- return result;
- }
-
- return defaultResult;
- }
-
- internal static void AddRevertActionAllowNull(this AtomicComposition atomicComposition, Action action)
- {
- Assumes.NotNull(action);
-
- if (atomicComposition == null)
- {
- action();
- }
- else
- {
- atomicComposition.AddRevertAction(action);
- }
- }
-
- internal static void AddCompleteActionAllowNull(this AtomicComposition atomicComposition, Action action)
- {
- Assumes.NotNull(action);
-
- if (atomicComposition == null)
- {
- action();
- }
- else
- {
- atomicComposition.AddCompleteAction(action);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogChangeProxy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogChangeProxy.cs deleted file mode 100644 index d78db6d055b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogChangeProxy.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class CatalogExportProvider : ExportProvider, IDisposable
- {
- private class CatalogChangeProxy : ComposablePartCatalog
- {
- private ComposablePartCatalog _originalCatalog;
- private List<ComposablePartDefinition> _addedParts;
- private HashSet<ComposablePartDefinition> _removedParts;
-
- public CatalogChangeProxy(ComposablePartCatalog originalCatalog,
- IEnumerable<ComposablePartDefinition> addedParts,
- IEnumerable<ComposablePartDefinition> removedParts)
- {
- this._originalCatalog = originalCatalog;
- this._addedParts = new List<ComposablePartDefinition>(addedParts);
- this._removedParts = new HashSet<ComposablePartDefinition>(removedParts);
- }
-
- public override IQueryable<ComposablePartDefinition> Parts
- {
- get
- {
- return this._originalCatalog.Parts.Concat(this._addedParts).Except(this._removedParts);
- }
- }
-
- public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(
- ImportDefinition definition)
- {
- Requires.NotNull(definition, "definition");
-
- var originalExports = this._originalCatalog.GetExports(definition);
- var trimmedExports = originalExports.Where(partAndExport =>
- !this._removedParts.Contains(partAndExport.Item1));
-
- var addedExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
- foreach (var part in this._addedParts)
- {
- foreach (var export in part.ExportDefinitions)
- {
- if (definition.IsConstraintSatisfiedBy(export))
- {
- addedExports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(part, export));
- }
- }
- }
- return trimmedExports.Concat(addedExports);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs deleted file mode 100644 index 0741cf3f4f5..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs +++ /dev/null @@ -1,132 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class CatalogExportProvider
- {
- private class CatalogExport : Export
- {
- protected readonly CatalogExportProvider _catalogExportProvider;
- protected readonly ComposablePartDefinition _partDefinition;
- protected readonly ExportDefinition _definition;
- protected ComposablePart _part;
-
- public CatalogExport(CatalogExportProvider catalogExportProvider,
- ComposablePartDefinition partDefinition, ExportDefinition definition)
- {
- this._catalogExportProvider = catalogExportProvider;
- this._partDefinition = partDefinition;
- this._definition = definition;
- }
-
- public override ExportDefinition Definition
- {
- get
- {
- return this._definition;
- }
- }
-
- protected virtual bool IsSharedPart
- {
- get
- {
- return true;
- }
- }
-
- protected override object GetExportedValueCore()
- {
- ComposablePart part = this._catalogExportProvider.GetComposablePart(this._partDefinition, this.IsSharedPart);
- object exportedValue = this._catalogExportProvider.GetExportedValue(part, this._definition, this.IsSharedPart);
- this._part = part;
-
- return exportedValue;
- }
-
- [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- public static CatalogExport CreateExport(CatalogExportProvider catalogExportProvider,
- ComposablePartDefinition partDefinition, ExportDefinition definition, CreationPolicy importCreationPolicy)
- {
- CreationPolicy partPolicy = partDefinition.Metadata.GetValue<CreationPolicy>(CompositionConstants.PartCreationPolicyMetadataName);
- bool isSharedPart = ShouldUseSharedPart(partPolicy, importCreationPolicy);
-
- if (isSharedPart)
- {
- return new CatalogExport(catalogExportProvider, partDefinition, definition);
- }
- else
- {
- return new NonSharedCatalogExport(catalogExportProvider, partDefinition, definition);
- }
- }
-
- 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;
- }
- }
- }
- }
-
- private sealed class NonSharedCatalogExport : CatalogExport, IDisposable
- {
- public NonSharedCatalogExport(CatalogExportProvider catalogExportProvider,
- ComposablePartDefinition partDefinition, ExportDefinition definition)
- : base(catalogExportProvider, partDefinition, definition)
- {
- }
-
- protected override bool IsSharedPart
- {
- get
- {
- return false;
- }
- }
-
- void IDisposable.Dispose()
- {
- if (this._part != null)
- {
- this._catalogExportProvider.ReleasePart(this.Value, this._part, null);
- this._part = null;
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.PartCreatorExport.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.PartCreatorExport.cs deleted file mode 100644 index 14d4a42d137..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.PartCreatorExport.cs +++ /dev/null @@ -1,132 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Linq;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class CatalogExportProvider
- {
- internal class PartCreatorExport : Export
- {
- private readonly CatalogExportProvider _catalogExportProvider;
- private readonly ComposablePartDefinition _partDefinition;
- private readonly ExportDefinition _exportDefinition;
- private ExportDefinition _partCreatorExportDefinition;
- private PartCreatorPartDefinition _partCreatorPartDefinition;
-
- public PartCreatorExport(CatalogExportProvider catalogExportProvider, ComposablePartDefinition partDefinition, ExportDefinition exportDefinition)
- {
- this._catalogExportProvider = catalogExportProvider;
- this._partDefinition = partDefinition;
- this._exportDefinition = exportDefinition;
- this._partCreatorExportDefinition = new PartCreatorExportDefinition(this._exportDefinition);
- }
-
- public override ExportDefinition Definition
- {
- get { return this._partCreatorExportDefinition; }
- }
-
- protected override object GetExportedValueCore()
- {
- if (this._partCreatorPartDefinition == null)
- {
- this._partCreatorPartDefinition = new PartCreatorPartDefinition(this);
- }
- return this._partCreatorPartDefinition;
- }
-
- public Export CreateExportProduct()
- {
- return new NonSharedCatalogExport(this._catalogExportProvider, this._partDefinition, this._exportDefinition);
- }
-
- private class PartCreatorPartDefinition : ComposablePartDefinition
- {
- private readonly PartCreatorExport _partCreatorExport;
-
- public PartCreatorPartDefinition(PartCreatorExport partCreatorExport)
- {
- this._partCreatorExport = partCreatorExport;
- }
-
- public override IEnumerable<ExportDefinition> ExportDefinitions
- {
- get { return new ExportDefinition[] { this._partCreatorExport.Definition }; }
- }
-
- public override IEnumerable<ImportDefinition> ImportDefinitions
- {
- get { return Enumerable.Empty<ImportDefinition>(); }
- }
-
- public ExportDefinition PartCreatorExportDefinition
- {
- get { return this._partCreatorExport.Definition; }
- }
-
- public Export CreateProductExport()
- {
- return this._partCreatorExport.CreateExportProduct();
- }
-
- public override ComposablePart CreatePart()
- {
- return new PartCreatorPart(this);
- }
- }
-
- private sealed class PartCreatorPart : ComposablePart, IDisposable
- {
- private readonly PartCreatorPartDefinition _definition;
- private readonly Export _export;
-
- public PartCreatorPart(PartCreatorPartDefinition definition)
- {
- this._definition = definition;
- this._export = definition.CreateProductExport();
- }
-
- public override IEnumerable<ExportDefinition> ExportDefinitions
- {
- get { return this._definition.ExportDefinitions; }
- }
-
- public override IEnumerable<ImportDefinition> ImportDefinitions
- {
- get { return this._definition.ImportDefinitions; }
- }
-
- public override object GetExportedValue(ExportDefinition definition)
- {
- if (definition != this._definition.PartCreatorExportDefinition)
- {
- throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart("definition");
- }
-
- return this._export.Value;
- }
-
- public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports)
- {
- throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart("definition");
- }
-
- public void Dispose()
- {
- IDisposable disposable = this._export as IDisposable;
-
- if (disposable != null)
- {
- disposable.Dispose();
- }
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs deleted file mode 100644 index 5c00b5a004f..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs +++ /dev/null @@ -1,816 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Diagnostics;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class CatalogExportProvider : ExportProvider, IDisposable
- {
- private readonly CompositionLock _lock;
- private Dictionary<ComposablePartDefinition, ComposablePart> _activatedParts = new Dictionary<ComposablePartDefinition, ComposablePart>();
- private HashSet<ComposablePartDefinition> _rejectedParts = new HashSet<ComposablePartDefinition>();
- private ConditionalWeakTable<object, List<ComposablePart>> _conditionalReferencesForRecomposableParts = new ConditionalWeakTable<object, List<ComposablePart>>();
- private HashSet<IDisposable> _partsToDispose = new HashSet<IDisposable>();
- private ComposablePartCatalog _catalog;
- private volatile bool _isDisposed = false;
- private volatile bool _isRunning = false;
- private ExportProvider _sourceProvider;
- private ImportEngine _importEngine;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CatalogExportProvider"/> class.
- /// </summary>
- /// <param name="catalog">
- /// The <see cref="ComposablePartCatalog"/> that the <see cref="CatalogExportProvider"/>
- /// uses to produce <see cref="Export"/> objects.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="catalog"/> is <see langword="null"/>.
- /// </exception>
- public CatalogExportProvider(ComposablePartCatalog catalog)
- : this(catalog, false)
- {
- }
-
- public CatalogExportProvider(ComposablePartCatalog catalog, bool isThreadSafe)
- {
- Requires.NotNull(catalog, "catalog");
-
- this._catalog = catalog;
-
- var notifyCatalogChanged = this._catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalogChanged != null)
- {
- notifyCatalogChanged.Changing += this.OnCatalogChanging;
- }
-
- this._lock = new CompositionLock(isThreadSafe);
- }
-
- /// <summary>
- /// Gets the composable part catalog that the provider users to
- /// produce exports.
- /// </summary>
- /// <value>
- /// The <see cref="ComposablePartCatalog"/> that the
- /// <see cref="CatalogExportProvider"/>
- /// uses to produce <see cref="Export"/> objects.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public ComposablePartCatalog Catalog
- {
- get
- {
- ThrowIfDisposed();
-
- return this._catalog;
- }
- }
-
- /// <summary>
- /// Gets the export provider which provides the provider access to additional
- /// exports.
- /// </summary>
- /// <value>
- /// The <see cref="ExportProvider"/> which provides the
- /// <see cref="CatalogExportProvider"/> access to additional
- /// <see cref="Export"/> objects. The default is <see langword="null"/>.
- /// </value>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="value"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// This property has already been set.
- /// <para>
- /// -or-
- /// </para>
- /// The methods on the <see cref="CatalogExportProvider"/>
- /// have already been accessed.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CatalogExportProvider"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// This property must be set before accessing any methods on the
- /// <see cref="CatalogExportProvider"/>.
- /// </remarks>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="EnsureCanSet ensures that the property is set only once, Dispose is not required")]
- public ExportProvider SourceProvider
- {
- get
- {
- this.ThrowIfDisposed();
- using (this._lock.LockStateForRead())
- {
- return this._sourceProvider;
- }
- }
- set
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(value, "value");
-
- ImportEngine newImportEngine = null;
- bool isThrowing = true;
- try
- {
- newImportEngine = new ImportEngine(value, this._lock.IsThreadSafe);
- value.ExportsChanging += this.OnExportsChangingInternal;
-
- using (this._lock.LockStateForWrite())
- {
- this.EnsureCanSet(this._sourceProvider);
-
- this._sourceProvider = value;
- this._importEngine = newImportEngine;
-
- isThrowing = false;
- }
- }
- finally
- {
- if (isThrowing)
- {
- value.ExportsChanging -= this.OnExportsChangingInternal;
- newImportEngine.Dispose();
- }
- }
- }
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (!this._isDisposed)
- {
- bool disposeLock = false;
- INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
- HashSet<IDisposable> partsToDispose = null;
- ExportProvider sourceProviderToUnsubscribeFrom = null;
- ImportEngine importEngineToDispose = null;
-
- try
- {
- using (this._lock.LockStateForWrite())
- {
- if (!this._isDisposed)
- {
- catalogToUnsubscribeFrom = this._catalog as INotifyComposablePartCatalogChanged;
- this._catalog = null;
-
- sourceProviderToUnsubscribeFrom = this._sourceProvider;
- this._sourceProvider = null;
-
- importEngineToDispose = this._importEngine;
- this._importEngine = null;
-
- partsToDispose = this._partsToDispose;
- this._partsToDispose = new HashSet<IDisposable>();
- this._activatedParts.Clear();
- this._conditionalReferencesForRecomposableParts = null;
-
- disposeLock = true;
- this._isDisposed = true;
- }
- }
- }
- finally
- {
- if (catalogToUnsubscribeFrom != null)
- {
- catalogToUnsubscribeFrom.Changing -= this.OnCatalogChanging;
- }
-
- if (sourceProviderToUnsubscribeFrom != null)
- {
- sourceProviderToUnsubscribeFrom.ExportsChanging -= this.OnExportsChangingInternal;
- }
-
- if (importEngineToDispose != null)
- {
- importEngineToDispose.Dispose();
- }
-
- if (partsToDispose != null)
- {
- foreach (var part in partsToDispose)
- {
- part.Dispose();
- }
- }
-
- if (disposeLock)
- {
- this._lock.Dispose();
- }
- }
- }
- }
- }
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> to get.</param>
- /// <returns></returns>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <remarks>
- /// <note type="inheritinfo">
- /// The implementers should not treat the cardinality-related mismatches as errors, and are not
- /// expected to throw exceptions in those cases.
- /// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
- /// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
- /// </note>
- /// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- // Use the version of the catalog appropriate to this atomicComposition
- ComposablePartCatalog currentCatalog = atomicComposition.GetValueAllowNull(this._catalog);
-
- IPartCreatorImportDefinition partCreatorDefinition = definition as IPartCreatorImportDefinition;
- bool isPartCreator = false;
-
- if (partCreatorDefinition != null)
- {
- definition = partCreatorDefinition.ProductImportDefinition;
- isPartCreator = true;
- }
-
- CreationPolicy importPolicy = definition.GetRequiredCreationPolicy();
-
- List<Export> exports = new List<Export>();
- foreach (var partDefinitionAndExportDefinition in currentCatalog.GetExports(definition))
- {
- if (!IsRejected(partDefinitionAndExportDefinition.Item1, atomicComposition))
- {
- if (isPartCreator)
- {
- exports.Add(new PartCreatorExport(this,
- partDefinitionAndExportDefinition.Item1,
- partDefinitionAndExportDefinition.Item2));
- }
- else
- {
- exports.Add(CatalogExport.CreateExport(this,
- partDefinitionAndExportDefinition.Item1,
- partDefinitionAndExportDefinition.Item2,
- importPolicy));
- }
- }
- }
-
- return exports;
- }
-
- private void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
- {
- UpdateRejections(e.AddedExports.Concat(e.RemovedExports), e.AtomicComposition);
- }
-
- private static ExportDefinition[] GetExportsFromPartDefinitions(IEnumerable<ComposablePartDefinition> partDefinitions)
- {
- List<ExportDefinition> exports = new List<ExportDefinition>();
-
- foreach (var partDefinition in partDefinitions)
- {
- foreach (var export in partDefinition.ExportDefinitions)
- {
- exports.Add(export);
-
- // While creating a PartCreatorExportDefinition for every changed definition may not be the most
- // efficient way to do this the PartCreatorExportDefinition is very efficient and doesn't do any
- // real work unless its metadata is pulled on. If this turns out to be a bottleneck then we
- // will need to start tracking all the PartCreator's we hand out and only send those which we
- // have handed out. In fact we could do the same thing for all the Exports if we wished but
- // that requires a cache management which we don't want to do at this point.
- exports.Add(new PartCreatorExportDefinition(export));
- }
- }
-
- return exports.ToArray();
- }
-
- [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
- {
- using (var atomicComposition = new AtomicComposition(e.AtomicComposition))
- {
- // Save the preview catalog to use in place of the original while handling
- // this event
- atomicComposition.SetValue(this._catalog,
- new CatalogChangeProxy(this._catalog, e.AddedDefinitions, e.RemovedDefinitions));
-
- IEnumerable<ExportDefinition> addedExports = GetExportsFromPartDefinitions(e.AddedDefinitions);
- IEnumerable<ExportDefinition> removedExports = GetExportsFromPartDefinitions(e.RemovedDefinitions);
-
- // Remove any parts based on eliminated definitions (in a atomicComposition-friendly
- // fashion)
- foreach (var definition in e.RemovedDefinitions)
- {
- ComposablePart removedPart = null;
- bool removed = false;
-
- using (this._lock.LockStateForRead())
- {
- removed = this._activatedParts.TryGetValue(definition, out removedPart);
- }
- if (removed)
- {
- var capturedDefinition = definition;
- ReleasePart(null, removedPart, atomicComposition);
- atomicComposition.AddCompleteActionAllowNull(() =>
- {
- using (this._lock.LockStateForWrite())
- {
- this._activatedParts.Remove(capturedDefinition);
- }
- });
- }
- }
-
- UpdateRejections(addedExports.ConcatAllowingNull(removedExports), atomicComposition);
-
- this.OnExportsChanging(
- new ExportsChangeEventArgs(addedExports, removedExports, atomicComposition));
-
- atomicComposition.AddCompleteAction(() => this.OnExportsChanged(
- new ExportsChangeEventArgs(addedExports, removedExports, null)));
-
- atomicComposition.Complete();
- }
- }
-
- private ComposablePart GetComposablePart(ComposablePartDefinition partDefinition, bool isSharedPart)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- ComposablePart part;
-
- if (isSharedPart)
- {
- part = GetSharedPart(partDefinition);
- }
- else
- {
- part = partDefinition.CreatePart();
-
- IDisposable disposablePart = part as IDisposable;
- if (disposablePart != null)
- {
- using (this._lock.LockStateForWrite())
- {
- this._partsToDispose.Add(disposablePart);
- }
- }
- }
-
- return part;
- }
-
- private ComposablePart GetSharedPart(ComposablePartDefinition partDefinition)
- {
- ComposablePart part;
- bool found = false;
-
- using (this._lock.LockStateForRead())
- {
- found = this._activatedParts.TryGetValue(partDefinition, out part);
- }
-
- if (!found)
- {
- ComposablePart newPart = partDefinition.CreatePart();
-
- using (this._lock.LockStateForWrite())
- {
- found = this._activatedParts.TryGetValue(partDefinition, out part);
-
- if (!found)
- {
- part = newPart;
- this._activatedParts.Add(partDefinition, part);
- IDisposable disposablePart = part as IDisposable;
- if (disposablePart != null)
- {
- this._partsToDispose.Add(disposablePart);
- }
- }
- }
- }
-
- return part;
- }
-
- private object GetExportedValue(ComposablePart part, ExportDefinition export, bool isSharedPart)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- Assumes.NotNull(part, export);
-
- object exportedValue = CompositionServices.GetExportedValueFromComposedPart(
- this._importEngine, part, export);
-
- // Only hold conditional references for recomposable non-shared parts because we are
- // already holding strong references to the shared parts.
- if (exportedValue != null && !isSharedPart && part.IsRecomposable())
- {
- SetConditionalReferenceForRecomposablePart(exportedValue, part);
- }
-
- return exportedValue;
- }
-
- private void ReleasePart(object exportedValue, ComposablePart part, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- Assumes.NotNull(part);
-
- this._importEngine.ReleaseImports(part, atomicComposition);
-
- if (exportedValue != null)
- {
- atomicComposition.AddCompleteActionAllowNull(() =>
- {
- using (this._lock.LockStateForWrite())
- {
- this._conditionalReferencesForRecomposableParts.Remove(exportedValue);
- }
- });
- }
-
- IDisposable diposablePart = part as IDisposable;
- if (diposablePart != null)
- {
- atomicComposition.AddCompleteActionAllowNull(() =>
- {
- bool removed = false;
- using (this._lock.LockStateForWrite())
- {
- removed = this._partsToDispose.Remove(diposablePart);
- }
- if (removed)
- {
- diposablePart.Dispose();
- }
- });
- }
- }
-
- private void SetConditionalReferenceForRecomposablePart(object exportedValue, ComposablePart part)
- {
- Assumes.NotNull(exportedValue, part);
-
- List<ComposablePart> partList;
-
- using (this._lock.LockStateForWrite())
- {
- if (!this._conditionalReferencesForRecomposableParts.TryGetValue(exportedValue, out partList))
- {
- partList = new List<ComposablePart>();
- this._conditionalReferencesForRecomposableParts.Add(exportedValue, partList);
- }
-
- // There is one really obscure case (one part exporting exact value multiple times) where
- // the part may already be in the list but it isn't a scenario that is interesting so
- // we simply always add. Later if we change this to support more than non-shared we may
- // need to check if the part already exists to pervent adding it multiple times.
- partList.Add(part);
- }
- }
-
- 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 (this._lock.LockStateForRead())
- {
- 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);
- }
-
- private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition parentAtomicComposition)
- {
- ChangeRejectedException exception = null;
-
- using (var localAtomicComposition = new AtomicComposition(parentAtomicComposition))
- {
- // The part definition we're currently working on is treated optimistically
- // as if we know it hasn't been rejected. This handles recursion, and if we
- // later decide that it has been rejected we'll discard all nested progress so
- // all side-effects of the mistake are erased.
- //
- // Note that this means that recursive failures that would be detected by the
- // import engine are not discovered by rejection currently. Loops among
- // prerequisites, runaway import chains involving factories, and prerequisites
- // that cannot be fully satisfied still result in runtime errors. Doing
- // otherwise would be possible but potentially expensive - and could be a v2
- // improvement if deemed worthwhile.
- UpdateAtomicCompositionQuery(localAtomicComposition,
- def => definition.Equals(def), AtomicCompositionQueryState.TreatAsValidated);
-
- var newPart = definition.CreatePart();
- try
- {
- this._importEngine.PreviewImports(newPart, localAtomicComposition);
-
- // Reuse the partially-fleshed out part the next time we need a shared
- // instance to keep the expense of pre-validation to a minimum. Note that
- // _activatedParts holds references to both shared and non-shared parts.
- // The non-shared parts will only be used for rejection purposes only but
- // the shared parts will be handed out when requested via GetExports as
- // well as be used for rejection purposes.
- localAtomicComposition.AddCompleteActionAllowNull(() =>
- {
- using (this._lock.LockStateForWrite())
- {
- if (!this._activatedParts.ContainsKey(definition))
- {
- this._activatedParts.Add(definition, newPart);
- IDisposable newDisposablePart = newPart as IDisposable;
- if (newDisposablePart != null)
- {
- this._partsToDispose.Add(newDisposablePart);
- }
- }
- }
- });
-
- // Success! Complete any recursive work that was conditioned on this part's validation
- localAtomicComposition.Complete();
-
- return false;
- }
- catch (ChangeRejectedException ex)
- {
- exception = ex;
- }
- }
-
- // If we've reached this point then this part has been rejected so we need to
- // record the rejection in our parent composition or execute it immediately if
- // one doesn't exist.
- parentAtomicComposition.AddCompleteActionAllowNull(() =>
- {
- using (this._lock.LockStateForWrite())
- {
- this._rejectedParts.Add(definition);
- }
-
- CompositionTrace.PartDefinitionRejected(definition, exception);
-
- });
- if (parentAtomicComposition != null)
- {
- UpdateAtomicCompositionQuery(parentAtomicComposition,
- def => definition.Equals(def), AtomicCompositionQueryState.TreatAsRejected);
- }
-
- return true;
- }
-
- private void UpdateRejections(IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
- {
- using (var localAtomicComposition = new AtomicComposition(atomicComposition))
- {
- // Reconsider every part definition that has been previously
- // rejected to see if any of them can be added back.
- var affectedRejections = new HashSet<ComposablePartDefinition>();
- var atomicCompositionQuery = GetAtomicCompositionQuery(localAtomicComposition);
-
- ComposablePartDefinition[] rejectedParts;
- using (this._lock.LockStateForRead())
- {
- rejectedParts = this._rejectedParts.ToArray();
- }
- foreach (var definition in rejectedParts)
- {
- if (atomicCompositionQuery(definition) == AtomicCompositionQueryState.TreatAsValidated)
- {
- continue;
- }
-
- foreach (var import in definition.ImportDefinitions.Where(ImportEngine.IsRequiredImportForPreview))
- {
- if (changedExports.Any(export => import.IsConstraintSatisfiedBy(export)))
- {
- affectedRejections.Add(definition);
- break;
- }
- }
- }
- UpdateAtomicCompositionQuery(localAtomicComposition,
- def => affectedRejections.Contains(def), AtomicCompositionQueryState.NeedsTesting);
-
- // Determine if any of the resurrectable parts is now available so that we can
- // notify listeners of the exact changes to exports
- var resurrectedExports = new List<ExportDefinition>();
-
- foreach (var partDefinition in affectedRejections)
- {
- if (!IsRejected(partDefinition, localAtomicComposition))
- {
- // Notify listeners of the newly available exports and
- // prepare to remove the rejected part from the list of rejections
- resurrectedExports.AddRange(partDefinition.ExportDefinitions);
-
- // Capture the local so that the closure below refers to the current definition
- // in the loop and not the value of 'partDefinition' when the closure executes
- var capturedPartDefinition = partDefinition;
- localAtomicComposition.AddCompleteAction(() =>
- {
- using (this._lock.LockStateForWrite())
- {
- this._rejectedParts.Remove(capturedPartDefinition);
- }
-
- CompositionTrace.PartDefinitionResurrected(capturedPartDefinition);
- });
- }
- }
-
- // Notify anyone sourcing exports that the resurrected exports have appeared
- if (resurrectedExports.Any())
- {
- this.OnExportsChanging(
- new ExportsChangeEventArgs(resurrectedExports, new ExportDefinition[0], localAtomicComposition));
-
- localAtomicComposition.AddCompleteAction(() => this.OnExportsChanged(
- new ExportsChangeEventArgs(resurrectedExports, new ExportDefinition[0], null)));
- }
-
- localAtomicComposition.Complete();
- }
- }
-
- [DebuggerStepThrough]
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
-
- /// <summary>
- /// EnsureCanRun must be called from within a lock.
- /// </summary>
- [DebuggerStepThrough]
- private void EnsureCanRun()
- {
- if ((this._sourceProvider == null) || (this._importEngine == null))
- {
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
- }
- }
-
- [DebuggerStepThrough]
- private void EnsureRunning()
- {
- if (!this._isRunning)
- {
- using (this._lock.LockStateForWrite())
- {
- if (!this._isRunning)
- {
- this.EnsureCanRun();
- this._isRunning = true;
- }
- }
- }
- }
-
- /// <summary>
- /// EnsureCanSet<T> must be called from within a lock.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="currentValue"></param>
- [DebuggerStepThrough]
- private void EnsureCanSet<T>(T currentValue)
- where T : class
- {
- if ((this._isRunning) || (currentValue != null))
- {
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ObjectAlreadyInitialized));
- }
- }
-
- private Func<ComposablePartDefinition, AtomicCompositionQueryState> GetAtomicCompositionQuery(AtomicComposition atomicComposition)
- {
- Func<ComposablePartDefinition, AtomicCompositionQueryState> atomicCompositionQuery;
- atomicComposition.TryGetValue(this, out atomicCompositionQuery);
-
- if (atomicCompositionQuery == null)
- {
- return (definition) => AtomicCompositionQueryState.Unknown;
- }
-
- return atomicCompositionQuery;
- }
-
- private void UpdateAtomicCompositionQuery(
- AtomicComposition atomicComposition,
- Func<ComposablePartDefinition, bool> query,
- AtomicCompositionQueryState state)
- {
- var parentQuery = GetAtomicCompositionQuery(atomicComposition);
- Func<ComposablePartDefinition, AtomicCompositionQueryState> newQuery = definition =>
- {
- if (query(definition))
- {
- return state;
- }
- return parentQuery(definition);
- };
-
- atomicComposition.SetValue(this, newQuery);
- }
-
- private enum AtomicCompositionQueryState
- {
- Unknown,
- TreatAsRejected,
- TreatAsValidated,
- NeedsTesting
- };
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs deleted file mode 100644 index bbb20feaf4e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// Provides data for the <see cref="INotifyComposablePartCatalogChanged.Changed"/> and
- /// <see cref="INotifyComposablePartCatalogChanged.Changing"/> events.
- /// </summary>
- public class ComposablePartCatalogChangeEventArgs : EventArgs
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartCatalogChangeEventArgs"/>.
- /// </summary>
- /// <param name="addedDefinitions">
- /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that
- /// are being added to the <see cref="ComposablePartCatalog"/>.
- /// </param>
- /// <param name="removedDefinitions">
- /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that
- /// are being removed from the <see cref="ComposablePartCatalog"/>.
- /// </param>
- /// <param name="atomicComposition">
- /// A <see cref="AtomicComposition"/> representing all tentative changes that will
- /// be completed if the change is successful, or discarded if it is not.
- /// <see langword="null"/> if being applied outside a <see cref="AtomicComposition"/>
- /// or during a <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="addedDefinitions"/> or <paramref name="removedDefinitions"/> is <see langword="null"/>.
- /// </exception>
- public ComposablePartCatalogChangeEventArgs(IEnumerable<ComposablePartDefinition> addedDefinitions,
- IEnumerable<ComposablePartDefinition> removedDefinitions, AtomicComposition atomicComposition)
- {
- Requires.NotNull(addedDefinitions, "addedDefinitions");
- Requires.NotNull(removedDefinitions, "removedDefinitions");
-
- this.AddedDefinitions = addedDefinitions.AsArray();
- this.RemovedDefinitions = removedDefinitions.AsArray();
- this.AtomicComposition = atomicComposition;
- }
-
- /// <summary>
- /// Gets the identifiers of the parts that have been added.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that
- /// have been added to the <see cref="ComposablePartCatalog"/>.
- /// </value>
- public IEnumerable<ComposablePartDefinition> AddedDefinitions { get; private set; }
-
- /// <summary>
- /// Gets the identifiers of the parts that have been removed.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that
- /// have been removed from from the <see cref="ComposablePartCatalog"/>.
- /// </value>
- public IEnumerable<ComposablePartDefinition> RemovedDefinitions { get; private set; }
-
- /// <summary>
- /// Gets the atomicComposition, if any, that this change applies to.
- /// </summary>
- /// <value>
- /// A <see cref="AtomicComposition"/> that this set of changes applies too.
- /// It can be <see langword="null"/> if the changes are being applied outside a
- /// <see cref="AtomicComposition"/> or during a
- /// <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
- ///
- /// When the value is non-null it should be used to record temporary changed state
- /// and actions that will be executed when the atomicComposition is completeed.
- /// </value>
- public AtomicComposition AtomicComposition { get; private set; }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs deleted file mode 100644 index 466ab688872..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs +++ /dev/null @@ -1,420 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.ObjectModel;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Diagnostics;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// This class implements a threadsafe ICollection{T} of ComposablePartCatalog.
- /// It is exposed as an ICollection(ComposablePartCatalog)
- /// It is threadsafe, notifications are not marshalled using a SynchronizationContext.
- /// It is Disposable.
- /// </summary>
- internal class ComposablePartCatalogCollection : ICollection<ComposablePartCatalog>, INotifyComposablePartCatalogChanged, IDisposable
- {
- private readonly Lock _lock = new Lock();
- private Action<ComposablePartCatalogChangeEventArgs> _onChanged;
- private Action<ComposablePartCatalogChangeEventArgs> _onChanging;
- private List<ComposablePartCatalog> _catalogs = new List<ComposablePartCatalog>();
- private volatile bool _isCopyNeeded = false;
- private volatile bool _isDisposed = false;
- private bool _hasChanged = false;
-
- public ComposablePartCatalogCollection(IEnumerable<ComposablePartCatalog> catalogs)
- : this(catalogs, null, null)
- {
- }
-
- public ComposablePartCatalogCollection(
- IEnumerable<ComposablePartCatalog> catalogs,
- Action<ComposablePartCatalogChangeEventArgs> onChanged,
- Action<ComposablePartCatalogChangeEventArgs> onChanging)
- {
- catalogs = catalogs ?? Enumerable.Empty<ComposablePartCatalog>();
- this._catalogs = new List<ComposablePartCatalog>(catalogs);
- this._onChanged = onChanged;
- this._onChanging = onChanging;
-
- SubscribeToCatalogNotifications(catalogs);
- }
-
- public void Add(ComposablePartCatalog item)
- {
- Requires.NotNull(item, "item");
-
- this.ThrowIfDisposed();
-
- var addedParts = new Lazy<IEnumerable<ComposablePartDefinition>>(() => item.Parts.ToArray(), false);
-
- using (var atomicComposition = new AtomicComposition())
- {
- this.RaiseChangingEvent(addedParts, null, atomicComposition);
-
- using (new WriteLock(this._lock))
- {
- if (this._isCopyNeeded)
- {
- this._catalogs = new List<ComposablePartCatalog>(this._catalogs);
- this._isCopyNeeded = false;
- }
- this._hasChanged = true;
- this._catalogs.Add(item);
- }
-
- this.SubscribeToCatalogNotifications(item);
-
- // Complete after the catalog changes are written
- atomicComposition.Complete();
- }
-
- this.RaiseChangedEvent(addedParts, null);
- }
-
- /// <summary>
- /// Notify when the contents of the Catalog has changed.
- /// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
-
- /// <summary>
- /// Notify when the contents of the Catalog has changing.
- /// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
-
- public void Clear()
- {
- this.ThrowIfDisposed();
-
- // No action is required if we are already empty
- ComposablePartCatalog[] catalogs = null;
- using (new ReadLock(this._lock))
- {
- if (this._catalogs.Count == 0)
- {
- return;
- }
- catalogs = this._catalogs.ToArray();
- }
-
- //TODO-MT: This is pretty suspect - we can easily eliminate catalogs that aren't listed as being
- // removed. Then again, the idea of trying to mutate the catalog on two threads at the same time is pretty
- // suspect to begin with. When would that ever result in a meaningful composition?
-
- // We are doing this outside of the lock, so it's possible that the catalog will continute propagating events from things
- // we are about to unsubscribe from. Given the non-specificity of our event, in the worst case scenario we would simply fire
- // unnecessary events.
-
- var removedParts = new Lazy<IEnumerable<ComposablePartDefinition>>(() => catalogs.SelectMany(catalog => catalog.Parts).ToArray(), false);
-
- // Validate the changes before applying them
- using (var atomicComposition = new AtomicComposition())
- {
- this.RaiseChangingEvent(null, removedParts, atomicComposition);
- this.UnsubscribeFromCatalogNotifications(catalogs);
-
- using (new WriteLock(this._lock))
- {
- this._catalogs = new List<ComposablePartCatalog>();
-
- this._isCopyNeeded = false;
- this._hasChanged = true;
- }
-
- // Complete after the catalog changes are written
- atomicComposition.Complete();
- }
-
- this.RaiseChangedEvent(null, removedParts);
- }
-
- public bool Contains(ComposablePartCatalog item)
- {
- Requires.NotNull(item, "item");
-
- this.ThrowIfDisposed();
-
- using (new ReadLock(this._lock))
- {
- return this._catalogs.Contains(item);
- }
- }
-
- public void CopyTo(ComposablePartCatalog[] array, int arrayIndex)
- {
- this.ThrowIfDisposed();
-
- using (new ReadLock(this._lock))
- {
- this._catalogs.CopyTo(array, arrayIndex);
- }
- }
-
- public int Count
- {
- get
- {
- this.ThrowIfDisposed();
-
- using (new ReadLock(this._lock))
- {
- return this._catalogs.Count;
- }
- }
- }
-
- public bool IsReadOnly
- {
- get
- {
- this.ThrowIfDisposed();
-
- return false;
- }
- }
-
- public bool Remove(ComposablePartCatalog item)
- {
- Requires.NotNull(item, "item");
-
- this.ThrowIfDisposed();
-
- using (new ReadLock(this._lock))
- {
- if (!this._catalogs.Contains(item))
- {
- return false;
- }
- }
-
- bool isSuccessfulRemoval = false;
-
- var removedParts = new Lazy<IEnumerable<ComposablePartDefinition>>(() => item.Parts.ToArray(), false);
- using (var atomicComposition = new AtomicComposition())
- {
- this.RaiseChangingEvent(null, removedParts, atomicComposition);
-
- using (new WriteLock(this._lock))
- {
- if (_isCopyNeeded)
- {
- this._catalogs = new List<ComposablePartCatalog>(this._catalogs);
- this._isCopyNeeded = false;
- }
-
- isSuccessfulRemoval = this._catalogs.Remove(item);
- if (isSuccessfulRemoval)
- {
- this._hasChanged = true;
- }
- }
-
- this.UnsubscribeFromCatalogNotifications(item);
-
- // Complete after the catalog changes are written
- atomicComposition.Complete();
- }
-
- this.RaiseChangedEvent(null, removedParts);
-
- return isSuccessfulRemoval;
- }
-
- internal bool HasChanged
- {
- get
- {
- this.ThrowIfDisposed();
-
- using (new ReadLock(this._lock))
- {
- return this._hasChanged;
- }
- }
- }
-
- public IEnumerator<ComposablePartCatalog> GetEnumerator()
- {
- this.ThrowIfDisposed();
-
- using (new ReadLock(this._lock))
- {
- IEnumerator<ComposablePartCatalog> enumerator = this._catalogs.GetEnumerator();
- this._isCopyNeeded = true;
- return enumerator;
- }
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return this.GetEnumerator();
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (!this._isDisposed)
- {
- bool disposeLock = false;
- IEnumerable<ComposablePartCatalog> catalogs = null;
- try
- {
- using (new WriteLock(this._lock))
- {
- if (!this._isDisposed)
- {
- disposeLock = true;
-
- catalogs = this._catalogs;
- this._catalogs = null;
-
- this._isDisposed = true;
- }
- }
- }
- finally
- {
- if (catalogs != null)
- {
- this.UnsubscribeFromCatalogNotifications(catalogs);
- catalogs.ForEach(catalog => catalog.Dispose());
- }
-
- if (disposeLock)
- {
- this._lock.Dispose();
- }
- }
- }
- }
- }
-
- private void RaiseChangedEvent(
- Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions,
- Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions)
- {
- if (this._onChanged == null || this.Changed == null)
- {
- return;
- }
-
- var added = (addedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : addedDefinitions.Value);
- var removed = (removedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : removedDefinitions.Value);
-
- this._onChanged.Invoke(new ComposablePartCatalogChangeEventArgs(added, removed, null));
- }
-
- public void OnChanged(object sender, ComposablePartCatalogChangeEventArgs e)
- {
- var changedEvent = this.Changed;
- if (changedEvent != null)
- {
- changedEvent(sender, e);
- }
- }
-
- private void RaiseChangingEvent(
- Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions,
- Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions,
- AtomicComposition atomicComposition)
- {
- if (this._onChanging == null || this.Changing == null)
- {
- return;
- }
- var added = (addedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : addedDefinitions.Value);
- var removed = (removedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : removedDefinitions.Value);
-
- this._onChanging.Invoke(new ComposablePartCatalogChangeEventArgs(added, removed, atomicComposition));
- }
-
- public void OnChanging(object sender, ComposablePartCatalogChangeEventArgs e)
- {
- var changingEvent = this.Changing;
- if (changingEvent != null)
- {
- changingEvent(sender, e);
- }
- }
-
- private void OnContainedCatalogChanged(object sender, ComposablePartCatalogChangeEventArgs e)
- {
- if (this._onChanged == null || this.Changed == null)
- {
- return;
- }
-
- this._onChanged.Invoke(e);
- }
-
- private void OnContainedCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
- {
- if (this._onChanging == null || this.Changing == null)
- {
- return;
- }
-
- this._onChanging.Invoke(e);
- }
-
- private void SubscribeToCatalogNotifications(ComposablePartCatalog catalog)
- {
- INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
- {
- notifyCatalog.Changed += this.OnContainedCatalogChanged;
- notifyCatalog.Changing += this.OnContainedCatalogChanging;
- }
- }
-
- private void SubscribeToCatalogNotifications(IEnumerable<ComposablePartCatalog> catalogs)
- {
- foreach (var catalog in catalogs)
- {
- SubscribeToCatalogNotifications(catalog);
- }
- }
-
- private void UnsubscribeFromCatalogNotifications(ComposablePartCatalog catalog)
- {
- INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged;
- if (notifyCatalog != null)
- {
- notifyCatalog.Changed -= this.OnContainedCatalogChanged;
- notifyCatalog.Changing -= this.OnContainedCatalogChanging;
- }
- }
-
- private void UnsubscribeFromCatalogNotifications(IEnumerable<ComposablePartCatalog> catalogs)
- {
- foreach (var catalog in catalogs)
- {
- UnsubscribeFromCatalogNotifications(catalog);
- }
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs deleted file mode 100644 index e8c68eab905..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs +++ /dev/null @@ -1,396 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public class ComposablePartExportProvider : ExportProvider, IDisposable
- {
- private List<ComposablePart> _parts = new List<ComposablePart>();
- private volatile bool _isDisposed = false;
- private volatile bool _isRunning = false;
- private CompositionLock _lock = null;
- private ExportProvider _sourceProvider;
- private ImportEngine _importEngine;
- private volatile bool _currentlyComposing;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartExportProvider"/> class.
- /// </summary>
- public ComposablePartExportProvider() :
- this(false)
- {
- }
-
- public ComposablePartExportProvider(bool isThreadSafe)
- {
- this._lock = new CompositionLock(isThreadSafe);
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (!this._isDisposed)
- {
- bool disposeLock = false;
- ImportEngine oldImportEngine = null;
- try
- {
- using (this._lock.LockStateForWrite())
- {
- if (!this._isDisposed)
- {
- oldImportEngine = this._importEngine;
- this._importEngine = null;
- this._sourceProvider = null;
- this._isDisposed = true;
- disposeLock = true;
- }
- }
- }
- finally
- {
- if (oldImportEngine != null)
- {
- oldImportEngine.Dispose();
- }
-
- if (disposeLock)
- {
- this._lock.Dispose();
- }
- }
- }
- }
- }
-
- /// <summary>
- /// Gets the export provider which provides the provider access to
- /// exports.
- /// </summary>
- /// <value>
- /// The <see cref="ExportProvider"/> which provides the
- /// <see cref="ComposablePartExportProvider"/> access to <see cref="Export"/> objects.
- /// The default is <see langword="null"/>.
- /// </value>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="value"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// This property has already been set.
- /// <para>
- /// -or-
- /// </para>
- /// The methods on the <see cref="ComposablePartExportProvider"/>
- /// have already been accessed.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePartExportProvider"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// This property must be set before accessing any methods on the
- /// <see cref="ComposablePartExportProvider"/>.
- /// </remarks>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")]
- public ExportProvider SourceProvider
- {
- get
- {
- this.ThrowIfDisposed();
-
- return this._sourceProvider;
- }
- set
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(value, "value");
- using (this._lock.LockStateForWrite())
- {
- this.EnsureCanSet(this._sourceProvider);
- this._sourceProvider = value;
- }
-
- // This should be safe to do outside the lock, because only the first setter will ever win
- // and others will throw
- ImportEngine importEngine = new ImportEngine(this._sourceProvider, this._lock.IsThreadSafe);
- Thread.MemoryBarrier();
- this._importEngine = importEngine;
- }
- }
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> to get.</param>
- /// <returns></returns>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <remarks>
- /// <note type="inheritinfo">
- /// The implementers should not treat the cardinality-related mismatches as errors, and are not
- /// expected to throw exceptions in those cases.
- /// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
- /// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
- /// </note>
- /// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- // Determine whether there is a composition atomicComposition-specific list of parts to use,
- // failing that use the usual list. We never change the list of parts in place,
- // but rather copy, change and write a new list atomically. Therefore all we need
- // to do here is to read the _parts member.
- List<ComposablePart> parts = null;
- using (this._lock.LockStateForRead())
- {
- parts = atomicComposition.GetValueAllowNull(this, this._parts);
- }
-
- if (parts.Count == 0)
- {
- return Enumerable.Empty<Export>();
- }
-
- List<Export> exports = new List<Export>();
- foreach (var part in parts)
- {
- foreach (var exportDefinition in part.ExportDefinitions)
- {
- if (definition.IsConstraintSatisfiedBy(exportDefinition))
- {
- exports.Add(this.CreateExport(part, exportDefinition));
- }
- }
- }
- return exports;
- }
-
- public void Compose(CompositionBatch batch)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- Requires.NotNull(batch, "batch");
-
- // Quick exit test can be done prior to cloning since it's just an optimization, not a
- // change in behavior
- if ((batch.PartsToAdd.Count == 0) && (batch.PartsToRemove.Count == 0))
- {
- return;
- }
-
- CompositionResult result = CompositionResult.SucceededResult;
-
- // Clone the batch, so that the external changes wouldn't happen half-way thorugh compose
- // NOTE : this does not guarantee the atomicity of cloning, which is not the goal anyway,
- // rather the fact that all subsequent calls will deal with an unchanging batch
- batch = new CompositionBatch(batch.PartsToAdd, batch.PartsToRemove);
-
- var newParts = GetUpdatedPartsList(batch);
-
- // Allow only recursive calls from the import engine to see the changes until
- // they've been verified ...
- using (var atomicComposition = new AtomicComposition())
- {
- // Don't allow reentrant calls to compose during previewing to prevent
- // corrupted state.
- if (this._currentlyComposing)
- {
- throw new InvalidOperationException(Strings.ReentrantCompose);
- }
-
- this._currentlyComposing = true;
-
- try
- {
- // In the meantime recursive calls need to be able to see the list as well
- atomicComposition.SetValue(this, newParts);
-
- // Recompose any existing imports effected by the these changes first so that
- // adapters, resurrected parts, etc. can all play their role in satisfying
- // imports for added parts
- this.Recompose(batch, atomicComposition);
-
- // Ensure that required imports can be satisfied
- foreach (ComposablePart part in batch.PartsToAdd)
- {
- // collect the result of previewing all the adds in the batch
- try
- {
- this._importEngine.PreviewImports(part, atomicComposition);
- }
- catch (ChangeRejectedException ex)
- {
- result = result.MergeResult(new CompositionResult(ex.Errors));
- }
- }
-
- result.ThrowOnErrors(atomicComposition);
-
- // Complete the new parts since they passed previewing.`
- using (this._lock.LockStateForWrite())
- {
- this._parts = newParts;
- }
-
- atomicComposition.Complete();
- }
- finally
- {
- this._currentlyComposing = false;
- }
- }
-
- // Satisfy Imports
- // - Satisfy imports on all newly added component parts
- foreach (ComposablePart part in batch.PartsToAdd)
- {
- result = result.MergeResult(CompositionServices.TryInvoke(() =>
- this._importEngine.SatisfyImports(part)));
- }
-
- // return errors
- result.ThrowOnErrors();
- }
-
- private List<ComposablePart> GetUpdatedPartsList(CompositionBatch batch)
- {
- Assumes.NotNull(batch);
-
- // Copy the current list of parts - we are about to modify it
- // This is an OK thing to do as this is the only method that can modify the List AND Compose can
- // only be executed on one thread at a time - thus two different threads cannot tramp over each other
- List<ComposablePart> parts = null;
- using (this._lock.LockStateForRead())
- {
- parts = this._parts.ToList(); // this copies the list
- }
-
- foreach (ComposablePart part in batch.PartsToAdd)
- {
- parts.Add(part);
- }
-
- foreach (ComposablePart part in batch.PartsToRemove)
- {
- parts.Remove(part);
- }
-
- return parts;
- }
-
- private void Recompose(CompositionBatch batch, AtomicComposition atomicComposition)
- {
- Assumes.NotNull(batch);
-
- // Unregister any removed component parts
- foreach (ComposablePart part in batch.PartsToRemove)
- {
- this._importEngine.ReleaseImports(part, atomicComposition);
- }
-
- // Recompose any imports effected by the these changes (the changes are
- // observable through GetExports in the appropriate atomicComposition, thus we can fire
- // the event
- IEnumerable<ExportDefinition> addedExports = batch.PartsToAdd.Count != 0 ?
- batch.PartsToAdd.SelectMany(part => part.ExportDefinitions).ToArray() :
- new ExportDefinition[0];
-
- IEnumerable<ExportDefinition> removedExports = batch.PartsToRemove.Count != 0 ?
- batch.PartsToRemove.SelectMany(part => part.ExportDefinitions).ToArray() :
- new ExportDefinition[0];
-
- this.OnExportsChanging(
- new ExportsChangeEventArgs(addedExports, removedExports, atomicComposition));
-
- atomicComposition.AddCompleteAction(() => this.OnExportsChanged(
- new ExportsChangeEventArgs(addedExports, removedExports, null)));
- }
-
- private Export CreateExport(ComposablePart part, ExportDefinition export)
- {
- return new Export(export, () => GetExportedValue(part, export));
- }
-
- private object GetExportedValue(ComposablePart part, ExportDefinition export)
- {
- this.ThrowIfDisposed();
- this.EnsureRunning();
-
- return CompositionServices.GetExportedValueFromComposedPart(this._importEngine, part, export);
- }
-
- [DebuggerStepThrough]
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw new ObjectDisposedException(this.GetType().Name);
- }
- }
-
- [DebuggerStepThrough]
- private void EnsureCanRun()
- {
- if ((this._sourceProvider == null) || (this._importEngine == null))
- {
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
- }
- }
-
- [DebuggerStepThrough]
- private void EnsureRunning()
- {
- if (!this._isRunning)
- {
- using (this._lock.LockStateForWrite())
- {
- if (!this._isRunning)
- {
- this.EnsureCanRun();
- this._isRunning = true;
- }
- }
- }
- }
-
- [DebuggerStepThrough]
- private void EnsureCanSet<T>(T currentValue)
- where T : class
- {
- if ((this._isRunning) || (currentValue != null))
- {
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.ObjectAlreadyInitialized));
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs deleted file mode 100644 index a2d2f7a3cff..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- partial class CompositionBatch
- {
- // Represents a part that exports a single export
- private class SingleExportComposablePart : ComposablePart
- {
- private readonly Export _export;
-
- public SingleExportComposablePart(Export export)
- {
- Assumes.NotNull(export);
-
- this._export = export;
- }
-
- public override IDictionary<string, object> Metadata
- {
- get { return MetadataServices.EmptyMetadata; }
- }
-
- public override IEnumerable<ExportDefinition> ExportDefinitions
- {
- get { return new ExportDefinition[] { _export.Definition }; }
- }
-
- public override IEnumerable<ImportDefinition> ImportDefinitions
- {
- get { return Enumerable.Empty<ImportDefinition>(); }
- }
-
- public override object GetExportedValue(ExportDefinition definition)
- {
- Requires.NotNull(definition, "definition");
-
- if (definition != _export.Definition)
- {
- throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart("definition");
- }
-
- return _export.Value;
- }
-
- public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports)
- {
- Requires.NotNull(definition, "definition");
- Requires.NotNullOrNullElements(exports, "exports");
-
- throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart("definition");
- }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionBatch.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionBatch.cs deleted file mode 100644 index 62f0a4d4416..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionBatch.cs +++ /dev/null @@ -1,174 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq;
-using Microsoft.Internal;
-using System.Collections.ObjectModel;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class CompositionBatch
- {
- private object _lock = new object();
- private bool _copyNeededForAdd;
- private bool _copyNeededForRemove;
- private List<ComposablePart> _partsToAdd;
- private ReadOnlyCollection<ComposablePart> _readOnlyPartsToAdd;
- private List<ComposablePart> _partsToRemove;
- private ReadOnlyCollection<ComposablePart> _readOnlyPartsToRemove;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionBatch"/> class.
- /// </summary>
- public CompositionBatch() :
- this(null, null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionBatch"/> class.
- /// </summary>
- /// <param name="partsToAdd">The parts to add.</param>
- /// <param name="partsToRemove">The parts to remove.</param>
- public CompositionBatch(IEnumerable<ComposablePart> partsToAdd, IEnumerable<ComposablePart> partsToRemove)
- {
- this._partsToAdd = new List<ComposablePart>();
- if (partsToAdd != null)
- {
- foreach (var part in partsToAdd)
- {
- if (part == null)
- {
- throw ExceptionBuilder.CreateContainsNullElement("partsToAdd");
- }
- this._partsToAdd.Add(part);
- }
- }
- this._readOnlyPartsToAdd = this._partsToAdd.AsReadOnly();
-
- this._partsToRemove = new List<ComposablePart>();
- if (partsToRemove != null)
- {
- foreach (var part in partsToRemove)
- {
- if (part == null)
- {
- throw ExceptionBuilder.CreateContainsNullElement("partsToRemove");
- }
- this._partsToRemove.Add(part);
- }
- }
- this._readOnlyPartsToRemove = this._partsToRemove.AsReadOnly();
- }
-
- /// <summary>
- /// Returns the collection of parts that will be added.
- /// </summary>
- /// <value>The parts to be added.</value>
- public ReadOnlyCollection<ComposablePart> PartsToAdd
- {
- get
- {
- lock (this._lock)
- {
- this._copyNeededForAdd = true;
- return this._readOnlyPartsToAdd;
- }
- }
- }
-
- /// <summary>
- /// Returns the collection of parts that will be removed.
- /// </summary>
- /// <value>The parts to be removed.</value>
- public ReadOnlyCollection<ComposablePart> PartsToRemove
- {
- get
- {
- lock (this._lock)
- {
- this._copyNeededForRemove = true;
- return this._readOnlyPartsToRemove;
- }
- }
- }
-
- /// <summary>
- /// Adds the specified part to the <see cref="CompositionBatch"/>.
- /// </summary>
- /// <param name="part">
- /// The part.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="part"/> is <see langword="null"/>.
- /// </exception>
- public void AddPart(ComposablePart part)
- {
- Requires.NotNull(part, "part");
- lock (this._lock)
- {
- if (this._copyNeededForAdd)
- {
- this._partsToAdd = new List<ComposablePart>(this._partsToAdd);
- this._readOnlyPartsToAdd = this._partsToAdd.AsReadOnly();
- this._copyNeededForAdd = false;
- }
- this._partsToAdd.Add(part);
- }
- }
-
- /// <summary>
- /// Removes the specified part from the <see cref="CompositionBatch"/>.
- /// </summary>
- /// <param name="part">
- /// The part.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="part"/> is <see langword="null"/>.
- /// </exception>
- public void RemovePart(ComposablePart part)
- {
- Requires.NotNull(part, "part");
- lock (this._lock)
- {
- if (this._copyNeededForRemove)
- {
- this._partsToRemove = new List<ComposablePart>(this._partsToRemove);
- this._readOnlyPartsToRemove = this._partsToRemove.AsReadOnly();
- this._copyNeededForRemove = false;
- }
- this._partsToRemove.Add(part);
- }
- }
-
- /// <summary>
- /// Adds the specified export to the <see cref="CompositionBatch"/>.
- /// </summary>
- /// <param name="export">
- /// The <see cref="Export"/> to add to the <see cref="CompositionBatch"/>.
- /// </param>
- /// <returns>
- /// A <see cref="ComposablePart"/> that can be used remove the <see cref="Export"/>
- /// from the <see cref="CompositionBatch"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="export"/> is <see langword="null"/>.
- /// </exception>
- /// <remarks>
- /// </remarks>
- public ComposablePart AddExport(Export export)
- {
- Requires.NotNull(export, "export");
-
- ComposablePart part = new SingleExportComposablePart(export);
-
- this.AddPart(part);
-
- return part;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionConstants.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionConstants.cs deleted file mode 100644 index e8cbaa144a2..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionConstants.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public static class CompositionConstants
- {
- private const string CompositionNamespace = "System.ComponentModel.Composition";
-
- public const string PartCreationPolicyMetadataName = CompositionNamespace + ".CreationPolicy";
- public const string ExportTypeIdentityMetadataName = "ExportTypeIdentity";
- internal const string ProductDefinitionMetadataName = "ProductDefinition";
-
- internal const string PartCreatorContractName = CompositionNamespace + ".Contracts.ExportFactory";
- internal static readonly string PartCreatorTypeIdentity = AttributedModelServices.GetTypeIdentity(typeof(ComposablePartDefinition));
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionContainer.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionContainer.cs deleted file mode 100644 index bdbd5c0595d..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionContainer.cs +++ /dev/null @@ -1,410 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class CompositionContainer : ExportProvider, ICompositionService, IDisposable
- {
- private ImportEngine _importEngine;
- private ComposablePartExportProvider _partExportProvider;
- private AggregateExportProvider _aggregatingExportProvider;
- private ExportProvider _rootProvider;
- private CatalogExportProvider _catalogExportProvider;
- private readonly ReadOnlyCollection<ExportProvider> _providers;
- private volatile int _isDisposed = 0;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContainer"/> class.
- /// </summary>
- public CompositionContainer()
- : this((ComposablePartCatalog)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContainer"/> class
- /// with the specified export providers.
- /// </summary>
- /// <param name="providers">
- /// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
- /// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
- /// or <see langword="null"/> to set <see cref="Providers"/> to an empty
- /// <see cref="ReadOnlyCollection{T}"/>.
- /// </param>
- /// <exception cref="ArgumentException">
- /// <paramref name="providers"/> contains an element that is <see langword="null"/>.
- /// </exception>
- public CompositionContainer(params ExportProvider[] providers) :
- this((ComposablePartCatalog)null, providers)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CompositionContainer"/> class
- /// with the specified catalog and export providers.
- /// </summary>
- /// <param name="providers">
- /// A <see cref="Array"/> of <see cref="ExportProvider"/> objects which provide
- /// the <see cref="CompositionContainer"/> access to <see cref="Export"/> objects,
- /// or <see langword="null"/> to set <see cref="Providers"/> to an empty
- /// <see cref="ReadOnlyCollection{T}"/>.
- /// </param>
- /// <exception cref="ArgumentException">
- /// <paramref name="providers"/> contains an element that is <see langword="null"/>.
- /// </exception>
- public CompositionContainer(ComposablePartCatalog catalog, params ExportProvider[] providers):
- this(catalog, false, providers)
- {
- }
-
- public CompositionContainer(ComposablePartCatalog catalog, bool isThreadSafe, params ExportProvider[] providers)
- {
- this._importEngine = new ImportEngine(this, isThreadSafe);
- this._partExportProvider = new ComposablePartExportProvider(isThreadSafe);
- this._partExportProvider.SourceProvider = this;
- this._providers = new ReadOnlyCollection<ExportProvider>(providers != null ? (ExportProvider[])providers.Clone() : new ExportProvider[0]);
-
- List<ExportProvider> providerList = new List<ExportProvider>();
-
- providerList.Add(this._partExportProvider);
-
- if (catalog != null)
- {
- this._catalogExportProvider = new CatalogExportProvider(catalog, isThreadSafe);
- this._catalogExportProvider.SourceProvider = this;
-
- providerList.Add(this._catalogExportProvider);
- }
-
- foreach (var provider in this._providers)
- {
- if (provider == null)
- {
- throw ExceptionBuilder.CreateContainsNullElement("providers");
- }
- providerList.Add(provider);
- }
-
- // we only build the aggregating provider if necessary - that is, if we have more than one provider to aggregate
- if (providerList.Count > 1)
- {
- this._aggregatingExportProvider = new AggregateExportProvider(providerList);
- this._rootProvider = this._aggregatingExportProvider;
- }
- else
- {
- Assumes.IsTrue(providerList.Count == 1);
- this._rootProvider = providerList[0];
- }
-
- this._rootProvider.ExportsChanged += this.OnExportsChangedInternal;
- this._rootProvider.ExportsChanging += this.OnExportsChangingInternal;
- }
-
- /// <summary>
- /// Gets the catalog which provides the container access to exports produced
- /// from composable parts.
- /// </summary>
- /// <value>
- /// The <see cref="ComposablePartCatalog"/> which provides the
- /// <see cref="CompositionContainer"/> access to exports produced from
- /// <see cref="ComposablePart"/> objects. The default is <see langword="null"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public ComposablePartCatalog Catalog
- {
- get
- {
- ThrowIfDisposed();
-
- if (_catalogExportProvider != null)
- {
- return _catalogExportProvider.Catalog;
- }
-
- return null;
- }
- }
-
- /// <summary>
- /// Gets the export providers which provide the container access to additional exports.
- /// </summary>
- /// <value>
- /// A <see cref="ReadOnlyCollection{T}"/> of <see cref="ExportProvider"/> objects
- /// which provide the <see cref="CompositionContainer"/> access to additional
- /// <see cref="Export"/> objects. The default is an empty
- /// <see cref="ReadOnlyCollection{T}"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public ReadOnlyCollection<ExportProvider> Providers
- {
- get
- {
- this.ThrowIfDisposed();
-
- return this._providers;
- }
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- // NOTE : According to http://msdn.microsoft.com/en-us/library/4bw5ewxy.aspx, the warning is bogus when used with Interlocked API.
-#pragma warning disable 420
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
-#pragma warning restore 420
- {
- this._rootProvider.ExportsChanged -= this.OnExportsChangedInternal;
- this._rootProvider.ExportsChanging -= this.OnExportsChangingInternal;
- if (this._aggregatingExportProvider != null)
- {
- this._aggregatingExportProvider.Dispose();
- }
- this._partExportProvider.Dispose();
- if (this._catalogExportProvider != null)
- {
- this._catalogExportProvider.Dispose();
- }
- this._importEngine.Dispose();
- }
- }
- }
-
- public void Compose(CompositionBatch batch)
- {
- Requires.NotNull(batch, "batch");
-
- this.ThrowIfDisposed();
- this._partExportProvider.Compose(batch);
- }
-
- /// <summary>
- /// Releases the <see cref="Export"/> from the <see cref="CompositionContainer"/>. The behavior
- /// may vary depending on the implementation of the <see cref="ExportProvider"/> that produced
- /// the <see cref="Export"/> instance. As a general rule non shared exports should be early
- /// released causing them to be detached from the container.
- ///
- /// For example the <see cref="CatalogExportProvider"/> will only release
- /// an <see cref="Export"/> if it comes from a <see cref="ComposablePart"/> that was constructed
- /// under a <see cref="CreationPolicy.NonShared" /> context. Release in this context means walking
- /// the dependency chain of the <see cref="Export"/>s, detaching references from the container and
- /// calling Dispose on the <see cref="ComposablePart"/>s as needed. If the <see cref="Export"/>
- /// was constructed under a <see cref="CreationPolicy.Shared" /> context the
- /// <see cref="CatalogExportProvider"/> will do nothing as it may be in use by other requestors.
- /// Those will only be detached when the container is itself disposed.
- /// </summary>
- /// <param name="export"><see cref="Export"/> that needs to be released.</param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="export"/> is <see langword="null"/>.
- /// </exception>
- [SuppressMessage("Microsoft.Performance", "CA1822")]
- public void ReleaseExport(Export export)
- {
- Requires.NotNull(export, "export");
-
- IDisposable dependency = export as IDisposable;
-
- if (dependency != null)
- {
- dependency.Dispose();
- }
- }
-
- /// <summary>
- /// Releases the <see cref="Lazy{T}"/> from the <see cref="CompositionContainer"/>. The behavior
- /// may vary depending on the implementation of the <see cref="ExportProvider"/> that produced
- /// the <see cref="Export"/> instance. As a general rule non shared exports should be early
- /// released causing them to be detached from the container.
- ///
- /// For example the <see cref="CatalogExportProvider"/> will only release
- /// an <see cref="Lazy{T}"/> if it comes from a <see cref="ComposablePart"/> that was constructed
- /// under a <see cref="CreationPolicy.NonShared" /> context. Release in this context means walking
- /// the dependency chain of the <see cref="Export"/>s, detaching references from the container and
- /// calling Dispose on the <see cref="ComposablePart"/>s as needed. If the <see cref="Export"/>
- /// was constructed under a <see cref="CreationPolicy.Shared" /> context the
- /// <see cref="CatalogExportProvider"/> will do nothing as it may be in use by other requestors.
- /// Those will only be detached when the container is itself disposed.
- /// </summary>
- /// <param name="export"><see cref="Export"/> that needs to be released.</param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="export"/> is <see langword="null"/>.
- /// </exception>
- [SuppressMessage("Microsoft.Performance", "CA1822")]
- public void ReleaseExport<T>(Lazy<T> export)
- {
- Requires.NotNull(export, "export");
-
- IDisposable dependency = export as IDisposable;
-
- if (dependency != null)
- {
- dependency.Dispose();
- }
- }
-
- /// <summary>
- /// Releases a set of <see cref="Export"/>s from the <see cref="CompositionContainer"/>.
- /// See also <see cref="ReleaseExport"/>.
- /// </summary>
- /// <param name="exports"><see cref="Export"/>s that need to be released.</param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="exports"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="exports"/> contains an element that is <see langword="null"/>.
- /// </exception>
- public void ReleaseExports(IEnumerable<Export> exports)
- {
- Requires.NotNullOrNullElements(exports, "exports");
-
- foreach (Export export in exports)
- {
- this.ReleaseExport(export);
- }
- }
-
- /// <summary>
- /// Releases a set of <see cref="Export"/>s from the <see cref="CompositionContainer"/>.
- /// See also <see cref="ReleaseExport"/>.
- /// </summary>
- /// <param name="exports"><see cref="Export"/>s that need to be released.</param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="exports"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="exports"/> contains an element that is <see langword="null"/>.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public void ReleaseExports<T>(IEnumerable<Lazy<T>> exports)
- {
- Requires.NotNullOrNullElements(exports, "exports");
-
- foreach (Lazy<T> export in exports)
- {
- this.ReleaseExport(export);
- }
- }
-
- /// <summary>
- /// Releases a set of <see cref="Export"/>s from the <see cref="CompositionContainer"/>.
- /// See also <see cref="ReleaseExport"/>.
- /// </summary>
- /// <param name="exports"><see cref="Export"/>s that need to be released.</param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="exports"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="exports"/> contains an element that is <see langword="null"/>.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public void ReleaseExports<T, TMetadataView>(IEnumerable<Lazy<T, TMetadataView>> exports)
- {
- Requires.NotNullOrNullElements(exports, "exports");
-
- foreach (Lazy<T, TMetadataView> export in exports)
- {
- this.ReleaseExport(export);
- }
- }
-
- /// <summary>
- /// Sets the imports of the specified composable part exactly once and they will not
- /// ever be recomposed.
- /// </summary>
- /// <param name="part">
- /// The <see cref="ComposablePart"/> to set the imports.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="part"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ICompositionService"/> has been disposed of.
- /// </exception>
- public void SatisfyImportsOnce(ComposablePart part)
- {
- this.ThrowIfDisposed();
- this._importEngine.SatisfyImportsOnce(part);
- }
-
- internal void OnExportsChangedInternal(object sender, ExportsChangeEventArgs e)
- {
- this.OnExportsChanged(e);
- }
-
- internal void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
- {
- this.OnExportsChanging(e);
- }
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> to get.</param>
- /// <returns></returns>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <remarks>
- /// <note type="inheritinfo">
- /// The implementers should not treat the cardinality-related mismatches as errors, and are not
- /// expected to throw exceptions in those cases.
- /// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
- /// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
- /// </note>
- /// </remarks>
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
-
- IEnumerable<Export> exports = null;
- this._rootProvider.TryGetExports(definition, atomicComposition, out exports);
-
- return exports;
- }
-
- [DebuggerStepThrough]
- private void ThrowIfDisposed()
- {
- if (this._isDisposed == 1)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionLock.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionLock.cs deleted file mode 100644 index b3dd0ea062f..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionLock.cs +++ /dev/null @@ -1,153 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#define SINGLETHREADEDLOCKENFORCEMENT
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- // This a a lock class that needs to be held in order to perform any mutation of the parts/parts state in the composition
- // Today's implementation relies on the AppDomain-wide re-entrant lock for changes on the composition, and a narrow lock for changes in
- // the state of the specific ImportEngine
- // Today we make several assumptions to ensure thread-safety:
- // 1. Each composition doesn't change lock affinity
- // 2. Every part of the system that updates the status of the parts (in our case ImportEngine) needs to hold the same wide - lock
- // 3. State of the import engine that gets accessed outside of the wide lock needs to be accessed in the context of the narrow lock
- // 4. Narrow lock CAN be taken inside the wide lock
- // 5. Wide lock CANNOT be taken inside the narrow lock
- // 6. No 3rd party code will EVER get called inside the narrow lock
- // Sadly, this means that we WILL be calling 3rd party code under a lock, but as long as the lock is re-entrant and they can't invoke us on anotehr thread
- // we have no issue, other than potential overlocking
- internal sealed class CompositionLock : IDisposable
- {
- // narrow lock
- private readonly Lock _stateLock = null;
- // wide lock
- private static object _compositionLock = new object();
-
- private int _isDisposed = 0;
- private bool _isThreadSafe = false;
-
- private static readonly EmptyLockHolder _EmptyLockHolder = new EmptyLockHolder();
-
- public CompositionLock(bool isThreadSafe)
- {
- this._isThreadSafe = isThreadSafe;
- if (isThreadSafe)
- {
- this._stateLock = new Lock();
- }
- }
-
- public void Dispose()
- {
- if (this._isThreadSafe)
- {
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
- {
- this._stateLock.Dispose();
- }
- }
- }
-
- public bool IsThreadSafe
- {
- get
- {
- return this._isThreadSafe;
- }
- }
-
- private void EnterCompositionLock()
- {
-#pragma warning disable 618
- if (this._isThreadSafe)
- {
- Monitor.Enter(_compositionLock);
- }
-#pragma warning restore 618
- }
-
- private void ExitCompositionLock()
- {
- if (this._isThreadSafe)
- {
- Monitor.Exit(_compositionLock);
- }
- }
-
- public IDisposable LockComposition()
- {
- if (this._isThreadSafe)
- {
- return new CompositionLockHolder(this);
- }
- else
- {
- return _EmptyLockHolder;
- }
- }
-
- public IDisposable LockStateForRead()
- {
- if (this._isThreadSafe)
- {
- return new ReadLock(this._stateLock);
- }
- else
- {
- return _EmptyLockHolder;
- }
- }
-
- public IDisposable LockStateForWrite()
- {
- if (this._isThreadSafe)
- {
- return new WriteLock(this._stateLock);
- }
- else
- {
- return _EmptyLockHolder;
- }
- }
-
- // NOTE : this should NOT be changed to a struct as ImportEngine relies on it
- public sealed class CompositionLockHolder : IDisposable
- {
- private CompositionLock _lock;
- private int _isDisposed;
-
- public CompositionLockHolder(CompositionLock @lock)
- {
- this._lock = @lock;
-
- this._isDisposed = 0;
- this._lock.EnterCompositionLock();
- }
-
- public void Dispose()
- {
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
- {
- this._lock.ExitCompositionLock();
- }
- }
- }
-
- private sealed class EmptyLockHolder : IDisposable
- {
- public void Dispose()
- {
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionServices.cs deleted file mode 100644 index 5a7d9851e57..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/CompositionServices.cs +++ /dev/null @@ -1,522 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.ComponentModel.Composition;
-using System.ComponentModel.Composition.AttributedModel;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.ReflectionModel;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- internal static class CompositionServices
- {
- internal static readonly Type InheritedExportAttributeType = typeof(InheritedExportAttribute);
- internal static readonly Type ExportAttributeType = typeof(ExportAttribute);
- internal static readonly Type AttributeType = typeof(Attribute);
- internal static readonly Type ObjectType = typeof(object);
-
- private static readonly string[] reservedMetadataNames = new string[]
- {
- CompositionConstants.PartCreationPolicyMetadataName
- };
-
- internal static Type GetDefaultTypeFromMember(this MemberInfo member)
- {
- Assumes.NotNull(member);
-
- switch (member.MemberType)
- {
- case MemberTypes.Property:
- return ((PropertyInfo)member).PropertyType;
-
- case MemberTypes.NestedType:
- case MemberTypes.TypeInfo:
- return ((Type)member);
-
- case MemberTypes.Field:
- default:
- Assumes.IsTrue(member.MemberType == MemberTypes.Field);
- return ((FieldInfo)member).FieldType;
- }
- }
-
- internal static string GetContractNameFromExport(this MemberInfo member, ExportAttribute export)
- {
- if (!string.IsNullOrEmpty(export.ContractName))
- {
- return export.ContractName;
- }
-
- if (export.ContractType != null)
- {
- return AttributedModelServices.GetContractName(export.ContractType);
- }
-
- if (member.MemberType == MemberTypes.Method)
- {
- return AttributedModelServices.GetTypeIdentity((MethodInfo)member);
- }
-
- return AttributedModelServices.GetContractName(member.GetDefaultTypeFromMember());
- }
-
- internal static string GetTypeIdentityFromExport(this MemberInfo member, ExportAttribute export)
- {
- if (export.ContractType != null)
- {
- return AttributedModelServices.GetTypeIdentity(export.ContractType);
- }
-
- if (member.MemberType == MemberTypes.Method)
- {
- return AttributedModelServices.GetTypeIdentity((MethodInfo)member);
- }
-
- return AttributedModelServices.GetTypeIdentity(member.GetDefaultTypeFromMember());
- }
-
- internal static Type GetContractTypeFromImport(this IAttributedImport import, ImportType importType)
- {
- if (import.ContractType != null)
- {
- return import.ContractType;
- }
-
- return importType.ContractType;
- }
-
- internal static string GetContractNameFromImport(this IAttributedImport import, ImportType importType)
- {
- if (!string.IsNullOrEmpty(import.ContractName))
- {
- return import.ContractName;
- }
-
- Type contractType = import.GetContractTypeFromImport(importType);
-
- return AttributedModelServices.GetContractName(contractType);
- }
-
- internal static string GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType)
- {
- Type contractType = import.GetContractTypeFromImport(importType);
-
- // For our importers we treat object as not having a type identity
- if (contractType == CompositionServices.ObjectType)
- {
- return null;
- }
-
- return AttributedModelServices.GetTypeIdentity(contractType);
- }
-
- internal static IDictionary<string, object> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy)
- {
- IDictionary<string, object> dictionary = new Dictionary<string, object>(StringComparers.MetadataKeyNames);
-
- if (creationPolicy != CreationPolicy.Any)
- {
- dictionary.Add(CompositionConstants.PartCreationPolicyMetadataName, creationPolicy);
- }
-
- foreach (PartMetadataAttribute partMetadata in type.GetAttributes<PartMetadataAttribute>())
- {
- if (reservedMetadataNames.Contains(partMetadata.Name, StringComparers.MetadataKeyNames)
- || dictionary.ContainsKey(partMetadata.Name))
- {
- // Perhaps we should log an error here so that people know this value is being ignored.
- continue;
- }
-
- dictionary.Add(partMetadata.Name, partMetadata.Value);
- }
-
- if (dictionary.Count == 0)
- {
- return MetadataServices.EmptyMetadata;
- }
- else
- {
- return dictionary;
- }
- }
-
- internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary<string, object> dictionary)
- {
- dictionary = new Dictionary<string, object>();
-
- foreach (var attr in member.GetAttributes<Attribute>())
- {
- var provider = attr as ExportMetadataAttribute;
-
- if (provider != null)
- {
- if (reservedMetadataNames.Contains(provider.Name, StringComparers.MetadataKeyNames))
- {
- throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name);
- }
-
- // we pass "null" for valueType which would make it inferred. We don;t have additional type information when metadata
- // goes through the ExportMetadataAttribute path
- if (!dictionary.TryContributeMetadataValue(provider.Name, provider.Value, null, provider.IsMultiple))
- {
- throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_DuplicateMetadataNameValues, member.GetDisplayName(), provider.Name);
- }
- }
- else
- {
- Type attrType = attr.GetType();
- if ((attrType != CompositionServices.ExportAttributeType) && attrType.IsAttributeDefined<MetadataAttributeAttribute>(true))
- {
- bool allowsMultiple = false;
- AttributeUsageAttribute usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(true);
-
- if (usage != null)
- {
- allowsMultiple = usage.AllowMultiple;
- }
-
- foreach (PropertyInfo pi in attrType.GetProperties())
- {
- if (pi.DeclaringType == CompositionServices.ExportAttributeType || pi.DeclaringType == CompositionServices.AttributeType)
- {
- // Don't contribute metadata properies from the base attribute types.
- continue;
- }
-
- if (reservedMetadataNames.Contains(pi.Name, StringComparers.MetadataKeyNames))
- {
- throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name);
- }
-
- object value = pi.GetValue(attr, null);
-
- if (value != null && !IsValidAttributeType(value.GetType()))
- {
- throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_MetadataContainsValueWithInvalidType, pi.GetDisplayName(), value.GetType().GetDisplayName());
- }
-
- if (!dictionary.TryContributeMetadataValue(pi.Name, value, pi.PropertyType, allowsMultiple))
- {
- throw ExceptionBuilder.CreateDiscoveryException(Strings.Discovery_DuplicateMetadataNameValues, member.GetDisplayName(), pi.Name);
- }
- }
- }
- }
- }
-
- // Need Keys.ToArray because we alter the dictionary in the loop
- foreach (var key in dictionary.Keys.ToArray())
- {
- var list = dictionary[key] as MetadataList;
- if (list != null)
- {
- dictionary[key] = list.ToArray();
- }
- }
-
- return;
- }
-
- private static bool TryContributeMetadataValue(this IDictionary<string, object> dictionary, string name, object value, Type valueType, bool allowsMultiple)
- {
- object metadataValue;
- if (!dictionary.TryGetValue(name, out metadataValue))
- {
- if (allowsMultiple)
- {
- var list = new MetadataList();
- list.Add(value, valueType);
- value = list;
- }
-
- dictionary.Add(name, value);
- }
- else
- {
- var list = metadataValue as MetadataList;
- if (!allowsMultiple || list == null)
- {
- // Either single value already found when should be multiple
- // or a duplicate name already exists
- dictionary.Remove(name);
- return false;
- }
-
- list.Add(value, valueType);
- }
- return true;
- }
-
- private class MetadataList
- {
- private Type _arrayType = null;
- private bool _containsNulls = false;
- private static readonly Type ObjectType = typeof(object);
- private static readonly Type TypeType = typeof(Type);
- private Collection<object> _innerList = new Collection<object>();
-
- public void Add(object item, Type itemType)
- {
- this._containsNulls |= (item == null);
-
- // if we've been passed typeof(object), we basically have no type inmformation
- if (itemType == ObjectType)
- {
- itemType = null;
- }
-
- // if we have no type information, get it from the item, if we can
- if ((itemType == null) && (item != null))
- {
- itemType = item.GetType();
- }
-
- // Types are special, because the are abstract classes, so if the item casts to Type, we assume System.Type
- if (item is Type)
- {
- itemType = TypeType;
- }
-
- // only try to call this if we got a meaningful type
- if (itemType != null)
- {
- this.InferArrayType(itemType);
- }
-
- this._innerList.Add(item);
- }
-
- private void InferArrayType(Type itemType)
- {
- Assumes.NotNull(itemType);
-
- if (this._arrayType == null)
- {
- // this is the first typed element we've been given, it sets the type of the array
- this._arrayType = itemType;
- }
- else
- {
- // if there's a disagreement on the array type, we flip to Object
- // NOTE : we can try to do better in the future to find common base class, but given that we support very limited set of types
- // in metadata right now, it's a moot point
- if (this._arrayType != itemType)
- {
- this._arrayType = ObjectType;
- }
- }
- }
-
- public Array ToArray()
- {
- if (this._arrayType == null)
- {
- // if the array type has not been set, assume Object
- this._arrayType = ObjectType;
- }
- else if (this._containsNulls && this._arrayType.IsValueType)
- {
- // if the array type is a value type and we have seen nulls, then assume Object
- this._arrayType = ObjectType;
- }
-
- Array array = Array.CreateInstance(this._arrayType, this._innerList.Count);
-
- for(int i = 0; i < array.Length; i++)
- {
- array.SetValue(this._innerList[i], i);
- }
- return array;
- }
- }
-
- //UNDONE: Need to add these warnings somewhere...Dev10:472538 should address this.
- //internal static CompositionResult MatchRequiredMetadata(this IDictionary<string, object> metadata, IEnumerable<string> requiredMetadata, string contractName)
- //{
- // Assumes.IsTrue(metadata != null);
-
- // var result = CompositionResult.SucceededResult;
-
- // var missingMetadata = (requiredMetadata == null) ? null : requiredMetadata.Except<string>(metadata.Keys);
- // if (missingMetadata != null && missingMetadata.Any())
- // {
- // result = result.MergeIssue(
- // CompositionError.CreateIssueAsWarning(CompositionErrorId.RequiredMetadataNotFound,
- // Strings.RequiredMetadataNotFound,
- // contractName,
- // string.Join(", ", missingMetadata.ToArray())));
-
- // return new CompositionResult(false, result.Issues);
- // }
-
- // return result;
- //}
-
- internal static IEnumerable<KeyValuePair<string, Type>> GetRequiredMetadata(Type metadataViewType)
- {
- if ((metadataViewType == null) ||
- ExportServices.IsDefaultMetadataViewType(metadataViewType) ||
- ExportServices.IsDictionaryConstructorViewType(metadataViewType) ||
- !metadataViewType.IsInterface)
- {
- return Enumerable.Empty<KeyValuePair<string, Type>>();
- }
-
- // A metadata view is required to be an Intrerface, and therefore only properties are allowed
- List<PropertyInfo> properties = metadataViewType.GetAllProperties().
- Where(property => property.GetFirstAttribute<DefaultValueAttribute>() == null).
- ToList();
-
- // NOTE : this is a carefully found balance between eager and delay-evaluation - the properties are filtered once and upfront
- // whereas the key/Type pairs are created every time. The latter is fine as KVPs are structs and as such copied on access regardless.
- // This also allows us to avoid creation of List<KVP> which - at least according to FxCop - leads to isues with NGEN
- return properties.Select(property => new KeyValuePair<string, Type>(property.Name, property.PropertyType));
- }
-
- internal static object GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition)
- {
- try
- {
- engine.SatisfyImports(part);
- }
- catch (CompositionException ex)
- {
- throw ExceptionBuilder.CreateCannotGetExportedValue(part, definition, ex);
- }
-
- try
- {
- return part.GetExportedValue(definition);
- }
- catch (ComposablePartException ex)
- {
- throw ExceptionBuilder.CreateCannotGetExportedValue(part, definition, ex);
- }
- }
-
- internal static bool IsRecomposable(this ComposablePart part)
- {
- return part.ImportDefinitions.Any(import => import.IsRecomposable);
- }
-
- internal static CompositionResult<T> TryInvoke<T>(Func<T> action)
- {
- try
- {
- T value = action();
- return new CompositionResult<T>(value);
- }
- catch (CompositionException ex)
- {
- return new CompositionResult<T>(ex.Errors);
- }
- }
-
- internal static CompositionResult TryInvoke(Action action)
- {
- try
- {
- action();
- return CompositionResult.SucceededResult;
- }
- catch (CompositionException ex)
- {
- return new CompositionResult(ex.Errors);
- }
- }
-
- internal static CompositionResult TryFire<TEventArgs>(EventHandler<TEventArgs> _delegate, object sender, TEventArgs e)
- where TEventArgs : EventArgs
- {
- CompositionResult result = CompositionResult.SucceededResult;
- foreach (EventHandler<TEventArgs> _subscriber in _delegate.GetInvocationList())
- {
- try
- {
- _subscriber.Invoke(sender, e);
- }
- catch (CompositionException ex)
- {
- result = result.MergeErrors(ex.Errors);
- }
- }
-
- return result;
- }
-
- internal static CreationPolicy GetRequiredCreationPolicy(this ImportDefinition definition)
- {
- ContractBasedImportDefinition contractDefinition = definition as ContractBasedImportDefinition;
-
- if (contractDefinition != null)
- {
- return contractDefinition.RequiredCreationPolicy;
- }
-
- return CreationPolicy.Any;
- }
-
- /// <summary>
- /// Returns a value indicating whether cardinality is
- /// <see cref="ImportCardinality.ZeroOrOne"/> or
- /// <see cref="ImportCardinality.ExactlyOne"/>.
- /// </summary>
- internal static bool IsAtMostOne(this ImportCardinality cardinality)
- {
- return cardinality == ImportCardinality.ZeroOrOne || cardinality == ImportCardinality.ExactlyOne;
- }
-
- private static bool IsValidAttributeType(Type type)
- {
- return IsValidAttributeType(type, true);
- }
-
- private static bool IsValidAttributeType(Type type, bool arrayAllowed)
- {
- Assumes.NotNull(type);
- // Definitions of valid attribute type taken from C# 3.0 Specification section 17.1.3.
-
- // One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
- if (type.IsPrimitive)
- {
- return true;
- }
-
- if (type == typeof(string))
- {
- return true;
- }
-
- // An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility
- if (type.IsEnum && type.IsVisible)
- {
- return true;
- }
-
- if (typeof(Type).IsAssignableFrom(type))
- {
- return true;
- }
-
- // Single-dimensional arrays of the above types.
- if (arrayAllowed && type.IsArray &&
- type.GetArrayRank() == 1 &&
- IsValidAttributeType(type.GetElementType(), false))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs deleted file mode 100644 index 074cf6166d8..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#if !SILVERLIGHT
-
-using System;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- partial class DirectoryCatalog
- {
- internal class DirectoryCatalogDebuggerProxy
- {
- private readonly DirectoryCatalog _catalog;
-
- public DirectoryCatalogDebuggerProxy(DirectoryCatalog catalog)
- {
- Requires.NotNull(catalog, "catalog");
-
- this._catalog = catalog;
- }
-
- public ReadOnlyCollection<Assembly> Assemblies
- {
- get
- {
- return this._catalog._assemblyCatalogs.Values.Select(catalog => catalog.Assembly)
- .ToReadOnlyCollection();
- }
- }
-
- public string SearchPattern
- {
- get { return this._catalog.SearchPattern; }
- }
-
- public string Path
- {
- get { return this._catalog._path; }
- }
-
- public string FullPath
- {
- get { return this._catalog._fullPath; }
- }
-
- public ReadOnlyCollection<string> LoadedFiles
- {
- get { return this._catalog._loadedFiles; }
- }
-
- public ReadOnlyCollection<ComposablePartDefinition> Parts
- {
- // NOTE: This shouldn't be cached, so that on every query of
- // the current value of the underlying catalog is respected.
- // We use ReadOnlyCollection as arrays do not have the
- // appropriate debugger display attributes applied to them.
- get { return this._catalog.Parts.ToReadOnlyCollection(); }
- }
- }
- }
-}
-
-#endif
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs deleted file mode 100644 index be49bdbfca9..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs +++ /dev/null @@ -1,542 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#if !SILVERLIGHT
-
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.ComponentModel.Composition.Diagnostics;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-using IOPath = System.IO.Path;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- [DebuggerTypeProxy(typeof(DirectoryCatalogDebuggerProxy))]
- public partial class DirectoryCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged, ICompositionElement
- {
- private readonly Lock _thisLock = new Lock();
- private ComposablePartCatalogCollection _catalogCollection;
- private Dictionary<string, AssemblyCatalog> _assemblyCatalogs;
- private volatile bool _isDisposed = false;
- private string _path;
- private string _fullPath;
- private string _searchPattern;
- private ReadOnlyCollection<string> _loadedFiles;
- private IQueryable<ComposablePartDefinition> _partsQuery;
-
- /// <summary>
- /// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
- /// in the given directory path.
- ///
- /// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
- /// <see cref="Assembly.Load(AssemblyName)"/> can throw.
- /// </summary>
- /// <param name="path">
- /// Path to the directory to scan for assemblies to add to the catalog.
- /// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
- /// </param>
- /// <exception cref="ArgumentException">
- /// If <paramref name="path"/> is a zero-length string, contains only white space, or
- /// contains one or more implementation-specific invalid characters.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="path"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="DirectoryNotFoundException">
- /// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
- /// </exception>
- /// <exception cref="PathTooLongException">
- /// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
- /// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
- /// be less than 260 characters.
- /// </exception>
- /// <exception cref="UnauthorizedAccessException">
- /// The caller does not have the required permission.
- /// </exception>
- public DirectoryCatalog(string path) : this(path, "*.dll")
- {
- }
-
- /// <summary>
- /// Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the given searchPattern
- /// over the files in the given directory path.
- ///
- /// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
- /// <see cref="Assembly.Load(AssemblyName)"/> can throw.
- /// </summary>
- /// <param name="path">
- /// Path to the directory to scan for assemblies to add to the catalog.
- /// The path needs to be absolute or relative to <see cref="AppDomain.BaseDirectory"/>
- /// </param>
- /// <param name="searchPattern">
- /// Any valid searchPattern that <see cref="Directory.GetFiles(string, string)"/> will accept.
- /// </param>
- /// <exception cref="ArgumentException">
- /// If <paramref name="path"/> is a zero-length string, contains only white space, or
- /// contains one or more implementation-specific invalid characters. Or <paramref name="searchPattern"/>
- /// does not contain a valid pattern.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="path"/> is <see langword="null"/> or <paramref name="searchPattern"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="DirectoryNotFoundException">
- /// The specified <paramref name="path"/> is invalid (for example, it is on an unmapped drive).
- /// </exception>
- /// <exception cref="PathTooLongException">
- /// The specified <paramref name="path"/>, file name, or both exceed the system-defined maximum length.
- /// For example, on Windows-based platforms, paths must be less than 248 characters and file names must
- /// be less than 260 characters.
- /// </exception>
- /// <exception cref="UnauthorizedAccessException">
- /// The caller does not have the required permission.
- /// </exception>
- public DirectoryCatalog(string path, string searchPattern)
- {
- Requires.NotNullOrEmpty(path, "path");
- this.Initialize(path, searchPattern);
- }
-
- /// <summary>
- /// Translated absolute path of the path passed into the constructor of <see cref="DirectoryCatalog"/>.
- /// </summary>
- public string FullPath
- {
- get
- {
- return this._fullPath;
- }
- }
-
- /// <summary>
- /// Set of files that have currently been loaded into the catalog.
- /// </summary>
- public ReadOnlyCollection<string> LoadedFiles
- {
- get
- {
- using (new ReadLock(this._thisLock))
- {
- return this._loadedFiles;
- }
- }
- }
-
- /// <summary>
- /// Path passed into the constructor of <see cref="DirectoryCatalog"/>.
- /// </summary>
- public string Path
- {
- get
- {
- return this._path;
- }
- }
-
- /// <summary>
- /// Gets the part definitions of the directory catalog.
- /// </summary>
- /// <value>
- /// A <see cref="IQueryable{T}"/> of <see cref="ComposablePartDefinition"/> objects of the
- /// <see cref="DirectoryCatalog"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="DirectoryCatalog"/> has been disposed of.
- /// </exception>
- public override IQueryable<ComposablePartDefinition> Parts
- {
- get
- {
- this.ThrowIfDisposed();
- return this._partsQuery;
- }
- }
-
- /// <summary>
- /// SearchPattern passed into the constructor of <see cref="DirectoryCatalog"/>, or the default *.dll.
- /// </summary>
- public string SearchPattern
- {
- get
- {
- return this._searchPattern;
- }
- }
-
- /// <summary>
- /// Notify when the contents of the Catalog has changed.
- /// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
-
- /// <summary>
- /// Notify when the contents of the Catalog has changing.
- /// </summary>
- public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (disposing)
- {
- if (!this._isDisposed)
- {
- bool disposeLock = false;
- ComposablePartCatalogCollection catalogs = null;
-
- try
- {
- using (new WriteLock(this._thisLock))
- {
- if (!this._isDisposed)
- {
- disposeLock = true;
- catalogs = this._catalogCollection;
- this._catalogCollection = null;
- this._assemblyCatalogs = null;
- this._isDisposed = true;
- }
- }
- }
- finally
- {
- if (catalogs != null)
- {
- catalogs.Dispose();
- }
-
- if (disposeLock)
- {
- this._thisLock.Dispose();
- }
- }
- }
- }
- }
- finally
- {
- base.Dispose(disposing);
- }
- }
-
- /// <summary>
- /// Returns the export definitions that match the constraint defined by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="ExportDefinition"/> objects to return.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
- /// <see cref="ExportDefinition"/> objects and their associated
- /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
- /// by <paramref name="definition"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="DirectoryCatalog"/> has been disposed of.
- /// </exception>
- public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(definition, "definition");
-
- return this._catalogCollection.SelectMany(catalog => catalog.GetExports(definition));
- }
-
- /// <summary>
- /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
- /// </summary>
- /// <param name="e">
- /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
- /// </param>
- protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
- {
- EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = this.Changed;
- if (changedEvent != null)
- {
- changedEvent(this, e);
- }
- }
-
- /// <summary>
- /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event.
- /// </summary>
- /// <param name="e">
- /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
- /// </param>
- protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
- {
- EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = this.Changing;
- if (changingEvent != null)
- {
- changingEvent(this, e);
- }
- }
-
- /// <summary>
- /// Refreshes the <see cref="ComposablePartDefinition"/>s with the latest files in the directory that match
- /// the searchPattern. If any files have been added they will be added to the catalog and if any files were
- /// removed they will be removed from the catalog. For files that have been removed keep in mind that the
- /// assembly cannot be unloaded from the process so <see cref="ComposablePartDefinition"/>s for those files
- /// will simply be removed from the catalog.
- ///
- /// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or
- /// <see cref="Assembly.Load(AssemblyName)"/> can throw.
- /// </summary>
- /// <exception cref="DirectoryNotFoundException">
- /// The specified <paramref name="path"/> has been removed since object construction.
- /// </exception>
- public void Refresh()
- {
- this.ThrowIfDisposed();
- Assumes.NotNull(this._loadedFiles);
-
- List<Tuple<string, AssemblyCatalog>> catalogsToAdd;
- List<Tuple<string, AssemblyCatalog>> catalogsToRemove;
- ComposablePartDefinition[] addedDefinitions;
- ComposablePartDefinition[] removedDefinitions;
- object changeReferenceObject;
- string[] afterFiles;
- string[] beforeFiles;
-
- while (true)
- {
- afterFiles = this.GetFiles();
-
- using (new ReadLock(this._thisLock))
- {
- changeReferenceObject = this._loadedFiles;
- beforeFiles = this._loadedFiles.ToArray();
- }
-
- this.DiffChanges(beforeFiles, afterFiles, out catalogsToAdd, out catalogsToRemove);
-
- // Don't go any further if there's no work to do
- if (catalogsToAdd.Count == 0 && catalogsToRemove.Count == 0)
- {
- return;
- }
-
- // Notify listeners to give them a preview before completeting the changes
- addedDefinitions = catalogsToAdd
- .SelectMany(cat => cat.Item2.Parts)
- .ToArray<ComposablePartDefinition>();
-
- removedDefinitions = catalogsToRemove
- .SelectMany(cat => cat.Item2.Parts)
- .ToArray<ComposablePartDefinition>();
-
- using (var atomicComposition = new AtomicComposition())
- {
- var changingArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, atomicComposition);
- this.OnChanging(changingArgs);
-
- // if the change went through then write the catalog changes
- using (new WriteLock(this._thisLock))
- {
- if (changeReferenceObject != this._loadedFiles)
- {
- // Someone updated the list while we were diffing so we need to try the diff again
- continue;
- }
-
- foreach (var catalogToAdd in catalogsToAdd)
- {
- this._assemblyCatalogs.Add(catalogToAdd.Item1, catalogToAdd.Item2);
- this._catalogCollection.Add(catalogToAdd.Item2);
- }
-
- foreach (var catalogToRemove in catalogsToRemove)
- {
- this._assemblyCatalogs.Remove(catalogToRemove.Item1);
- this._catalogCollection.Remove(catalogToRemove.Item2);
- }
-
- this._partsQuery = this._catalogCollection.AsQueryable().SelectMany(catalog => catalog.Parts);
- this._loadedFiles = afterFiles.ToReadOnlyCollection();
-
- // Lastly complete any changes added to the atomicComposition during the change event
- atomicComposition.Complete();
-
- // Break out of the while(true)
- break;
- } // WriteLock
- } // AtomicComposition
- } // while (true)
-
- var changedArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, null);
- this.OnChanged(changedArgs);
- }
-
- /// <summary>
- /// Returns a string representation of the directory catalog.
- /// </summary>
- /// <returns>
- /// A <see cref="String"/> containing the string representation of the <see cref="DirectoryCatalog"/>.
- /// </returns>
- public override string ToString()
- {
- return GetDisplayName();
- }
-
- private AssemblyCatalog CreateAssemblyCatalogGuarded(string assemblyFilePath)
- {
- Exception exception = null;
-
- try
- {
- return new AssemblyCatalog(assemblyFilePath, this);
- }
- catch (FileNotFoundException ex)
- { // Files should always exists but don't blow up here if they don't
- exception = ex;
- }
- catch (FileLoadException ex)
- { // File was found but could not be loaded
- exception = ex;
- }
- catch (BadImageFormatException ex)
- { // Dlls that contain native code are not loaded, but do not invalidate the Directory
- exception = ex;
- }
- catch (ReflectionTypeLoadException ex)
- { // Dlls that have missing Managed dependencies are not loaded, but do not invalidate the Directory
- exception = ex;
- }
-
- CompositionTrace.AssemblyLoadFailed(this, assemblyFilePath, exception);
-
- return null;
- }
-
- private void DiffChanges(string[] beforeFiles, string[] afterFiles,
- out List<Tuple<string, AssemblyCatalog>> catalogsToAdd,
- out List<Tuple<string, AssemblyCatalog>> catalogsToRemove)
- {
- catalogsToAdd = new List<Tuple<string, AssemblyCatalog>>();
- catalogsToRemove = new List<Tuple<string, AssemblyCatalog>>();
-
- IEnumerable<string> filesToAdd = afterFiles.Except(beforeFiles);
- foreach (string file in filesToAdd)
- {
- AssemblyCatalog catalog = CreateAssemblyCatalogGuarded(file);
-
- if (catalog != null)
- {
- catalogsToAdd.Add(new Tuple<string, AssemblyCatalog>(file, catalog));
- }
- }
-
- IEnumerable<string> filesToRemove = beforeFiles.Except(afterFiles);
- using (new ReadLock(this._thisLock))
- {
- foreach (string file in filesToRemove)
- {
- AssemblyCatalog catalog;
- if (this._assemblyCatalogs.TryGetValue(file, out catalog))
- {
- catalogsToRemove.Add(new Tuple<string, AssemblyCatalog>(file, catalog));
- }
- }
- }
- }
-
- private string GetDisplayName()
- {
- return string.Format(CultureInfo.CurrentCulture,
- "{0} (Path=\"{1}\")", // NOLOC
- this.GetType().Name,
- this._path);
- }
-
- private string[] GetFiles()
- {
- return Directory.GetFiles(this._fullPath, this._searchPattern);
- }
-
- private static string GetFullPath(string path)
- {
- if (!IOPath.IsPathRooted(path) && AppDomain.CurrentDomain.BaseDirectory != null)
- {
- path = IOPath.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
- }
-
- return IOPath.GetFullPath(path);
- }
-
- private void Initialize(string path, string searchPattern)
- {
- this._path = path;
- this._fullPath = GetFullPath(path);
- this._searchPattern = searchPattern;
- this._assemblyCatalogs = new Dictionary<string, AssemblyCatalog>();
- this._catalogCollection = new ComposablePartCatalogCollection(null);
-
- this._loadedFiles = GetFiles().ToReadOnlyCollection();
-
- foreach (string file in this._loadedFiles)
- {
- AssemblyCatalog assemblyCatalog = null;
- assemblyCatalog = CreateAssemblyCatalogGuarded(file);
-
- if (assemblyCatalog != null)
- {
- this._assemblyCatalogs.Add(file, assemblyCatalog);
- this._catalogCollection.Add(assemblyCatalog);
- }
- }
- this._partsQuery = this._catalogCollection.AsQueryable().SelectMany(catalog => catalog.Parts);
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
-
- /// <summary>
- /// Gets the display name of the directory catalog.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a human-readable display name of the <see cref="DirectoryCatalog"/>.
- /// </value>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- string ICompositionElement.DisplayName
- {
- get { return this.GetDisplayName(); }
- }
-
- /// <summary>
- /// Gets the composition element from which the directory catalog originated.
- /// </summary>
- /// <value>
- /// This property always returns <see langword="null"/>.
- /// </value>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
- {
- get { return null; }
- }
- }
-}
-
-#endif
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs deleted file mode 100644 index 01f2175f331..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs +++ /dev/null @@ -1,817 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Collections.ObjectModel;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public abstract partial class ExportProvider
- {
- /// <summary>
- /// Returns the export with the contract name derived from the specified type parameter,
- /// throwing an exception if there is not exactly one matching export.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T}"/> object to return. The contract name is also
- /// derived from this type parameter.
- /// </typeparam>
- /// <returns>
- /// The <see cref="Lazy{T}"/> object with the contract name derived from
- /// <typeparamref name="T"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The returned <see cref="Lazy{T}"/> object is an instance of
- /// <see cref="Lazy{T, TMetadataView}"/> underneath, where
- /// <c>TMetadataView</c>
- /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
- /// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
- /// </para>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are zero <see cref="Lazy{T}"/> objects with the contract name derived
- /// from <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
- /// </para>
- /// -or-
- /// <para>
- /// There are more than one <see cref="Lazy{T}"/> objects with the contract name
- /// derived from <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public Lazy<T> GetExport<T>()
- {
- return this.GetExport<T>((string)null);
- }
-
- /// <summary>
- /// Returns the export with the specified contract name, throwing an exception if there
- /// is not exactly one matching export.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T}"/> object to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the <see cref="Lazy{T}"/>
- /// object to return; or <see langword="null"/> or an empty string ("") to use the
- /// default contract name.
- /// </param>
- /// <returns>
- /// The <see cref="Lazy{T}"/> object with the specified contract name.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The returned <see cref="Lazy{T}"/> object is an instance of
- /// <see cref="Lazy{T, TMetadataView}"/> underneath, where
- /// <c>TMetadataView</c>
- /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
- /// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
- /// </para>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The default contract name is compared using a case-sensitive, non-linguistic
- /// comparison using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are zero <see cref="Lazy{T}"/> objects with the specified contract name
- /// in the <see cref="CompositionContainer"/>.
- /// </para>
- /// -or-
- /// <para>
- /// There are more than one <see cref="Lazy{T}"/> objects with the specified contract
- /// name in the <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public Lazy<T> GetExport<T>(string contractName)
- {
- return this.GetExportCore<T>(contractName);
- }
-
- /// <summary>
- /// Returns the export with the contract name derived from the specified type parameter,
- /// throwing an exception if there is not exactly one matching export.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T, TMetadataView}"/> object to return. The
- /// contract name is also derived from this type parameter.
- /// </typeparam>
- /// <typeparam name="TMetadataView">
- /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> object
- /// to return.
- /// </typeparam>
- /// <returns>
- /// The <see cref="Lazy{T, TMetadataView}"/> object with the contract name derived
- /// from <typeparamref name="T"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are zero <see cref="Lazy{T, TMetadataView}"/> objects with the contract
- /// name derived from <typeparamref name="T"/> in the
- /// <see cref="CompositionContainer"/>.
- /// </para>
- /// -or-
- /// <para>
- /// There are more than one <see cref="Lazy{T, TMetadataView}"/> objects with the
- /// contract name derived from <typeparamref name="T"/> in the
- /// <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public Lazy<T, TMetadataView> GetExport<T, TMetadataView>()
- {
- return this.GetExport<T, TMetadataView>((string)null);
- }
-
- /// <summary>
- /// Returns the export with the specified contract name, throwing an exception if there
- /// is not exactly one matching export.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T, TMetadataView}"/> object to return.
- /// </typeparam>
- /// <typeparam name="TMetadataView">
- /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> object
- /// to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="Lazy{T, TMetadataView}"/> object to return; or <see langword="null"/>
- /// or an empty string ("") to use the default contract name.
- /// </param>
- /// <returns>
- /// The <see cref="Lazy{T, TMetadataView}"/> object with the specified contract name.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are zero <see cref="Lazy{T, TMetadataView}"/> objects with the
- /// specified contract name in the <see cref="CompositionContainer"/>.
- /// </para>
- /// -or-
- /// <para>
- /// There are more than one <see cref="Lazy{T, TMetadataView}"/> objects with the
- /// specified contract name in the <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- public Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName)
- {
- return this.GetExportCore<T, TMetadataView>(contractName);
- }
-
- /// <summary>
- /// Returns the exports with the specified contract name.
- /// </summary>
- /// <param name="type">
- /// The <see cref="Type"/> of the <see cref="Export"/> objects to return.
- /// </param>
- /// <param name="metadataViewType">
- /// The <see cref="Type"/> of the metadata view of the <see cref="Export"/> objects to
- /// return.
- /// </param>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="Export"/> object to return; or <see langword="null"/>
- /// or an empty string ("") to use the default contract name.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{Object, Object}"/> objects
- /// with the specified contract name, if found; otherwise, an empty
- /// <see cref="IEnumerable{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The returned <see cref="Export"/> objects are instances of
- /// <see cref="Lazy{T, TMetadataView}"/> underneath, where <c>T</c>
- /// is <paramref name="type"/> and <c>TMetadataView</c> is
- /// <paramref name="metadataViewType"/>.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <paramref name="type"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="type"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// <paramref name="metadataViewType"/> is not a valid metadata view type.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<object, object>> GetExports(Type type, Type metadataViewType, string contractName)
- {
- IEnumerable<Export> exports = this.GetExportsCore(type, metadataViewType, contractName, ImportCardinality.ZeroOrMore);
- Collection<Lazy<object, object>> result = new Collection<Lazy<object, object>>();
-
- Func<Export, Lazy<object, object>> typedExportFactory = ExportServices.CreateSemiStronglyTypedLazyFactory(type, metadataViewType);
- foreach (Export export in exports)
- {
- result.Add(typedExportFactory.Invoke(export));
- }
-
- return result;
- }
-
- /// <summary>
- /// Returns the exports with the contract name derived from the specified type parameter.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T}"/> objects to return. The contract name is also
- /// derived from this type parameter.
- /// </typeparam>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{T}"/> objects
- /// with the contract name derived from <typeparamref name="T"/>, if found; otherwise,
- /// an empty <see cref="IEnumerable{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The returned <see cref="Lazy{T}"/> objects are instances of
- /// <see cref="Lazy{T, TMetadataView}"/> underneath, where
- /// <c>TMetadataView</c>
- /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
- /// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
- /// </para>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<T>> GetExports<T>()
- {
- return this.GetExports<T>((string)null);
- }
-
- /// <summary>
- /// Returns the exports with the specified contract name.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T}"/> objects to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the <see cref="Lazy{T}"/>
- /// objects to return; or <see langword="null"/> or an empty string ("") to use the
- /// default contract name.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{T}"/> objects
- /// with the specified contract name, if found; otherwise, an empty
- /// <see cref="IEnumerable{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The returned <see cref="Lazy{T}"/> objects are instances of
- /// <see cref="Lazy{T, TMetadataView}"/> underneath, where
- /// <c>TMetadataView</c>
- /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c>
- /// is <see cref="String"/> and <c>TValue</c> is <see cref="Object"/>.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<T>> GetExports<T>(string contractName)
- {
- return this.GetExportsCore<T>(contractName);
- }
-
- /// <summary>
- /// Returns the exports with the contract name derived from the specified type parameter.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T, TMetadataView}"/> objects to return. The
- /// contract name is also derived from this type parameter.
- /// </typeparam>
- /// <typeparam name="TMetadataView">
- /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> objects
- /// to return.
- /// </typeparam>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> containing the
- /// <see cref="Lazy{T, TMetadataView}"/> objects with the contract name derived from
- /// <typeparamref name="T"/>, if found; otherwise, an empty
- /// <see cref="IEnumerable{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="InvalidOperationException">
- /// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>()
- {
- return this.GetExports<T, TMetadataView>((string)null);
- }
-
- /// <summary>
- /// Returns the exports with the specified contract name.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the <see cref="Lazy{T, TMetadataView}"/> objects to return. The
- /// contract name is also derived from this type parameter.
- /// </typeparam>
- /// <typeparam name="TMetadataView">
- /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> objects
- /// to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="Lazy{T, TMetadataView}"/> objects to return; or <see langword="null"/>
- /// or an empty string ("") to use the default contract name.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> containing the
- /// <see cref="Lazy{T, TMetadataView}"/> objects with the specified contract name if
- /// found; otherwise, an empty <see cref="IEnumerable{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="InvalidOperationException">
- /// <typeparamref name="TMetadataView"/> is not a valid metadata view type.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006")]
- public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName)
- {
- return this.GetExportsCore<T, TMetadataView>(contractName);
- }
-
- /// <summary>
- /// Returns the exported value with the contract name derived from the specified type
- /// parameter, throwing an exception if there is not exactly one matching exported value.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the exported value to return. The contract name is also
- /// derived from this type parameter.
- /// </typeparam>
- /// <returns>
- /// The exported <see cref="Object"/> with the contract name derived from
- /// <typeparamref name="T"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="CompositionContractMismatchException">
- /// The underlying exported value cannot be cast to <typeparamref name="T"/>.
- /// </exception>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are zero exported values with the contract name derived from
- /// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
- /// </para>
- /// -or-
- /// <para>
- /// There are more than one exported values with the contract name derived from
- /// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- public T GetExportedValue<T>()
- {
- return this.GetExportedValue<T>((string)null);
- }
-
- /// <summary>
- /// Returns the exported value with the specified contract name, throwing an exception
- /// if there is not exactly one matching exported value.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the exported value to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the exported value to return,
- /// or <see langword="null"/> or an empty string ("") to use the default contract name.
- /// </param>
- /// <returns>
- /// The exported <see cref="Object"/> with the specified contract name.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="CompositionContractMismatchException">
- /// The underlying exported value cannot be cast to <typeparamref name="T"/>.
- /// </exception>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are zero exported values with the specified contract name in the
- /// <see cref="CompositionContainer"/>.
- /// </para>
- /// -or-
- /// <para>
- /// There are more than one exported values with the specified contract name in the
- /// <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- public T GetExportedValue<T>(string contractName)
- {
- return this.GetExportedValueCore<T>(contractName, ImportCardinality.ExactlyOne);
- }
-
- /// <summary>
- /// Returns the exported value with the contract name derived from the specified type
- /// parameter, throwing an exception if there is more than one matching exported value.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the exported value to return. The contract name is also
- /// derived from this type parameter.
- /// </typeparam>
- /// <returns>
- /// The exported <see cref="Object"/> with the contract name derived from
- /// <typeparamref name="T"/>, if found; otherwise, the default value for
- /// <typeparamref name="T"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// If the exported value is not found, then this method returns the appropriate
- /// default value for <typeparamref name="T"/>; for example, 0 (zero) for integer
- /// types, <see langword="false"/> for Boolean types, and <see langword="null"/>
- /// for reference types.
- /// </para>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="CompositionContractMismatchException">
- /// The underlying exported value cannot be cast to <typeparamref name="T"/>.
- /// </exception>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// There are more than one exported values with the contract name derived from
- /// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>.
- /// </para>
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- public T GetExportedValueOrDefault<T>()
- {
- return this.GetExportedValueOrDefault<T>((string)null);
- }
-
- /// <summary>
- /// Returns the exported value with the specified contract name, throwing an exception
- /// if there is more than one matching exported value.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the exported value to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the exported value to return,
- /// or <see langword="null"/> or an empty string ("") to use the default contract name.
- /// </param>
- /// <returns>
- /// The exported <see cref="Object"/> with the specified contract name, if found;
- /// otherwise, the default value for <typeparamref name="T"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// If the exported value is not found, then this method returns the appropriate
- /// default value for <typeparamref name="T"/>; for example, 0 (zero) for integer
- /// types, <see langword="false"/> for Boolean types, and <see langword="null"/>
- /// for reference types.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="CompositionContractMismatchException">
- /// The underlying exported value cannot be cast to <typeparamref name="T"/>.
- /// </exception>
- /// <exception cref="ImportCardinalityMismatchException">
- /// There are more than one exported values with the specified contract name in the
- /// <see cref="CompositionContainer"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- public T GetExportedValueOrDefault<T>(string contractName)
- {
- return this.GetExportedValueCore<T>(contractName, ImportCardinality.ZeroOrOne);
- }
-
- /// <summary>
- /// Returns the exported values with the contract name derived from the specified type
- /// parameter.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the exported value to return. The contract name is also
- /// derived from this type parameter.
- /// </typeparam>
- /// <returns>
- /// An <see cref="Collection{T}"/> containing the exported values with the contract name
- /// derived from the specified type parameter, if found; otherwise, an empty
- /// <see cref="Collection{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="CompositionContractMismatchException">
- /// One or more of the underlying exported values cannot be cast to
- /// <typeparamref name="T"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- public IEnumerable<T> GetExportedValues<T>()
- {
- return this.GetExportedValues<T>((string)null);
- }
-
- /// <summary>
- /// Returns the exported values with the specified contract name.
- /// </summary>
- /// <typeparam name="T">
- /// The type of the exported value to return.
- /// </typeparam>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the exported values to
- /// return; or <see langword="null"/> or an empty string ("") to use the default
- /// contract name.
- /// </param>
- /// <returns>
- /// An <see cref="Collection{T}"/> containing the exported values with the specified
- /// contract name, if found; otherwise, an empty <see cref="Collection{T}"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- /// <exception cref="CompositionContractMismatchException">
- /// One or more of the underlying exported values cannot be cast to
- /// <typeparamref name="T"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="CompositionContainer"/> has been disposed of.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- public IEnumerable<T> GetExportedValues<T>(string contractName)
- {
- return this.GetExportedValuesCore<T>(contractName);
- }
-
- private IEnumerable<T> GetExportedValuesCore<T>(string contractName)
- {
- IEnumerable<Export> exports = this.GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
-
- Collection<T> result = new Collection<T>();
- foreach (Export export in exports)
- {
- result.Add(ExportServices.GetCastedExportedValue<T>(export));
- }
- return result;
- }
-
- private T GetExportedValueCore<T>(string contractName, ImportCardinality cardinality)
- {
- Assumes.IsTrue(cardinality.IsAtMostOne());
-
- Export export = this.GetExportsCore(typeof(T), (Type)null, contractName, cardinality).SingleOrDefault();
-
- return (export != null) ? ExportServices.GetCastedExportedValue<T>(export) : default(T);
- }
-
- private IEnumerable<Lazy<T>> GetExportsCore<T>(string contractName)
- {
- IEnumerable<Export> exports = this.GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
-
- Collection<Lazy<T>> result = new Collection<Lazy<T>>();
- foreach (Export export in exports)
- {
- result.Add(ExportServices.CreateStronglyTypedLazyOfT<T>(export));
- }
- return result;
- }
-
- private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string contractName)
- {
- IEnumerable<Export> exports = this.GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ZeroOrMore);
-
- Collection<Lazy<T, TMetadataView>> result = new Collection<Lazy<T, TMetadataView>>();
- foreach (Export export in exports)
- {
- result.Add(ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export));
- }
- return result;
- }
-
- private Lazy<T, TMetadataView> GetExportCore<T, TMetadataView>(string contractName)
- {
- Export export = this.GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
-
- return (export != null) ? ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export) : null;
- }
-
- private Lazy<T> GetExportCore<T>(string contractName)
- {
- Export export = this.GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault();
-
- return (export != null) ? ExportServices.CreateStronglyTypedLazyOfT<T>(export) : null;
- }
-
- private IEnumerable<Export> GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
- {
- // Only 'type' cannot be null - the other parameters have sensible defaults.
- Requires.NotNull(type, "type");
-
- if (string.IsNullOrEmpty(contractName))
- {
- contractName = AttributedModelServices.GetContractName(type);
- }
-
- if (metadataViewType == null)
- {
- metadataViewType = ExportServices.DefaultMetadataViewType;
- }
-
- if (!MetadataViewProvider.IsViewTypeValid(metadataViewType))
- {
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidMetadataView, metadataViewType.Name));
- }
-
- ImportDefinition importDefinition = BuildImportDefinition(type, metadataViewType, contractName, cardinality);
- return this.GetExports(importDefinition, null);
- }
-
- private static ImportDefinition BuildImportDefinition(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
- {
- Assumes.NotNull(type, metadataViewType, contractName);
-
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType);
-
- string requiredTypeIdentity = null;
- if (type != typeof(object))
- {
- requiredTypeIdentity = AttributedModelServices.GetTypeIdentity(type);
- }
-
- return new ContractBasedImportDefinition(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, CreationPolicy.Any);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportProvider.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportProvider.cs deleted file mode 100644 index 015996ecf24..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportProvider.cs +++ /dev/null @@ -1,231 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Linq;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// Defines the <see langword="abstract"/> base class for export providers, which provide
- /// methods for retrieving <see cref="Export"/> objects.
- /// </summary>
- public abstract partial class ExportProvider
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportProvider"/> class.
- /// </summary>
- protected ExportProvider()
- {
- }
-
- /// <summary>
- /// Occurs when the exports in the <see cref="ExportProvider"/> have changed.
- /// </summary>
- public event EventHandler<ExportsChangeEventArgs> ExportsChanged;
-
- /// <summary>
- /// Occurs when the exports in the <see cref="ExportProvider"/> are changing.
- /// </summary>
- public event EventHandler<ExportsChangeEventArgs> ExportsChanging;
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> objects to get.
- /// </param>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ExactlyOne"/> and
- /// there are zero <see cref="Export"/> objects that match the conditions of the specified
- /// <see cref="ImportDefinition"/>.
- /// </para>
- /// -or-
- /// <para>
- /// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
- /// <see cref="ImportCardinality.ExactlyOne"/> and there are more than one <see cref="Export"/>
- /// objects that match the conditions of the specified <see cref="ImportDefinition"/>.
- /// </para>
- /// </exception>
- public IEnumerable<Export> GetExports(ImportDefinition definition)
- {
- return GetExports(definition, null);
- }
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> objects to get.
- /// </param>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ImportCardinalityMismatchException">
- /// <para>
- /// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ExactlyOne"/> and
- /// there are zero <see cref="Export"/> objects that match the conditions of the specified
- /// <see cref="ImportDefinition"/>.
- /// </para>
- /// -or-
- /// <para>
- /// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
- /// <see cref="ImportCardinality.ExactlyOne"/> and there are more than one <see cref="Export"/>
- /// objects that match the conditions of the specified <see cref="ImportDefinition"/>.
- /// </para>
- /// </exception>
- public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
- {
- Requires.NotNull(definition, "definition");
-
- IEnumerable<Export> exports;
- ExportCardinalityCheckResult result = this.TryGetExportsCore(definition, atomicComposition, out exports);
- switch(result)
- {
- case ExportCardinalityCheckResult.Match:
- return exports;
- case ExportCardinalityCheckResult.NoExports:
- throw new ImportCardinalityMismatchException(string.Format(CultureInfo.CurrentCulture, Strings.CardinalityMismatch_NoExports, definition.Constraint.Body.ToString()));
- default:
- Assumes.IsTrue(result == ExportCardinalityCheckResult.TooManyExports);
- throw new ImportCardinalityMismatchException(string.Format(CultureInfo.CurrentCulture, Strings.CardinalityMismatch_TooManyExports, definition.Constraint.Body.ToString()));
- }
- }
-
- /// <summary>
- /// Returns all exports that match the conditions of the specified import.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> objects to get.
- /// </param>
- /// <param name="exports">
- /// When this method returns, contains an <see cref="IEnumerable{T}"/> of <see cref="Export"/>
- /// objects that match the conditions defined by <see cref="ImportDefinition"/>, if found;
- /// otherwise, an empty <see cref="IEnumerable{T}"/>.
- /// </param>
- /// <returns>
- /// <see langword="true"/> if <see cref="ImportDefinition.Cardinality"/> is
- /// <see cref="ImportCardinality.ZeroOrOne"/> or <see cref="ImportCardinality.ZeroOrMore"/> and
- /// there are zero <see cref="Export"/> objects that match the conditions of the specified
- /// <see cref="ImportDefinition"/>. <see langword="true"/> if
- /// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
- /// <see cref="ImportCardinality.ExactlyOne"/> and there is exactly one <see cref="Export"/>
- /// that matches the conditions of the specified <see cref="ImportDefinition"/>; otherwise,
- /// <see langword="false"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- public bool TryGetExports(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
- {
- Requires.NotNull(definition, "definition");
-
- exports = null;
- ExportCardinalityCheckResult result = this.TryGetExportsCore(definition, atomicComposition, out exports);
- return (result == ExportCardinalityCheckResult.Match);
- }
-
- /// <summary>
- /// Returns all exports that match the constraint defined by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="Export"/> objects to return.
- /// </param>
- /// <result>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
- /// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
- /// empty <see cref="IEnumerable{T}"/>.
- /// </result>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this method should not treat cardinality-related mismatches
- /// as errors, and should not throw exceptions in those cases. For instance,
- /// if <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ExactlyOne"/>
- /// and there are zero <see cref="Export"/> objects that match the conditions of the
- /// specified <see cref="ImportDefinition"/>, an <see cref="IEnumerable{T}"/> should be returned.
- /// </note>
- /// </remarks>
- protected abstract IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition);
-
- /// <summary>
- /// Raises the <see cref="ExportsChanged"/> event.
- /// </summary>
- /// <param name="e">
- /// An <see cref="ExportsChangeEventArgs"/> containing the data for the event.
- /// </param>
- protected virtual void OnExportsChanged(ExportsChangeEventArgs e)
- {
- EventHandler<ExportsChangeEventArgs> changedEvent = this.ExportsChanged;
- if (changedEvent != null)
- {
- CompositionResult result = CompositionServices.TryFire(changedEvent, this, e);
- result.ThrowOnErrors(e.AtomicComposition);
- }
- }
-
- /// <summary>
- /// Raises the <see cref="ExportsChanging"/> event.
- /// </summary>
- /// <param name="e">
- /// An <see cref="ExportsChangeEventArgs"/> containing the data for the event.
- /// </param>
- protected virtual void OnExportsChanging(ExportsChangeEventArgs e)
- {
- EventHandler<ExportsChangeEventArgs> changingEvent = this.ExportsChanging;
- if (changingEvent != null)
- {
- CompositionResult result = CompositionServices.TryFire(changingEvent, this, e);
- result.ThrowOnErrors(e.AtomicComposition);
- }
- }
-
- private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
- {
- Assumes.NotNull(definition);
-
- exports = this.GetExportsCore(definition, atomicComposition);
-
- if (exports == null)
- {
- exports = Enumerable.Empty<Export>();
- }
-
- var checkResult = ExportServices.CheckCardinality(definition, exports);
-
- // Export providers treat >1 match as zero for cardinality 0-1 imports
- // If this policy is moved we need to revisit the assumption that the
- // ImportEngine made during previewing the only required imports to
- // now also preview optional imports.
- if (checkResult == ExportCardinalityCheckResult.TooManyExports &&
- definition.Cardinality == ImportCardinality.ZeroOrOne)
- {
- checkResult = ExportCardinalityCheckResult.Match;
- exports = Enumerable.Empty<Export>();
- }
-
- return checkResult;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs deleted file mode 100644 index 58f962fbf43..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs +++ /dev/null @@ -1,110 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Linq;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// Provides data for the <see cref="ExportProvider.ExportsChanged"/> and
- /// <see cref="ExportProvider.ExportsChanging"/> events.
- /// </summary>
- public class ExportsChangeEventArgs : EventArgs
- {
- private IEnumerable<string> _changedContractNames = null;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportsChangeEventArgs"/> class with
- /// the specified changed export definitions.
- /// </summary>
- /// <param name="addedExports">
- /// An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/>s of the exports
- /// that have been added.
- /// </param>
- /// <param name="removedExports">
- /// An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/>s of the exports
- /// that have been removed.
- /// </param>
- /// <param name="atomicComposition">
- /// A <see cref="AtomicComposition"/> representing all tentative changes that will
- /// be completed if the change is successful, or discarded if it is not.
- /// <see langword="null"/> if being applied outside a <see cref="AtomicComposition"/>
- /// or during a <see cref="ExportProvider.ExportsChanged"/> event.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="addedExports"/> or <paramref name="removedExports"/> is <see langword="null"/>.
- /// </exception>
- public ExportsChangeEventArgs(IEnumerable<ExportDefinition> addedExports,
- IEnumerable<ExportDefinition> removedExports, AtomicComposition atomicComposition)
- {
- Requires.NotNull(addedExports, "addedExports");
- Requires.NotNull(removedExports, "removedExports");
-
- this.AddedExports = addedExports.AsArray();
- this.RemovedExports = removedExports.AsArray();
- this.AtomicComposition = atomicComposition;
- }
-
- /// <summary>
- /// Gets the export definitions for the exports that have been added.
- /// </summary>
- /// <value>
- /// A <see cref="IEnumerable{T}"/> of ExportDefinitions representing
- /// the exports that have been added to the <see cref="CompositionContainer"/>.
- /// </value>
- public IEnumerable<ExportDefinition> AddedExports { get; private set; }
-
- /// <summary>
- /// Gets the export definitions for the exports that have been removed.
- /// </summary>
- /// <value>
- /// A <see cref="IEnumerable{T}"/> of ExportDefinitions representing
- /// the exports that have been added to the <see cref="CompositionContainer"/>.
- /// </value>
- public IEnumerable<ExportDefinition> RemovedExports { get; private set; }
-
- /// <summary>
- /// Gets the contract names of the exports that have changed.
- /// </summary>
- /// <value>
- /// A <see cref="IEnumerable{T}"/> of strings representing the contract names of
- /// the exports that have changed in the <see cref="CompositionContainer"/>.
- /// </value>
- public IEnumerable<string> ChangedContractNames
- {
- get
- {
- if (this._changedContractNames == null)
- {
- this._changedContractNames = this.AddedExports
- .Concat(this.RemovedExports)
- .Select(export => export.ContractName)
- .Distinct()
- .ToArray();
- }
- return this._changedContractNames;
- }
- }
-
- /// <summary>
- /// Gets the atomicComposition, if any, that this change applies to.
- /// </summary>
- /// <value>
- /// A <see cref="AtomicComposition"/> that this set of changes applies too.
- ///
- /// It can be <see langword="null"/> if the changes are being applied outside a
- /// <see cref="AtomicComposition"/> or during a
- /// <see cref="ExportProvider.ExportsChanged"/> event.
- ///
- /// When the value is non-null it should be used to record temporary changed state
- /// and actions that will be executed when the atomicComposition is completeed.
- /// </value>
- public AtomicComposition AtomicComposition { get; private set; }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs deleted file mode 100644 index 4e5f8259631..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs +++ /dev/null @@ -1,19 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// Notifications when a ComposablePartCatalog changes.
- /// </summary>
- public interface INotifyComposablePartCatalogChanged
- {
- event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
- event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs deleted file mode 100644 index 890b01952cb..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class ImportEngine
- {
- /// <summary>
- /// Used to wrap the start and stop of enforcing export changes don't
- /// break required imports. This context is stored in a AtomicComposition.
- /// </summary>
- private class EngineContext
- {
- private ImportEngine _importEngine;
- private List<PartManager> _addedPartManagers = new List<PartManager>();
- private List<PartManager> _removedPartManagers = new List<PartManager>();
- private EngineContext _parentEngineContext;
-
- public EngineContext(ImportEngine importEngine, EngineContext parentEngineContext)
- {
- this._importEngine = importEngine;
- this._parentEngineContext = parentEngineContext;
- }
-
- public void AddPartManager(PartManager part)
- {
- Assumes.NotNull(part);
- if (!this._removedPartManagers.Remove(part))
- {
- this._addedPartManagers.Add(part);
- }
- }
-
- public void RemovePartManager(PartManager part)
- {
- Assumes.NotNull(part);
- if (!this._addedPartManagers.Remove(part))
- {
- this._removedPartManagers.Add(part);
- }
- }
-
- public IEnumerable<PartManager> GetAddedPartManagers()
- {
- if (this._parentEngineContext != null)
- {
- return this._addedPartManagers.ConcatAllowingNull(this._parentEngineContext.GetAddedPartManagers());
- }
- return this._addedPartManagers;
- }
-
- public IEnumerable<PartManager> GetRemovedPartManagers()
- {
- if (this._parentEngineContext != null)
- {
- return this._removedPartManagers.ConcatAllowingNull(this._parentEngineContext.GetRemovedPartManagers());
- }
- return this._removedPartManagers;
- }
-
- public void Complete()
- {
- foreach (var partManager in this._addedPartManagers)
- {
- this._importEngine.StartSatisfyingImports(partManager, null);
- }
-
- foreach (var partManager in this._removedPartManagers)
- {
- this._importEngine.StopSatisfyingImports(partManager, null);
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs deleted file mode 100644 index d092c670113..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs +++ /dev/null @@ -1,211 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class ImportEngine
- {
- /// <summary>
- /// Used by the <see cref="ImportEngine"/> to manage the composition of a given part.
- /// It stores things like the list of disposable exports used to satisfy the imports as
- /// well as the caching of the exports discovered during previewing of a part.
- /// </summary>
- private class PartManager
- {
- private Dictionary<ImportDefinition, List<IDisposable>> _importedDisposableExports;
- private Dictionary<ImportDefinition, Export[]> _importCache;
- private string[] _importedContractNames;
- private ComposablePart _part;
- private ImportState _state = ImportState.NoImportsSatisfied;
- private readonly ImportEngine _importEngine;
-
- public PartManager(ImportEngine importEngine, ComposablePart part)
- {
- this._importEngine = importEngine;
- this._part = part;
- }
-
- public ComposablePart Part
- {
- get
- {
- return this._part;
- }
- }
-
- public ImportState State
- {
- get
- {
- using (this._importEngine._lock.LockStateForRead())
- {
- return this._state;
- }
- }
- set
- {
- using (this._importEngine._lock.LockStateForWrite())
- {
- this._state = value;
- }
- }
- }
-
- public bool TrackingImports { get; set; }
-
- public IEnumerable<string> GetImportedContractNames()
- {
- if (this.Part == null)
- {
- return Enumerable.Empty<string>();
- }
-
- if (this._importedContractNames == null)
- {
- this._importedContractNames = this.Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray();
- }
- return this._importedContractNames;
- }
-
- public CompositionResult TrySetImport(ImportDefinition import, IEnumerable<Export> exports)
- {
- try
- {
- this.Part.SetImport(import, exports);
- UpdateDisposableDependencies(import, exports);
- return CompositionResult.SucceededResult;
- }
- catch (CompositionException ex)
- { // Pulling on one of the exports failed
-
- return new CompositionResult(
- ErrorBuilder.CreatePartCannotSetImport(Part, import, ex));
- }
- catch (ComposablePartException ex)
- { // Type mismatch between export and import
-
- return new CompositionResult(
- ErrorBuilder.CreatePartCannotSetImport(Part, import, ex));
- }
- }
-
- public void SetSavedImport(ImportDefinition import, Export[] exports, AtomicComposition atomicComposition)
- {
- if (atomicComposition != null)
- {
- var savedExports = this.GetSavedImport(import);
-
- // Add a revert action to revert the stored exports
- // in the case that this atomicComposition gets rolled back.
- atomicComposition.AddRevertAction(() =>
- this.SetSavedImport(import, savedExports, null));
- }
-
- if (this._importCache == null)
- {
- this._importCache = new Dictionary<ImportDefinition, Export[]>();
- }
-
- this._importCache[import] = exports;
- }
-
- public Export[] GetSavedImport(ImportDefinition import)
- {
- Export[] exports = null;
- if (this._importCache != null)
- {
- // We don't care about the return value we just want the exports
- // and if it isn't present we just return the initialized null value
- this._importCache.TryGetValue(import, out exports);
- }
- return exports;
- }
-
- public void ClearSavedImports()
- {
- this._importCache = null;
- }
-
- public CompositionResult TryOnComposed()
- {
- try
- {
- this.Part.Activate();
- return CompositionResult.SucceededResult;
- }
- catch (ComposablePartException ex)
- { // Type failed to be constructed, imports could not be set, etc
- return new CompositionResult(
- ErrorBuilder.CreatePartCannotActivate(this.Part, ex));
- }
- }
-
- public void UpdateDisposableDependencies(ImportDefinition import, IEnumerable<Export> exports)
- {
- // Determine if there are any new disposable exports, optimizing for the most
- // likely case, which is that there aren't any
- List<IDisposable> disposableExports = null;
- foreach (var disposableExport in exports.OfType<IDisposable>())
- {
- if (disposableExports == null)
- {
- disposableExports = new List<IDisposable>();
- }
- disposableExports.Add(disposableExport);
- }
-
- // Dispose any existing references previously set on this import
- List<IDisposable> oldDisposableExports = null;
- if (this._importedDisposableExports != null &&
- this._importedDisposableExports.TryGetValue(import, out oldDisposableExports))
- {
- oldDisposableExports.ForEach(disposable => disposable.Dispose());
-
- // If there aren't any replacements, get rid of the old storage
- if (disposableExports == null)
- {
- this._importedDisposableExports.Remove(import);
- if (!this._importedDisposableExports.FastAny())
- {
- this._importedDisposableExports = null;
- }
-
- return;
- }
- }
-
- // Record the new collection
- if (disposableExports != null)
- {
- if (this._importedDisposableExports == null)
- {
- this._importedDisposableExports = new Dictionary<ImportDefinition, List<IDisposable>>();
- }
- this._importedDisposableExports[import] = disposableExports;
- }
- }
-
- public void DisposeAllDependencies()
- {
- if (this._importedDisposableExports != null)
- {
- IEnumerable<IDisposable> dependencies = this._importedDisposableExports.Values
- .SelectMany(exports => exports);
-
- this._importedDisposableExports = null;
-
- dependencies.ForEach(disposableExport => disposableExport.Dispose());
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs deleted file mode 100644 index ff3eb19dee6..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs +++ /dev/null @@ -1,159 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- public partial class ImportEngine
- {
- /// <summary>
- /// Used by the <see cref="ImportEngine"/> to effiecently store and retrieve the list of parts
- /// that will be affected by changes to exports. This allows the <see cref="ImportEngine"/> to properly
- /// block breaking changes and also recompose imports as appropriate.
- /// </summary>
- private class RecompositionManager
- {
- private WeakReferenceCollection<PartManager> _partsToIndex = new WeakReferenceCollection<PartManager>();
- private WeakReferenceCollection<PartManager> _partsToUnindex = new WeakReferenceCollection<PartManager>();
- private Dictionary<string, WeakReferenceCollection<PartManager>> _partManagerIndex = new Dictionary<string, WeakReferenceCollection<PartManager>>();
-
- public void AddPartToIndex(PartManager partManager)
- {
- this._partsToIndex.Add(partManager);
- }
-
- public void AddPartToUnindex(PartManager partManager)
- {
- this._partsToUnindex.Add(partManager);
- }
-
- public IEnumerable<PartManager> GetAffectedParts(IEnumerable<string> changedContractNames)
- {
- this.UpdateImportIndex();
-
- List<PartManager> parts = new List<PartManager>();
-
- parts.AddRange(GetPartsImporting(ImportDefinition.EmptyContractName));
-
- foreach (string contractName in changedContractNames)
- {
- parts.AddRange(GetPartsImporting(contractName));
- }
-
- return parts;
- }
-
- public static IEnumerable<ImportDefinition> GetAffectedImports(ComposablePart part, IEnumerable<ExportDefinition> changedExports)
- {
- return part.ImportDefinitions.Where(import => IsAffectedImport(import, changedExports));
- }
-
- private static bool IsAffectedImport(ImportDefinition import, IEnumerable<ExportDefinition> changedExports)
- {
- // This could be more efficient still if the export definitions were indexed by contract name,
- // only worth revisiting if we need to squeeze more performance out of recomposition
- foreach (var export in changedExports)
- {
- if (import.IsConstraintSatisfiedBy(export))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public IEnumerable<PartManager> GetPartsImporting(string contractName)
- {
- WeakReferenceCollection<PartManager> partManagerList;
- if (!this._partManagerIndex.TryGetValue(contractName, out partManagerList))
- {
- return Enumerable.Empty<PartManager>();
- }
-
- return partManagerList.AliveItemsToList();
- }
-
- private void AddIndexEntries(PartManager partManager)
- {
- foreach (string contractName in partManager.GetImportedContractNames())
- {
- WeakReferenceCollection<PartManager> indexEntries;
- if (!this._partManagerIndex.TryGetValue(contractName, out indexEntries))
- {
- indexEntries = new WeakReferenceCollection<PartManager>();
- this._partManagerIndex.Add(contractName, indexEntries);
- }
-
- if (!indexEntries.Contains(partManager))
- {
- indexEntries.Add(partManager);
- }
- }
- }
-
- private void RemoveIndexEntries(PartManager partManager)
- {
- foreach (string contractName in partManager.GetImportedContractNames())
- {
- WeakReferenceCollection<PartManager> indexEntries;
- if (this._partManagerIndex.TryGetValue(contractName, out indexEntries))
- {
- indexEntries.Remove(partManager);
- var aliveItems = indexEntries.AliveItemsToList();
-
- if (aliveItems.Count == 0)
- {
- this._partManagerIndex.Remove(contractName);
- }
- }
- }
- }
-
- private void UpdateImportIndex()
- {
- var partsToIndex = this._partsToIndex.AliveItemsToList();
- this._partsToIndex.Clear();
-
- var partsToUnindex = this._partsToUnindex.AliveItemsToList();
- this._partsToUnindex.Clear();
-
- if (partsToIndex.Count == 0 && partsToUnindex.Count == 0)
- {
- return;
- }
-
- foreach (var partManager in partsToIndex)
- {
- var index = partsToUnindex.IndexOf(partManager);
-
- // If the same part is being added and removed we can ignore both
- if (index >= 0)
- {
- partsToUnindex[index] = null;
- }
- else
- {
- AddIndexEntries(partManager);
- }
- }
-
- foreach (var partManager in partsToUnindex)
- {
- if (partManager != null)
- {
- RemoveIndexEntries(partManager);
- }
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.cs deleted file mode 100644 index 29bd329c3ca..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/ImportEngine.cs +++ /dev/null @@ -1,754 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- // This class guarantees thread-safety under the follwoing conditions:
- // - Each composition is executed on a single thread
- // - No recomposition ever takes place
- // - The class is created with isThreadSafe=true
- public partial class ImportEngine : ICompositionService, IDisposable
- {
- private const int MaximumNumberOfCompositionIterations = 100;
-
- private volatile bool _isDisposed;
- private ExportProvider _sourceProvider;
- private Stack<PartManager> _recursionStateStack = new Stack<PartManager>();
- private ConditionalWeakTable<ComposablePart, PartManager> _partManagers = new ConditionalWeakTable<ComposablePart, PartManager>();
- private RecompositionManager _recompositionManager = new RecompositionManager();
- private readonly CompositionLock _lock = null;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportEngine"/> class.
- /// </summary>
- /// <param name="sourceProvider">
- /// The <see cref="ExportProvider"/> which provides the
- /// <see cref="ImportEngine"/> access to <see cref="Export"/>s.
- /// </param>
- public ImportEngine(ExportProvider sourceProvider)
- : this(sourceProvider, false)
- {
- }
-
- public ImportEngine(ExportProvider sourceProvider, bool isThreadSafe)
- {
- Requires.NotNull(sourceProvider, "sourceProvider");
-
- this._sourceProvider = sourceProvider;
- this._sourceProvider.ExportsChanging += this.OnExportsChanging;
- this._lock = new CompositionLock(isThreadSafe);
- }
-
- /// <summary>
- /// Previews all the required imports for the given <see cref="ComposablePart"/> to
- /// ensure they can all be satisified. The preview does not actually set the imports
- /// only ensures that they exist in the source provider. If the preview succeeds then
- /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source
- /// provider will not break any of the required imports. If this enforcement needs to be
- /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this
- /// <see cref="ComposablePart"/>.
- /// </summary>
- /// <param name="part">
- /// The <see cref="ComposablePart"/> to preview the required imports.
- /// </param>
- /// <param name="atomicComposition"></param>
- /// <exception cref="CompositionException">
- /// An error occurred during previewing and <paramref name="atomicComposition"/> is null.
- /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred.
- /// The pre-existing composition is in an unknown state, depending on the errors that occured.
- /// </exception>
- /// <exception cref="ChangeRejectedException">
- /// An error occurred during the previewing and <paramref name="atomicComposition"/> is not null.
- /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred.
- /// The pre-existing composition remains in valid state.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ImportEngine"/> has been disposed of.
- /// </exception>
- public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(part, "part");
-
- // NOTE : this is a very intricate area threading-wise, please use caution when changing, otherwise state corruption or deadlocks will ensue
- // The gist of what we are doing is as follows:
- // We need to lock the composition, as we will proceed modifying our internal state. The tricky part is when we release the lock
- // Due to the fact that some actions will take place AFTER we leave this method, we need to KEEP THAT LOCK HELD until the transation is commiited or rolled back
- // This is the reason we CAN'T use "using here.
- // Instead, if the transaction is present we will queue up the release of the lock, otherwise we will release it when we exit this method
- // We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless.
-
- // This will take the lock, if necesary
- IDisposable compositionLockHolder = this._lock.IsThreadSafe ? this._lock.LockComposition() : null;
- bool compositionLockTaken = (compositionLockHolder != null);
- try
- {
- // revert actions are processed in the reverse order, so we have to add the "release lock" action now
- if (compositionLockTaken && (atomicComposition != null))
- {
- atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose());
- }
-
- var partManager = GetPartManager(part, true);
- var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition);
- result.ThrowOnErrors(atomicComposition);
-
- StartSatisfyingImports(partManager, atomicComposition);
-
- // Add the "release lock" to the commit actions
- if (compositionLockTaken && (atomicComposition != null))
- {
- atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose());
- }
- }
- finally
- {
- // We haven't updated the queues, so we can release the lock now
- if (compositionLockTaken && (atomicComposition == null))
- {
- compositionLockHolder.Dispose();
- }
- }
- }
-
- /// <summary>
- /// Satisfies the imports of the specified composable part. If the satisfy succeeds then
- /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source
- /// provider will not break any of the required imports. If this enforcement needs to be
- /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this
- /// <see cref="ComposablePart"/>.
- /// </summary>
- /// <param name="part">
- /// The <see cref="ComposablePart"/> to set the imports.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="part"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ImportEngine"/> has been disposed of.
- /// </exception>
- public void SatisfyImports(ComposablePart part)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(part, "part");
-
- // NOTE : the following two calls use the state lock
- PartManager partManager = this.GetPartManager(part, true);
- if (partManager.State == ImportState.Composed)
- {
- return;
- }
-
- using (this._lock.LockComposition())
- {
- var result = TrySatisfyImports(partManager, part, true);
- result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException
- }
- }
-
- /// <summary>
- /// Sets the imports of the specified composable part exactly once and they will not
- /// ever be recomposed.
- /// </summary>
- /// <param name="part">
- /// The <see cref="ComposablePart"/> to set the imports.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="part"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ICompositionService"/> has been disposed of.
- /// </exception>
- public void SatisfyImportsOnce(ComposablePart part)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(part, "part");
-
- // NOTE : the following two calls use the state lock
- PartManager partManager = this.GetPartManager(part, true);
- if (partManager.State == ImportState.Composed)
- {
- return;
- }
-
- using (this._lock.LockComposition())
- {
- var result = TrySatisfyImports(partManager, part, false);
- result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException
- }
- }
-
- /// <summary>
- /// Removes any state stored in the <see cref="ImportEngine"/> for the associated
- /// <see cref="ComposablePart"/> and releases all the <see cref="Export"/>s used to
- /// satisfy the imports on the <see cref="ComposablePart"/>.
- ///
- /// Also removes the enforcement for changes that would break a required import on
- /// <paramref name="part"/>.
- /// </summary>
- /// <param name="part">
- /// The <see cref="ComposablePart"/> to release the imports on.
- /// </param>
- /// <param name="atomicComposition">
- /// The <see cref="AtomicComposition"/> that the release imports is running under.
- /// </param>
- public void ReleaseImports(ComposablePart part, AtomicComposition atomicComposition)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(part, "part");
-
- using (this._lock.LockComposition())
- {
- PartManager partManager = this.GetPartManager(part, false);
- if (partManager != null)
- {
- this.StopSatisfyingImports(partManager, atomicComposition);
- }
- }
- }
-
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources
- /// </summary>
- /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (!this._isDisposed)
- {
- bool disposeLock = false;
- ExportProvider sourceProviderToUnsubscribeFrom = null;
- using (this._lock.LockStateForWrite())
- {
- if (!this._isDisposed)
- {
- sourceProviderToUnsubscribeFrom = this._sourceProvider;
- this._sourceProvider = null;
- this._recompositionManager = null;
- this._partManagers = null;
- this._isDisposed = true;
- disposeLock = true;
- }
- }
-
- if (sourceProviderToUnsubscribeFrom != null)
- {
- sourceProviderToUnsubscribeFrom.ExportsChanging -= this.OnExportsChanging;
- }
-
- if (disposeLock)
- {
- this._lock.Dispose();
- }
- }
- }
- }
-
- private CompositionResult TryPreviewImportsStateMachine(PartManager partManager,
- ComposablePart part, AtomicComposition atomicComposition)
- {
- var result = CompositionResult.SucceededResult;
-
- if (partManager.State == ImportState.ImportsPreviewing)
- {
- // We shouldn't nomally ever hit this case but if we do
- // then we should just error with a cycle error.
- return new CompositionResult(ErrorBuilder.CreatePartCycle(part));
- }
-
- // Transition from NoImportsStatisified to ImportsPreviewed
- if (partManager.State == ImportState.NoImportsSatisfied)
- {
- partManager.State = ImportState.ImportsPreviewing;
-
- var requiredImports = part.ImportDefinitions.Where(IsRequiredImportForPreview);
-
- // If this atomicComposition gets rolledback for any reason we need to reset our state
- atomicComposition.AddRevertActionAllowNull(() => partManager.State = ImportState.NoImportsSatisfied);
-
- result = result.MergeResult(
- this.TrySatisfyImportSubset(partManager, requiredImports, atomicComposition));
-
- if (!result.Succeeded)
- {
- partManager.State = ImportState.NoImportsSatisfied;
- return result;
- }
-
- partManager.State = ImportState.ImportsPreviewed;
- }
-
- return result;
- }
-
- private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, ComposablePart part)
- {
- var result = CompositionResult.SucceededResult;
-
- while (partManager.State < ImportState.Composed)
- {
- var previousState = partManager.State;
-
- switch (partManager.State)
- {
- // "ed" states which represent a some sort of steady state and will
- // attempt to do a state transition
- case ImportState.NoImportsSatisfied:
- case ImportState.ImportsPreviewed:
- {
- partManager.State = ImportState.PreExportImportsSatisfying;
-
- var prereqImports = part.ImportDefinitions.Where(import => import.IsPrerequisite);
- result = result.MergeResult(
- this.TrySatisfyImportSubset(partManager, prereqImports, null));
-
- partManager.State = ImportState.PreExportImportsSatisfied;
- break;
- }
- case ImportState.PreExportImportsSatisfied:
- {
- partManager.State = ImportState.PostExportImportsSatisfying;
-
- var requiredImports = part.ImportDefinitions.Where(import => !import.IsPrerequisite);
-
- result = result.MergeResult(
- this.TrySatisfyImportSubset(partManager, requiredImports, null));
-
- partManager.State = ImportState.PostExportImportsSatisfied;
- break;
- }
- case ImportState.PostExportImportsSatisfied:
- {
- partManager.State = ImportState.ComposedNotifying;
-
- partManager.ClearSavedImports();
- result = result.MergeResult(partManager.TryOnComposed());
-
- partManager.State = ImportState.Composed;
- break;
- }
-
-
- // "ing" states which represent some sort of cycle
- // These state should always return, error or not, instead of breaking
- case ImportState.ImportsPreviewing:
- {
- // We shouldn't nomally ever hit this case but if we do
- // then we should just error with a cycle error.
- return new CompositionResult(ErrorBuilder.CreatePartCycle(part));
- }
- case ImportState.PreExportImportsSatisfying:
- case ImportState.PostExportImportsSatisfying:
- {
- if (InPrerequisiteLoop())
- {
- return result.MergeError(ErrorBuilder.CreatePartCycle(part));
- }
- // Cycles in post export imports are allowed so just return in that case
- return result;
- }
- case ImportState.ComposedNotifying:
- {
- // We are currently notifying so don't notify again just return
- return result;
- }
- }
-
- // if an error occured while doing a state transition
- if (!result.Succeeded)
- {
- // revert to the previous state and return the error
- partManager.State = previousState;
- return result;
- }
- }
- return result;
- }
-
- private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part, bool shouldTrackImports)
- {
- Assumes.NotNull(part);
-
- var result = CompositionResult.SucceededResult;
-
- // get out if the part is already composed
- if (partManager.State == ImportState.Composed)
- {
- return result;
- }
-
- // Track number of recursive iterations and throw an exception before the stack
- // fills up and debugging the root cause becomes tricky
- if (this._recursionStateStack.Count >= MaximumNumberOfCompositionIterations)
- {
- return result.MergeError(
- ErrorBuilder.ComposeTookTooManyIterations(MaximumNumberOfCompositionIterations));
- }
-
- // Maintain the stack to detect whether recursive loops cross prerequisites
- this._recursionStateStack.Push(partManager);
- try
- {
- result = result.MergeResult(
- TrySatisfyImportsStateMachine(partManager, part));
- }
- finally
- {
- this._recursionStateStack.Pop();
- }
-
- if (shouldTrackImports)
- {
- StartSatisfyingImports(partManager, null);
- }
-
- return result;
- }
-
- private CompositionResult TrySatisfyImportSubset(PartManager partManager,
- IEnumerable<ImportDefinition> imports, AtomicComposition atomicComposition)
- {
- CompositionResult result = CompositionResult.SucceededResult;
-
- var part = partManager.Part;
- foreach (ImportDefinition import in imports)
- {
- var exports = partManager.GetSavedImport(import);
-
- if (exports == null)
- {
- CompositionResult<IEnumerable<Export>> exportsResult = TryGetExports(
- this._sourceProvider, part, import, atomicComposition);
-
- if (!exportsResult.Succeeded)
- {
- result = result.MergeResult(exportsResult.ToResult());
- continue;
- }
- exports = exportsResult.Value.AsArray();
- }
-
- if (atomicComposition == null)
- {
- result = result.MergeResult(
- partManager.TrySetImport(import, exports));
- }
- else
- {
- partManager.SetSavedImport(import, exports, atomicComposition);
- }
- }
- return result;
- }
-
- private void OnExportsChanging(object sender, ExportsChangeEventArgs e)
- {
- CompositionResult result = CompositionResult.SucceededResult;
-
- // Prepare for the recomposition effort by minimizing the amount of work we'll have to do later
- AtomicComposition atomicComposition = e.AtomicComposition;
-
- IEnumerable<PartManager> affectedParts = this._recompositionManager.GetAffectedParts(e.ChangedContractNames);
-
- // When in a atomicComposition account for everything that isn't yet reflected in the
- // index
- if (atomicComposition != null)
- {
- EngineContext engineContext;
- if (atomicComposition.TryGetValue(this, out engineContext))
- {
- // always added the new part managers to see if they will also be
- // affected by these changes
- affectedParts = affectedParts.ConcatAllowingNull(engineContext.GetAddedPartManagers())
- .Except(engineContext.GetRemovedPartManagers());
- }
- }
-
- var changedExports = e.AddedExports.ConcatAllowingNull(e.RemovedExports);
-
- foreach (var partManager in affectedParts)
- {
- result = result.MergeResult(this.TryRecomposeImports(partManager, changedExports, atomicComposition));
- }
-
- result.ThrowOnErrors(atomicComposition);
- }
-
- private CompositionResult TryRecomposeImports(PartManager partManager,
- IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
- {
- var result = CompositionResult.SucceededResult;
-
- switch (partManager.State)
- {
- case ImportState.ImportsPreviewed:
- case ImportState.Composed:
- // Validate states to continue.
- break;
-
- default:
- {
- // All other states are invalid and for recomposition.
- return new CompositionResult(ErrorBuilder.InvalidStateForRecompposition(partManager.Part));
- }
- }
-
- var affectedImports = RecompositionManager.GetAffectedImports(partManager.Part, changedExports);
- bool partComposed = (partManager.State == ImportState.Composed);
-
- bool recomposedImport = false;
- foreach (var import in affectedImports)
- {
- result = result.MergeResult(
- TryRecomposeImport(partManager, partComposed, import, atomicComposition));
-
- recomposedImport = true;
- }
-
- // Knowing that the part has already been composed before and that the only possible
- // changes are to recomposable imports, we can safely go ahead and do this now or
- // schedule it for later
- if (result.Succeeded && recomposedImport && partComposed)
- {
- if (atomicComposition == null)
- {
- result = result.MergeResult(partManager.TryOnComposed());
- }
- else
- {
- atomicComposition.AddCompleteAction(() => partManager.TryOnComposed().ThrowOnErrors());
- }
- }
-
- return result;
- }
-
- private CompositionResult TryRecomposeImport(PartManager partManager, bool partComposed,
- ImportDefinition import, AtomicComposition atomicComposition)
- {
- if (partComposed && !import.IsRecomposable)
- {
- return new CompositionResult(ErrorBuilder.PreventedByExistingImport(partManager.Part, import));
- }
-
- // During recomposition you must always requery with the new atomicComposition you cannot use any
- // cached value in the part manager
- var exportsResult = TryGetExports(this._sourceProvider, partManager.Part, import, atomicComposition);
- if (!exportsResult.Succeeded)
- {
- return exportsResult.ToResult();
- }
- var exports = exportsResult.Value.AsArray();
-
- if (partComposed)
- {
- // Knowing that the part has already been composed before and that the only possible
- // changes are to recomposable imports, we can safely go ahead and do this now or
- // schedule it for later
- if (atomicComposition == null)
- {
- return partManager.TrySetImport(import, exports);
- }
- else
- {
- atomicComposition.AddCompleteAction(() => partManager.TrySetImport(import, exports).ThrowOnErrors());
- }
- }
- else
- {
- partManager.SetSavedImport(import, exports, atomicComposition);
- }
-
- return CompositionResult.SucceededResult;
- }
-
- private void StartSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition)
- {
- // When not running in a atomicCompositional state, schedule reindexing after ensuring
- // that this isn't a redundant addition
- if (atomicComposition == null)
- {
- if (!partManager.TrackingImports)
- {
- partManager.TrackingImports = true;
- this._recompositionManager.AddPartToIndex(partManager);
- }
- }
- else
- {
- // While in a atomicCompositional state use a less efficient but effective means
- // of achieving the same results
- GetEngineContext(atomicComposition).AddPartManager(partManager);
- }
- }
-
- private void StopSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition)
- {
- // When not running in a atomicCompositional state, schedule reindexing after ensuring
- // that this isn't a redundant removal
- if (atomicComposition == null)
- {
- this._partManagers.Remove(partManager.Part);
-
- // Take care of lifetime requirements
- partManager.DisposeAllDependencies();
-
- if (partManager.TrackingImports)
- {
- partManager.TrackingImports = false;
- this._recompositionManager.AddPartToUnindex(partManager);
- }
- }
- else
- {
- // While in a atomicCompositional state use a less efficient but effective means
- // of achieving the same results
- GetEngineContext(atomicComposition).RemovePartManager(partManager);
- }
- }
-
- private PartManager GetPartManager(ComposablePart part, bool createIfNotpresent)
- {
- PartManager partManager = null;
- using (this._lock.LockStateForRead())
- {
- if (this._partManagers.TryGetValue(part, out partManager))
- {
- return partManager;
- }
- }
-
- if (createIfNotpresent)
- {
- using (this._lock.LockStateForWrite())
- {
- if (!this._partManagers.TryGetValue(part, out partManager))
- {
- partManager = new PartManager(this, part);
- this._partManagers.Add(part, partManager);
- }
- }
- }
- return partManager;
- }
-
-
- private EngineContext GetEngineContext(AtomicComposition atomicComposition)
- {
- Assumes.NotNull(atomicComposition);
-
- EngineContext engineContext;
- if (!atomicComposition.TryGetValue(this, true, out engineContext))
- {
- EngineContext parentContext;
- atomicComposition.TryGetValue(this, false, out parentContext);
- engineContext = new EngineContext(this, parentContext);
- atomicComposition.SetValue(this, engineContext);
- atomicComposition.AddCompleteAction(engineContext.Complete);
- }
- return engineContext;
- }
-
- private bool InPrerequisiteLoop()
- {
- PartManager firstPart = this._recursionStateStack.First();
- PartManager lastPart = null;
-
- foreach (PartManager testPart in this._recursionStateStack.Skip(1))
- {
- if (testPart.State == ImportState.PreExportImportsSatisfying)
- {
- return true;
- }
-
- if (testPart == firstPart)
- {
- lastPart = testPart;
- break;
- }
- }
-
- // This should only be called when a loop has been detected - so it should always be on the stack
- Assumes.IsTrue(lastPart == firstPart);
- return false;
- }
-
- [DebuggerStepThrough]
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
-
- private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider provider,
- ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition)
- {
- try
- {
- var exports = provider.GetExports(definition, atomicComposition).AsArray();
- return new CompositionResult<IEnumerable<Export>>(exports);
- }
- catch (ImportCardinalityMismatchException ex)
- {
- // Either not enough or too many exports that match the definition
- CompositionException exception = new CompositionException(ErrorBuilder.CreateImportCardinalityMismatch(ex, definition));
-
- return new CompositionResult<IEnumerable<Export>>(
- ErrorBuilder.CreatePartCannotSetImport(part, definition, exception));
- }
- }
-
- internal static bool IsRequiredImportForPreview(ImportDefinition import)
- {
- return import.Cardinality == ImportCardinality.ExactlyOne;
- }
-
- // Ordering of this enum is important so be sure to use caution if you
- // try to reorder them.
- private enum ImportState
- {
- NoImportsSatisfied = 0,
- ImportsPreviewing = 1,
- ImportsPreviewed = 2,
- PreExportImportsSatisfying = 3,
- PreExportImportsSatisfied = 4,
- PostExportImportsSatisfying = 5,
- PostExportImportsSatisfied = 6,
- ComposedNotifying = 7,
- Composed = 8,
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/TypeCatalog.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/TypeCatalog.cs deleted file mode 100644 index cabc1e5dc5c..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/TypeCatalog.cs +++ /dev/null @@ -1,347 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.AttributedModel;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Hosting
-{
- /// <summary>
- /// An immutable ComposablePartCatalog created from a type array or a list of managed types. This class is threadsafe.
- /// It is Disposable.
- /// </summary>
- [DebuggerTypeProxy(typeof(ComposablePartCatalogDebuggerProxy))]
- public class TypeCatalog : ComposablePartCatalog, ICompositionElement
- {
- private readonly object _thisLock = new object();
- private Type[] _types = null;
- private volatile IQueryable<ComposablePartDefinition> _queryableParts;
- private volatile bool _isDisposed = false;
- private readonly ICompositionElement _definitionOrigin;
- private readonly Lazy<IDictionary<string, List<ComposablePartDefinition>>> _contractPartIndex;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="TypeCatalog"/> class
- /// with the specified types.
- /// </summary>
- /// <param name="types">
- /// An <see cref="Array"/> of attributed <see cref="Type"/> objects to add to the
- /// <see cref="TypeCatalog"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="types"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="types"/> contains an element that is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="types"/> contains an element that was loaded in the Reflection-only context.
- /// </exception>
- public TypeCatalog(params Type[] types)
- : this(types, (ICompositionElement)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="TypeCatalog"/> class
- /// with the specified types.
- /// </summary>
- /// <param name="types">
- /// An <see cref="IEnumerable{T}"/> of attributed <see cref="Type"/> objects to add
- /// to the <see cref="TypeCatalog"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="types"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="types"/> contains an element that is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="types"/> contains an element that was loaded in the reflection-only context.
- /// </exception>
- public TypeCatalog(IEnumerable<Type> types)
- : this(types, (ICompositionElement)null)
- {
- }
-
- internal TypeCatalog(IEnumerable<Type> types, ICompositionElement definitionOrigin)
- {
- Requires.NotNull(types, "types");
-
- foreach (Type type in types)
- {
- if (type == null)
- {
- throw ExceptionBuilder.CreateContainsNullElement("types");
- }
-#if !SILVERLIGHT
- if (type.Assembly.ReflectionOnly)
- {
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Argument_ElementReflectionOnlyType, "types"), "types");
- }
-#endif
- }
-
- this._types = types.ToArray();
- this._definitionOrigin = definitionOrigin ?? this;
-#if !SILVERLIGHT
- this._contractPartIndex = new Lazy<IDictionary<string, List<ComposablePartDefinition>>>(this.CreateIndex, true);
-#else
- this._contractPartIndex = new Lazy<IDictionary<string, List<ComposablePartDefinition>>>(this.CreateIndex);
-#endif
-
- }
-
- /// <summary>
- /// Gets the part definitions of the catalog.
- /// </summary>
- /// <value>
- /// A <see cref="IQueryable{T}"/> of <see cref="ComposablePartDefinition"/> objects of the
- /// <see cref="TypeCatalog"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="TypeCatalog"/> has been disposed of.
- /// </exception>
- public override IQueryable<ComposablePartDefinition> Parts
- {
- get
- {
- this.ThrowIfDisposed();
-
- return this.PartsInternal;
- }
- }
-
- /// <summary>
- /// Gets the display name of the type catalog.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a human-readable display name of the <see cref="TypeCatalog"/>.
- /// </value>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- string ICompositionElement.DisplayName
- {
- get { return this.GetDisplayName(); }
- }
-
- /// <summary>
- /// Gets the composition element from which the type catalog originated.
- /// </summary>
- /// <value>
- /// This property always returns <see langword="null"/>.
- /// </value>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
- ICompositionElement ICompositionElement.Origin
- {
- get { return null; }
- }
-
- private IQueryable<ComposablePartDefinition> PartsInternal
- {
- get
- {
- if (this._queryableParts == null)
- {
- lock (this._thisLock)
- {
- if (this._queryableParts == null)
- {
- Assumes.NotNull(this._types);
-
- var collection = new List<ComposablePartDefinition>();
- foreach (Type type in this._types)
- {
- var definition = AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, _definitionOrigin);
- if (definition != null)
- {
- collection.Add(definition);
- }
- }
- IQueryable<ComposablePartDefinition> queryableParts = collection.AsQueryable();
- Thread.MemoryBarrier();
-
- this._types = null;
- this._queryableParts = queryableParts;
- }
- }
- }
-
- return this._queryableParts;
- }
- }
-
- /// <summary>
- /// Returns the export definitions that match the constraint defined by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="ExportDefinition"/> objects to return.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
- /// <see cref="ExportDefinition"/> objects and their associated
- /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
- /// by <paramref name="definition"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePartCatalog"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>, if no
- /// <see cref="ExportDefinition"/> match the conditions defined by
- /// <paramref name="definition"/>, return an empty <see cref="IEnumerable{T}"/>.
- /// </note>
- /// </remarks>
- public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(definition, "definition");
-
- IEnumerable<ComposablePartDefinition> candidateParts = this.GetCandidateParts(definition);
- if (candidateParts == null)
- {
- return Enumerable.Empty<Tuple<ComposablePartDefinition, ExportDefinition>>();
- }
-
- var exports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
- foreach (var part in candidateParts)
- {
- foreach (var export in part.ExportDefinitions)
- {
- if (definition.IsConstraintSatisfiedBy(export))
- {
- exports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(part, export));
- }
- }
- }
- return exports;
- }
-
- private IEnumerable<ComposablePartDefinition> GetCandidateParts(ImportDefinition definition)
- {
- string contractName = definition.ContractName;
-
- // Empty string represents a non-contract based import and thus the constraint needs
- // to be applied to all the possible exports in this catalog.
- if (string.IsNullOrEmpty(contractName))
- {
- return this.PartsInternal;
- }
-
- List<ComposablePartDefinition> candidateParts = null;
- if (this._contractPartIndex.Value.TryGetValue(contractName, out candidateParts))
- {
- return candidateParts;
- }
- else
- {
- return null;
- }
- }
-
- private IDictionary<string, List<ComposablePartDefinition>> CreateIndex()
- {
- Dictionary<string, List<ComposablePartDefinition>> index = new Dictionary<string, List<ComposablePartDefinition>>(StringComparers.ContractName);
-
- foreach (var part in this.PartsInternal)
- {
- foreach (string contractName in part.ExportDefinitions.Select(export => export.ContractName).Distinct())
- {
- List<ComposablePartDefinition> contractParts = null;
- if (!index.TryGetValue(contractName, out contractParts))
- {
- contractParts = new List<ComposablePartDefinition>();
- index.Add(contractName, contractParts);
- }
- contractParts.Add(part);
- }
- }
- return index;
- }
-
- /// <summary>
- /// Returns a string representation of the type catalog.
- /// </summary>
- /// <returns>
- /// A <see cref="String"/> containing the string representation of the <see cref="TypeCatalog"/>.
- /// </returns>
- public override string ToString()
- {
- return this.GetDisplayName();
- }
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- this._isDisposed = true;
- }
-
- base.Dispose(disposing);
- }
-
- private string GetDisplayName()
- {
- return String.Format(CultureInfo.CurrentCulture,
- Strings.TypeCatalog_DisplayNameFormat,
- this.GetType().Name,
- this.GetTypesDisplay());
- }
-
- private string GetTypesDisplay()
- {
- int count = this.PartsInternal.Count();
- if (count == 0)
- {
- return Strings.TypeCatalog_Empty;
- }
-
- const int displayCount = 2;
- StringBuilder builder = new StringBuilder();
- foreach (ReflectionComposablePartDefinition definition in this.PartsInternal.Take(displayCount))
- {
- if (builder.Length > 0)
- {
- builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
- builder.Append(" ");
- }
-
- builder.Append(definition.GetPartType().GetDisplayName());
- }
-
- if (count > displayCount)
- { // Add an elipse to indicate that there
- // are more types than actually listed
- builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
- builder.Append(" ...");
- }
-
- return builder.ToString();
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/IAttributedImport.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/IAttributedImport.cs deleted file mode 100644 index a2f9c166d27..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/IAttributedImport.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- internal interface IAttributedImport
- {
- string ContractName { get; }
- Type ContractType { get; }
- bool AllowRecomposition { get; }
- CreationPolicy RequiredCreationPolicy { get; }
- ImportCardinality Cardinality { get; }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ICompositionError.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ICompositionError.cs deleted file mode 100644 index a31430ff72d..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ICompositionError.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- // Internal interface for providing access to the composition error
- // identifier for an exception or error that participates in composition.
- internal interface ICompositionError
- {
- CompositionErrorId Id
- {
- get;
- }
-
- ICompositionElement Element
- {
- get;
- }
-
- Exception InnerException
- {
- get;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ICompositionService.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ICompositionService.cs deleted file mode 100644 index 45a4dd90162..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ICompositionService.cs +++ /dev/null @@ -1,34 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Provides methods for composing <see cref="ComposablePart"/> objects.
- /// </summary>
- public interface ICompositionService
- {
- /// <summary>
- /// Sets the imports of the specified composable part exactly once and they will not
- /// ever be recomposed.
- /// </summary>
- /// <param name="part">
- /// The <see cref="ComposablePart"/> to set the imports.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="part"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ICompositionService"/> has been disposed of.
- /// </exception>
- void SatisfyImportsOnce(ComposablePart part);
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/IPartImportsSatisfiedNotification.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/IPartImportsSatisfiedNotification.cs deleted file mode 100644 index 60d592016ca..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/IPartImportsSatisfiedNotification.cs +++ /dev/null @@ -1,12 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition
-{
- public interface IPartImportsSatisfiedNotification
- {
- void OnImportsSatisfied();
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportAttribute.cs deleted file mode 100644 index b4015271fbc..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportAttribute.cs +++ /dev/null @@ -1,181 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies that a property, field, or parameter imports a particular export.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
- [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
- AllowMultiple = false, Inherited = false)]
- public class ImportAttribute : Attribute, IAttributedImport
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportAttribute"/> class, importing the
- /// export with the default contract name.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property, field,
- /// or parameter type that this is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ImportAttribute()
- : this((string)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportAttribute"/> class, importing the
- /// export with the contract name derived from the specified type.
- /// </summary>
- /// <param name="contractType">
- /// A <see cref="Type"/> of which to derive the contract name of the export to import, or
- /// <see langword="null"/> to use the default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on
- /// <paramref name="contractType"/>.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property, field,
- /// or parameter type that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ImportAttribute(Type contractType)
- : this((string)null, contractType)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportAttribute"/> class, importing the
- /// export with the specified contract name.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the export to import, or
- /// <see langword="null"/> or an empty string ("") to use the default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property, field,
- /// or parameter type that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ImportAttribute(string contractName)
- : this(contractName, (Type)null)
- {
- }
-
- public ImportAttribute(string contractName, Type contractType)
- {
- this.ContractName = contractName;
- this.ContractType = contractType;
- }
-
- /// <summary>
- /// Gets the contract name of the export to import.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the contract name of the export to import. The
- /// default value is an empty string ("").
- /// </value>
- public string ContractName { get; private set; }
-
- /// <summary>
- /// Get the contract type of the export to import.
- /// </summary>
- /// <value>
- /// A <see cref="Type"/> of the export that this import is expecting. The default value is
- /// <see langword="null"/> which means that the type will be obtained by looking at the type on
- /// the member that this import is attached to. If the type is <see cref="object"/> then the
- /// importer is delaring they can accept any exported type.
- /// </value>
- public Type ContractType { get; private set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether the property, field or parameter will be set
- /// to its type's default value when an export with the contract name is not present in
- /// the container.
- /// </summary>
- /// <value>
- /// <see langword="true"/> if the property, field or parameter will be set
- /// its type's default value when an export with the <see cref="ContractName"/> is not
- /// present in the <see cref="CompositionContainer"/>; otherwise, <see langword="false"/>.
- /// The default value is <see langword="false"/>.
- /// </value>
- /// <remarks>
- /// <para>
- /// The default value of a property's, field's or parameter's type is
- /// <see langword="null"/> for reference types and 0 for numeric value types. For
- /// other value types, the default value will be each field of the value type
- /// initialized to zero, if the field is a value type or <see langword="null"/> if
- /// the field is a reference type.
- /// </para>
- /// </remarks>
- public bool AllowDefault { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether the property or field will be recomposed
- /// when exports that provide the same contract that this import expects, have changed
- /// in the container.
- /// </summary>
- /// <value>
- /// <see langword="true"/> if the property or field allows for recomposition when exports
- /// that provide the same <see cref="ContractName"/> are added or removed from the
- /// <see cref="CompositionContainer"/>; otherwise, <see langword="false"/>.
- /// The default value is <see langword="false"/>.
- /// </value>
- public bool AllowRecomposition { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating that the importer requires a specific
- /// <see cref="CreationPolicy"/> for the exports used to satisfy this import. T
- /// </summary>
- /// <value>
- /// <see cref="CreationPolicy.Any"/> - default value, used if the importer doesn't
- /// require a specific <see cref="CreationPolicy"/>.
- ///
- /// <see cref="CreationPolicy.Shared"/> - Requires that all exports used should be shared
- /// by everyone in the container.
- ///
- /// <see cref="CreationPolicy.NonShared"/> - Requires that all exports used should be
- /// non-shared in a container and thus everyone gets their own instance.
- /// </value>
- public CreationPolicy RequiredCreationPolicy { get; set; }
-
- ImportCardinality IAttributedImport.Cardinality
- {
- get
- {
- if (this.AllowDefault == true)
- {
- return ImportCardinality.ZeroOrOne;
- }
- return ImportCardinality.ExactlyOne;
- }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs deleted file mode 100644 index 9048f5c6362..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Runtime.Serialization;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// The exception that is thrown when the cardinality of a <see cref="ImportDefinition"/>
- /// does not match the cardinality of the <see cref="Export"/> objects available in an
- /// <see cref="ExportProvider"/>.
- /// </summary>
- [Serializable]
- public class ImportCardinalityMismatchException : Exception
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportCardinalityMismatchException"/> class.
- /// </summary>
- public ImportCardinalityMismatchException()
- : this((string)null, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportCardinalityMismatchException"/> class
- /// with the specified error message.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- public ImportCardinalityMismatchException(string message)
- : this(message, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportCardinalityMismatchException"/> class
- /// with the specified error message and exception that is the cause of the
- /// exception.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- /// <param name="innerException">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
- /// </param>
- public ImportCardinalityMismatchException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
-
-#if !SILVERLIGHT
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportCardinalityMismatchException"/> class
- /// with the specified serialization data.
- /// </summary>
- /// <param name="info">
- /// The <see cref="SerializationInfo"/> that holds the serialized object data about the
- /// <see cref="ImportCardinalityMismatchException"/>.
- /// </param>
- /// <param name="context">
- /// The <see cref="StreamingContext"/> that contains contextual information about the
- /// source or destination.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="info"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="SerializationException">
- /// <paramref name="info"/> is missing a required value.
- /// </exception>
- /// <exception cref="InvalidCastException">
- /// <paramref name="info"/> contains a value that cannot be cast to the correct type.
- /// </exception>
- [System.Security.SecuritySafeCritical]
- protected ImportCardinalityMismatchException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
-#endif //!SILVERLIGHT
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportManyAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportManyAttribute.cs deleted file mode 100644 index 79f706f6044..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportManyAttribute.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies that a property, field, or parameter imports a particular set of exports.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
- [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
- AllowMultiple = false, Inherited = false)]
- public class ImportManyAttribute : Attribute, IAttributedImport
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportManyAttribute"/> class, importing the
- /// set of exports with the default contract name.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the element\item type of
- /// theproperty, field, or parameter type that this is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ImportManyAttribute()
- : this((string)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportManyAttribute"/> class, importing the
- /// set of exports with the contract name derived from the specified type.
- /// </summary>
- /// <param name="contractType">
- /// A <see cref="Type"/> of which to derive the contract name of the exports to import, or
- /// <see langword="null"/> to use the default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on
- /// <paramref name="contractType"/>.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property, field,
- /// or parameter type that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ImportManyAttribute(Type contractType)
- : this((string)null, contractType)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportManyAttribute"/> class, importing the
- /// set of exports with the specified contract name.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the exports to import, or
- /// <see langword="null"/> or an empty string ("") to use the default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the property, field,
- /// or parameter type that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public ImportManyAttribute(string contractName)
- : this(contractName, (Type)null)
- {
- }
-
- public ImportManyAttribute(string contractName, Type contractType)
- {
- this.ContractName = contractName;
- this.ContractType = contractType;
- }
-
- /// <summary>
- /// Gets the contract name of the exports to import.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the contract name of the exports to import. The
- /// default value is an empty string ("").
- /// </value>
- public string ContractName { get; private set; }
-
- /// <summary>
- /// Get the contract type of the export to import.
- /// </summary>
- /// <value>
- /// A <see cref="Type"/> of the export that this import is expecting. The default value is
- /// <see langword="null"/> which means that the type will be obtained by looking at the type on
- /// the member that this import is attached to. If the type is <see cref="object"/> then the
- /// importer is delaring they can accept any exported type.
- /// </value>
- public Type ContractType { get; private set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether the property or field will be recomposed
- /// when exports that provide the same contract that this import expects, have changed
- /// in the container.
- /// </summary>
- /// <value>
- /// <see langword="true"/> if the property or field allows for recomposition when exports
- /// that provide the same <see cref="ContractName"/> are added or removed from the
- /// <see cref="CompositionContainer"/>; otherwise, <see langword="false"/>.
- /// The default value is <see langword="false"/>.
- /// </value>
- public bool AllowRecomposition { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating that the importer requires a specific
- /// <see cref="CreationPolicy"/> for the exports used to satisfy this import. T
- /// </summary>
- /// <value>
- /// <see cref="CreationPolicy.Any"/> - default value, used if the importer doesn't
- /// require a specific <see cref="CreationPolicy"/>.
- ///
- /// <see cref="CreationPolicy.Shared"/> - Requires that all exports used should be shared
- /// by everyone in the container.
- ///
- /// <see cref="CreationPolicy.NonShared"/> - Requires that all exports used should be
- /// non-shared in a container and thus everyone gets their own instance.
- /// </value>
- public CreationPolicy RequiredCreationPolicy { get; set; }
-
- ImportCardinality IAttributedImport.Cardinality
- {
- get { return ImportCardinality.ZeroOrMore; }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportingConstructorAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportingConstructorAttribute.cs deleted file mode 100644 index 2263316d43c..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ImportingConstructorAttribute.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies that a constructor should be used when constructing an attributed part.
- /// </summary>
- /// <remarks>
- /// By default, only a default parameter-less constructor, if available, is used to
- /// construct an attributed part. Use this attribute to indicate that a specific constructor
- /// should be used.
- /// </remarks>
- [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
- [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
- public class ImportingConstructorAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportingConstructorAttribute"/> class.
- /// </summary>
- public ImportingConstructorAttribute()
- {
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/InheritedExportAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/InheritedExportAttribute.cs deleted file mode 100644 index ab42dfab9ab..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/InheritedExportAttribute.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies that a type or interface that provides a particular export.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = true)]
- public class InheritedExportAttribute : ExportAttribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type marked with this attribute under the default contract name.
- /// </summary>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the type itself,
- /// that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public InheritedExportAttribute()
- : this((string)null, (Type)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type marked with this attribute under a contract name derived from the specified type.
- /// </summary>
- /// <param name="contractType">
- /// A <see cref="Type"/> of which to derive the contract name to export the type
- /// marked with this attribute, under; or <see langword="null"/> to use the
- /// default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on
- /// <paramref name="contractType"/>.
- /// </para>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on the type of the
- /// itself, that is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public InheritedExportAttribute(Type contractType)
- : this((string)null, contractType)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type or member marked with this attribute under the specified contract name.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name to export the type
- /// marked with this attribute, under; or <see langword="null"/> or an empty string
- /// ("") to use the default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on
- /// the type itself that this is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public InheritedExportAttribute(string contractName)
- : this(contractName, (Type)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportAttribute"/> class, exporting the
- /// type or member marked with this attribute under the specified contract name.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name to export the type
- /// marked with this attribute, under; or <see langword="null"/> or an empty string
- /// ("") to use the default contract name.
- /// </param>
- /// <param name="contractType">
- /// A <see cref="Type"/> of which to derive the contract name to export the type
- /// marked with this attribute, under; or <see langword="null"/> to use the
- /// default contract name.
- /// </param>
- /// <remarks>
- /// <para>
- /// The default contract name is the result of calling
- /// <see cref="AttributedModelServices.GetContractName(Type)"/> on
- /// the type itself that this is marked with this attribute.
- /// </para>
- /// <para>
- /// The contract name is compared using a case-sensitive, non-linguistic comparison
- /// using <see cref="StringComparer.Ordinal"/>.
- /// </para>
- /// </remarks>
- public InheritedExportAttribute(string contractName, Type contractType)
- : base(contractName, contractType)
- {
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataAttributeAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataAttributeAttribute.cs deleted file mode 100644 index 59aad485329..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataAttributeAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies that an attribute can be used to provide metadata for a type, property, field,
- /// or method marked with the <see cref="ExportAttribute"/>.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class,
- AllowMultiple=false, Inherited=true)]
- public sealed class MetadataAttributeAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="MetadataAttributeAttribute"/> class.
- /// </summary>
- public MetadataAttributeAttribute()
- {
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataServices.cs deleted file mode 100644 index 6446c665ea8..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataServices.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition
-{
- internal static class MetadataServices
- {
- public static readonly IDictionary<string, object> EmptyMetadata = new ReadOnlyDictionary<string, object>(null);
-
- public static IDictionary<string, object> AsReadOnly(this IDictionary<string, object> metadata)
- {
- if (metadata == null)
- {
- return EmptyMetadata;
- }
-
- if (metadata is ReadOnlyDictionary<string, object>)
- {
- return metadata;
- }
-
- return new ReadOnlyDictionary<string, object>(metadata);
- }
-
- public static T GetValue<T>(this IDictionary<string, object> metadata, string key)
- {
- Assumes.NotNull(metadata, "metadata");
-
- object untypedValue = true;
- if (!metadata.TryGetValue(key, out untypedValue))
- {
- return default(T);
- }
-
- if (untypedValue is T)
- {
- return (T)untypedValue;
- }
- else
- {
- return default(T);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataViewGenerator.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataViewGenerator.cs deleted file mode 100644 index e582774eaa4..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataViewGenerator.cs +++ /dev/null @@ -1,321 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using System.Threading;
-using Microsoft.Internal;
-using System.Reflection.Emit;
-using System.Collections;
-
-namespace System.ComponentModel.Composition
-{
- // // Assume TMetadataView is
- // //interface Foo
- // //{
- // // public typeRecord1 Record1 { get; }
- // // public typeRecord2 Record2 { get; }
- // // public typeRecord3 Record3 { get; }
- // // public typeRecord4 Record4 { get; }
- // //}
- // // The class to be generated will look approximately like:
- // public class __Foo__MedataViewProxy : TMetadataView
- // {
- // public __Foo__MedataViewProxy (IDictionary<string, object> metadata)
- // {
- // if(metadata == null)
- // {
- // throw InvalidArgumentException("metadata");
- // }
- // try
- // {
- // Record1 = (typeRecord1)Record1;
- // Record2 = (typeRecord1)Record2;
- // Record3 = (typeRecord1)Record3;
- // Record4 = (typeRecord1)Record4;
- // }
- // catch(InvalidCastException ice)
- // {
- // //Annotate exception .Data with diagnostic info
- // }
- // catch(NulLReferenceException ice)
- // {
- // //Annotate exception .Data with diagnostic info
- // }
- // }
- // // Interface
- // public typeRecord1 Record1 { get; }
- // public typeRecord2 Record2 { get; }
- // public typeRecord3 Record3 { get; }
- // public typeRecord4 Record4 { get; }
- // }
- internal static class MetadataViewGenerator
- {
- public const string MetadataViewType = "MetadataViewType";
- public const string MetadataItemKey = "MetadataItemKey";
- public const string MetadataItemTargetType = "MetadataItemTargetType";
- public const string MetadataItemSourceType = "MetadataItemSourceType";
- public const string MetadataItemValue = "MetadataItemValue";
-
- private static Lock _lock = new Lock();
- private static Dictionary<Type, Type> _proxies = new Dictionary<Type, Type>();
-
- private static AssemblyName ProxyAssemblyName = new AssemblyName(string.Format(CultureInfo.InvariantCulture, "MetadataViewProxies_{0}", Guid.NewGuid()));
- private static AssemblyBuilder ProxyAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(ProxyAssemblyName, AssemblyBuilderAccess.Run);
- private static ModuleBuilder ProxyModuleBuilder = ProxyAssemblyBuilder.DefineDynamicModule("MetadataViewProxiesModule");
- private static Type[] CtorArgumentTypes = new Type[] { typeof(IDictionary<string, object>) };
- private static MethodInfo _mdvDictionaryTryGet = CtorArgumentTypes[0].GetMethod("TryGetValue");
- private static readonly MethodInfo ObjectGetType = typeof(object).GetMethod("GetType", Type.EmptyTypes);
-
- 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
- using (new WriteLock(_lock))
- {
- foundProxy = _proxies.TryGetValue(viewType, out proxyType);
-
- if (!foundProxy)
- {
- proxyType = GenerateInterfaceViewProxyType(viewType);
- Assumes.NotNull(proxyType);
-
- _proxies.Add(viewType, proxyType);
- }
- }
- }
- return proxyType;
- }
-
- private static void GenerateLocalAssignmentFromDefaultAttribute(this ILGenerator IL, DefaultValueAttribute[] attrs, LocalBuilder local)
- {
- if (attrs.Length > 0)
- {
- DefaultValueAttribute defaultAttribute = attrs[0];
- IL.LoadValue(defaultAttribute.Value);
- if ((defaultAttribute.Value != null) && (defaultAttribute.Value.GetType().IsValueType))
- {
- IL.Emit(OpCodes.Box, defaultAttribute.Value.GetType());
- }
- IL.Emit(OpCodes.Stloc, local);
- }
- }
-
- private static void GenerateFieldAssignmentFromLocalValue(this ILGenerator IL, LocalBuilder local, FieldBuilder field)
- {
- IL.Emit(OpCodes.Ldarg_0);
- IL.Emit(OpCodes.Ldloc, local);
- IL.Emit(field.FieldType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, field.FieldType);
- IL.Emit(OpCodes.Stfld, field);
- }
-
- private static void GenerateLocalAssignmentFromFlag(this ILGenerator IL, LocalBuilder local, bool flag)
- {
- IL.Emit(flag ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
- IL.Emit(OpCodes.Stloc, local);
- }
-
- // This must be called with _readerWriterLock held for Write
- private static Type GenerateInterfaceViewProxyType(Type viewType)
- {
- // View type is an interface let's cook an implementation
- Type proxyType;
- TypeBuilder proxyTypeBuilder;
- Type[] interfaces = { viewType };
-
- proxyTypeBuilder = ProxyModuleBuilder.DefineType(
- string.Format(CultureInfo.InvariantCulture, "_proxy_{0}_{1}", viewType.FullName, Guid.NewGuid()),
- TypeAttributes.Public,
- typeof(object),
- interfaces);
-
- // Implement Constructor
- ILGenerator proxyCtorIL = proxyTypeBuilder.CreateGeneratorForPublicConstructor(CtorArgumentTypes);
- LocalBuilder exception = proxyCtorIL.DeclareLocal(typeof(Exception));
- LocalBuilder exceptionData = proxyCtorIL.DeclareLocal(typeof(IDictionary));
- LocalBuilder sourceType = proxyCtorIL.DeclareLocal(typeof(Type));
- LocalBuilder value = proxyCtorIL.DeclareLocal(typeof(object));
- LocalBuilder usesExportedMD = proxyCtorIL.DeclareLocal(typeof(bool));
-
- Label tryConstructView = proxyCtorIL.BeginExceptionBlock();
-
- // Implement interface properties
- foreach (PropertyInfo propertyInfo in viewType.GetAllProperties())
- {
- string fieldName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}", propertyInfo.Name, Guid.NewGuid());
-
- // Cache names and type for exception
- string propertyName = string.Format(CultureInfo.InvariantCulture, "{0}", propertyInfo.Name);
-
- Type[] propertyTypeArguments = new Type[] { propertyInfo.PropertyType };
- Type[] optionalModifiers = null;
- Type[] requiredModifiers = null;
-
-#if !SILVERLIGHT
- // PropertyInfo does not support GetOptionalCustomModifiers and GetRequiredCustomModifiers on Silverlight
- optionalModifiers = propertyInfo.GetOptionalCustomModifiers();
- requiredModifiers = propertyInfo.GetRequiredCustomModifiers();
- Array.Reverse(optionalModifiers);
- Array.Reverse(requiredModifiers);
-#endif
- // Generate field
- FieldBuilder proxyFieldBuilder = proxyTypeBuilder.DefineField(
- fieldName,
- propertyInfo.PropertyType,
- FieldAttributes.Private);
-
- // Generate property
- PropertyBuilder proxyPropertyBuilder = proxyTypeBuilder.DefineProperty(
- propertyName,
- PropertyAttributes.None,
- propertyInfo.PropertyType,
- propertyTypeArguments);
-
- // Generate constructor code for retrieving the metadata value and setting the field
- Label tryCastValue = proxyCtorIL.BeginExceptionBlock();
- Label innerTryCastValue;
-
- DefaultValueAttribute[] attrs = propertyInfo.GetAttributes<DefaultValueAttribute>(false);
- if(attrs.Length > 0)
- {
- innerTryCastValue = proxyCtorIL.BeginExceptionBlock();
- }
-
- // In constructor set the backing field with the value from the dictionary
- Label doneGettingDefaultValue = proxyCtorIL.DefineLabel();
- GenerateLocalAssignmentFromFlag(proxyCtorIL, usesExportedMD, true);
-
- proxyCtorIL.Emit(OpCodes.Ldarg_1);
- proxyCtorIL.Emit(OpCodes.Ldstr, propertyInfo.Name);
- proxyCtorIL.Emit(OpCodes.Ldloca, value);
- proxyCtorIL.Emit(OpCodes.Callvirt, _mdvDictionaryTryGet);
- proxyCtorIL.Emit(OpCodes.Brtrue, doneGettingDefaultValue);
-
- proxyCtorIL.GenerateLocalAssignmentFromFlag(usesExportedMD, false);
- proxyCtorIL.GenerateLocalAssignmentFromDefaultAttribute(attrs, value);
-
- proxyCtorIL.MarkLabel(doneGettingDefaultValue);
- proxyCtorIL.GenerateFieldAssignmentFromLocalValue(value, proxyFieldBuilder);
- proxyCtorIL.Emit(OpCodes.Leave, tryCastValue);
-
- // catch blocks for innerTryCastValue start here
- if (attrs.Length > 0)
- {
- proxyCtorIL.BeginCatchBlock(typeof(InvalidCastException));
- {
- Label notUsesExportedMd = proxyCtorIL.DefineLabel();
- proxyCtorIL.Emit(OpCodes.Ldloc, usesExportedMD);
- proxyCtorIL.Emit(OpCodes.Brtrue, notUsesExportedMd);
- proxyCtorIL.Emit(OpCodes.Rethrow);
- proxyCtorIL.MarkLabel(notUsesExportedMd);
- proxyCtorIL.GenerateLocalAssignmentFromDefaultAttribute(attrs, value);
- proxyCtorIL.GenerateFieldAssignmentFromLocalValue(value, proxyFieldBuilder);
- }
- proxyCtorIL.EndExceptionBlock();
- }
-
- // catch blocks for tryCast start here
- proxyCtorIL.BeginCatchBlock(typeof(NullReferenceException));
- {
- proxyCtorIL.Emit(OpCodes.Stloc, exception);
-
- proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
- proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemKey, propertyName);
- proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemTargetType, propertyInfo.PropertyType);
- proxyCtorIL.Emit(OpCodes.Rethrow);
- }
-
- proxyCtorIL.BeginCatchBlock(typeof(InvalidCastException));
- {
- proxyCtorIL.Emit(OpCodes.Stloc, exception);
-
- proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
- proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemKey, propertyName);
- proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataItemTargetType, propertyInfo.PropertyType);
- proxyCtorIL.Emit(OpCodes.Rethrow);
- }
-
- proxyCtorIL.EndExceptionBlock();
-
- if (propertyInfo.CanWrite)
- {
- // The MetadataView '{0}' is invalid because property '{1}' has a property set method.
- throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
- Strings.InvalidSetterOnMetadataField,
- viewType,
- propertyName));
- }
- if (propertyInfo.CanRead)
- {
- // Generate "get" method implementation.
- MethodBuilder getMethodBuilder = proxyTypeBuilder.DefineMethod(
- string.Format(CultureInfo.InvariantCulture, "get_{0}", propertyName),
- MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
- CallingConventions.HasThis,
- propertyInfo.PropertyType,
- requiredModifiers,
- optionalModifiers,
- Type.EmptyTypes, null, null);
-
- proxyTypeBuilder.DefineMethodOverride(getMethodBuilder, propertyInfo.GetGetMethod());
- ILGenerator getMethodIL = getMethodBuilder.GetILGenerator();
- getMethodIL.Emit(OpCodes.Ldarg_0);
- getMethodIL.Emit(OpCodes.Ldfld, proxyFieldBuilder);
- getMethodIL.Emit(OpCodes.Ret);
-
- proxyPropertyBuilder.SetGetMethod(getMethodBuilder);
- }
- }
-
- proxyCtorIL.Emit(OpCodes.Leave, tryConstructView);
-
- // catch blocks for constructView start here
- proxyCtorIL.BeginCatchBlock(typeof(NullReferenceException));
- {
- proxyCtorIL.Emit(OpCodes.Stloc, exception);
-
- proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
- proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataViewType, viewType);
- proxyCtorIL.Emit(OpCodes.Rethrow);
- }
- proxyCtorIL.BeginCatchBlock(typeof(InvalidCastException));
- {
- proxyCtorIL.Emit(OpCodes.Stloc, exception);
-
- proxyCtorIL.GetExceptionDataAndStoreInLocal(exception, exceptionData);
- proxyCtorIL.Emit(OpCodes.Ldloc, value);
- proxyCtorIL.Emit(OpCodes.Call, ObjectGetType);
- proxyCtorIL.Emit(OpCodes.Stloc, sourceType);
- proxyCtorIL.AddItemToLocalDictionary(exceptionData, MetadataViewType, viewType);
- proxyCtorIL.AddLocalToLocalDictionary(exceptionData, MetadataItemSourceType, sourceType);
- proxyCtorIL.AddLocalToLocalDictionary(exceptionData, MetadataItemValue, value);
- proxyCtorIL.Emit(OpCodes.Rethrow);
- }
- proxyCtorIL.EndExceptionBlock();
-
- // Finished implementing interface and constructor
- proxyCtorIL.Emit(OpCodes.Ret);
- proxyType = proxyTypeBuilder.CreateType();
-
- return proxyType;
- }
-
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataViewProvider.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataViewProvider.cs deleted file mode 100644 index 8e22770cad6..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/MetadataViewProvider.cs +++ /dev/null @@ -1,106 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Text;
-using Microsoft.Internal;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Diagnostics.CodeAnalysis;
-
-namespace System.ComponentModel.Composition
-{
- internal static class MetadataViewProvider
- {
- [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
- {
- Type metadataViewType = typeof(TMetadataView);
-
- // If the Metadata dictionary is cast compatible with the passed in type
- if (metadataViewType.IsAssignableFrom(typeof(IDictionary<string, object>)))
- {
- return (TMetadataView)metadata;
- }
- // otherwise is it a metadata view
- else
- {
- Type proxyType;
- if (metadataViewType.IsInterface)
- {
- try
- {
- proxyType = MetadataViewGenerator.GenerateView(metadataViewType);
- }
- catch (TypeLoadException ex)
- {
- throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Strings.NotSupportedInterfaceMetadataView, metadataViewType.FullName), ex);
- }
- }
- else
- {
- proxyType = metadataViewType;
- }
-
- // Now we have the type for the proxy create it
- try
- {
- return (TMetadataView)proxyType.SafeCreateInstance(metadata);
- }
- catch (MissingMethodException ex)
- {
- // Unable to create an Instance of the Metadata view '{0}' because a constructor could not be selected. Ensure that the type implements a constructor which takes an argument of type IDictionary<string, object>.
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
- Strings.CompositionException_MetadataViewInvalidConstructor,
- proxyType.AssemblyQualifiedName), ex);
- }
- catch (TargetInvocationException ex)
- {
- //Unwrap known failures that we want to present as CompositionContractMismatchException
- if(metadataViewType.IsInterface)
- {
- if(ex.InnerException.GetType() == typeof(InvalidCastException))
- {
- // Unable to create an Instance of the Metadata view {0} because the exporter exported the metadata for the item {1} with the value {2} as type {3} but the view imports it as type {4}.
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
- Strings.ContractMismatch_InvalidCastOnMetadataField,
- ex.InnerException.Data[MetadataViewGenerator.MetadataViewType],
- ex.InnerException.Data[MetadataViewGenerator.MetadataItemKey],
- ex.InnerException.Data[MetadataViewGenerator.MetadataItemValue],
- ex.InnerException.Data[MetadataViewGenerator.MetadataItemSourceType],
- ex.InnerException.Data[MetadataViewGenerator.MetadataItemTargetType]), ex);
- }
- else if (ex.InnerException.GetType() == typeof(NullReferenceException))
- {
- // Unable to create an Instance of the Metadata view {0} because the exporter exported the metadata for the item {1} with a null value and null is not a valid value for type {2}.
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
- Strings.ContractMismatch_NullReferenceOnMetadataField,
- ex.InnerException.Data[MetadataViewGenerator.MetadataViewType],
- ex.InnerException.Data[MetadataViewGenerator.MetadataItemKey],
- ex.InnerException.Data[MetadataViewGenerator.MetadataItemTargetType]), ex);
- }
- }
- throw;
- }
- }
- }
-
- public static bool IsViewTypeValid(Type metadataViewType)
- {
- Assumes.NotNull(metadataViewType);
-
- // If the Metadata dictionary is cast compatible with the passed in type
- if (ExportServices.IsDefaultMetadataViewType(metadataViewType)
- || metadataViewType.IsInterface
- || ExportServices.IsDictionaryConstructorViewType(metadataViewType))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreationPolicyAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreationPolicyAttribute.cs deleted file mode 100644 index 844fb3925de..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreationPolicyAttribute.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies <see cref="CreationPolicy"/> for a given <see cref="ComposablePart" />.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
- public sealed class PartCreationPolicyAttribute : Attribute
- {
- internal static PartCreationPolicyAttribute Default = new PartCreationPolicyAttribute(CreationPolicy.Any);
- internal static PartCreationPolicyAttribute Shared = new PartCreationPolicyAttribute(CreationPolicy.Shared);
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PartCreationPolicyAttribute"/> class.
- /// </summary>
- public PartCreationPolicyAttribute(CreationPolicy creationPolicy)
- {
- this.CreationPolicy = creationPolicy;
- }
-
- /// <summary>
- /// Gets or sets a value indicating the creation policy of the attributed part.
- /// </summary>
- /// <value>
- /// One of the <see cref="CreationPolicy"/> values indicating the creation policy of the
- /// attributed part. The default is
- /// <see cref="System.ComponentModel.Composition.CreationPolicy.Any"/>.
- /// </value>
- public CreationPolicy CreationPolicy { get; private set; }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreatorOfT.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreatorOfT.cs deleted file mode 100644 index 37198b1b214..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreatorOfT.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using Microsoft.Internal;
-
-#if SILVERLIGHT
-
-namespace System.ComponentModel.Composition
-{
- public class PartCreator<T>
- {
- private readonly Func<PartLifetimeContext<T>> _creator;
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public PartCreator(Func<PartLifetimeContext<T>> creator)
- {
- Requires.NotNull(creator, "creator");
- this._creator = creator;
- }
-
- public PartLifetimeContext<T> CreatePart()
- {
- return this._creator();
- }
- }
-}
-
-#endif
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreatorOfTTMetadata.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreatorOfTTMetadata.cs deleted file mode 100644 index c352adfd839..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartCreatorOfTTMetadata.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-#if SILVERLIGHT
-
-namespace System.ComponentModel.Composition
-{
- public class PartCreator<T, TMetadata> : PartCreator<T>
- {
- private readonly TMetadata _metadata;
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public PartCreator(Func<PartLifetimeContext<T>> creator, TMetadata metadata)
- : base(creator)
- {
- this._metadata = metadata;
- }
-
- public TMetadata Metadata
- {
- get { return this._metadata; }
- }
- }
-}
-
-#endif
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartLifetimeContextOfT.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartLifetimeContextOfT.cs deleted file mode 100644 index 75aea437971..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartLifetimeContextOfT.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-#if SILVERLIGHT
-
-namespace System.ComponentModel.Composition
-{
- public sealed class PartLifetimeContext<T> : IDisposable
- {
- private readonly T _exportedValue;
- private readonly Action _dispose;
-
- public PartLifetimeContext(T exportedValue, Action dispose)
- {
- this._exportedValue = exportedValue;
- this._dispose = dispose;
- }
-
- public T ExportedValue
- {
- get { return this._exportedValue; }
- }
-
- public void Dispose()
- {
- this._dispose();
- }
- }
-}
-
-#endif
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartMetadataAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartMetadataAttribute.cs deleted file mode 100644 index a700a293c1b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartMetadataAttribute.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Specifies metadata for a type to be used as a <see cref="ComposablePartDefinition"/> and
- /// <see cref="ComposablePart"/>.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
- public sealed class PartMetadataAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="PartMetadataAttribute"/> with the
- /// specified name and metadata value.
- /// </summary>
- /// <param name="name">
- /// A <see cref="String"/> containing the name of the metadata value; or
- /// <see langword="null"/> to use an empty string ("").
- /// </param>
- /// <param name="value">
- /// An <see cref="object"/> containing the metadata value. This can be
- /// <see langword="null"/>.
- /// </param>
- public PartMetadataAttribute(string name, object value)
- {
- this.Name = name ?? string.Empty;
- this.Value = value;
- }
-
- /// <summary>
- /// Gets the name of the metadata value.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the name of the metadata value.
- /// </value>
- public string Name
- {
- get;
- private set;
- }
-
- /// <summary>
- /// Gets the metadata value.
- /// </summary>
- /// <value>
- /// An <see cref="object"/> containing the metadata value.
- /// </value>
- public object Value
- {
- get;
- private set;
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartNotDiscoverableAttribute.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartNotDiscoverableAttribute.cs deleted file mode 100644 index 1436a6a9725..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/PartNotDiscoverableAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition
-{
- /// <summary>
- /// Place on a type that should not be discovered as a <see cref="ComposablePart" /> in
- /// a <see cref="ComposablePartCatalog" />.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
- public sealed class PartNotDiscoverableAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="PartNotDiscoverableAttribute"/> class.
- /// </summary>
- public PartNotDiscoverableAttribute()
- {
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/.gitattributes deleted file mode 100644 index 5aa9b2a9d55..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/.gitattributes +++ /dev/null @@ -1,17 +0,0 @@ -/ComposablePart.cs -crlf -/ComposablePartCatalog.cs -crlf -/ComposablePartCatalogDebuggerProxy.cs -crlf -/ComposablePartDefinition.cs -crlf -/ComposablePartException.cs -crlf -/CompositionElement.cs -crlf -/CompositionElementDebuggerProxy.cs -crlf -/CompositionElementExtensions.cs -crlf -/ContractBasedImportDefinition.cs -crlf -/Export.cs -crlf -/ExportDefinition.cs -crlf -/ExportedDelegate.cs -crlf -/ICompositionElement.cs -crlf -/IPartCreatorImportDefinition.cs -crlf -/ImportCardinality.cs -crlf -/ImportDefinition.cs -crlf -/SerializableCompositionElement.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePart.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePart.cs deleted file mode 100644 index 3b74eecc307..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePart.cs +++ /dev/null @@ -1,210 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Defines the <see langword="abstract"/> base class for composable parts, which
- /// import and produce exported values.
- /// </summary>
- public abstract class ComposablePart
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePart"/> class.
- /// </summary>
- protected ComposablePart()
- {
- }
-
- /// <summary>
- /// Gets the export definitions that describe the exported values provided by the part.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/> objects describing
- /// the exported values provided by the <see cref="ComposablePart"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePart"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <para>
- /// <note type="inheritinfo">
- /// If the <see cref="ComposablePart"/> was created from a
- /// <see cref="ComposablePartDefinition"/>, this property should return the result of
- /// <see cref="ComposablePartDefinition.ExportDefinitions"/>.
- /// </note>
- /// </para>
- /// <para>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>.
- /// If the <see cref="ComposablePart"/> does not have exports, return an empty
- /// <see cref="IEnumerable{T}"/> instead.
- /// </note>
- /// </para>
- /// </remarks>
- public abstract IEnumerable<ExportDefinition> ExportDefinitions { get; }
-
- /// <summary>
- /// Gets the import definitions that describe the imports required by the part.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="ImportDefinition"/> objects describing
- /// the imports required by the <see cref="ComposablePart"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePart"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <para>
- /// <note type="inheritinfo">
- /// If the <see cref="ComposablePart"/> was created from a
- /// <see cref="ComposablePartDefinition"/>, this property should return the result of
- /// <see cref="ComposablePartDefinition.ImportDefinitions"/>.
- /// </note>
- /// </para>
- /// <para>
- /// <note type="inheritinfo">
- /// Overrides of this property should never return <see langword="null"/>.
- /// If the <see cref="ComposablePart"/> does not have imports, return an empty
- /// <see cref="IEnumerable{T}"/> instead.
- /// </note>
- /// </para>
- /// </remarks>
- public abstract IEnumerable<ImportDefinition> ImportDefinitions { get; }
-
- /// <summary>
- /// Gets the metadata of the part.
- /// </summary>
- /// <value>
- /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
- /// <see cref="ComposablePart"/>. The default is an empty, read-only
- /// <see cref="IDictionary{TKey, TValue}"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePart"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <para>
- /// <note type="inheritinfo">
- /// If the <see cref="ComposablePart"/> was created from a
- /// <see cref="ComposablePartDefinition"/>, this property should return the result of
- /// <see cref="ComposablePartDefinition.Metadata"/>.
- /// </note>
- /// </para>
- /// <para>
- /// <note type="inheritinfo">
- /// Overriders of this property should return a read-only
- /// <see cref="IDictionary{TKey, TValue}"/> object with a case-sensitive,
- /// non-linguistic comparer, such as <see cref="StringComparer.Ordinal"/>,
- /// and should never return <see langword="null"/>. If the
- /// <see cref="ComposablePart"/> does not contain metadata, return an
- /// empty <see cref="IDictionary{TKey, TValue}"/> instead.
- /// </note>
- /// </para>
- /// </remarks>
- public virtual IDictionary<string, object> Metadata
- {
- get
- {
- return MetadataServices.EmptyMetadata;
- }
- }
-
- /// <summary>
- /// Called by the composition engine when all required imports on the part have been
- /// satisfied.
- /// </summary>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePart"/> has been disposed of.
- /// </exception>
- /// <exception cref="ComposablePartException">
- /// An error occurred activating the <see cref="ComposablePart"/>.
- /// </exception>
- public virtual void Activate()
- {
- }
-
- /// <summary>
- /// Gets the exported value described by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// One of the <see cref="ExportDefinition"/> objects from the
- /// <see cref="ExportDefinitions"/> property describing the exported value
- /// to return.
- /// </param>
- /// <returns>
- /// The exported value described by <paramref name="definition"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="definition"/> did not originate from the <see cref="ExportDefinitions"/>
- /// property on the <see cref="ComposablePart"/>.
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// One or more pre-requisite imports, indicated by <see cref="ImportDefinition.IsPrerequisite"/>,
- /// have not been set.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePart"/> has been disposed of.
- /// </exception>
- /// <exception cref="ComposablePartException">
- /// An error occurred getting the exported value described by the <see cref="ExportDefinition"/>.
- /// </exception>
- public abstract object GetExportedValue(ExportDefinition definition);
-
- /// <summary>
- /// Sets the import described by the specified definition with the specified exports.
- /// </summary>
- /// <param name="definition">
- /// One of the <see cref="ImportDefinition"/> objects from the
- /// <see cref="ImportDefinitions"/> property describing the import to be set.
- /// </param>
- /// <param name="exports">
- /// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects of which
- /// to set the import described by <paramref name="definition"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exports"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="definition"/> did not originate from the <see cref="ImportDefinitions"/>
- /// property on the <see cref="ComposablePart"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exports"/> contains an element that is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exports"/> is empty and <see cref="ImportDefinition.Cardinality"/> is
- /// <see cref="ImportCardinality.ExactlyOne"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exports"/> contains more than one element and
- /// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
- /// <see cref="ImportCardinality.ExactlyOne"/>.
- /// </exception>
- /// <exception cref="InvalidOperationException">
- /// <see cref="Activate"/> has been previously called and
- /// <see cref="ImportDefinition.IsRecomposable"/> is <see langword="false"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePart"/> has been disposed of.
- /// </exception>
- /// <exception cref="ComposablePartException">
- /// An error occurred setting the import described by the <see cref="ImportDefinition"/>.
- /// </exception>
- public abstract void SetImport(ImportDefinition definition, IEnumerable<Export> exports);
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs deleted file mode 100644 index 22fe9a20ff4..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs +++ /dev/null @@ -1,129 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Linq.Expressions;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Defines the <see langword="abstract"/> base class for composable part catalogs, which produce
- /// and return <see cref="ComposablePartDefinition"/> objects.
- /// </summary>
- /// <remarks>
- /// This type is thread safe.
- /// </remarks>
- [DebuggerTypeProxy(typeof(ComposablePartCatalogDebuggerProxy))]
- public abstract class ComposablePartCatalog : IDisposable
- {
- private bool _isDisposed;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartCatalog"/> class.
- /// </summary>
- protected ComposablePartCatalog()
- {
- }
-
- /// <summary>
- /// Gets the part definitions of the catalog.
- /// </summary>
- /// <value>
- /// A <see cref="IQueryable{T}"/> of <see cref="ComposablePartDefinition"/> objects of the
- /// <see cref="ComposablePartCatalog"/>.
- /// </value>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePartCatalog"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>.
- /// </note>
- /// </remarks>
- public abstract IQueryable<ComposablePartDefinition> Parts
- {
- get;
- }
-
- /// <summary>
- /// Returns the export definitions that match the constraint defined by the specified definition.
- /// </summary>
- /// <param name="definition">
- /// The <see cref="ImportDefinition"/> that defines the conditions of the
- /// <see cref="ExportDefinition"/> objects to return.
- /// </param>
- /// <returns>
- /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
- /// <see cref="ExportDefinition"/> objects and their associated
- /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
- /// by <paramref name="definition"/>.
- /// </returns>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ObjectDisposedException">
- /// The <see cref="ComposablePartCatalog"/> has been disposed of.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>, if no
- /// <see cref="ExportDefinition"/> match the conditions defined by
- /// <paramref name="definition"/>, return an empty <see cref="IEnumerable{T}"/>.
- /// </note>
- /// </remarks>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public virtual IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
- {
- this.ThrowIfDisposed();
-
- Requires.NotNull(definition, "definition");
-
- var exports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
- foreach (var part in this.Parts)
- {
- foreach (var export in part.ExportDefinitions)
- {
- if (definition.IsConstraintSatisfiedBy(export))
- {
- exports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(part, export));
- }
- }
- }
- return exports;
-
- }
-
- /// <summary>
- /// Releases the unmanaged resources used by the <see cref="ComposablePartCatalog"/> and
- /// optionally releases the managed resources.
- /// </summary>
- /// <param name="disposing">
- /// <see langword="true"/> to release both managed and unmanaged resources;
- /// <see langword="false"/> to release only unmanaged resources.
- /// </param>
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- this._isDisposed = true;
- }
-
- private void ThrowIfDisposed()
- {
- if (this._isDisposed)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartCatalogDebuggerProxy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartCatalogDebuggerProxy.cs deleted file mode 100644 index 3d5f72af59b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartCatalogDebuggerProxy.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.ObjectModel;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- // This proxy is needed to pretty up ComposablePartCatalog.Parts; IQueryable<T>
- // instances are not displayed in a very friendly way in the debugger.
- internal class ComposablePartCatalogDebuggerProxy
- {
- private readonly ComposablePartCatalog _catalog;
-
- public ComposablePartCatalogDebuggerProxy(ComposablePartCatalog catalog)
- {
- Requires.NotNull(catalog, "catalog");
-
- this._catalog = catalog;
- }
-
- public ReadOnlyCollection<ComposablePartDefinition> Parts
- {
- // NOTE: This shouldn't be cached, so that on every query of
- // the current value of the underlying catalog is respected.
- // We use ReadOnlyCollection as arrays do not have the
- // appropriate debugger display attributes applied to them.
- get { return this._catalog.Parts.ToReadOnlyCollection(); }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs deleted file mode 100644 index 979022a4f82..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Defines the <see langword="abstract"/> base class for composable part definitions, which
- /// describe, and allow the creation of, <see cref="ComposablePart"/> objects.
- /// </summary>
- public abstract class ComposablePartDefinition
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartDefinition"/> class.
- /// </summary>
- protected ComposablePartDefinition()
- {
- }
-
- /// <summary>
- /// Gets the export definitions that describe the exported values provided by parts
- /// created by the definition.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/> objects describing
- /// the exported values provided by <see cref="ComposablePart"/> objects created by the
- /// <see cref="ComposablePartDefinition"/>.
- /// </value>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overrides of this property should never return <see langword="null"/>.
- /// If the <see cref="ComposablePart"/> objects created by the
- /// <see cref="ComposablePartDefinition"/> do not provide exported values, return
- /// an empty <see cref="IEnumerable{T}"/> instead.
- /// </note>
- /// </remarks>
- public abstract IEnumerable<ExportDefinition> ExportDefinitions { get; }
-
- /// <summary>
- /// Gets the import definitions that describe the imports required by parts created
- /// by the definition.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of <see cref="ImportDefinition"/> objects describing
- /// the imports required by <see cref="ComposablePart"/> objects created by the
- /// <see cref="ComposablePartDefinition"/>.
- /// </value>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>.
- /// If the <see cref="ComposablePart"/> objects created by the
- /// <see cref="ComposablePartDefinition"/> do not have imports, return an empty
- /// <see cref="IEnumerable{T}"/> instead.
- /// </note>
- /// </remarks>
- public abstract IEnumerable<ImportDefinition> ImportDefinitions { get; }
-
- /// <summary>
- /// Gets the metadata of the definition.
- /// </summary>
- /// <value>
- /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
- /// <see cref="ComposablePartDefinition"/>. The default is an empty, read-only
- /// <see cref="IDictionary{TKey, TValue}"/>.
- /// </value>
- /// <remarks>
- /// <para>
- /// <note type="inheritinfo">
- /// Overriders of this property should return a read-only
- /// <see cref="IDictionary{TKey, TValue}"/> object with a case-sensitive,
- /// non-linguistic comparer, such as <see cref="StringComparer.Ordinal"/>,
- /// and should never return <see langword="null"/>. If the
- /// <see cref="ComposablePartDefinition"/> does contain metadata,
- /// return an empty <see cref="IDictionary{TKey, TValue}"/> instead.
- /// </note>
- /// </para>
- /// </remarks>
- public virtual IDictionary<string, object> Metadata
- {
- get { return MetadataServices.EmptyMetadata; }
- }
-
- /// <summary>
- /// Creates a new instance of a part that the definition describes.
- /// </summary>
- /// <returns>
- /// The created <see cref="ComposablePart"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// <note type="inheritinfo">
- /// Derived types overriding this method should return a new instance of a
- /// <see cref="ComposablePart"/> on every invoke and should never return
- /// <see langword="null"/>.
- /// </note>
- /// </para>
- /// </remarks>
- public abstract ComposablePart CreatePart();
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartException.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartException.cs deleted file mode 100644 index 2f05593f13a..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ComposablePartException.cs +++ /dev/null @@ -1,214 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using Microsoft.Internal;
-
-#if !SILVERLIGHT
-using Microsoft.Internal.Runtime.Serialization;
-#endif
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// The exception that is thrown when an error occurs when calling methods on a
- /// <see cref="ComposablePart"/>.
- /// </summary>
- [Serializable]
- public class ComposablePartException : Exception, ICompositionError
- {
- private readonly CompositionErrorId _id;
- private readonly ICompositionElement _element;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartException"/> class.
- /// </summary>
- public ComposablePartException()
- : this(CompositionErrorId.Unknown, (string)null, (ICompositionElement)null, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartException"/> class
- /// with the specified error message.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- /// <param name="element">
- /// The <see cref="ICompositionElement"/> that is the cause of the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="ComposablePartException.Element"/> property to
- /// <see langword="null"/>.
- /// </param>
- public ComposablePartException(string message)
- : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartException"/> class
- /// with the specified error message and composition element that is the cause of
- /// the exception.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- public ComposablePartException(string message, ICompositionElement element)
- : this(CompositionErrorId.Unknown, message, element, (Exception)null)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartException"/> class
- /// with the specified error message and exception that is the cause of the
- /// exception.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- /// <param name="innerException">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
- /// </param>
- public ComposablePartException(string message, Exception innerException)
- : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, innerException)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartException"/> class
- /// with the specified error message, and composition element and exception that
- /// are the cause of the exception.
- /// </summary>
- /// <param name="message">
- /// A <see cref="String"/> containing a message that describes the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.Message"/> property to its default value.
- /// </param>
- /// <param name="element">
- /// The <see cref="ICompositionElement"/> that is the cause of the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="ComposablePartException.Element"/> property to
- /// <see langword="null"/>.
- /// </param>
- /// <param name="innerException">
- /// The <see cref="Exception"/> that is the underlying cause of the
- /// <see cref="ComposablePartException"/>; or <see langword="null"/> to set
- /// the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
- /// </param>
- public ComposablePartException(string message, ICompositionElement element, Exception innerException)
- : this(CompositionErrorId.Unknown, message, element, innerException)
- {
- }
-
- internal ComposablePartException(CompositionErrorId id, string message)
- : this(id, message, (ICompositionElement)null, (Exception)null)
- {
- }
-
- internal ComposablePartException(CompositionErrorId id, string message, Exception exception)
- : this(id, message, (ICompositionElement)null, exception)
- {
- }
-
- internal ComposablePartException(CompositionErrorId id, string message, ICompositionElement element)
- : this(id, message, (ICompositionElement)element, (Exception)null)
- {
- }
-
- internal ComposablePartException(CompositionErrorId id, string message, ICompositionElement element, Exception innerException)
- : base(message, innerException)
- {
- _id = id;
- _element = element;
- }
-
-#if !SILVERLIGHT
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ComposablePartException"/> class
- /// with the specified serialization data.
- /// </summary>
- /// <param name="info">
- /// The <see cref="SerializationInfo"/> that holds the serialized object data about the
- /// <see cref="ComposablePartException"/>.
- /// </param>
- /// <param name="context">
- /// The <see cref="StreamingContext"/> that contains contextual information about the
- /// source or destination.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="info"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="SerializationException">
- /// <paramref name="info"/> is missing a required value.
- /// </exception>
- /// <exception cref="InvalidCastException">
- /// <paramref name="info"/> contains a value that cannot be cast to the correct type.
- /// </exception>
- [System.Security.SecuritySafeCritical]
- protected ComposablePartException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- _id = info.GetValue<CompositionErrorId>("Id");
- _element = info.GetValue<ICompositionElement>("Element");
- }
-
-#endif
-
- /// <summary>
- /// Gets the composition element that is the cause of the exception.
- /// </summary>
- /// <value>
- /// The <see cref="ICompositionElement"/> that is the cause of the
- /// <see cref="ComposablePartException"/>. The default is <see langword="null"/>.
- /// </value>
- public ICompositionElement Element
- {
- get { return _element; }
- }
-
- CompositionErrorId ICompositionError.Id
- {
- get { return _id; }
- }
-
-#if !SILVERLIGHT
-
- /// <summary>
- /// Gets the serialization data of the exception.
- /// </summary>
- /// <param name="info">
- /// The <see cref="SerializationInfo"/> that holds the serialized object data about the
- /// <see cref="ComposablePartException"/>.
- /// </param>
- /// <param name="context">
- /// The <see cref="StreamingContext"/> that contains contextual information about the
- /// source or destination.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="info"/> is <see langword="null"/>.
- /// </exception>
- [System.Security.SecurityCritical]
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
-
- info.AddValue("Id", _id);
- info.AddValue("Element", _element.ToSerializableElement());
- }
-
-#endif
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElement.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElement.cs deleted file mode 100644 index 4cb34de38d7..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElement.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Diagnostics;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- // Represents the ICompositionElement placeholder for an
- // object that does not implement ICompositionElement
- [DebuggerTypeProxy(typeof(CompositionElementDebuggerProxy))]
- [Serializable]
- internal class CompositionElement : SerializableCompositionElement
- {
- private static readonly ICompositionElement UnknownOrigin = new SerializableCompositionElement(Strings.CompositionElement_UnknownOrigin, (ICompositionElement)null);
- private readonly object _underlyingObject;
-
- public CompositionElement(object underlyingObject)
- : base(underlyingObject.ToString(), UnknownOrigin)
- {
- this._underlyingObject = underlyingObject;
- }
-
- public object UnderlyingObject
- {
- get { return _underlyingObject; }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs deleted file mode 100644 index 9a12a7d99f3..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- // Because the debugger displays only the members available on ICompositionElement
- // when viewing CompositionError.Element in the watch and data tips windows, we
- // need this proxy so that the underlying object wrapped by the CompositionElement
- // placeholder is displayed by default.
- internal class CompositionElementDebuggerProxy
- {
- private readonly CompositionElement _element;
-
- public CompositionElementDebuggerProxy(CompositionElement element)
- {
- Requires.NotNull(element, "element");
-
- this._element = element;
- }
-
- public string DisplayName
- {
- get { return this._element.DisplayName; }
- }
-
- public ICompositionElement Origin
- {
- get { return this._element.Origin; }
- }
-
- public object UnderlyingObject
- {
- get { return this._element.UnderlyingObject; }
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs deleted file mode 100644 index 62fe9678d3e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- internal static class CompositionElementExtensions
- {
-#if !SILVERLIGHT
- public static ICompositionElement ToSerializableElement(this ICompositionElement element)
- {
- return SerializableCompositionElement.FromICompositionElement(element);
- }
-#endif
- public static ICompositionElement ToElement(this Export export)
- {
- // First try the export
- ICompositionElement element = export as ICompositionElement;
- if (element != null)
- {
- return element;
- }
-
- // Otherwise, try the definition
- return ToElement(export.Definition);
- }
-
- public static ICompositionElement ToElement(this ExportDefinition definition)
- {
- return ToElementCore(definition);
- }
-
- public static ICompositionElement ToElement(this ImportDefinition definition)
- {
- return ToElementCore(definition);
- }
-
- public static ICompositionElement ToElement(this ComposablePart part)
- {
- return ToElementCore(part);
- }
-
- public static ICompositionElement ToElement(this ComposablePartDefinition definition)
- {
- return ToElementCore(definition);
- }
-
- public static string GetDisplayName(this ComposablePartDefinition definition)
- {
- return GetDisplayNameCore(definition);
- }
-
- public static string GetDisplayName(this ComposablePartCatalog catalog)
- {
- return GetDisplayNameCore(catalog);
- }
-
- private static string GetDisplayNameCore(object value)
- {
- ICompositionElement element = value as ICompositionElement;
- if (element != null)
- {
- return element.DisplayName;
- }
-
- return value.ToString();
- }
-
- private static ICompositionElement ToElementCore(object value)
- {
- ICompositionElement element = value as ICompositionElement;
- if (element != null)
- {
- return element;
- }
-
- return new CompositionElement(value);
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs deleted file mode 100644 index 010fad17899..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs +++ /dev/null @@ -1,309 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Linq.Expressions;
-using Microsoft.Internal;
-using System.Globalization;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Represents a contract name and metadata-based import
- /// required by a <see cref="ComposablePart"/> object.
- /// </summary>
- public class ContractBasedImportDefinition : ImportDefinition
- {
- // Unlike contract name, required metadata has a sensible default; set it to an empty
- // enumerable, so that derived definitions only need to override ContractName by default.
- private readonly IEnumerable<KeyValuePair<string, Type>> _requiredMetadata = Enumerable.Empty<KeyValuePair<string, Type>>();
- private Expression<Func<ExportDefinition, bool>> _constraint;
- private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any;
- private readonly string _requiredTypeIdentity = null;
- private bool _isRequiredMetadataValidated = false;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class.
- /// </summary>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Derived types calling this constructor can optionally override the
- /// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>,
- /// <see cref="RequiredMetadata"/>, <see cref="ImportDefinition.Cardinality"/>,
- /// <see cref="ImportDefinition.IsPrerequisite"/>, <see cref="ImportDefinition.IsRecomposable"/>
- /// and <see cref="RequiredCreationPolicy"/> properties.
- /// </note>
- /// </remarks>
- protected ContractBasedImportDefinition()
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ContractBasedImportDefinition"/> class
- /// with the specified contract name, required metadataq, cardinality, value indicating
- /// if the import definition is recomposable and a value indicating if the import definition
- /// is a prerequisite.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="Export"/> required by the <see cref="ContractBasedImportDefinition"/>.
- /// </param>
- /// <param name="requiredTypeIdentity">
- /// The type identity of the export type expected. Use <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
- /// to generate a type identity for a given type. If no specific type is required pass <see langword="null"/>.
- /// </param>
- /// <param name="requiredMetadata">
- /// An <see cref="IEnumerable{T}"/> of <see cref="String"/> objects containing
- /// the metadata names of the <see cref="Export"/> required by the
- /// <see cref="ContractBasedImportDefinition"/>; or <see langword="null"/> to
- /// set the <see cref="RequiredMetadata"/> property to an empty <see cref="IEnumerable{T}"/>.
- /// </param>
- /// <param name="cardinality">
- /// One of the <see cref="ImportCardinality"/> values indicating the
- /// cardinality of the <see cref="Export"/> objects required by the
- /// <see cref="ContractBasedImportDefinition"/>.
- /// </param>
- /// <param name="isRecomposable">
- /// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> can be satisfied
- /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
- /// <see langword="false"/>.
- /// </param>
- /// <param name="isPrerequisite">
- /// <see langword="true"/> if the <see cref="ContractBasedImportDefinition"/> is required to be
- /// satisfied before a <see cref="ComposablePart"/> can start producing exported
- /// objects; otherwise, <see langword="false"/>.
- /// </param>
- /// <param name="requiredCreationPolicy">
- /// A value indicating that the importer requires a specific <see cref="CreationPolicy"/> for
- /// the exports used to satisfy this import. If no specific <see cref="CreationPolicy"/> is needed
- /// pass the default <see cref="CreationPolicy.Any"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="contractName"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="contractName"/> is an empty string ("").
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="requiredMetadata"/> contains an element that is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
- /// values.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy)
- : base(contractName, cardinality, isRecomposable, isPrerequisite)
- {
- Requires.NotNullOrEmpty(contractName, "contractName");
-
- this._requiredTypeIdentity = requiredTypeIdentity;
-
- if (requiredMetadata != null)
- {
- this._requiredMetadata = requiredMetadata;
- }
-
- this._requiredCreationPolicy = requiredCreationPolicy;
- }
-
- /// <summary>
- /// The type identity of the export type expected.
- /// </summary>
- /// <value>
- /// A <see cref="string"/> that is generated by <see cref="AttributedModelServices.GetTypeIdentity(Type)"/>
- /// on the type that this import expects. If the value is <see langword="null"/> then this import
- /// doesn't expect a particular type.
- /// </value>
- public virtual string RequiredTypeIdentity
- {
- get { return this._requiredTypeIdentity; }
- }
-
- /// <summary>
- /// Gets the metadata names of the export required by the import definition.
- /// </summary>
- /// <value>
- /// An <see cref="IEnumerable{T}"/> of pairs of metadata keys and types of the <see cref="Export"/> required by the
- /// <see cref="ContractBasedImportDefinition"/>. The default is an empty
- /// <see cref="IEnumerable{T}"/>.
- /// </value>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>
- /// or return an <see cref="IEnumerable{T}"/> that contains an element that is
- /// <see langword="null"/>. If the definition does not contain required metadata,
- /// return an empty <see cref="IEnumerable{T}"/> instead.
- /// </note>
- /// </remarks>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public virtual IEnumerable<KeyValuePair<string, Type>> RequiredMetadata
- {
- get
- {
- // NOTE : unlike other arguments, we validate this one as late as possible, because its validation may lead to type loading
- this.ValidateRequiredMetadata();
-
- return this._requiredMetadata;
- }
- }
-
- private void ValidateRequiredMetadata()
- {
- if (!this._isRequiredMetadataValidated)
- {
- foreach (KeyValuePair<string, Type> metadataItem in this._requiredMetadata)
- {
- if ((metadataItem.Key == null) || (metadataItem.Value == null))
- {
- throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, Strings.Argument_NullElement, "requiredMetadata"));
- }
- }
- this._isRequiredMetadataValidated = true;
- }
- }
-
- /// <summary>
- /// Gets or sets a value indicating that the importer requires a specific
- /// <see cref="CreationPolicy"/> for the exports used to satisfy this import. T
- /// </summary>
- /// <value>
- /// <see cref="CreationPolicy.Any"/> - default value, used if the importer doesn't
- /// require a specific <see cref="CreationPolicy"/>.
- ///
- /// <see cref="CreationPolicy.Shared"/> - Requires that all exports used should be shared
- /// by everyone in the container.
- ///
- /// <see cref="CreationPolicy.NonShared"/> - Requires that all exports used should be
- /// non-shared in a container and thus everyone gets their own instance.
- /// </value>
- public virtual CreationPolicy RequiredCreationPolicy
- {
- get { return this._requiredCreationPolicy; }
- }
-
- /// <summary>
- /// Gets an expression that defines conditions that must be matched for the import
- /// described by the import definition to be satisfied.
- /// </summary>
- /// <returns>
- /// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
- /// that defines the conditions that must be matched for the
- /// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>.
- /// </returns>
- /// <remarks>
- /// <para>
- /// This property returns an expression that defines conditions based on the
- /// <see cref="ImportDefinition.ContractName"/>, <see cref="RequiredTypeIdentity"/>,
- /// <see cref="RequiredMetadata"/>, and <see cref="RequiredCreationPolicy"/>
- /// properties.
- /// </para>
- /// </remarks>
- public override Expression<Func<ExportDefinition, bool>> Constraint
- {
- get
- {
- if (this._constraint == null)
- {
- this._constraint = ConstraintServices.CreateConstraint(this.ContractName, this.RequiredTypeIdentity, this.RequiredMetadata, this.RequiredCreationPolicy);
- }
-
- return this._constraint;
- }
- }
-
- /// <summary>
- /// Executes an optimized version of the contraint given by the <see cref="Constraint"/> property
- /// </summary>
- /// <param name="exportDefinition">
- /// A definition for a <see cref="Export"/> used to determine if it satisfies the
- /// requirements for this <see cref="ImportDefinition"/>.
- /// </param>
- /// <returns>
- /// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for
- /// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>.
- /// </returns>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overrides of this method can provide a more optimized execution of the
- /// <see cref="Constraint"/> property but the result should remain consistent.
- /// </note>
- /// </remarks>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="exportDefinition"/> is <see langword="null"/>.
- /// </exception>
- public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
- {
- Requires.NotNull(exportDefinition, "exportDefinition");
-
- if (!StringComparers.ContractName.Equals(this.ContractName, exportDefinition.ContractName))
- {
- return false;
- }
-
- return MatchRequiredMatadata(exportDefinition);
- }
-
- private bool MatchRequiredMatadata(ExportDefinition definition)
- {
- if (!string.IsNullOrEmpty(this.RequiredTypeIdentity))
- {
- string exportTypeIdentity = definition.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
-
- if (!StringComparers.ContractName.Equals(this.RequiredTypeIdentity, exportTypeIdentity))
- {
- return false;
- }
- }
-
- foreach (KeyValuePair<string, Type> metadataItem in this.RequiredMetadata)
- {
- string metadataKey = metadataItem.Key;
- Type metadataValueType = metadataItem.Value;
-
- object metadataValue = null;
- if (!definition.Metadata.TryGetValue(metadataKey, out metadataValue))
- {
- return false;
- }
-
- if (metadataValue != null)
- {
- // the metadata value is not null, we can rely on IsInstanceOfType to do the right thing
- if (!metadataValueType.IsInstanceOfType(metadataValue))
- {
- return false;
- }
- }
- else
- {
- // this is an unfortunate special case - typeof(object).IsInstanceofType(null) == false
- // basically nulls are not considered valid values for anything
- // We want them to match anything that is a reference type
- if (metadataValueType.IsValueType)
- {
- // this is a pretty expensive check, but we only invoke it when metadata values are null, which is very rare
- return false;
- }
- }
- }
-
- if (this.RequiredCreationPolicy == CreationPolicy.Any)
- {
- return true;
- }
-
- CreationPolicy exportPolicy = definition.Metadata.GetValue<CreationPolicy>(CompositionConstants.PartCreationPolicyMetadataName);
- return exportPolicy == CreationPolicy.Any ||
- exportPolicy == this.RequiredCreationPolicy;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/Export.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/Export.cs deleted file mode 100644 index 8beaa09b907..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/Export.cs +++ /dev/null @@ -1,245 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Represents an export. That is, a type that is made up of a delay-created exported value
- /// and metadata that describes that object.
- /// </summary>
- public class Export
- {
- private readonly ExportDefinition _definition;
- private readonly Func<object> _exportedValueGetter;
- private static readonly object _EmptyValue = new object();
- private volatile object _exportedValue = Export._EmptyValue;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Export"/> class.
- /// </summary>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Derived types calling this constructor must override <see cref="Definition"/>
- /// and <see cref="GetExportedValueCore"/>.
- /// </note>
- /// </remarks>
- protected Export()
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Export"/> class
- /// with the specified contract name and exported value getter.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="Export"/>.
- /// </param>
- /// <param name="exportedValueGetter">
- /// A <see cref="Func{T}"/> that is called to create the exported value of the
- /// <see cref="Export"/>. This allows the creation of the object to be delayed
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="contractName"/> is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exportedValueGetter"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="contractName"/> is an empty string ("").
- /// </exception>
- public Export(string contractName, Func<object> exportedValueGetter)
- : this(new ExportDefinition(contractName, (IDictionary<string, object>)null), exportedValueGetter)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Export"/> class
- /// with the specified contract name, metadata and exported value getter.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="Export"/>.
- /// </param>
- /// <param name="metadata">
- /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
- /// <see cref="Export"/>; or <see langword="null"/> to set the
- /// <see cref="Metadata"/> property to an empty, read-only
- /// <see cref="IDictionary{TKey, TValue}"/>.
- /// </param>
- /// <param name="exportedValueGetter">
- /// A <see cref="Func{T}"/> that is called to create the exported value of the
- /// <see cref="Export"/>. This allows the creation of the object to be delayed.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="contractName"/> is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exportedValueGetter"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="contractName"/> is an empty string ("").
- /// </exception>
- public Export(string contractName, IDictionary<string, object> metadata, Func<object> exportedValueGetter)
- : this(new ExportDefinition(contractName, metadata), exportedValueGetter)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Export"/> class
- /// with the specified export definition and exported value getter.
- /// </summary>
- /// <param name="definition">
- /// An <see cref="ExportDefinition"/> that describes the contract that the
- /// <see cref="Export"/> satisfies.
- /// </param>
- /// <param name="exportedValueGetter">
- /// A <see cref="Func{T}"/> that is called to create the exported value of the
- /// <see cref="Export"/>. This allows the creation of the object to be delayed.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="definition"/> is <see langword="null"/>.
- /// <para>
- /// -or-
- /// </para>
- /// <paramref name="exportedValueGetter"/> is <see langword="null"/>.
- /// </exception>
- public Export(ExportDefinition definition, Func<object> exportedValueGetter)
- {
- Requires.NotNull(definition, "definition");
- Requires.NotNull(exportedValueGetter, "exportedValueGetter");
-
- this._definition = definition;
- this._exportedValueGetter = exportedValueGetter;
- }
-
- /// <summary>
- /// Gets the definition that describes the contract that the export satisfies.
- /// </summary>
- /// <value>
- /// An <see cref="ExportDefinition"/> that describes the contract that
- /// the <see cref="Export"/> satisfies.
- /// </value>
- /// <exception cref="NotImplementedException">
- /// This property was not overridden by a derived class.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return
- /// <see langword="null"/>.
- /// </note>
- /// </remarks>
- public virtual ExportDefinition Definition
- {
- get
- {
- if (_definition != null)
- {
- return _definition;
- }
-
- throw ExceptionBuilder.CreateNotOverriddenByDerived("Definition");
- }
- }
-
- /// <summary>
- /// Gets the metadata of the export.
- /// </summary>
- /// <value>
- /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
- /// <see cref="Export"/>.
- /// </value>
- /// <exception cref="NotImplementedException">
- /// The <see cref="Definition"/> property was not overridden by a derived class.
- /// </exception>
- /// <remarks>
- /// <para>
- /// This property returns the value of <see cref="ExportDefinition.Metadata"/>
- /// of the <see cref="Definition"/> property.
- /// </para>
- /// </remarks>
- public IDictionary<string, object> Metadata
- {
- get { return Definition.Metadata; }
- }
-
- /// <summary>
- /// Returns the exported value of the export.
- /// </summary>
- /// <returns>
- /// The exported <see cref="Object"/> of the <see cref="Export"/>.
- /// </returns>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="CompositionContractMismatchException">
- /// The current instance is an instance of <see cref="Lazy{T}"/> and the underlying
- /// exported value cannot be cast to <c>T</c>.
- /// </exception>
- /// <exception cref="NotImplementedException">
- /// The <see cref="GetExportedValueCore"/> method was not overridden by a derived class.
- /// </exception>
- public object Value
- {
- get
- {
- // NOTE : the logic below guarantees that the value will be set exactly once. It DOES NOT, however, guarantee that GetExportedValueCore() will be executed
- // more than once, as locking would be required for that. The said locking is problematic, as we can't reliable call 3rd party code under a lock.
- if (this._exportedValue == Export._EmptyValue)
- {
- object exportedValue = this.GetExportedValueCore();
-
- // NOTE : According to http://msdn.microsoft.com/en-us/library/4bw5ewxy.aspx, the warning is bogus when used with Interlocked API.
-#pragma warning disable 420
- Interlocked.CompareExchange(ref this._exportedValue, exportedValue, Export._EmptyValue);
-#pragma warning restore 420
- }
-
- return this._exportedValue;
- }
- }
-
- /// <summary>
- /// Returns the exported value of the export.
- /// </summary>
- /// <returns>
- /// The exported <see cref="Object"/> of the <see cref="Export"/>.
- /// </returns>
- /// <exception cref="CompositionException">
- /// An error occurred during composition. <see cref="CompositionException.Errors"/> will
- /// contain a collection of errors that occurred.
- /// </exception>
- /// <exception cref="CompositionContractMismatchException">
- /// The current instance is an instance of <see cref="Lazy{T}"/> and the underlying
- /// exported value cannot be cast to <c>T</c>.
- /// </exception>
- /// <exception cref="NotImplementedException">
- /// The method was not overridden by a derived class.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this method should never return
- /// <see langword="null"/>.
- /// </note>
- /// </remarks>
- [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
- protected virtual object GetExportedValueCore()
- {
- if (this._exportedValueGetter != null)
- {
- return this._exportedValueGetter.Invoke();
- }
-
- throw ExceptionBuilder.CreateNotOverriddenByDerived("GetExportedValueCore");
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ExportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ExportDefinition.cs deleted file mode 100644 index f4bf8291a7e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ExportDefinition.cs +++ /dev/null @@ -1,131 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Describes the contract that an <see cref="Export"/> object satisfies.
- /// </summary>
- public class ExportDefinition
- {
- // Unlike contract name, metadata has a sensible default; set it to an empty bag,
- // so that derived definitions only need to override ContractName by default.
- private readonly IDictionary<string, object> _metadata = MetadataServices.EmptyMetadata;
- private readonly string _contractName;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportDefinition"/> class.
- /// </summary>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Derived types calling this constructor must override <see cref="ContractName"/>
- /// and optionally, <see cref="Metadata"/>. By default, <see cref="Metadata"/>
- /// returns an empty, read-only dictionary.
- /// </note>
- /// </remarks>
- protected ExportDefinition()
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExportDefinition"/> class with
- /// the specified contract name and metadata.
- /// </summary>
- /// <param name="contractName">
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="ExportDefinition"/>.
- /// </param>
- /// <param name="metadata">
- /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
- /// <see cref="ExportDefinition"/>; or <see langword="null"/> to set the
- /// <see cref="Metadata"/> property to an empty, read-only
- /// <see cref="IDictionary{TKey, TValue}"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="contractName"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="contractName"/> is an empty string ("").
- /// </exception>
- public ExportDefinition(string contractName, IDictionary<string, object> metadata)
- {
- Requires.NotNullOrEmpty(contractName, "contractName");
-
- _contractName = contractName;
-
- if (metadata != null)
- {
- _metadata = metadata.AsReadOnly();
- }
- }
-
- /// <summary>
- /// Gets the contract name of the export definition.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the contract name of the
- /// <see cref="ExportDefinition"/>.
- /// </value>
- /// <exception cref="NotImplementedException">
- /// The property was not overridden by a derived class.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>
- /// or an empty string ("").
- /// </note>
- /// </remarks>
- public virtual string ContractName
- {
- get
- {
- if (_contractName != null)
- {
- return _contractName;
- }
-
- throw ExceptionBuilder.CreateNotOverriddenByDerived("ContractName");
- }
- }
-
- /// <summary>
- /// Gets the metadata of the export definition.
- /// </summary>
- /// <value>
- /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
- /// <see cref="ExportDefinition"/>. The default is an empty, read-only
- /// <see cref="IDictionary{TKey, TValue}"/>.
- /// </value>
- /// <remarks>
- /// <para>
- /// <note type="inheritinfo">
- /// Overriders of this property should return a read-only
- /// <see cref="IDictionary{TKey, TValue}"/> object with a case-sensitive,
- /// non-linguistic comparer, such as <see cref="StringComparer.Ordinal"/>,
- /// and should never return <see langword="null"/>.
- /// If the <see cref="ExportDefinition"/> does not contain metadata
- /// return an empty <see cref="IDictionary{TKey, TValue}"/> instead.
- /// </note>
- /// </para>
- /// </remarks>
- public virtual IDictionary<string, object> Metadata
- {
- get { return _metadata; }
- }
-
- /// <summary>
- /// Returns a string representation of the export definition.
- /// </summary>
- /// <returns>
- /// A <see cref="String"/> containing the value of the <see cref="ContractName"/> property.
- /// </returns>
- public override string ToString()
- {
- return this.ContractName;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs deleted file mode 100644 index d6bc6297170..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
- public class ExportedDelegate
- {
- private object _instance;
- private MethodInfo _method;
-
- protected ExportedDelegate() { }
-#if !SILVERLIGHT
- [System.Security.SecurityCritical]
-#endif
- public ExportedDelegate(object instance, MethodInfo method)
- {
- Requires.NotNull(method, "method");
-
- this._instance = instance;
- this._method = method;
- }
-
- public virtual Delegate CreateDelegate(Type delegateType)
- {
- Requires.NotNull(delegateType, "delegateType");
-
- if (delegateType == typeof(Delegate) || delegateType == typeof(MulticastDelegate))
- {
- Type funcOrAction = ConvertMethodInfoToFuncOrActionType(this._method);
-
- if (funcOrAction != null)
- {
- delegateType = funcOrAction;
- }
- else
- {
- return null;
- }
- }
-
- return Delegate.CreateDelegate(delegateType, this._instance, this._method, false);
- }
-
- private static Type[] _funcTypes =
- {
- typeof(Func<>), typeof(Func<,>), typeof(Func<,,>), typeof(Func<,,,>), typeof(Func<,,,,>)
-#if CLR40 && !SILVERLIGHT
- , typeof(Func<,,,,,>), typeof(Func<,,,,,,>), typeof(Func<,,,,,,,>), typeof(Func<,,,,,,,,>)
-#endif
- };
-
- private static Type[] _actionTypes =
- {
- typeof(Action), typeof(Action<>), typeof(Action<,>), typeof(Action<,,>), typeof(Action<,,,>)
-#if CLR40 && !SILVERLIGHT
- , typeof(Action<,,,,>), typeof(Action<,,,,,>), typeof(Action<,,,,,,>), typeof(Action<,,,,,,,>)
-#endif
- };
-
- private static Type ConvertMethodInfoToFuncOrActionType(MethodInfo method)
- {
- ParameterInfo[] parameters = method.GetParameters();
-
- bool isVoid = method.ReturnType == typeof(void);
- Type[] typeArray = isVoid ? _actionTypes : _funcTypes;
-
- if (parameters.Length >= typeArray.Length)
- {
- return null;
- }
-
- Type[] genericArgTypes = new Type[parameters.Length + (isVoid ? 0 : 1)];
-
- for (int i = 0; i < parameters.Length; i++)
- {
- genericArgTypes[i] = parameters[i].ParameterType;
- }
-
- if (!isVoid)
- {
- genericArgTypes[parameters.Length] = method.ReturnType;
- }
-
- Type delegateType = typeArray[parameters.Length].IsGenericType ?
- typeArray[parameters.Length].MakeGenericType(genericArgTypes) :
- typeArray[parameters.Length];
-
- return delegateType;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ICompositionElement.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ICompositionElement.cs deleted file mode 100644 index 6c4863ef067..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ICompositionElement.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Represents an element that participates in composition.
- /// </summary>
- public interface ICompositionElement
- {
- /// <summary>
- /// Gets the display name of the composition element.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing a human-readable display name of the <see cref="ICompositionElement"/>.
- /// </value>
- /// <remarks>
- /// <note type="implementnotes">
- /// Implementors of this property should never return <see langword="null"/> or an empty
- /// string ("").
- /// </note>
- /// </remarks>
- string DisplayName
- {
- get;
- }
-
- /// <summary>
- /// Gets the composition element from which the current composition element
- /// originated.
- /// </summary>
- /// <value>
- /// A <see cref="ICompositionElement"/> from which the current
- /// <see cref="ICompositionElement"/> originated, or <see langword="null"/>
- /// if the <see cref="ICompositionElement"/> is the root composition element.
- /// </value>
- ICompositionElement Origin
- {
- get;
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/IPartCreatorImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/IPartCreatorImportDefinition.cs deleted file mode 100644 index 307481c847f..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/IPartCreatorImportDefinition.cs +++ /dev/null @@ -1,12 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- internal interface IPartCreatorImportDefinition
- {
- ContractBasedImportDefinition ProductImportDefinition { get; }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ImportCardinality.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ImportCardinality.cs deleted file mode 100644 index d59dc9bea0b..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ImportCardinality.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Indicates the cardinality of the <see cref="Export"/> objects required by an <see cref="ImportDefinition"/>.
- /// </summary>
- public enum ImportCardinality
- {
- /// <summary>
- /// Zero or one <see cref="Export"/> objects are required by an <see cref="ImportDefinition"/>.
- /// </summary>
- ZeroOrOne = 0,
-
- /// <summary>
- /// Exactly one <see cref="Export"/> object is required by an <see cref="ImportDefinition"/>.
- /// </summary>
- ExactlyOne = 1,
-
- /// <summary>
- /// Zero or more <see cref="Export"/> objects are required by an <see cref="ImportDefinition"/>.
- /// </summary>
- ZeroOrMore = 2,
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ImportDefinition.cs deleted file mode 100644 index 9c81b51c90f..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/ImportDefinition.cs +++ /dev/null @@ -1,236 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq.Expressions;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- /// <summary>
- /// Represents an import required by a <see cref="ComposablePart"/> object.
- /// </summary>
- public class ImportDefinition
- {
- internal static readonly string EmptyContractName = string.Empty;
- private readonly Expression<Func<ExportDefinition, bool>> _constraint;
- private readonly ImportCardinality _cardinality = ImportCardinality.ExactlyOne;
- private readonly string _contractName = EmptyContractName;
- private readonly bool _isRecomposable;
- private readonly bool _isPrerequisite = true;
- private Func<ExportDefinition, bool> _compiledConstraint;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportDefinition"/> class.
- /// </summary>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Derived types calling this constructor must override the <see cref="Constraint"/>
- /// property, and optionally, the <see cref="Cardinality"/>, <see cref="IsPrerequisite"/>
- /// and <see cref="IsRecomposable"/>
- /// properties.
- /// </note>
- /// </remarks>
- protected ImportDefinition()
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ImportDefinition"/> class
- /// with the specified constraint, cardinality, value indicating if the import
- /// definition is recomposable and a value indicating if the import definition
- /// is a prerequisite.
- /// </summary>
- /// <param name="constraint">
- /// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
- /// that defines the conditions that must be matched for the <see cref="ImportDefinition"/>
- /// to be satisfied by an <see cref="Export"/>.
- /// </param>
- /// <param name="contractName">
- /// The contract name of the export that this import is interested in. The contract name
- /// property is used as guidance and not automatically enforced in the constraint. If
- /// the contract name is a required in the constraint then it should be added to the constraint
- /// by the caller of this constructor.
- /// </param>
- /// <param name="cardinality">
- /// One of the <see cref="ImportCardinality"/> values indicating the
- /// cardinality of the <see cref="Export"/> objects required by the
- /// <see cref="ImportDefinition"/>.
- /// </param>
- /// <param name="isRecomposable">
- /// <see langword="true"/> if the <see cref="ImportDefinition"/> can be satisfied
- /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
- /// <see langword="false"/>.
- /// </param>
- /// <param name="isPrerequisite">
- /// <see langword="true"/> if the <see cref="ImportDefinition"/> is required to be
- /// satisfied before a <see cref="ComposablePart"/> can start producing exported
- /// objects; otherwise, <see langword="false"/>.
- /// </param>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="constraint"/> is <see langword="null"/>.
- /// </exception>
- /// <exception cref="ArgumentException">
- /// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
- /// values.
- /// </exception>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite)
- : this(contractName, cardinality, isRecomposable, isPrerequisite)
- {
- Requires.NotNull(constraint, "constraint");
-
- this._constraint = constraint;
- }
-
- internal ImportDefinition(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite)
- {
- if (
- (cardinality != ImportCardinality.ExactlyOne) &&
- (cardinality != ImportCardinality.ZeroOrMore) &&
- (cardinality != ImportCardinality.ZeroOrOne)
- )
- {
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ArgumentOutOfRange_InvalidEnum, "cardinality", cardinality, typeof(ImportCardinality).Name), "cardinality");
- }
-
- this._contractName = contractName ?? EmptyContractName;
- this._cardinality = cardinality;
- this._isRecomposable = isRecomposable;
- this._isPrerequisite = isPrerequisite;
- }
-
- /// <summary>
- /// Gets the contract name of the export required by the import definition.
- /// </summary>
- /// <value>
- /// A <see cref="String"/> containing the contract name of the <see cref="Export"/>
- /// required by the <see cref="ContractBasedImportDefinition"/>. This property should
- /// return <see cref="String.Empty"/> for imports that do not require a specific
- /// contract name.
- /// </value>
- public virtual string ContractName
- {
- get { return this._contractName; }
- }
-
- /// <summary>
- /// Gets the cardinality of the exports required by the import definition.
- /// </summary>
- /// <value>
- /// One of the <see cref="ImportCardinality"/> values indicating the
- /// cardinality of the <see cref="Export"/> objects required by the
- /// <see cref="ImportDefinition"/>. The default is
- /// <see cref="ImportCardinality.ExactlyOne"/>
- /// </value>
- public virtual ImportCardinality Cardinality
- {
- get { return this._cardinality; }
- }
-
- /// <summary>
- /// Gets an expression that defines conditions that must be matched for the import
- /// described by the import definition to be satisfied.
- /// </summary>
- /// <returns>
- /// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
- /// that defines the conditions that must be matched for the
- /// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>.
- /// </returns>
- /// <exception cref="NotImplementedException">
- /// The property was not overridden by a derived class.
- /// </exception>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overriders of this property should never return <see langword="null"/>.
- /// </note>
- /// </remarks>
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public virtual Expression<Func<ExportDefinition, bool>> Constraint
- {
- get
- {
- if (this._constraint != null)
- {
- return this._constraint;
- }
-
- throw ExceptionBuilder.CreateNotOverriddenByDerived("Constraint");
- }
- }
-
- /// <summary>
- /// Gets a value indicating whether the import definition is required to be
- /// satisfied before a part can start producing exported values.
- /// </summary>
- /// <value>
- /// <see langword="true"/> if the <see cref="ImportDefinition"/> is required to be
- /// satisfied before a <see cref="ComposablePart"/> can start producing exported
- /// objects; otherwise, <see langword="false"/>. The default is <see langword="true"/>.
- /// </value>
- public virtual bool IsPrerequisite
- {
- get { return this._isPrerequisite; }
- }
-
- /// <summary>
- /// Gets a value indicating whether the import definition can be satisfied multiple times.
- /// </summary>
- /// <value>
- /// <see langword="true"/> if the <see cref="ImportDefinition"/> can be satisfied
- /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
- /// <see langword="false"/>. The default is <see langword="false"/>.
- /// </value>
- public virtual bool IsRecomposable
- {
- get { return this._isRecomposable; }
- }
-
- /// <summary>
- /// Executes of the constraint provided by the <see cref="Constraint"/> property
- /// against a given <see cref="ExportDefinition"/> to determine if this
- /// <see cref="ImportDefinition"/> can be satisfied by the given <see cref="Export"/>.
- /// </summary>
- /// <param name="exportDefinition">
- /// A definition for a <see cref="Export"/> used to determine if it satisfies the
- /// requirements for this <see cref="ImportDefinition"/>.
- /// </param>
- /// <returns>
- /// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for
- /// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>.
- /// </returns>
- /// <remarks>
- /// <note type="inheritinfo">
- /// Overrides of this method can provide a more optimized execution of the
- /// <see cref="Constraint"/> property but the result should remain consistent.
- /// </note>
- /// </remarks>
- /// <exception cref="ArgumentNullException">
- /// <paramref name="exportDefinition"/> is <see langword="null"/>.
- /// </exception>
- public virtual bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
- {
- Requires.NotNull(exportDefinition, "exportDefinition");
-
- if (this._compiledConstraint == null)
- {
- this._compiledConstraint = this.Constraint.Compile();
- }
-
- return this._compiledConstraint.Invoke(exportDefinition);
- }
-
- /// <summary>
- /// Returns a string representation of the import definition.
- /// </summary>
- /// <returns>
- /// A <see cref="String"/> containing the value of the <see cref="Constraint"/> property.
- /// </returns>
- public override string ToString()
- {
- return this.Constraint.Body.ToString();
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs deleted file mode 100644 index f84d5a1ec50..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.Primitives
-{
- // As most objects that implement ICompositionElement (such as Export, ComposablePart,
- // ComposablePartCatalog, etc) are not serializable, this class is used as a serializable
- // placeholder for these types when ICompositionElement is used within serializable types,
- // such as CompositionException, CompositionIssue, etc.
- [Serializable]
- internal class SerializableCompositionElement : ICompositionElement
- {
- private readonly string _displayName;
- private readonly ICompositionElement _origin;
-
- public SerializableCompositionElement(string displayName, ICompositionElement origin)
- {
-#if !SILVERLIGHT
- Assumes.IsTrue(origin == null || origin.GetType().IsSerializable);
-#endif
- this._displayName = displayName ?? string.Empty;
- this._origin = origin;
- }
-
- public string DisplayName
- {
- get { return this._displayName; }
- }
-
- public ICompositionElement Origin
- {
- get { return this._origin; }
- }
-
- public override string ToString()
- {
- return this.DisplayName;
- }
-
- public static ICompositionElement FromICompositionElement(ICompositionElement element)
- {
- if (element == null)
- { // Null is always serializable
-
- return null;
- }
-
- ICompositionElement origin = FromICompositionElement(element.Origin);
-
- // Otherwise, we need to create a serializable wrapper
- return new SerializableCompositionElement(element.DisplayName, origin);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/.gitattributes b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/.gitattributes deleted file mode 100644 index 8fcb7fbb6d5..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/.gitattributes +++ /dev/null @@ -1,28 +0,0 @@ -/DisposableReflectionComposablePart.cs -crlf -/ExportingMember.cs -crlf -/IReflectionPartCreationInfo.cs -crlf -/ImportType.cs -crlf -/ImportingItem.cs -crlf -/ImportingMember.cs -crlf -/ImportingParameter.cs -crlf -/LazyMemberInfo.cs -crlf -/PartCreatorExportDefinition.cs -crlf -/PartCreatorMemberImportDefinition.cs -crlf -/PartCreatorParameterImportDefinition.cs -crlf -/ReflectionComposablePart.cs -crlf -/ReflectionComposablePartDefinition.cs -crlf -/ReflectionExtensions.cs -crlf -/ReflectionField.cs -crlf -/ReflectionImportDefinition.cs -crlf -/ReflectionItem.cs -crlf -/ReflectionItemType.cs -crlf -/ReflectionMember.cs -crlf -/ReflectionMemberExportDefinition.cs -crlf -/ReflectionMemberImportDefinition.cs -crlf -/ReflectionMethod.cs -crlf -/ReflectionModelServices.cs -crlf -/ReflectionParameter.cs -crlf -/ReflectionParameterImportDefinition.cs -crlf -/ReflectionProperty.cs -crlf -/ReflectionType.cs -crlf -/ReflectionWritableMember.cs -crlf diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs deleted file mode 100644 index c6b9854691a..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs +++ /dev/null @@ -1,57 +0,0 @@ -
-// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal sealed class DisposableReflectionComposablePart : ReflectionComposablePart, IDisposable
- {
- private volatile int _isDisposed = 0;
-
- public DisposableReflectionComposablePart(ReflectionComposablePartDefinition definition)
- : base(definition)
- {
- }
-
- protected override void ReleaseInstanceIfNecessary(object instance)
- {
- IDisposable disposable = instance as IDisposable;
- if (disposable != null)
- {
- disposable.Dispose();
- }
- }
-
- protected override void EnsureRunning()
- {
- base.EnsureRunning();
- if (this._isDisposed == 1)
- {
- throw ExceptionBuilder.CreateObjectDisposed(this);
- }
- }
-
- void IDisposable.Dispose()
- {
- // NOTE : According to http://msdn.microsoft.com/en-us/library/4bw5ewxy.aspx, the warning is bogus when used with Interlocked API.
-#pragma warning disable 420
- if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
-#pragma warning restore 420
- {
- this.ReleaseInstanceIfNecessary(this.CachedInstance);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs deleted file mode 100644 index 5276e7a1528..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ExportingMember
- {
- private readonly ExportDefinition _definition;
- private readonly ReflectionMember _member;
- private object _cachedValue = null;
- private volatile bool _isValueCached = false;
-
- public ExportingMember(ExportDefinition definition, ReflectionMember member)
- {
- Assumes.NotNull(definition, member);
-
- this._definition = definition;
- this._member = member;
- }
-
- public bool RequiresInstance
- {
- get { return _member.RequiresInstance; }
- }
-
- public ExportDefinition Definition
- {
- get { return _definition; }
- }
-
- public object GetExportedValue(object instance, object @lock)
- {
- this.EnsureReadable();
-
- if (!this._isValueCached)
- {
- object exportedValue;
- try
- {
- exportedValue = this._member.GetValue(instance);
- }
- catch (TargetInvocationException exception)
- { // Member threw an exception. Avoid letting this
- // leak out as a 'raw' unhandled exception, instead,
- // we'll add some context and rethrow.
-
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ExportThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ExportThrewException,
- this._member.GetDisplayName()),
- Definition.ToElement(),
- exception.InnerException);
- }
-
- lock (@lock)
- {
- if (!this._isValueCached)
- {
- this._cachedValue = exportedValue;
- Thread.MemoryBarrier();
-
- this._isValueCached = true;
- }
- }
- }
-
- return this._cachedValue;
- }
-
- private void EnsureReadable()
- {
- if (!this._member.CanRead)
- { // Property does not have a getter
-
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ExportNotReadable,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ExportNotReadable,
- this._member.GetDisplayName()),
- Definition.ToElement());
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs deleted file mode 100644 index ac2a31a98f0..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Reflection;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal interface IReflectionPartCreationInfo : ICompositionElement
- {
- Type GetPartType();
- Lazy<Type> GetLazyPartType();
- ConstructorInfo GetConstructor();
- IDictionary<string, object> GetMetadata();
- IEnumerable<ExportDefinition> GetExports();
- IEnumerable<ImportDefinition> GetImports();
- bool IsDisposalRequired { get; }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportType.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportType.cs deleted file mode 100644 index 60da83d83a9..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportType.cs +++ /dev/null @@ -1,140 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Reflection;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- // Describes the import type of a Reflection-based import definition
- internal class ImportType
- {
- private static readonly Type LazyOfTType = typeof(Lazy<>);
- private static readonly Type LazyOfTMType = typeof(Lazy<,>);
- private const string ExportFactoryTypeName = "System.ComponentModel.Composition.ExportFactory";
-
- private readonly Type _type;
- private readonly bool _isAssignableCollectionType;
- private readonly Type _contractType;
- private Func<Export, object> _castSingleValue;
-
- public ImportType(Type type, ImportCardinality cardinality)
- {
- Assumes.NotNull(type);
-
- this._type = type;
- this._contractType = type;
-
- if (cardinality == ImportCardinality.ZeroOrMore)
- {
- this._isAssignableCollectionType = IsTypeAssignableCollectionType(type);
- this._contractType = CheckForCollection(type);
- }
-
- this._contractType = CheckForLazyAndPartCreator(this._contractType);
- }
-
- public bool IsAssignableCollectionType
- {
- get { return this._isAssignableCollectionType; }
- }
-
- public Type ElementType { get; private set; }
-
- public Type ActualType
- {
- get { return this._type; }
- }
-
- public bool IsPartCreator { get; private set; }
-
- public Type ContractType { get { return this._contractType; } }
-
- public Func<Export, object> CastExport { get { return this._castSingleValue; } }
-
- public Type MetadataViewType { get; private set; }
-
- private Type CheckForCollection(Type type)
- {
- this.ElementType = CollectionServices.GetEnumerableElementType(type);
- if (this.ElementType != null)
- {
- return this.ElementType;
- }
- return type;
- }
-
- 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;
- }
-
- private static bool IsTypeAssignableCollectionType(Type type)
- {
- if (type.IsArray || CollectionServices.IsEnumerableOfT(type))
- {
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs deleted file mode 100644 index 3b07368b974..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs +++ /dev/null @@ -1,116 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Globalization;
-using System.Linq;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal abstract class ImportingItem
- {
- private readonly ContractBasedImportDefinition _definition;
- private readonly ImportType _importType;
-
- protected ImportingItem(ContractBasedImportDefinition definition, ImportType importType)
- {
- Assumes.NotNull(definition);
-
- this._definition = definition;
- this._importType = importType;
- }
-
- public ContractBasedImportDefinition Definition
- {
- get { return this._definition; }
- }
-
- public ImportType ImportType
- {
- get { return this._importType; }
- }
-
- public object CastExportsToImportType(Export[] exports)
- {
- if (this.Definition.Cardinality == ImportCardinality.ZeroOrMore)
- {
- return CastExportsToCollectionImportType(exports);
- }
- else
- {
- return CastExportsToSingleImportType(exports);
- }
- }
-
- private object CastExportsToCollectionImportType(Export[] exports)
- {
- Assumes.NotNull(exports);
-
- // Element type could be null if the actually import type of the member is not a collection
- // This particular case will end up failing when we set the member.
- Type elementType = this.ImportType.ElementType ?? typeof(object);
-
- Array array = Array.CreateInstance(elementType, exports.Length);
-
- for (int i = 0; i < array.Length; i++)
- {
- object value = CastSingleExportToImportType(elementType, exports[i]);
-
- array.SetValue(value, i);
- }
-
- return array;
- }
-
- private object CastExportsToSingleImportType(Export[] exports)
- {
- Assumes.NotNull(exports);
- Assumes.IsTrue(exports.Length < 2);
-
- if (exports.Length == 0)
- {
- return null;
- }
-
- return CastSingleExportToImportType(this.ImportType.ActualType, exports[0]);
- }
-
- private object CastSingleExportToImportType(Type type, Export export)
- {
- if (this.ImportType.CastExport != null)
- {
- return this.ImportType.CastExport(export);
- }
-
- return Cast(type, export);
- }
-
- private object Cast(Type type, Export export)
- {
- // TODO: Need to catch CompositionException to provide
- // additional information about what member we're setting
- // and the current dependency graph.
- object value = export.Value;
-
- object result;
- if (!ContractServices.TryCast(type, value, out result))
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportNotAssignableFromExport,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportNotAssignableFromExport,
- export.ToElement().DisplayName,
- type.FullName),
- this.Definition.ToElement());
- }
-
- return result;
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs deleted file mode 100644 index 6e5cffe183a..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs +++ /dev/null @@ -1,253 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ImportingMember : ImportingItem
- {
- private readonly ReflectionWritableMember _member;
-
- public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member, ImportType importType)
- : base(definition, importType)
- {
- Assumes.NotNull(definition, member);
-
- this._member = member;
- }
-
- public void SetExportedValue(object instance, object value)
- {
- if (RequiresCollectionNormalization())
- {
- this.SetCollectionMemberValue(instance, (IEnumerable)value);
- }
- else
- {
- this.SetSingleMemberValue(instance, value);
- }
- }
-
- private bool RequiresCollectionNormalization()
- {
- if (this.Definition.Cardinality != ImportCardinality.ZeroOrMore)
- { // If we're not looking at a collection import, then don't
- // 'normalize' the collection.
-
- return false;
- }
-
- if (this._member.CanWrite && this.ImportType.IsAssignableCollectionType)
- { // If we can simply replace the entire value of the property/field, then
- // we don't need to 'normalize' the collection.
-
- return false;
- }
-
- return true;
- }
-
- private void SetSingleMemberValue(object instance, object value)
- {
- EnsureWritable();
-
- try
- {
- this._member.SetValue(instance, value);
- }
- catch (TargetInvocationException exception)
- { // Member threw an exception. Avoid letting this
- // leak out as a 'raw' unhandled exception, instead,
- // we'll add some context and rethrow.
-
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportThrewException,
- this._member.GetDisplayName()),
- Definition.ToElement(),
- exception.InnerException);
- }
- }
-
- private void EnsureWritable()
- {
- if (!this._member.CanWrite)
- { // Property does not have a setter, or
- // field is marked as read-only.
-
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportNotWritable,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportNotWritable,
- this._member.GetDisplayName()),
- Definition.ToElement());
- }
- }
-
- private void SetCollectionMemberValue(object instance, IEnumerable values)
- {
- Assumes.NotNull(values);
-
- ICollection<object> collection = null;
- Type itemType = CollectionServices.GetCollectionElementType(this.ImportType.ActualType);
- if (itemType != null)
- {
- collection = GetNormalizedCollection(itemType, instance);
- }
-
- EnsureCollectionIsWritable(collection);
- PopulateCollection(collection, values);
- }
-
- private ICollection<object> GetNormalizedCollection(Type itemType, object instance)
- {
- Assumes.NotNull(itemType);
-
- object collectionObject = null;
-
- if (this._member.CanRead)
- {
- try
- {
- collectionObject = this._member.GetValue(instance);
- }
- catch (TargetInvocationException exception)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionGetThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionGetThrewException,
- this._member.GetDisplayName()),
- this.Definition.ToElement(),
- exception.InnerException);
- }
- }
-
- if (collectionObject == null)
- {
- ConstructorInfo constructor = this.ImportType.ActualType.GetConstructor(Type.EmptyTypes);
-
- // If it contains a default public constructor create a new instance.
- if (constructor != null)
- {
- try
- {
- collectionObject = constructor.SafeInvoke();
- }
- catch (TargetInvocationException exception)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionConstructionThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionConstructionThrewException,
- this._member.GetDisplayName(),
- this.ImportType.ActualType.FullName),
- this.Definition.ToElement(),
- exception.InnerException);
- }
-
- SetSingleMemberValue(instance, collectionObject);
- }
- }
-
- if (collectionObject == null)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionNull,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionNull,
- this._member.GetDisplayName()),
- this.Definition.ToElement());
- }
-
- return CollectionServices.GetCollectionWrapper(itemType, collectionObject);
- }
-
- [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- private void EnsureCollectionIsWritable(ICollection<object> collection)
- {
- bool isReadOnly = true;
-
- try
- {
- if (collection != null)
- {
- isReadOnly = collection.IsReadOnly;
- }
- }
- catch (Exception exception)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionIsReadOnlyThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionIsReadOnlyThrewException,
- this._member.GetDisplayName(),
- collection.GetType().FullName),
- this.Definition.ToElement(),
- exception);
- }
-
- if (isReadOnly)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionNotWritable,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionNotWritable,
- this._member.GetDisplayName()),
- this.Definition.ToElement());
- }
- }
-
- [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- private void PopulateCollection(ICollection<object> collection, IEnumerable values)
- {
- Assumes.NotNull(collection, values);
-
- try
- {
- collection.Clear();
- }
- catch (Exception exception)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionClearThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionClearThrewException,
- this._member.GetDisplayName(),
- collection.GetType().FullName),
- this.Definition.ToElement(),
- exception);
- }
-
- foreach (object value in values)
- {
- try
- {
- collection.Add(value);
- }
- catch (Exception exception)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportCollectionAddThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportCollectionAddThrewException,
- this._member.GetDisplayName(),
- collection.GetType().FullName),
- this.Definition.ToElement(),
- exception);
- }
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingParameter.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingParameter.cs deleted file mode 100644 index a454189613a..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ImportingParameter.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ImportingParameter : ImportingItem
- {
- public ImportingParameter(ContractBasedImportDefinition definition, ImportType importType)
- : base(definition, importType)
- {
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs deleted file mode 100644 index 6b492cf7308..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs +++ /dev/null @@ -1,207 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- public struct LazyMemberInfo
- {
- private readonly MemberTypes _memberType;
- private MemberInfo[] _accessors;
- private readonly Func<MemberInfo[]> _accessorsCreator;
-
- public LazyMemberInfo(MemberInfo member)
- {
- Requires.NotNull(member, "member");
- EnsureSupportedMemberType(member.MemberType, "member");
-
- this._accessorsCreator = null;
- this._memberType = member.MemberType;
-
- switch(this._memberType)
- {
- case MemberTypes.Property:
- PropertyInfo property = (PropertyInfo)member;
- Assumes.NotNull(property);
- this._accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true) };
- break;
- case MemberTypes.Event:
- EventInfo event_ = (EventInfo)member;
- this._accessors = new MemberInfo[] { event_.GetRaiseMethod(true), event_.GetAddMethod(true), event_.GetRemoveMethod(true) };
- break;
- default:
- this._accessors = new MemberInfo[] { member };
- break;
- }
- }
-
- public LazyMemberInfo(MemberTypes memberType, params MemberInfo[] accessors)
- {
- EnsureSupportedMemberType(memberType, "memberType");
- Requires.NotNull(accessors, "accessors");
-
- string errorMessage;
- if (!LazyMemberInfo.AreAccessorsValid(memberType, accessors, out errorMessage))
- {
- throw new ArgumentException(errorMessage, "accessors");
- }
-
- this._memberType = memberType;
- this._accessors = accessors;
- this._accessorsCreator = null;
- }
-
- public LazyMemberInfo(MemberTypes memberType, Func<MemberInfo[]> accessorsCreator)
- {
- EnsureSupportedMemberType(memberType, "memberType");
- Requires.NotNull(accessorsCreator, "accessorsCreator");
-
- this._memberType = memberType;
- this._accessors = null;
- this._accessorsCreator = accessorsCreator;
- }
-
- public MemberTypes MemberType
- {
- get { return this._memberType; }
- }
-
- public MemberInfo[] GetAccessors()
- {
- if ((this._accessors == null) && (this._accessorsCreator != null))
- {
- MemberInfo[] accessors = this._accessorsCreator.Invoke();
-
- string errorMessage;
- if (!LazyMemberInfo.AreAccessorsValid(this.MemberType, accessors, out errorMessage))
- {
- throw new InvalidOperationException(errorMessage);
- }
-
- this._accessors = accessors;
- }
-
- return this._accessors;
- }
-
- public override int GetHashCode()
- {
- if (this._accessorsCreator != null)
- {
- return this.MemberType.GetHashCode() ^ this._accessorsCreator.GetHashCode();
- }
- else
- {
- Assumes.NotNull(this._accessors);
- Assumes.NotNull(this._accessors[0]);
- return this.MemberType.GetHashCode() ^ this._accessors[0].GetHashCode();
- }
- }
-
- public override bool Equals(object obj)
- {
- LazyMemberInfo that = (LazyMemberInfo)obj;
-
- // Difefrent member types mean different members
- if (this._memberType != that._memberType)
- {
- return false;
- }
-
- // if any of the lazy memebers create accessors in a delay-loaded fashion, we simply compare the creators
- if ((this._accessorsCreator != null) || (that._accessorsCreator != null))
- {
- return object.Equals(this._accessorsCreator, that._accessorsCreator);
- }
-
- // we are dealing with explicitly passed accessors in both cases
- Assumes.NotNull(this._accessors);
- Assumes.NotNull(that._accessors);
- return this._accessors.SequenceEqual(that._accessors);
- }
-
- public static bool operator ==(LazyMemberInfo left, LazyMemberInfo right)
- {
- return left.Equals(right);
- }
-
- public static bool operator !=(LazyMemberInfo left, LazyMemberInfo right)
- {
- return !left.Equals(right);
- }
-
- private static void EnsureSupportedMemberType(MemberTypes memberType, string argument)
- {
- MemberTypes supportedTypes = MemberTypes.TypeInfo | MemberTypes.NestedType | MemberTypes.Constructor | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property | MemberTypes.Event;
- Requires.IsInMembertypeSet(memberType, argument, supportedTypes);
- }
-
- private static bool AreAccessorsValid(MemberTypes memberType, MemberInfo[] accessors, out string errorMessage)
- {
- errorMessage = string.Empty;
- if (accessors == null)
- {
- errorMessage = Strings.LazyMemberInfo_AccessorsNull;
- return false;
- }
-
- if (accessors.All(accessor => accessor == null))
- {
- errorMessage = Strings.LazyMemberInfo_NoAccessors;
- return false;
- }
-
- switch (memberType)
- {
- case MemberTypes.Property:
- if (accessors.Length != 2)
- {
- errorMessage = Strings.LazyMemberInfo_InvalidPropertyAccessors_Cardinality;
- return false;
- }
-
- if (accessors.Where(accessor => (accessor != null) && (accessor.MemberType != MemberTypes.Method)).Any())
- {
- errorMessage = Strings.LazyMemberinfo_InvalidPropertyAccessors_AccessorType;
- return false;
- }
-
- break;
-
- case MemberTypes.Event:
- if (accessors.Length != 3)
- {
- errorMessage = Strings.LazyMemberInfo_InvalidEventAccessors_Cardinality;
- return false;
- }
-
- if (accessors.Where(accessor => (accessor != null) && (accessor.MemberType != MemberTypes.Method)).Any())
- {
- errorMessage = Strings.LazyMemberinfo_InvalidPropertyAccessors_AccessorType;
- return false;
- }
-
- break;
-
- default:
- if (
- (accessors.Length != 1) ||
- ((accessors.Length == 1) && (accessors[0].MemberType != memberType)))
- {
- errorMessage = string.Format(CultureInfo.CurrentCulture, Strings.LazyMemberInfo_InvalidAccessorOnSimpleMember, memberType);
- return false;
- }
-
- break;
- }
- return true;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs deleted file mode 100644 index 2b135441a39..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class PartCreatorExportDefinition : ExportDefinition
- {
- private readonly ExportDefinition _productDefinition;
- private IDictionary<string, object> _metadata;
-
- public PartCreatorExportDefinition(ExportDefinition productDefinition)
- : base()
- {
- this._productDefinition = productDefinition;
- }
-
- public override string ContractName
- {
- get
- {
- return CompositionConstants.PartCreatorContractName;
- }
- }
-
- public override IDictionary<string, object> Metadata
- {
- get
- {
- if (this._metadata == null)
- {
- var metadata = new Dictionary<string, object>(this._productDefinition.Metadata);
- metadata[CompositionConstants.ExportTypeIdentityMetadataName] = CompositionConstants.PartCreatorTypeIdentity;
- metadata[CompositionConstants.ProductDefinitionMetadataName] = this._productDefinition;
-
- this._metadata = metadata.AsReadOnly();
- }
- return this._metadata;
- }
- }
-
- internal static bool IsProductConstraintSatisfiedBy(ImportDefinition productImportDefinition, ExportDefinition exportDefinition)
- {
- object productValue = null;
- if (exportDefinition.Metadata.TryGetValue(CompositionConstants.ProductDefinitionMetadataName, out productValue))
- {
- ExportDefinition productDefinition = productValue as ExportDefinition;
-
- if (productDefinition != null)
- {
- return productImportDefinition.IsConstraintSatisfiedBy(productDefinition);
- }
- }
-
- return false;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs deleted file mode 100644 index 8eb39638fe3..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq.Expressions;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class PartCreatorMemberImportDefinition : ReflectionMemberImportDefinition, IPartCreatorImportDefinition
- {
- private readonly ContractBasedImportDefinition _productImportDefinition;
-
- public PartCreatorMemberImportDefinition(
- LazyMemberInfo importingLazyMember,
- ICompositionElement origin,
- ContractBasedImportDefinition productImportDefinition)
- : base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
- productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, CreationPolicy.Any, origin)
- {
- Assumes.NotNull(productImportDefinition);
- this._productImportDefinition = productImportDefinition;
- }
-
- public ContractBasedImportDefinition ProductImportDefinition { get { return this._productImportDefinition; } }
-
- public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
- {
- if (!base.IsConstraintSatisfiedBy(exportDefinition))
- {
- return false;
- }
-
- return PartCreatorExportDefinition.IsProductConstraintSatisfiedBy(this._productImportDefinition, exportDefinition);
- }
-
- public override Expression<Func<ExportDefinition, bool>> Constraint
- {
- get
- {
- return ConstraintServices.CreatePartCreatorConstraint(base.Constraint, this._productImportDefinition);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs deleted file mode 100644 index df498e2a057..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Linq.Expressions;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class PartCreatorParameterImportDefinition : ReflectionParameterImportDefinition, IPartCreatorImportDefinition
- {
- private readonly ContractBasedImportDefinition _productImportDefinition;
-
- public PartCreatorParameterImportDefinition(
- Lazy<ParameterInfo> importingLazyParameter,
- ICompositionElement origin,
- ContractBasedImportDefinition productImportDefinition)
- : base(importingLazyParameter, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
- productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, CreationPolicy.Any, origin)
- {
- Assumes.NotNull(productImportDefinition);
- this._productImportDefinition = productImportDefinition;
- }
-
- public ContractBasedImportDefinition ProductImportDefinition { get { return this._productImportDefinition; } }
-
- public override bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
- {
- if (!base.IsConstraintSatisfiedBy(exportDefinition))
- {
- return false;
- }
- return PartCreatorExportDefinition.IsProductConstraintSatisfiedBy(this._productImportDefinition, exportDefinition);
- }
-
- public override Expression<Func<ExportDefinition, bool>> Constraint
- {
- get
- {
- return ConstraintServices.CreatePartCreatorConstraint(base.Constraint, this._productImportDefinition);
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs deleted file mode 100644 index 908b99baa41..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs +++ /dev/null @@ -1,565 +0,0 @@ -
-// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- // This
- internal class ReflectionComposablePart : ComposablePart, ICompositionElement
- {
- private readonly ReflectionComposablePartDefinition _definition;
- private readonly Dictionary<ImportDefinition, object> _importValues = new Dictionary<ImportDefinition, object>();
- private readonly Dictionary<ImportDefinition, ImportingItem> _importsCache = new Dictionary<ImportDefinition, ImportingItem>();
- private readonly Dictionary<ExportDefinition, ExportingMember> _exportsCache = new Dictionary<ExportDefinition, ExportingMember>();
- private bool _invokeImportsSatisfied = true;
- private bool _invokingImportsSatisfied = false;
- private bool _initialCompositionComplete = false;
- private volatile object _cachedInstance;
- private object _lock = new object();
-
- public ReflectionComposablePart(ReflectionComposablePartDefinition definition)
- {
- Requires.NotNull(definition, "definition");
-
- this._definition = definition;
- }
-
- public ReflectionComposablePart(ReflectionComposablePartDefinition definition, object attributedPart)
- {
- Requires.NotNull(definition, "definition");
- Requires.NotNull(attributedPart, "attributedPart");
-
- this._definition = definition;
-
- if (attributedPart is ValueType)
- {
- throw new ArgumentException(Strings.ArgumentValueType, "attributedPart");
- }
- this._cachedInstance = attributedPart;
- }
-
- protected virtual void EnsureRunning()
- {
- }
-
- protected virtual void ReleaseInstanceIfNecessary(object instance)
- {
- }
-
- protected object CachedInstance
- {
- get
- {
- lock (this._lock)
- {
- return this._cachedInstance;
- }
- }
- }
-
- public ReflectionComposablePartDefinition Definition
- {
- get
- {
- this.EnsureRunning();
- return this._definition;
- }
- }
-
- public override IDictionary<string, object> Metadata
- {
- get
- {
- this.EnsureRunning();
- return this.Definition.Metadata;
- }
- }
-
- public sealed override IEnumerable<ImportDefinition> ImportDefinitions
- {
- get
- {
- this.EnsureRunning();
- return this.Definition.ImportDefinitions;
- }
- }
-
- public sealed override IEnumerable<ExportDefinition> ExportDefinitions
- {
- get
- {
- this.EnsureRunning();
- return this.Definition.ExportDefinitions;
- }
- }
-
-
- string ICompositionElement.DisplayName
- {
- get { return GetDisplayName(); }
- }
-
- ICompositionElement ICompositionElement.Origin
- {
- get { return Definition; }
- }
-
- // This is the ONLY method which is not executed under the ImportEngine composition lock.
- // We need to protect all state that is accesses
- public override object GetExportedValue(ExportDefinition definition)
- {
- // given the implementation of the ImportEngine, this iwll be called under a lock if the part is still being composed
- // This is only called outside of the lock when the part is fully composed
- // based on that we only protect:
- // _exportsCache - and thus all calls to GetExportingMemberFromDefinition
- // access to _importValues
- // access to _initialCompositionComplete
- // access to _instance
- this.EnsureRunning();
- Requires.NotNull(definition, "definition");
-
- ExportingMember member = null;
- lock (this._lock)
- {
- member = GetExportingMemberFromDefinition(definition);
- if (member == null)
- {
- throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart("definition");
- }
- this.EnsureGettable();
- }
-
- return this.GetExportedValue(member);
- }
-
- public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports)
- {
- this.EnsureRunning();
-
- Requires.NotNull(definition, "definition");
- Requires.NotNull(exports, "exports");
-
- ImportingItem item = GetImportingItemFromDefinition(definition);
- if (item == null)
- {
- throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart("definition");
- }
-
- EnsureSettable(definition);
-
- // Avoid walking over exports many times
- Export[] exportsAsArray = exports.AsArray();
- EnsureCardinality(definition, exportsAsArray);
-
- SetImport(item, exportsAsArray);
- }
-
- public override void Activate()
- {
- this.EnsureRunning();
-
- this.SetNonPrerequisiteImports();
-
- // Whenever we are composed/recomposed notify the instance
- this.NotifyImportSatisfied();
-
- lock (this._lock)
- {
- this._initialCompositionComplete = true;
- }
- }
-
- public override string ToString()
- {
- return this.GetDisplayName();
- }
-
- private object GetExportedValue(ExportingMember member)
- {
- object instance = null;
- if (member.RequiresInstance)
- { // Only activate the instance if we actually need to
-
- instance = this.GetInstanceActivatingIfNeeded();
- }
-
- return member.GetExportedValue(instance, this._lock);
- }
-
- private void SetImport(ImportingItem item, Export[] exports)
- {
- object value = item.CastExportsToImportType(exports);
-
- lock (this._lock)
- {
- this._invokeImportsSatisfied = true;
- this._importValues[item.Definition] = value;
- }
- }
-
- private object GetInstanceActivatingIfNeeded()
- {
- if (this._cachedInstance != null)
- {
- return this._cachedInstance;
- }
- else
- {
- ConstructorInfo constructor = null;
- object[] arguments = null;
- // determine whether activation is required, and collect necessary information for activation
- // we need to do that under a lock
- lock (this._lock)
- {
- if (!this.RequiresActivation())
- {
- return null;
- }
-
- constructor = this.Definition.GetConstructor();
- if (constructor == null)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_PartConstructorMissing,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_PartConstructorMissing,
- this.Definition.GetPartType().FullName),
- this.Definition.ToElement());
- }
- arguments = this.GetConstructorArguments();
- }
-
- // create instance outside of the lock
- object createdInstance = this.CreateInstance(constructor, arguments);
-
- // set the created instance
- lock (this._lock)
- {
- if (this._cachedInstance == null)
- {
- this._cachedInstance = createdInstance;
- createdInstance = null;
- }
- }
-
- // if the instance has been already set
- if (createdInstance == null)
- {
- this.ReleaseInstanceIfNecessary(createdInstance);
- }
- }
-
- return this._cachedInstance;
- }
-
- private object[] GetConstructorArguments()
- {
- ReflectionParameterImportDefinition[] parameterImports = this.ImportDefinitions.OfType<ReflectionParameterImportDefinition>().ToArray();
- object[] arguments = new object[parameterImports.Length];
-
- this.UseImportedValues(
- parameterImports,
- (import, definition, value) =>
- {
- if (definition.Cardinality == ImportCardinality.ZeroOrMore && !import.ImportType.IsAssignableCollectionType)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned,
- this.Definition.GetPartType().FullName,
- definition.ImportingLazyParameter.Value.Name),
- this.Definition.ToElement());
- }
-
- arguments[definition.ImportingLazyParameter.Value.Position] = value;
- },
- true);
-
- return arguments;
- }
-
- // alwayc called under a lock
- private bool RequiresActivation()
- {
- // If we have any imports then we need activation
- // (static imports are not supported)
- if (this.ImportDefinitions.Any())
- {
- return true;
- }
-
- // If we have any instance exports, then we also
- // need activation.
- return this.ExportDefinitions.Any(definition =>
- {
- ExportingMember member = GetExportingMemberFromDefinition(definition);
-
- return member.RequiresInstance;
- });
- }
-
- // this is called under a lock
- private void EnsureGettable()
- {
- // If we're already composed then we know that
- // all pre-req imports have been satisfied
- if (_initialCompositionComplete)
- {
- return;
- }
-
- // Make sure all pre-req imports have been set
- foreach (ImportDefinition definition in ImportDefinitions.Where(definition => definition.IsPrerequisite))
- {
- if (!this._importValues.ContainsKey(definition))
- {
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
- Strings.InvalidOperation_GetExportedValueBeforePrereqImportSet,
- definition.ToElement().DisplayName));
- }
- }
- }
-
- private void EnsureSettable(ImportDefinition definition)
- {
- lock (this._lock)
- {
- if (this._initialCompositionComplete && !definition.IsRecomposable)
- {
- throw new InvalidOperationException(Strings.InvalidOperation_DefinitionCannotBeRecomposed);
- }
- }
- }
-
- private static void EnsureCardinality(ImportDefinition definition, Export[] exports)
- {
- Requires.NullOrNotNullElements(exports, "exports");
-
- ExportCardinalityCheckResult result = ExportServices.CheckCardinality(definition, exports);
-
- switch (result)
- {
- case ExportCardinalityCheckResult.NoExports:
- throw new ArgumentException(Strings.Argument_ExportsEmpty, "exports");
-
- case ExportCardinalityCheckResult.TooManyExports:
- throw new ArgumentException(Strings.Argument_ExportsTooMany, "exports");
-
- default:
- Assumes.IsTrue(result == ExportCardinalityCheckResult.Match);
- break;
- }
- }
-
- private object CreateInstance(ConstructorInfo constructor, object[] arguments)
- {
- Exception exception = null;
- object instance = null;
-
- try
- {
- instance = constructor.SafeInvoke(arguments);
- }
- catch (TypeInitializationException ex)
- {
- exception = ex;
- }
- catch (TargetInvocationException ex)
- {
- exception = ex.InnerException;
- }
-
- if (exception != null)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_PartConstructorThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_PartConstructorThrewException,
- Definition.GetPartType().FullName),
- Definition.ToElement(),
- exception);
- }
-
- return instance;
- }
-
- private void SetNonPrerequisiteImports()
- {
- IEnumerable<ImportDefinition> members = this.ImportDefinitions.Where(import => !import.IsPrerequisite);
-
- // NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition
- this.UseImportedValues(members, SetExportedValueForImport, false);
- }
-
- private void SetExportedValueForImport(ImportingItem import, ImportDefinition definition, object value)
- {
- ImportingMember importMember = (ImportingMember)import;
-
- object instance = this.GetInstanceActivatingIfNeeded();
-
- importMember.SetExportedValue(instance, value);
- }
-
- private void UseImportedValues<TImportDefinition>(IEnumerable<TImportDefinition> definitions, Action<ImportingItem, TImportDefinition, object> useImportValue, bool errorIfMissing)
- where TImportDefinition : ImportDefinition
- {
- var result = CompositionResult.SucceededResult;
-
- foreach (var definition in definitions)
- {
- ImportingItem import = GetImportingItemFromDefinition(definition);
-
- object value;
- if (!TryGetImportValue(definition, out value))
- {
- if (!errorIfMissing)
- {
- continue;
- }
-
- if (definition.Cardinality == ImportCardinality.ExactlyOne)
- {
- var error = CompositionError.Create(
- CompositionErrorId.ImportNotSetOnPart,
- Strings.ImportNotSetOnPart,
- this.Definition.GetPartType().FullName,
- definition.ToString());
- result = result.MergeError(error);
- continue;
- }
- else
- {
- value = import.CastExportsToImportType(new Export[0]);
- }
- }
-
- useImportValue(import, definition, value);
- }
-
- result.ThrowOnErrors();
- }
-
- private bool TryGetImportValue(ImportDefinition definition, out object value)
- {
- lock (this._lock)
- {
- if (this._importValues.TryGetValue(definition, out value))
- {
- this._importValues.Remove(definition);
- return true;
- }
- }
-
- value = null;
- return false;
- }
-
- [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
- private void NotifyImportSatisfied()
- {
- if (this._invokeImportsSatisfied && !this._invokingImportsSatisfied)
- {
- IPartImportsSatisfiedNotification notify = this.GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification;
- if (notify != null)
- {
- try
- {
- // Reentrancy on composition notifications is allowed, so set this first to avoid
- // an infinte loop of notifications.
- this._invokingImportsSatisfied = true;
-
- notify.OnImportsSatisfied();
- }
- catch (Exception exception)
- {
- throw new ComposablePartException(
- CompositionErrorId.ReflectionModel_PartOnImportsSatisfiedThrewException,
- String.Format(CultureInfo.CurrentCulture,
- Strings.ReflectionModel_PartOnImportsSatisfiedThrewException,
- Definition.GetPartType().FullName),
- Definition.ToElement(),
- exception);
- }
- finally
- {
- this._invokingImportsSatisfied = false;
- }
-
- this._invokeImportsSatisfied = false;
- }
- }
- }
-
- // this is always called under a lock
- private ExportingMember GetExportingMemberFromDefinition(ExportDefinition definition)
- {
- ExportingMember result;
- if (!_exportsCache.TryGetValue(definition, out result))
- {
- result = GetExportingMember(definition);
- if (result != null)
- {
- _exportsCache[definition] = result;
- }
- }
-
- return result;
- }
-
- private ImportingItem GetImportingItemFromDefinition(ImportDefinition definition)
- {
- ImportingItem result;
- if (!_importsCache.TryGetValue(definition, out result))
- {
- result = GetImportingItem(definition);
- if (result != null)
- {
- _importsCache[definition] = result;
- }
- }
-
- return result;
- }
-
- private static ImportingItem GetImportingItem(ImportDefinition definition)
- {
- ReflectionImportDefinition reflectionDefinition = definition as ReflectionImportDefinition;
- if (reflectionDefinition != null)
- {
- return reflectionDefinition.ToImportingItem();
- }
-
- // Don't recognize it
- return null;
- }
-
- private static ExportingMember GetExportingMember(ExportDefinition definition)
- {
- ReflectionMemberExportDefinition exportDefinition = definition as ReflectionMemberExportDefinition;
- if (exportDefinition != null)
- {
- return exportDefinition.ToExportingMember();
- }
-
- // Don't recognize it
- return null;
- }
-
- private string GetDisplayName()
- {
- return this.Definition.GetPartType().GetDisplayName();
- }
- }
-}
\ No newline at end of file diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs deleted file mode 100644 index 347fa2ed8fb..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs +++ /dev/null @@ -1,151 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Reflection;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionComposablePartDefinition : ComposablePartDefinition, ICompositionElement
- {
- private readonly IReflectionPartCreationInfo _creationInfo;
-
- private volatile IEnumerable<ImportDefinition> _imports;
- private volatile IEnumerable<ExportDefinition> _exports;
- private volatile IDictionary<string, object> _metadata;
- private volatile ConstructorInfo _constructor;
- private object _lock = new object();
-
- public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo)
- {
- Assumes.NotNull(creationInfo);
- this._creationInfo = creationInfo;
- }
-
- public Type GetPartType()
- {
- return this._creationInfo.GetPartType();
- }
-
- public Lazy<Type> GetLazyPartType()
- {
- return this._creationInfo.GetLazyPartType();
- }
-
- public ConstructorInfo GetConstructor()
- {
- if (this._constructor == null)
- {
- ConstructorInfo constructor = this._creationInfo.GetConstructor();
- lock (this._lock)
- {
- if (this._constructor == null)
- {
- this._constructor = constructor;
- }
- }
- }
-
- return this._constructor;
- }
-
- public override IEnumerable<ExportDefinition> ExportDefinitions
- {
- get
- {
- if (this._exports == null)
- {
- ExportDefinition[] exports = this._creationInfo.GetExports().ToArray();
- lock (this._lock)
- {
- if (this._exports == null)
- {
- this._exports = exports;
- }
- }
- }
- return this._exports;
- }
- }
-
- public override IEnumerable<ImportDefinition> ImportDefinitions
- {
- get
- {
- if (this._imports == null)
- {
- ImportDefinition[] imports = this._creationInfo.GetImports().ToArray();
- lock (this._lock)
- {
- if (this._imports == null)
- {
- this._imports = imports;
- }
- }
- }
- return this._imports;
- }
- }
-
- public override IDictionary<string, object> Metadata
- {
- get
- {
- if (this._metadata == null)
- {
- IDictionary<string, object> metadata = this._creationInfo.GetMetadata().AsReadOnly();
- lock (this._lock)
- {
- if (this._metadata == null)
- {
- this._metadata = metadata;
- }
- }
- }
- return this._metadata;
- }
- }
-
- internal bool IsDisposalRequired
- {
- get
- {
- return this._creationInfo.IsDisposalRequired;
- }
- }
-
- [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
- public override ComposablePart CreatePart()
- {
- if (this.IsDisposalRequired)
- {
- return new DisposableReflectionComposablePart(this);
- }
- else
- {
- return new ReflectionComposablePart(this);
- }
- }
-
- string ICompositionElement.DisplayName
- {
- get { return this._creationInfo.DisplayName; }
- }
-
- ICompositionElement ICompositionElement.Origin
- {
- get { return this._creationInfo.Origin; }
- }
-
- public override string ToString()
- {
- return this._creationInfo.DisplayName;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs deleted file mode 100644 index 47a3b97dedb..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs +++ /dev/null @@ -1,134 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-using System.Collections.Generic;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal static class ReflectionExtensions
- {
- public static ReflectionMember ToReflectionMember(this LazyMemberInfo lazyMember)
- {
- MemberInfo[] accessors = lazyMember.GetAccessors();
- MemberTypes memberType = lazyMember.MemberType;
-
- switch (memberType)
- {
- case MemberTypes.Field:
- Assumes.IsTrue(accessors.Length == 1);
- return ((FieldInfo)accessors[0]).ToReflectionField();
-
- case MemberTypes.Property:
- Assumes.IsTrue(accessors.Length == 2);
- return ReflectionExtensions.CreateReflectionProperty((MethodInfo)accessors[0], (MethodInfo)accessors[1]);
-
- case MemberTypes.NestedType:
- case MemberTypes.TypeInfo:
- return ((Type)accessors[0]).ToReflectionType();
-
- default:
- Assumes.IsTrue(memberType == MemberTypes.Method);
- return ((MethodInfo)accessors[0]).ToReflectionMethod();
- }
- }
-
- public static LazyMemberInfo ToLazyMember(this ReflectionMember reflectionMember)
- {
- Assumes.NotNull(reflectionMember);
-
- if (reflectionMember.ItemType == ReflectionItemType.Property)
- {
- ReflectionProperty reflectionProperty = reflectionMember as ReflectionProperty;
- Assumes.NotNull(reflectionProperty);
-
- MemberInfo[] accessors = new MemberInfo[] { reflectionProperty.UnderlyingGetMethod, reflectionProperty.UnderlyingSetMethod };
- return new LazyMemberInfo(MemberTypes.Property, accessors);
- }
- else
- {
- return new LazyMemberInfo(reflectionMember.UnderlyingMember.MemberType, reflectionMember.UnderlyingMember);
- }
- }
-
- public static LazyMemberInfo ToLazyMember(this MemberInfo member)
- {
- Assumes.NotNull(member);
-
- if (member.MemberType == MemberTypes.Property)
- {
- PropertyInfo property = member as PropertyInfo;
- Assumes.NotNull(property);
-
- MemberInfo[] accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true)};
- return new LazyMemberInfo(MemberTypes.Property, accessors);
- }
- else
- {
- return new LazyMemberInfo(member);
- }
- }
-
- 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;
- }
-
-
- public static ReflectionProperty ToReflectionProperty(this PropertyInfo property)
- {
- Assumes.NotNull(property);
- return CreateReflectionProperty(property.GetGetMethod(true), property.GetSetMethod(true));
- }
-
- public static ReflectionProperty CreateReflectionProperty(MethodInfo getMethod, MethodInfo setMethod)
- {
- Assumes.IsTrue(getMethod != null || setMethod != null);
-
- return new ReflectionProperty(getMethod, setMethod);
- }
-
- public static ReflectionParameter ToReflectionParameter(this ParameterInfo parameter)
- {
- Assumes.NotNull(parameter);
- return new ReflectionParameter(parameter);
- }
-
- public static ReflectionMethod ToReflectionMethod(this MethodInfo method)
- {
- Assumes.NotNull(method);
- return new ReflectionMethod(method);
- }
-
- public static ReflectionField ToReflectionField(this FieldInfo field)
- {
- Assumes.NotNull(field);
- return new ReflectionField(field);
- }
-
- public static ReflectionType ToReflectionType(this Type type)
- {
- Assumes.NotNull(type);
- return new ReflectionType(type);
- }
-
- public static ReflectionWritableMember ToReflectionWritableMember(this MemberInfo member)
- {
- Assumes.NotNull(member);
- if (member.MemberType == MemberTypes.Property)
- {
- return ((PropertyInfo)member).ToReflectionProperty();
- }
-
- return ((FieldInfo)member).ToReflectionField();
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs deleted file mode 100644 index 38879361ce2..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionField : ReflectionWritableMember
- {
- private readonly FieldInfo _field;
-
- public ReflectionField(FieldInfo field)
- {
- Assumes.NotNull(field);
-
- this._field = field;
- }
-
- public FieldInfo UndelyingField
- {
- get { return this._field; }
- }
-
- public override MemberInfo UnderlyingMember
- {
- get { return this.UndelyingField; }
- }
-
- public override bool CanRead
- {
- get { return true; }
- }
-
- public override bool CanWrite
- {
- get { return !this.UndelyingField.IsInitOnly; }
- }
-
- public override bool RequiresInstance
- {
- get { return !this.UndelyingField.IsStatic; }
- }
-
- public override Type ReturnType
- {
- get { return this.UndelyingField.FieldType; }
- }
-
- public override ReflectionItemType ItemType
- {
- get { return ReflectionItemType.Field; }
- }
-
- public override object GetValue(object instance)
- {
- return this.UndelyingField.SafeGetValue(instance);
- }
-
- public override void SetValue(object instance, object value)
- {
- this.UndelyingField.SafeSetValue(instance, value);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs deleted file mode 100644 index 95f61bcecba..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal abstract class ReflectionImportDefinition : ContractBasedImportDefinition, ICompositionElement
- {
- private readonly ICompositionElement _origin;
-
- public ReflectionImportDefinition(
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality,
- bool isRecomposable,
- bool isPrerequisite,
- CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
- : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy)
- {
- this._origin = origin;
- }
-
- string ICompositionElement.DisplayName
- {
- get { return this.GetDisplayName(); }
- }
-
- ICompositionElement ICompositionElement.Origin
- {
- get { return this._origin; }
- }
-
- public override string ToString()
- {
- return this.GetDisplayName();
- }
-
- public abstract ImportingItem ToImportingItem();
-
- protected abstract string GetDisplayName();
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs deleted file mode 100644 index 97420f14bc6..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Reflection;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal abstract class ReflectionItem
- {
- public abstract string Name { get; }
- public abstract string GetDisplayName();
- public abstract Type ReturnType { get; }
- public abstract ReflectionItemType ItemType { get; }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionItemType.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionItemType.cs deleted file mode 100644 index 2607fecaad8..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionItemType.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal enum ReflectionItemType : int
- {
- Parameter = 0,
- Field = 1,
- Property = 2,
- Method = 3,
- Type = 4,
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs deleted file mode 100644 index 9ccbc4d55e9..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal abstract class ReflectionMember : ReflectionItem
- {
- public abstract bool CanRead
- {
- get;
- }
-
- public Type DeclaringType
- {
- get { return this.UnderlyingMember.DeclaringType; }
- }
-
- public override string Name
- {
- get { return this.UnderlyingMember.Name; }
- }
-
- public override string GetDisplayName()
- {
- return this.UnderlyingMember.GetDisplayName();
- }
-
- public abstract bool RequiresInstance
- {
- get;
- }
-
- public abstract MemberInfo UnderlyingMember { get; }
-
- public abstract object GetValue(object instance);
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs deleted file mode 100644 index ac81434fbb6..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Hosting;
-using System.ComponentModel.Composition.Primitives;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionMemberExportDefinition : ExportDefinition, ICompositionElement
- {
- private readonly LazyMemberInfo _member;
- private readonly ExportDefinition _exportDefinition;
- private readonly ICompositionElement _origin;
- private IDictionary<string, object> _metadata;
-
- public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement origin)
- {
- Assumes.NotNull(exportDefinition);
-
- this._member = member;
- this._exportDefinition = exportDefinition;
- this._origin = origin;
- }
-
- public override string ContractName
- {
- get { return this._exportDefinition.ContractName; }
- }
-
- public LazyMemberInfo ExportingLazyMember
- {
- get { return this._member; }
- }
-
- public override IDictionary<string, object> Metadata
- {
- get
- {
- if (this._metadata == null)
- {
- var metadata = this._exportDefinition.Metadata ?? MetadataServices.EmptyMetadata;
- this._metadata = metadata.AsReadOnly();
- }
- return this._metadata;
- }
- }
-
- string ICompositionElement.DisplayName
- {
- get { return this.GetDisplayName(); }
- }
-
- ICompositionElement ICompositionElement.Origin
- {
- get { return this._origin; }
- }
-
- public override string ToString()
- {
- return this.GetDisplayName();
- }
-
- public ExportingMember ToExportingMember()
- {
- return new ExportingMember(this, this.ToReflectionMember());
- }
-
- private ReflectionMember ToReflectionMember()
- {
- return this.ExportingLazyMember.ToReflectionMember();
- }
-
- private string GetDisplayName()
- {
- return string.Format(CultureInfo.CurrentCulture,
- "{0} (ContractName=\"{1}\")", // NOLOC
- this.ToReflectionMember().GetDisplayName(),
- this.ContractName);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs deleted file mode 100644 index af179fb86ef..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-using Microsoft.Internal.Collections;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionMemberImportDefinition : ReflectionImportDefinition
- {
- private LazyMemberInfo _importingLazyMember;
-
- public ReflectionMemberImportDefinition(
- LazyMemberInfo importingLazyMember,
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality,
- bool isRecomposable,
- CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
- : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, false, requiredCreationPolicy, origin)
- {
- Assumes.NotNull(contractName);
-
- this._importingLazyMember = importingLazyMember;
- }
-
- public override ImportingItem ToImportingItem()
- {
- ReflectionWritableMember member = this.ImportingLazyMember.ToReflectionWriteableMember();
- return new ImportingMember(this, member, new ImportType(member.ReturnType, this.Cardinality));
- }
-
- public LazyMemberInfo ImportingLazyMember
- {
- get { return this._importingLazyMember; }
- }
-
- protected override string GetDisplayName()
- {
- return string.Format(
- CultureInfo.CurrentCulture,
- "{0} (ContractName=\"{1}\")", // NOLOC
- this.ImportingLazyMember.ToReflectionMember().GetDisplayName(),
- this.ContractName);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs deleted file mode 100644 index 9dd963ddb09..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.Hosting;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-using System.ComponentModel.Composition.Primitives;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal partial class ReflectionMethod : ReflectionMember
- {
- private readonly MethodInfo _method;
-
- public ReflectionMethod(MethodInfo method)
- {
- Assumes.NotNull(method);
-
- this._method = method;
- }
-
- public MethodInfo UnderlyingMethod
- {
- get { return this._method; }
- }
-
- public override MemberInfo UnderlyingMember
- {
- get { return this.UnderlyingMethod; }
- }
-
- public override bool CanRead
- {
- get { return true; }
- }
-
- public override bool RequiresInstance
- {
- get { return !this.UnderlyingMethod.IsStatic; }
- }
-
- public override Type ReturnType
- {
- get { return this.UnderlyingMethod.ReturnType; }
- }
-
- public override ReflectionItemType ItemType
- {
- get { return ReflectionItemType.Method; }
- }
-
- public override object GetValue(object instance)
- {
- return SafeCreateExportedDelegate(instance, _method);
- }
-#if !SILVERLIGHT
- [System.Security.SecuritySafeCritical]
-#endif
- private static ExportedDelegate SafeCreateExportedDelegate(object instance, MethodInfo method)
- {
- // We demand member access in place of the [SecurityCritical]
- // attribute on ExportDelegate constructor
- ReflectionInvoke.DemandMemberAccessIfNeeded(method);
-
- return new ExportedDelegate(instance, method);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs deleted file mode 100644 index 72cd0f817f3..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs +++ /dev/null @@ -1,444 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Linq;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
-#if !SILVERLIGHT
- [System.Security.SecurityCritical]
-#endif
- public static class ReflectionModelServices
- {
- public static Lazy<Type> GetPartType(ComposablePartDefinition partDefinition)
- {
- Requires.NotNull(partDefinition, "partDefinition");
-
- ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
- if (reflectionPartDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidPartDefinition, partDefinition.GetType()),
- "partDefinition");
- }
-
- return reflectionPartDefinition.GetLazyPartType();
- }
-
- public static bool IsDisposalRequired(ComposablePartDefinition partDefinition)
- {
- Requires.NotNull(partDefinition, "partDefinition");
-
- ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
- if (reflectionPartDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidPartDefinition, partDefinition.GetType()),
- "partDefinition");
- }
-
- return reflectionPartDefinition.IsDisposalRequired;
- }
-
- public static LazyMemberInfo GetExportingMember(ExportDefinition exportDefinition)
- {
- Requires.NotNull(exportDefinition, "exportDefinition");
-
- ReflectionMemberExportDefinition reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition;
- if (reflectionExportDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidExportDefinition, exportDefinition.GetType()),
- "exportDefinition");
- }
-
- return reflectionExportDefinition.ExportingLazyMember;
- }
-
- public static LazyMemberInfo GetImportingMember(ImportDefinition importDefinition)
- {
- Requires.NotNull(importDefinition, "importDefinition");
-
- ReflectionMemberImportDefinition reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition;
- if (reflectionMemberImportDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidMemberImportDefinition, importDefinition.GetType()),
- "importDefinition");
- }
-
- return reflectionMemberImportDefinition.ImportingLazyMember;
- }
-
- public static Lazy<ParameterInfo> GetImportingParameter(ImportDefinition importDefinition)
- {
- Requires.NotNull(importDefinition, "importDefinition");
-
- ReflectionParameterImportDefinition reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition;
- if (reflectionParameterImportDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidParameterImportDefinition, importDefinition.GetType()),
- "importDefinition");
- }
-
- return reflectionParameterImportDefinition.ImportingLazyParameter;
- }
-
- public static bool IsImportingParameter(ImportDefinition importDefinition)
- {
- Requires.NotNull(importDefinition, "importDefinition");
-
- ReflectionImportDefinition reflectionImportDefinition = importDefinition as ReflectionImportDefinition;
- if (reflectionImportDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
- "importDefinition");
- }
-
- return (importDefinition is ReflectionParameterImportDefinition);
- }
-
- internal static bool IsExportFactoryImportDefinition(ImportDefinition importDefinition)
- {
- Requires.NotNull(importDefinition, "importDefinition");
-
- ReflectionImportDefinition reflectionImportDefinition = importDefinition as ReflectionImportDefinition;
- if (reflectionImportDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
- "importDefinition");
- }
-
- return (importDefinition is IPartCreatorImportDefinition);
- }
-
- internal static ContractBasedImportDefinition GetPartCreatorProductImportDefinition(ImportDefinition importDefinition)
- {
- Requires.NotNull(importDefinition, "importDefinition");
-
- IPartCreatorImportDefinition partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition;
- if (partCreatorImportDefinition == null)
- {
- throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
- "importDefinition");
- }
-
- return partCreatorImportDefinition.ProductImportDefinition;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public static ComposablePartDefinition CreatePartDefinition(
- Lazy<Type> partType,
- bool isDisposalRequired,
- Lazy<IEnumerable<ImportDefinition>> imports,
- Lazy<IEnumerable<ExportDefinition>> exports,
- Lazy<IDictionary<string, object>> metadata,
- ICompositionElement origin)
- {
- Requires.NotNull(partType, "partType");
-
- return new ReflectionComposablePartDefinition(
- new ReflectionPartCreationInfo(
- partType,
- isDisposalRequired,
- imports,
- exports,
- metadata,
- origin));
- }
-
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public static ExportDefinition CreateExportDefinition(
- LazyMemberInfo exportingMember,
- string contractName,
- Lazy<IDictionary<string, object>> metadata,
- ICompositionElement origin)
- {
- Requires.NotNullOrEmpty(contractName, "contractName");
- Requires.IsInMembertypeSet(exportingMember.MemberType, "exportingMember", MemberTypes.Field | MemberTypes.Property | MemberTypes.NestedType | MemberTypes.TypeInfo | MemberTypes.Method);
-
- return new ReflectionMemberExportDefinition(
- exportingMember,
- new LazyExportDefinition(contractName, metadata),
- origin);
- }
-
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public static ContractBasedImportDefinition CreateImportDefinition(
- LazyMemberInfo importingMember,
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality,
- bool isRecomposable,
- CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
- {
- return CreateImportDefinition(importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, requiredCreationPolicy, false, origin);
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- internal static ContractBasedImportDefinition CreateImportDefinition(
- LazyMemberInfo importingMember,
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality,
- bool isRecomposable,
- CreationPolicy requiredCreationPolicy,
- bool isExportFactory,
- ICompositionElement origin)
- {
- Requires.NotNullOrEmpty(contractName, "contractName");
- Requires.IsInMembertypeSet(importingMember.MemberType, "importingMember", MemberTypes.Property | MemberTypes.Field);
-
- if (isExportFactory)
- {
- return new PartCreatorMemberImportDefinition(
- importingMember,
- origin,
- new ContractBasedImportDefinition(
- contractName,
- requiredTypeIdentity,
- requiredMetadata,
- cardinality,
- isRecomposable,
- false,
- CreationPolicy.NonShared));
- }
- else
- {
- return new ReflectionMemberImportDefinition(
- importingMember,
- contractName,
- requiredTypeIdentity,
- requiredMetadata,
- cardinality,
- isRecomposable,
- requiredCreationPolicy,
- origin);
- }
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- public static ContractBasedImportDefinition CreateImportDefinition(
- Lazy<ParameterInfo> parameter,
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality,
- CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
- {
- return CreateImportDefinition(parameter, contractName, requiredTypeIdentity, requiredMetadata, cardinality, requiredCreationPolicy, false, origin);
- }
-
- [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
- internal static ContractBasedImportDefinition CreateImportDefinition(
- Lazy<ParameterInfo> parameter,
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
- ImportCardinality cardinality,
- CreationPolicy requiredCreationPolicy,
- bool isExportFactory,
- ICompositionElement origin)
- {
- Requires.NotNull(parameter, "parameter");
- Requires.NotNullOrEmpty(contractName, "contractName");
-
- if (isExportFactory)
- {
- return new PartCreatorParameterImportDefinition(
- parameter,
- origin,
- new ContractBasedImportDefinition(
- contractName,
- requiredTypeIdentity,
- requiredMetadata,
- cardinality,
- false,
- true,
- CreationPolicy.NonShared));
- }
- else
- {
- return new ReflectionParameterImportDefinition(
- parameter,
- contractName,
- requiredTypeIdentity,
- requiredMetadata,
- cardinality,
- requiredCreationPolicy,
- origin);
- }
- }
- }
- internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo
- {
- private readonly Lazy<Type> _partType;
- private readonly Lazy<IEnumerable<ImportDefinition>> _imports;
- private readonly Lazy<IEnumerable<ExportDefinition>> _exports;
- private readonly Lazy<IDictionary<string, object>> _metadata;
- private readonly ICompositionElement _origin;
- private ConstructorInfo _constructor;
- private bool _isDisposalRequired;
-
- public ReflectionPartCreationInfo(
- Lazy<Type> partType,
- bool isDisposalRequired,
- Lazy<IEnumerable<ImportDefinition>> imports,
- Lazy<IEnumerable<ExportDefinition>> exports,
- Lazy<IDictionary<string, object>> metadata,
- ICompositionElement origin)
- {
- Assumes.NotNull(partType);
-
- this._partType = partType;
- this._isDisposalRequired = isDisposalRequired;
- this._imports = imports;
- this._exports = exports;
- this._metadata = metadata;
- this._origin = origin;
- }
-
- public Type GetPartType()
- {
- return this._partType.GetNotNullValue("type");
- }
-
- public Lazy<Type> GetLazyPartType()
- {
- return this._partType;
- }
-
- public ConstructorInfo GetConstructor()
- {
- if (this._constructor == null)
- {
- ConstructorInfo[] constructors = null;
- constructors = this.GetImports()
- .OfType<ReflectionParameterImportDefinition>()
- .Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member)
- .OfType<ConstructorInfo>()
- .Distinct()
- .ToArray();
-
- if (constructors.Length == 1)
- {
- this._constructor = constructors[0];
- }
- else if (constructors.Length == 0)
- {
- this._constructor = this.GetPartType().GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
- }
- }
- return this._constructor;
- }
-
- public bool IsDisposalRequired
- {
- get
- {
- return this._isDisposalRequired;
- }
- }
-
- public IDictionary<string, object> GetMetadata()
- {
- return (this._metadata != null) ? this._metadata.Value : null;
- }
-
- public IEnumerable<ExportDefinition> GetExports()
- {
- if (this._exports == null)
- {
- yield break;
- }
-
- IEnumerable<ExportDefinition> exports = this._exports.Value;
-
- if (exports == null)
- {
- yield break;
- }
-
- foreach (ExportDefinition export in exports)
- {
- ReflectionMemberExportDefinition reflectionExport = export as ReflectionMemberExportDefinition;
- if (reflectionExport == null)
- {
- throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidExportDefinition, export.GetType()));
- }
- yield return reflectionExport;
- }
- }
-
- public IEnumerable<ImportDefinition> GetImports()
- {
- if (this._imports == null)
- {
- yield break;
- }
-
- IEnumerable<ImportDefinition> imports = this._imports.Value;
-
- if (imports == null)
- {
- yield break;
- }
-
- foreach (ImportDefinition import in imports)
- {
- ReflectionImportDefinition reflectionImport = import as ReflectionImportDefinition;
- if (reflectionImport == null)
- {
- throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidMemberImportDefinition, import.GetType()));
- }
- yield return reflectionImport;
- }
- }
-
- public string DisplayName
- {
- get { return this.GetPartType().GetDisplayName(); }
- }
-
- public ICompositionElement Origin
- {
- get { return this._origin; }
- }
- }
-
- internal class LazyExportDefinition : ExportDefinition
- {
- private readonly Lazy<IDictionary<string, object>> _metadata;
-
- public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object>> metadata)
- : base(contractName, (IDictionary<string, object>)null)
- {
- this._metadata = metadata;
- }
-
- public override IDictionary<string, object> Metadata
- {
- get
- {
- return this._metadata.Value;
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs deleted file mode 100644 index 75312471560..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionParameter : ReflectionItem
- {
- private readonly ParameterInfo _parameter;
-
- public ReflectionParameter(ParameterInfo parameter)
- {
- Assumes.NotNull(parameter);
-
- this._parameter = parameter;
- }
-
- public ParameterInfo UnderlyingParameter
- {
- get { return this._parameter; }
- }
-
- public override string Name
- {
- get { return this.UnderlyingParameter.Name; }
- }
-
- public override string GetDisplayName()
- {
- return string.Format(
- CultureInfo.CurrentCulture,
- "{0} (Parameter=\"{1}\")", // NOLOC
- this.UnderlyingParameter.Member.GetDisplayName(),
- this.UnderlyingParameter.Name);
- }
-
- public override Type ReturnType
- {
- get { return this.UnderlyingParameter.ParameterType; }
- }
-
- public override ReflectionItemType ItemType
- {
- get { return ReflectionItemType.Parameter; }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs deleted file mode 100644 index 93e62387413..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Globalization;
-using System.Reflection;
-using Microsoft.Internal;
-using System.ComponentModel.Composition.ReflectionModel;
-using System.Collections.Generic;
-using System.ComponentModel.Composition.Primitives;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionParameterImportDefinition : ReflectionImportDefinition
- {
- private Lazy<ParameterInfo> _importingLazyParameter;
-
- public ReflectionParameterImportDefinition(
- Lazy<ParameterInfo> importingLazyParameter,
- string contractName,
- string requiredTypeIdentity,
- IEnumerable<KeyValuePair<string,Type>> requiredMetadata,
- ImportCardinality cardinality,
- CreationPolicy requiredCreationPolicy,
- ICompositionElement origin)
- : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, origin)
- {
- Assumes.NotNull(importingLazyParameter);
-
- this._importingLazyParameter = importingLazyParameter;
- }
-
- public override ImportingItem ToImportingItem()
- {
- return new ImportingParameter(this, new ImportType(this.ImportingLazyParameter.GetNotNullValue("parameter").ParameterType, this.Cardinality));
- }
-
- public Lazy<ParameterInfo> ImportingLazyParameter
- {
- get { return this._importingLazyParameter; }
- }
-
- protected override string GetDisplayName()
- {
- ParameterInfo parameter = this.ImportingLazyParameter.GetNotNullValue("parameter");
- return string.Format(
- CultureInfo.CurrentCulture,
- "{0} (Parameter=\"{1}\", ContractName=\"{2}\")", // NOLOC
- parameter.Member.GetDisplayName(),
- parameter.Name,
- this.ContractName);
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs deleted file mode 100644 index af62622fa9e..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs +++ /dev/null @@ -1,124 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- // Instead of representing properties as an actual PropertyInfo, we need to
- // represent them as two MethodInfo objects one for each accessor. This is so
- // that cached attribute part can go from a metadata token -> XXXInfo without
- // needing to walk all members of a particular type. Unfortunately, (probably
- // because you never see one of them in an IL stream), Reflection does not allow
- // you to go from a metadata token -> PropertyInfo like it does with types,
- // fields, and methods.
-
- internal class ReflectionProperty : ReflectionWritableMember
- {
- private readonly MethodInfo _getMethod;
- private readonly MethodInfo _setMethod;
-
- public ReflectionProperty(MethodInfo getMethod, MethodInfo setMethod)
- {
- Assumes.IsTrue(getMethod != null || setMethod != null);
-
- this._getMethod = getMethod;
- this._setMethod = setMethod;
- }
-
- public override MemberInfo UnderlyingMember
- {
- get { return this.UnderlyingGetMethod ?? this.UnderlyingSetMethod; }
- }
-
- public override bool CanRead
- {
- get { return this.UnderlyingGetMethod != null; }
- }
-
- public override bool CanWrite
- {
- get { return this.UnderlyingSetMethod != null; }
- }
-
- public MethodInfo UnderlyingGetMethod
- {
- get { return this._getMethod; }
- }
-
- public MethodInfo UnderlyingSetMethod
- {
- get { return this._setMethod; }
- }
-
- public override string Name
- {
- get
- {
- MethodInfo method = this.UnderlyingGetMethod ?? this.UnderlyingSetMethod;
-
- string name = method.Name;
-
- Assumes.IsTrue(name.Length > 4);
-
- // Remove 'get_' or 'set_'
- return name.Substring(4);
- }
- }
-
- public override string GetDisplayName()
- {
- return ReflectionServices.GetDisplayName(this.DeclaringType, this.Name);
- }
-
- public override bool RequiresInstance
- {
- get
- {
- MethodInfo method = this.UnderlyingGetMethod ?? this.UnderlyingSetMethod;
-
- return !method.IsStatic;
- }
- }
-
- public override Type ReturnType
- {
- get
- {
- if (this.UnderlyingGetMethod != null)
- {
- return this.UnderlyingGetMethod.ReturnType;
- }
-
- ParameterInfo[] parameters = this.UnderlyingSetMethod.GetParameters();
-
- Assumes.IsTrue(parameters.Length > 0);
-
- return parameters[parameters.Length - 1].ParameterType;
- }
- }
-
- public override ReflectionItemType ItemType
- {
- get { return ReflectionItemType.Property; }
- }
-
- public override object GetValue(object instance)
- {
- Assumes.NotNull(this._getMethod);
-
- return this.UnderlyingGetMethod.SafeInvoke(instance);
- }
-
- public override void SetValue(object instance, object value)
- {
- Assumes.NotNull(this._setMethod);
-
- this.UnderlyingSetMethod.SafeInvoke(instance, value);
- }
-
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs deleted file mode 100644 index 6d754d516a0..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.ComponentModel.Composition.AttributedModel;
-using System.Reflection;
-using Microsoft.Internal;
-using System.Threading;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal class ReflectionType : ReflectionMember
- {
- private Type _type;
-
- public ReflectionType(Type type)
- {
- Assumes.NotNull(type);
-
- this._type = type;
- }
-
- public override MemberInfo UnderlyingMember
- {
- get { return this._type; }
- }
-
- public Type UnderlyingType
- {
- get { return this._type; }
- }
-
- public override bool CanRead
- {
- get { return true; }
- }
-
- public override bool RequiresInstance
- {
- get { return true; }
- }
-
- public override Type ReturnType
- {
- get { return this._type; }
- }
-
- public override ReflectionItemType ItemType
- {
- get { return ReflectionItemType.Type; }
- }
-
- public override object GetValue(object instance)
- {
- return instance;
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs deleted file mode 100644 index 7640b3b1749..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs +++ /dev/null @@ -1,19 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Reflection;
-using Microsoft.Internal;
-
-namespace System.ComponentModel.Composition.ReflectionModel
-{
- internal abstract class ReflectionWritableMember : ReflectionMember
- {
- public abstract bool CanWrite
- {
- get;
- }
-
- public abstract void SetValue(object instance, object value);
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/Lazy.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/Lazy.cs deleted file mode 100644 index 6d3b11acfb3..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/Lazy.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#if !CLR40
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using Microsoft.Internal;
-
-namespace System
-{
- public class Lazy<T>
- {
- private T _value = default(T);
- private volatile bool _isValueCreated = false;
- private Func<T> _valueFactory = null;
- private object _lock;
-
- public Lazy()
- : this(() => Activator.CreateInstance<T>())
- {
- }
-
- public Lazy(bool isThreadSafe)
- : this(() => Activator.CreateInstance<T>(), isThreadSafe)
- {
- }
-
- public Lazy(Func<T> valueFactory):
- this(valueFactory, true)
- {
- }
-
- public Lazy(Func<T> valueFactory, bool isThreadSafe)
- {
- Requires.NotNull(valueFactory, "valueFactory");
- if(isThreadSafe)
- {
- this._lock = new object();
- }
-
- this._valueFactory = valueFactory;
- }
-
-
- public T Value
- {
- get
- {
- if (!this._isValueCreated)
- {
- if(this._lock != null)
- {
- Monitor.Enter(this._lock);
- }
-
- try
- {
- T value = this._valueFactory.Invoke();
- this._valueFactory = null;
- Thread.MemoryBarrier();
- this._value = value;
- this._isValueCreated = true;
- }
- finally
- {
- if(this._lock != null)
- {
- Monitor.Exit(this._lock);
- }
- }
- }
- return this._value;
- }
- }
- }
-}
-#endif
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/LazyOfTTMetadata.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/LazyOfTTMetadata.cs deleted file mode 100644 index 287babe3abd..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/LazyOfTTMetadata.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace System
-{
-#if CLR40 && !SILVERLIGHT
- [Serializable]
-#endif
- public class Lazy<T, TMetadata> : Lazy<T>
- {
- private TMetadata _metadata;
-
- public Lazy(Func<T> valueFactory, TMetadata metadata) :
- base(valueFactory)
- {
- this._metadata = metadata;
- }
-
- public Lazy(TMetadata metadata) :
- base()
- {
- this._metadata = metadata;
- }
-
-
- public Lazy(TMetadata metadata, bool isThreadSafe) :
- base(isThreadSafe)
- {
- this._metadata = metadata;
- }
-
- public Lazy(Func<T> valueFactory, TMetadata metadata, bool isThreadSafe) :
- base(valueFactory, isThreadSafe)
- {
- this._metadata = metadata;
- }
-
- public TMetadata Metadata
- {
- get
- {
- return this._metadata;
- }
- }
- }
-}
diff --git a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/Tuple.cs b/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/Tuple.cs deleted file mode 100644 index 03a48286d3c..00000000000 --- a/mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/Tuple.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -----------------------------------------------------------------------
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// -----------------------------------------------------------------------
-#if !CLR40
-using System;
-
-namespace System
-{
- // This is a very minimalistic implementation of Tuple'2 that allows us
- // to compile and work on versions of .Net eariler then 4.0.
- public struct Tuple<TItem1, TItem2>
- {
- public Tuple(TItem1 item1, TItem2 item2)
- {
- this = new Tuple<TItem1, TItem2>();
- this.Item1 = item1;
- this.Item2 = item2;
- }
-
- public TItem1 Item1 { get; private set; }
- public TItem2 Item2 { get; private set; }
-
- public override bool Equals(object obj)
- {
- if (obj is Tuple<TItem1, TItem2>)
- {
- Tuple<TItem1, TItem2> that = (Tuple<TItem1, TItem2>)obj;
- return object.Equals(this.Item1, that.Item1) && object.Equals(this.Item2, that.Item2);
- }
- else
- {
- return false;
- }
- }
-
- public override int GetHashCode()
- {
- return ((this.Item1 != null) ? this.Item1.GetHashCode() : 0) ^ ((this.Item2 != null) ? this.Item2.GetHashCode() : 0);
- }
-
- public static bool operator ==(Tuple<TItem1, TItem2> left, Tuple<TItem1, TItem2> right)
- {
- return left.Equals(right);
- }
-
- public static bool operator !=(Tuple<TItem1, TItem2> left, Tuple<TItem1, TItem2> right)
- {
- return !left.Equals(right);
- }
- }
-}
-#endif
\ No newline at end of file |