Imported Upstream version 5.0.0.42

Former-commit-id: fd56571888259555122d8a0f58c68838229cea2b
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2017-04-10 11:41:01 +00:00
parent 1190d13a04
commit 6bdd276d05
19939 changed files with 3099680 additions and 93811 deletions

View File

@@ -0,0 +1,8 @@
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\dir.props" />
<PropertyGroup>
<PackageVersion>1.1.0</PackageVersion>
<AssemblyVersion>1.0.32.0</AssemblyVersion>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<ItemGroup>
<Project Include="System.Composition.Convention.pkgproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.traversal.targets))\dir.traversal.targets" />
</Project>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<ItemGroup>
<ProjectReference Include="..\src\System.Composition.Convention.builds">
<SupportedFramework>net45;netcore45;netcoreapp1.0;wp8;wpa81;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<BuildConfigurations>
netstandard1.0;
netstandard;
</BuildConfigurations>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,121 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Internal;
using System.Reflection;
namespace Microsoft.Composition.Diagnostics
{
internal static class CompositionTrace
{
internal static void Registration_ConstructorConventionOverridden(Type type)
{
Assumes.NotNull(type);
if (CompositionTraceSource.CanWriteInformation)
{
CompositionTraceSource.WriteInformation(CompositionTraceId.Registration_ConstructorConventionOverridden,
Strings.Registration_ConstructorConventionOverridden,
type.FullName);
}
}
internal static void Registration_TypeExportConventionOverridden(Type type)
{
Assumes.NotNull(type);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_TypeExportConventionOverridden,
Strings.Registration_TypeExportConventionOverridden,
type.FullName);
}
}
internal static void Registration_MemberExportConventionOverridden(Type type, MemberInfo member)
{
Assumes.NotNull(type, member);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden,
Strings.Registration_MemberExportConventionOverridden,
member.Name, type.FullName);
}
}
internal static void Registration_MemberImportConventionOverridden(Type type, MemberInfo member)
{
Assumes.NotNull(type, member);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden,
Strings.Registration_MemberImportConventionOverridden,
member.Name, type.FullName);
}
}
internal static void Registration_OnSatisfiedImportNotificationOverridden(Type type, MemberInfo member)
{
Assumes.NotNull(type, member);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden,
Strings.Registration_OnSatisfiedImportNotificationOverridden,
member.Name, type.FullName);
}
}
internal static void Registration_PartCreationConventionOverridden(Type type)
{
Assumes.NotNull(type);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden,
Strings.Registration_PartCreationConventionOverridden,
type.FullName);
}
}
internal static void Registration_MemberImportConventionMatchedTwice(Type type, MemberInfo member)
{
Assumes.NotNull(type, member);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice,
Strings.Registration_MemberImportConventionMatchedTwice,
member.Name, type.FullName);
}
}
internal static void Registration_PartMetadataConventionOverridden(Type type)
{
Assumes.NotNull(type);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden,
Strings.Registration_PartMetadataConventionOverridden,
type.FullName);
}
}
internal static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter, ConstructorInfo constructor)
{
Assumes.NotNull(parameter, constructor);
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_ParameterImportConventionOverridden,
Strings.Registration_ParameterImportConventionOverridden,
parameter.Name, constructor.Name);
}
}
}
}

View File

@@ -0,0 +1,26 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.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
{
// Registration
Registration_ConstructorConventionOverridden = 101,
Registration_TypeExportConventionOverridden = 102,
Registration_MemberExportConventionOverridden = 103,
Registration_MemberImportConventionOverridden = 104,
Registration_PartCreationConventionOverridden = 105,
Registration_MemberImportConventionMatchedTwice = 106,
Registration_PartMetadataConventionOverridden = 107,
Registration_ParameterImportConventionOverridden = 108,
Registration_OnSatisfiedImportNotificationOverridden = 109,
}
}

View File

@@ -0,0 +1,59 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Internal;
namespace Microsoft.Composition.Diagnostics
{
internal static class CompositionTraceSource
{
#if FEATURE_TRACING
private static readonly TraceSourceTraceWriter s_source = new TraceSourceTraceWriter();
#else
private static readonly DebuggerTraceWriter s_source = new DebuggerTraceWriter();
#endif
public static bool CanWriteInformation
{
get { return s_source.CanWriteInformation; }
}
public static bool CanWriteWarning
{
get { return s_source.CanWriteWarning; }
}
public static bool CanWriteError
{
get { return s_source.CanWriteError; }
}
public static void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments)
{
EnsureEnabled(CanWriteInformation);
s_source.WriteInformation(traceId, format, arguments);
}
public static void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments)
{
EnsureEnabled(CanWriteWarning);
s_source.WriteWarning(traceId, format, arguments);
}
public static void WriteError(CompositionTraceId traceId, string format, params object[] arguments)
{
EnsureEnabled(CanWriteError);
s_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.");
}
}
}

View File

@@ -0,0 +1,89 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if !FEATURE_TRACING
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Microsoft.Composition.Diagnostics
{
internal sealed class DebuggerTraceWriter : TraceWriter
{
private static readonly string s_sourceName = "System.Composition";
public override bool CanWriteInformation
{
get { return false; }
}
public override bool CanWriteWarning
{
get { return false; /* Debugger.IsLogging(); */ }
}
public override bool CanWriteError
{
get { return false; /* 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 (true /* !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} : ",
s_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 //!FEATURE_TRACING

View File

@@ -0,0 +1,54 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if FEATURE_TRACING
using System;
using System.Diagnostics;
using Microsoft.Internal;
namespace Microsoft.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("Microsoft.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 //FEATURE_TRACING

View File

@@ -0,0 +1,24 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.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);
}
}

View File

@@ -0,0 +1,77 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Microsoft.Internal
{
internal static class AttributeServices
{
// MemberInfo Attribute helpers
public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo) where T : System.Attribute
{
return memberInfo.GetCustomAttributes<T>(false);
}
public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute
{
return memberInfo.GetCustomAttributes<T>(inherit);
}
public static T GetFirstAttribute<T>(this MemberInfo memberInfo) where T : System.Attribute
{
return GetAttributes<T>(memberInfo).FirstOrDefault();
}
public static T GetFirstAttribute<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute
{
return GetAttributes<T>(memberInfo, inherit).FirstOrDefault();
}
public static bool IsAttributeDefined<T>(this MemberInfo memberInfo) where T : System.Attribute
{
return memberInfo.IsDefined(typeof(T), false);
}
public static bool IsAttributeDefined<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute
{
return memberInfo.IsDefined(typeof(T), inherit);
}
// ParameterInfo Attribute helpers
public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo) where T : System.Attribute
{
return parameterInfo.GetCustomAttributes<T>(false);
}
public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute
{
return parameterInfo.GetCustomAttributes<T>(inherit);
}
public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo) where T : System.Attribute
{
return GetAttributes<T>(parameterInfo).FirstOrDefault();
}
public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute
{
return GetAttributes<T>(parameterInfo, inherit).FirstOrDefault();
}
public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo) where T : System.Attribute
{
return parameterInfo.IsDefined(typeof(T), false);
}
public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute
{
return parameterInfo.IsDefined(typeof(T), inherit);
}
}
}

View File

@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Microsoft.Internal
{
internal static class ReflectionServices
{
public static bool IsMemberInfoForType(this MemberInfo memberInfo)
{
return memberInfo is TypeInfo;
}
public static bool IsMemberInfoForProperty(this MemberInfo memberInfo)
{
return memberInfo is PropertyInfo;
}
public static bool IsMemberInfoForConstructor(this MemberInfo memberInfo)
{
return memberInfo is ConstructorInfo;
}
public static bool IsMemberInfoForMethod(this MemberInfo memberInfo)
{
return memberInfo is MethodInfo;
}
}
}

View File

@@ -0,0 +1,203 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.16815
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Internal {
using System;
using System.Reflection;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Composition.Convention.Strings", typeof(Strings).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The value of argument &apos;{0}&apos; is not supported. The expression must use operator new..
/// </summary>
internal static string Argument_ExpressionMustBeNew {
get {
return ResourceManager.GetString("Argument_ExpressionMustBeNew", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value of argument &apos;{0}&apos; is not supported. The expression must be a property member expression..
/// </summary>
internal static string Argument_ExpressionMustBePropertyMember {
get {
return ResourceManager.GetString("Argument_ExpressionMustBePropertyMember", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value of argument &apos;{0}&apos; is not supported. The expression must be a void Method() member expression.
/// </summary>
internal static string Argument_ExpressionMustBeVoidMethodWithNoArguments
{
get
{
return ResourceManager.GetString("Argument_ExpressionMustBeVoidMethodWithNoArguments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; cannot be an empty string (&quot;&quot;)..
/// </summary>
internal static string ArgumentException_EmptyString {
get {
return ResourceManager.GetString("ArgumentException_EmptyString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value of argument &apos;{0}&apos; ({1}) is not supported. Allowed values are : &apos;{2}&apos;..
/// </summary>
internal static string ArgumentOutOfRange_InvalidEnumInSet {
get {
return ResourceManager.GetString("ArgumentOutOfRange_InvalidEnumInSet", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Internal error occurred. Additional information: &apos;{0}&apos;..
/// </summary>
internal static string InternalExceptionMessage {
get {
return ResourceManager.GetString("InternalExceptionMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A constructor selection convention that would apply to Type &apos;{0}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_ConstructorConventionOverridden {
get {
return ResourceManager.GetString("Registration_ConstructorConventionOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An Export specification convention that would apply to Member &apos;{0}&apos; of type &apos;{1}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_MemberExportConventionOverridden {
get {
return ResourceManager.GetString("Registration_MemberExportConventionOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only one import specification convention can apply to a single Member. More than one convention specification applies to this Member &apos;{1}&apos; of Type &apos;{0}&apos;..
/// </summary>
internal static string Registration_MemberImportConventionMatchedTwice {
get {
return ResourceManager.GetString("Registration_MemberImportConventionMatchedTwice", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An Import specification convention that would apply to Member &apos;{0}&apos; of type &apos;{1}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_MemberImportConventionOverridden {
get {
return ResourceManager.GetString("Registration_MemberImportConventionOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A OnSatisfiedImport specification convention that would apply to Type &apos;{0}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_OnSatisfiedImportNotificationOverridden {
get
{
return ResourceManager.GetString("Registration_OnSatisfiedImportNotificationOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A ParameterImport specification convention that would apply to Parameter &apos;{0}&apos; of Constructor &apos;{1}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_ParameterImportConventionOverridden {
get {
return ResourceManager.GetString("Registration_ParameterImportConventionOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A PartCreationPolicy specification convention that would apply to Type &apos;{0}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_PartCreationConventionOverridden {
get {
return ResourceManager.GetString("Registration_PartCreationConventionOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A PartMetadata specification convention that would apply to Type &apos;{0}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_PartMetadataConventionOverridden {
get {
return ResourceManager.GetString("Registration_PartMetadataConventionOverridden", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An Export specification convention that would apply to type &apos;{0}&apos; has been overridden by attributes applied in the source file or by a prior convention..
/// </summary>
internal static string Registration_TypeExportConventionOverridden {
get {
return ResourceManager.GetString("Registration_TypeExportConventionOverridden", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,159 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ArgumentOutOfRange_InvalidEnumInSet" xml:space="preserve">
<value>The value of argument '{0}' ({1}) is not supported. Allowed values are : '{2}'.</value>
</data>
<data name="Argument_ExpressionMustBeNew" xml:space="preserve">
<value>The value of argument '{0}' is not supported. The expression must use operator new.</value>
</data>
<data name="Argument_ExpressionMustBePropertyMember" xml:space="preserve">
<value>The value of argument '{0}' is not supported. The expression must be a property member expression.</value>
</data>
<data name="Registration_ConstructorConventionOverridden" xml:space="preserve">
<value>A constructor selection convention that would apply to Type '{0}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Registration_TypeExportConventionOverridden" xml:space="preserve">
<value>An Export specification convention that would apply to type '{0}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Registration_MemberExportConventionOverridden" xml:space="preserve">
<value>An Export specification convention that would apply to Member '{0}' of type '{1}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Registration_MemberImportConventionOverridden" xml:space="preserve">
<value>An Import specification convention that would apply to Member '{0}' of type '{1}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Registration_MemberImportConventionMatchedTwice" xml:space="preserve">
<value>Only one import specification convention can apply to a single Member. More than one convention specification applies to this Member '{0}' of Type '{1}'.</value>
</data>
<data name="Registration_ParameterImportConventionOverridden" xml:space="preserve">
<value>A ParameterImport specification convention that would apply to Parameter '{0}' of Constructor '{1}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Registration_PartCreationConventionOverridden" xml:space="preserve">
<value>A PartCreationPolicy specification convention that would apply to Type '{0}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Registration_PartMetadataConventionOverridden" xml:space="preserve">
<value>A PartMetadata specification convention that would apply to Type '{0}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
<data name="Argument_ExpressionMustBeVoidMethodWithNoArguments" xml:space="preserve">
<value>The value of argument '{0}' is not supported. The expression must be a void Method() member expression.</value>
</data>
<data name="Registration_OnSatisfiedImportNotificationOverridden" xml:space="preserve">
<value>A OnSatisfiedImports specification convention that would apply to Type '{0}' has been overridden by attributes applied in the source file or by a prior convention.</value>
</data>
</root>

View File

@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{E6592FAD-10B5-4B56-9287-D72DD136992F}</ProjectGuid>
<AppDesignerFolder>Properties</AppDesignerFolder>
<AssemblyName>System.Composition.Convention</AssemblyName>
<PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard1.0'">netstandard1.0;portable-net45+win8+wp8+wpa81</PackageTargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.0-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.0-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="$(CommonPath)\Microsoft\Internal\Assumes.cs">
<Link>Microsoft\Internal\Assumes.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Microsoft\Internal\Assumes.InternalErrorException.cs">
<Link>Microsoft\Internal\Assumes.InternalErrorException.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Microsoft\Internal\CommonStrings.Designer.cs">
<Link>Microsoft\Internal\CommonStrings.Designer.cs</Link>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>CommonStrings.resx</DependentUpon>
</Compile>
<Compile Include="$(CommonPath)\Microsoft\Internal\EmptyArray.cs">
<Link>Microsoft\Internal\EmptyArray.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Microsoft\Internal\Requires.cs">
<Link>Microsoft\Internal\Requires.cs</Link>
</Compile>
<Compile Include="Microsoft\Composition\Diagnostics\CompositionTrace.cs" />
<Compile Include="Microsoft\Composition\Diagnostics\CompositionTraceId.cs" />
<Compile Include="Microsoft\Composition\Diagnostics\CompositionTraceSource.cs" />
<Compile Include="Microsoft\Composition\Diagnostics\DebuggerTraceWriter.cs" />
<Compile Include="Microsoft\Composition\Diagnostics\TraceSourceTraceWriter.cs" />
<Compile Include="Microsoft\Composition\Diagnostics\TraceWriter.cs" />
<Compile Include="Microsoft\Internal\AttributeServices.cs" />
<Compile Include="Microsoft\Internal\ReflectionServices.cs" />
<Compile Include="Strings.Designer.cs" />
<Compile Include="System\Composition\Convention\ConventionBuilder.cs" />
<Compile Include="System\Composition\Convention\ExportConventionBuilder.cs" />
<Compile Include="System\Composition\Convention\ImportConventionBuilder.cs" />
<Compile Include="System\Composition\Convention\ParameterImportConventionBuilder.cs" />
<Compile Include="System\Composition\Convention\PartConventionBuilder.cs" />
<Compile Include="System\Composition\Convention\PartConventionBuilderOfT.cs" />
<Compile Include="System\Composition\ExceptionBuilder.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="$(CommonPath)\Microsoft\Internal\CommonStrings.resx">
<Link>Microsoft\Internal\CommonStrings.resx</Link>
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>CommonStrings.Designer.cs</LastGenOutput>
<CustomToolNamespace>Microsoft.Internal</CustomToolNamespace>
</EmbeddedResource>
<EmbeddedResource Include="Strings.resx" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\System.Composition.AttributedModel\src\System.Composition.AttributedModel.csproj">
<Project>{c6257381-c624-494a-a9d9-5586e60856ea}</Project>
<Name>System.Composition.AttributedModel</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netstandard1.0'">
<Reference Include="System.Collections" />
<Reference Include="System.Diagnostics.Contracts" />
<Reference Include="System.Diagnostics.Debug" />
<Reference Include="System.Diagnostics.Tools" />
<Reference Include="System.Globalization" />
<Reference Include="System.Linq" />
<Reference Include="System.Linq.Expressions" />
<Reference Include="System.Reflection" />
<Reference Include="System.Reflection.Extensions" />
<Reference Include="System.Resources.ResourceManager" />
<Reference Include="System.Runtime" />
<Reference Include="System.Threading" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>

View File

@@ -0,0 +1,381 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Internal;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace System.Composition.Convention
{
/// <summary>
/// Entry point for defining rules that configure plain-old-CLR-objects as MEF parts.
/// </summary>
public class ConventionBuilder : AttributedModelProvider
{
private static readonly List<object> s_emptyList = new List<object>();
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
private readonly List<PartConventionBuilder> _conventions = new List<PartConventionBuilder>();
private readonly Dictionary<MemberInfo, List<Attribute>> _memberInfos = new Dictionary<MemberInfo, List<Attribute>>();
private readonly Dictionary<ParameterInfo, List<Attribute>> _parameters = new Dictionary<ParameterInfo, List<Attribute>>();
/// <summary>
/// Construct a new <see cref="ConventionBuilder"/>.
/// </summary>
public ConventionBuilder()
{
}
/// <summary>
/// Define a rule that will apply to all types that
/// derive from (or implement) the specified type.
/// </summary>
/// <typeparam name="T">The type from which matching types derive.</typeparam>
/// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns>
public PartConventionBuilder<T> ForTypesDerivedFrom<T>()
{
var partBuilder = new PartConventionBuilder<T>((t) => IsDescendentOf(t, typeof(T)));
_conventions.Add(partBuilder);
return partBuilder;
}
/// <summary>
/// Define a rule that will apply to all types that
/// derive from (or implement) the specified type.
/// </summary>
/// <param name="type">The type from which matching types derive.</param>
/// <returns>A <see cref="PartConventionBuilder"/> that must be used to specify the rule.</returns>
public PartConventionBuilder ForTypesDerivedFrom(Type type)
{
Requires.NotNull(type, nameof(type));
var partBuilder = new PartConventionBuilder((t) => IsDescendentOf(t, type));
_conventions.Add(partBuilder);
return partBuilder;
}
/// <summary>
/// Define a rule that will apply to the types <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to which the rule applies.</typeparam>
/// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns>
public PartConventionBuilder<T> ForType<T>()
{
var partBuilder = new PartConventionBuilder<T>((t) => t == typeof(T));
_conventions.Add(partBuilder);
return partBuilder;
}
/// <summary>
/// Define a rule that will apply to the types <paramref name="type"/>.
/// </summary>
/// <param name="type">The type to which the rule applies.</param>
/// <returns>A <see cref="PartConventionBuilder"/> that must be used to specify the rule.</returns>
public PartConventionBuilder ForType(Type type)
{
Requires.NotNull(type, nameof(type));
var partBuilder = new PartConventionBuilder((t) => t == type);
_conventions.Add(partBuilder);
return partBuilder;
}
/// <summary>
/// Define a rule that will apply to types assignable to <typeparamref name="T"/> that
/// match the supplied predicate.
/// </summary>
/// <param name="typeFilter">A predicate that selects matching types.</param>
/// <typeparam name="T">The type to which the rule applies.</typeparam>
/// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns>
public PartConventionBuilder<T> ForTypesMatching<T>(Predicate<Type> typeFilter)
{
Requires.NotNull(typeFilter, nameof(typeFilter));
var partBuilder = new PartConventionBuilder<T>(typeFilter);
_conventions.Add(partBuilder);
return partBuilder;
}
/// <summary>
/// Define a rule that will apply to types that
/// match the supplied predicate.
/// </summary>
/// <param name="typeFilter">A predicate that selects matching types.</param>
/// <returns>A <see cref="PartConventionBuilder{T}"/> that must be used to specify the rule.</returns>
public PartConventionBuilder ForTypesMatching(Predicate<Type> typeFilter)
{
Requires.NotNull(typeFilter, nameof(typeFilter));
var partBuilder = new PartConventionBuilder(typeFilter);
_conventions.Add(partBuilder);
return partBuilder;
}
private IEnumerable<Tuple<object, List<Attribute>>> EvaluateThisTypeInfoAgainstTheConvention(TypeInfo typeInfo)
{
List<Tuple<object, List<Attribute>>> results = new List<Tuple<object, List<Attribute>>>();
List<Attribute> attributes = new List<Attribute>();
var configuredMembers = new List<Tuple<object, List<Attribute>>>();
bool specifiedConstructor = false;
bool matchedConvention = false;
var type = typeInfo.AsType();
foreach (var builder in _conventions.Where(c => c.SelectType(type)))
{
attributes.AddRange(builder.BuildTypeAttributes(type));
specifiedConstructor |= builder.BuildConstructorAttributes(type, ref configuredMembers);
builder.BuildPropertyAttributes(type, ref configuredMembers);
builder.BuildOnImportsSatisfiedNotification(type, ref configuredMembers);
matchedConvention = true;
}
if (matchedConvention && !specifiedConstructor)
{
// DefaultConstructor
PartConventionBuilder.BuildDefaultConstructorAttributes(type, ref configuredMembers);
}
configuredMembers.Add(Tuple.Create((object)type.GetTypeInfo(), attributes));
return configuredMembers;
}
/// <summary>
/// Provide the list of attributes applied to the specified member.
/// </summary>
/// <param name="reflectedType">The reflectedType the type used to retrieve the memberInfo.</param>
/// <param name="member">The member to supply attributes for.</param>
/// <returns>The list of applied attributes.</returns>
public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member)
{
Requires.NotNull(member, nameof(member));
// Now edit the attributes returned from the base type
List<Attribute> cachedAttributes = null;
var typeInfo = member as TypeInfo;
if (typeInfo != null)
{
var memberInfo = typeInfo as MemberInfo;
_lock.EnterReadLock();
try
{
_memberInfos.TryGetValue(memberInfo, out cachedAttributes);
}
finally
{
_lock.ExitReadLock();
}
if (cachedAttributes == null)
{
_lock.EnterWriteLock();
try
{
//Double check locking another thread may have inserted one while we were away.
if (!_memberInfos.TryGetValue(memberInfo, out cachedAttributes))
{
List<Attribute> attributeList;
foreach (var element in EvaluateThisTypeInfoAgainstTheConvention(typeInfo))
{
attributeList = element.Item2;
if (attributeList != null)
{
var mi = element.Item1 as MemberInfo;
if (mi != null)
{
List<Attribute> memberAttributes;
if (mi != null && (mi.IsMemberInfoForConstructor() || mi.IsMemberInfoForType() || mi.IsMemberInfoForProperty() || mi.IsMemberInfoForMethod()))
{
if (!_memberInfos.TryGetValue(mi, out memberAttributes))
{
_memberInfos.Add(mi, element.Item2);
}
}
}
else
{
var pi = element.Item1 as ParameterInfo;
Assumes.NotNull(pi);
List<Attribute> parameterAttributes;
// Item contains as Constructor parameter to configure
if (!_parameters.TryGetValue(pi, out parameterAttributes))
{
_parameters.Add(pi, element.Item2);
}
}
}
}
}
// We will have updated all of the MemberInfos by now so lets reload cachedAttributes with the current store
_memberInfos.TryGetValue(memberInfo, out cachedAttributes);
}
finally
{
_lock.ExitWriteLock();
}
}
}
else if (member.IsMemberInfoForProperty() || member.IsMemberInfoForConstructor() || member.IsMemberInfoForMethod())
{
cachedAttributes = ReadMemberCustomAttributes(reflectedType, member);
}
IEnumerable<Attribute> appliedAttributes;
if (!(member is TypeInfo) && member.DeclaringType != reflectedType)
appliedAttributes = Enumerable.Empty<Attribute>();
else
appliedAttributes = member.GetCustomAttributes<Attribute>(false);
return cachedAttributes == null ? appliedAttributes : appliedAttributes.Concat(cachedAttributes);
}
private List<Attribute> ReadMemberCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member)
{
List<Attribute> cachedAttributes = null;
bool getMemberAttributes = false;
// Now edit the attributes returned from the base type
_lock.EnterReadLock();
try
{
if (!_memberInfos.TryGetValue(member, out cachedAttributes))
{
// If there is nothing for this member Cache any attributes for the DeclaringType
if (reflectedType != null
&& !_memberInfos.TryGetValue(member.DeclaringType.GetTypeInfo() as MemberInfo, out cachedAttributes))
{
// If there is nothing for this parameter look to see if the declaring Member has been cached yet?
// need to do it outside of the lock, so set the flag we'll check it in a bit
getMemberAttributes = true;
}
cachedAttributes = null;
}
}
finally
{
_lock.ExitReadLock();
}
if (getMemberAttributes)
{
GetCustomAttributes(null, reflectedType.GetTypeInfo() as MemberInfo);
// We should have run the rules for the enclosing parameter so we can again
_lock.EnterReadLock();
try
{
_memberInfos.TryGetValue(member, out cachedAttributes);
}
finally
{
_lock.ExitReadLock();
}
}
return cachedAttributes;
}
/// <summary>
/// Provide the list of attributes applied to the specified parameter.
/// </summary>
/// <param name="reflectedType">The reflectedType the type used to retrieve the parameterInfo.</param>
/// <param name="parameter">The parameter to supply attributes for.</param>
/// <returns>The list of applied attributes.</returns>
public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter)
{
Requires.NotNull(parameter, nameof(parameter));
var attributes = parameter.GetCustomAttributes<Attribute>(false);
List<Attribute> cachedAttributes = ReadParameterCustomAttributes(reflectedType, parameter);
return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes);
}
private List<Attribute> ReadParameterCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter)
{
List<Attribute> cachedAttributes = null;
bool getMemberAttributes = false;
// Now edit the attributes returned from the base type
_lock.EnterReadLock();
try
{
if (!_parameters.TryGetValue(parameter, out cachedAttributes))
{
// If there is nothing for this parameter Cache any attributes for the DeclaringType
if (reflectedType != null
&& !_memberInfos.TryGetValue(reflectedType.GetTypeInfo() as MemberInfo, out cachedAttributes))
{
// If there is nothing for this parameter look to see if the declaring Member has been cached yet?
// need to do it outside of the lock, so set the flag we'll check it in a bit
getMemberAttributes = true;
}
cachedAttributes = null;
}
}
finally
{
_lock.ExitReadLock();
}
if (getMemberAttributes)
{
GetCustomAttributes(null, reflectedType.GetTypeInfo() as MemberInfo);
// We should have run the rules for the enclosing parameter so we can again
_lock.EnterReadLock();
try
{
_parameters.TryGetValue(parameter, out cachedAttributes);
}
finally
{
_lock.ExitReadLock();
}
}
return cachedAttributes;
}
private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseType)
{
if (derivedType.BaseType == null)
return false;
if (derivedType.BaseType == baseType.AsType())
return true;
foreach (var iface in derivedType.ImplementedInterfaces)
{
if (iface.IsConstructedGenericType &&
iface.GetGenericTypeDefinition() == baseType.AsType())
return true;
}
return IsGenericDescendentOf(derivedType.BaseType.GetTypeInfo(), baseType);
}
private static bool IsDescendentOf(Type type, Type baseType)
{
if (type == baseType || type == typeof(object) || type == null)
{
return false;
}
var ti = type.GetTypeInfo();
var bti = baseType.GetTypeInfo();
// The baseType can be an open generic, in that case this ensures
// that the derivedType is checked against it
if (ti.IsGenericTypeDefinition || bti.IsGenericTypeDefinition)
{
return IsGenericDescendentOf(ti, bti);
}
return bti.IsAssignableFrom(ti);
}
}
}

View File

@@ -0,0 +1,141 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Internal;
namespace System.Composition.Convention
{
/// <summary>
/// Configures an export associated with a part.
/// </summary>
public sealed class ExportConventionBuilder
{
private string _contractName;
private Type _contractType;
private List<Tuple<string, object>> _metadataItems;
private List<Tuple<string, Func<Type, object>>> _metadataItemFuncs;
private Func<Type, string> _getContractNameFromPartType;
internal ExportConventionBuilder() { }
/// <summary>
/// Specify the contract type for the export.
/// </summary>
/// <typeparam name="T">The contract type.</typeparam>
/// <returns>An export builder allowing further configuration.</returns>
public ExportConventionBuilder AsContractType<T>()
{
return AsContractType(typeof(T));
}
/// <summary>
/// Specify the contract type for the export.
/// </summary>
/// <param name="type">The contract type.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ExportConventionBuilder AsContractType(Type type)
{
Requires.NotNull(type, nameof(type));
_contractType = type;
return this;
}
/// <summary>
/// Specify the contract name for the export.
/// </summary>
/// <param name="contractName">The contract name.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ExportConventionBuilder AsContractName(string contractName)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
_contractName = contractName;
return this;
}
/// <summary>
/// Specify the contract name for the export.
/// </summary>
/// <param name="getContractNameFromPartType">A Func to retrieve the contract name from the part typeThe contract name.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ExportConventionBuilder AsContractName(Func<Type, string> getContractNameFromPartType)
{
Requires.NotNull(getContractNameFromPartType, nameof(getContractNameFromPartType));
_getContractNameFromPartType = getContractNameFromPartType;
return this;
}
/// <summary>
/// Add export metadata to the export.
/// </summary>
/// <param name="name">The name of the metadata item.</param>
/// <param name="value">The value of the metadata item.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ExportConventionBuilder AddMetadata(string name, object value)
{
Requires.NotNullOrEmpty(name, nameof(name));
if (_metadataItems == null)
{
_metadataItems = new List<Tuple<string, object>>();
}
_metadataItems.Add(Tuple.Create(name, value));
return this;
}
/// <summary>
/// Add export metadata to the export.
/// </summary>
/// <param name="name">The name of the metadata item.</param>
/// <param name="getValueFromPartType">A function that calculates the metadata value based on the type.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ExportConventionBuilder AddMetadata(string name, Func<Type, object> getValueFromPartType)
{
Requires.NotNullOrEmpty(name, nameof(name));
Requires.NotNull(getValueFromPartType, nameof(getValueFromPartType));
if (_metadataItemFuncs == null)
{
_metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
}
_metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
return this;
}
internal void BuildAttributes(Type type, ref List<Attribute> attributes)
{
if (attributes == null)
{
attributes = new List<Attribute>();
}
var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName;
attributes.Add(new ExportAttribute(contractName, _contractType));
//Add metadata attributes from direct specification
if (_metadataItems != null)
{
foreach (var item in _metadataItems)
{
attributes.Add(new ExportMetadataAttribute(item.Item1, item.Item2));
}
}
//Add metadata attributes from func specification
if (_metadataItemFuncs != null)
{
foreach (var item in _metadataItemFuncs)
{
var name = item.Item1;
var value = (item.Item2 != null) ? item.Item2(type) : null;
attributes.Add(new ExportMetadataAttribute(name, value));
}
}
}
}
}

View File

@@ -0,0 +1,178 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Internal;
namespace System.Composition.Convention
{
/// <summary>
/// Configures an import associated with a part.
/// </summary>
public sealed class ImportConventionBuilder
{
private static readonly Type[] s_supportedImportManyTypes = new[] { typeof(IList<>), typeof(ICollection<>), typeof(IEnumerable<>) };
private string _contractName;
private bool? _asMany;
private bool _allowDefault;
private Func<Type, string> _getContractNameFromPartType;
private List<Tuple<string, object>> _metadataConstraintItems;
private List<Tuple<string, Func<Type, object>>> _metadataConstraintItemFuncs;
internal ImportConventionBuilder() { }
/// <summary>
/// Specify the contract name for the import.
/// </summary>
/// <param name="contractName"></param>
/// <returns>An import builder allowing further configuration.</returns>
public ImportConventionBuilder AsContractName(string contractName)
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
_contractName = contractName;
return this;
}
/// <summary>
/// Specify the contract name for the export.
/// </summary>
/// <param name="getContractNameFromPartType">A Func to retrieve the contract name from the part typeThe contract name.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ImportConventionBuilder AsContractName(Func<Type, string> getContractNameFromPartType)
{
Requires.NotNull(getContractNameFromPartType, nameof(getContractNameFromPartType));
_getContractNameFromPartType = getContractNameFromPartType;
return this;
}
/// <summary>
/// Configure the import to receive all exports of the contract.
/// </summary>
/// <returns>An import builder allowing further configuration.</returns>
public ImportConventionBuilder AsMany()
{
return AsMany(true);
}
/// <summary>
/// Configure the import to receive all exports of the contract.
/// </summary>
/// <param name="isMany">True if the import receives all values; otherwise false.</param>
/// <returns>An import builder allowing further configuration.</returns>
public ImportConventionBuilder AsMany(bool isMany)
{
_asMany = isMany;
return this;
}
/// <summary>
/// Allow the import to receive the default value for its type if
/// the contract cannot be supplied by another part.
/// </summary>
/// <returns>An import builder allowing further configuration.</returns>
public ImportConventionBuilder AllowDefault()
{
_allowDefault = true;
return this;
}
/// <summary>
/// Add an import constraint
/// </summary>
/// <param name="name">The name of the constraint item.</param>
/// <param name="value">The value to match.</param>
/// <returns>An import builder allowing further configuration.</returns>
public ImportConventionBuilder AddMetadataConstraint(string name, object value)
{
Requires.NotNullOrEmpty(name, nameof(name));
if (_metadataConstraintItems == null)
{
_metadataConstraintItems = new List<Tuple<string, object>>();
}
_metadataConstraintItems.Add(Tuple.Create(name, value));
return this;
}
/// <summary>
/// Add an import constraint
/// </summary>
/// <param name="name">The name of the constraint item.</param>
/// <param name="getConstraintValueFromPartType">A function that calculates the value to match.</param>
/// <returns>An export builder allowing further configuration.</returns>
public ImportConventionBuilder AddMetadataConstraint(string name, Func<Type, object> getConstraintValueFromPartType)
{
Requires.NotNullOrEmpty(name, nameof(name));
Requires.NotNull(getConstraintValueFromPartType, nameof(getConstraintValueFromPartType));
if (_metadataConstraintItemFuncs == null)
{
_metadataConstraintItemFuncs = new List<Tuple<string, Func<Type, object>>>();
}
_metadataConstraintItemFuncs.Add(Tuple.Create(name, getConstraintValueFromPartType));
return this;
}
internal void BuildAttributes(Type type, ref List<Attribute> attributes)
{
Attribute importAttribute;
var contractName = (_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName;
// Infer from Type when not explicitly set.
var asMany = _asMany ?? IsSupportedImportManyType(type.GetTypeInfo());
if (!asMany)
{
importAttribute = new ImportAttribute(contractName)
{
AllowDefault = _allowDefault
};
}
else
{
importAttribute = new ImportManyAttribute(contractName);
}
if (attributes == null)
{
attributes = new List<Attribute>();
}
attributes.Add(importAttribute);
//Add metadata attributes from direct specification
if (_metadataConstraintItems != null)
{
foreach (var item in _metadataConstraintItems)
{
attributes.Add(new ImportMetadataConstraintAttribute(item.Item1, item.Item2));
}
}
//Add metadata attributes from func specification
if (_metadataConstraintItemFuncs != null)
{
foreach (var item in _metadataConstraintItemFuncs)
{
var name = item.Item1;
var value = (item.Item2 != null) ? item.Item2(type) : null;
attributes.Add(new ImportMetadataConstraintAttribute(name, value));
}
}
return;
}
private bool IsSupportedImportManyType(TypeInfo typeInfo)
{
return typeInfo.IsArray ||
(typeInfo.IsGenericTypeDefinition && s_supportedImportManyTypes.Contains(typeInfo.AsType())) ||
(typeInfo.AsType().IsConstructedGenericType && s_supportedImportManyTypes.Contains(typeInfo.GetGenericTypeDefinition()));
}
}
}

View File

@@ -0,0 +1,42 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace System.Composition.Convention
{
/// <summary>
/// Used when configuring a <see cref="PartConventionBuilder{T}"/>. Used only
/// in expressions, instances of this type are never created.
/// </summary>
public abstract class ParameterImportConventionBuilder
{
private ParameterImportConventionBuilder() { }
/// <summary>
/// Import with contract <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <returns>The imported instance.</returns>
public T Import<T>()
{
return default(T);
}
/// <summary>
/// Import with contract <typeparamref name="T"/>.
/// </summary>
/// <param name="configure">Configuration for the import.</param>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <returns>The imported instance.</returns>
public T Import<T>(Action<ImportConventionBuilder> configure)
{
return default(T);
}
}
}

Some files were not shown because too many files have changed in this diff Show More