Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,260 @@
//---------------------------------------------------------------------
// <copyright file="AspProxy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security;
internal class AspProxy
{
private const string BUILD_MANAGER_TYPE_NAME = @"System.Web.Compilation.BuildManager";
private Assembly _webAssembly;
private bool _triedLoadingWebAssembly = false;
/// <summary>
/// Determine whether we are inside an ASP.NET application.
/// </summary>
/// <param name="webAssembly">The System.Web assembly</param>
/// <returns>true if we are running inside an ASP.NET application</returns>
internal bool IsAspNetEnvironment()
{
if (!TryInitializeWebAssembly())
{
return false;
}
try
{
string result = PrivateMapWebPath(EdmConstants.WebHomeSymbol);
return result != null;
}
catch (SecurityException)
{
// When running under partial trust but not running as an ASP.NET site the System.Web assembly
// may not be not treated as conditionally APTCA and hence throws a security exception. However,
// since this happens when not running as an ASP.NET site we can just return false because we're
// not in an ASP.NET environment.
return false;
}
catch (Exception e)
{
if (EntityUtil.IsCatchableExceptionType(e))
{
return false;
}
throw;
}
}
private bool TryInitializeWebAssembly()
{
// We cannot introduce a hard dependency on the System.Web assembly, so we load
// it via reflection.
//
if (_webAssembly != null)
{
return true;
}
else if (_triedLoadingWebAssembly)
{
return false;
}
Debug.Assert(_triedLoadingWebAssembly == false);
Debug.Assert(_webAssembly == null);
_triedLoadingWebAssembly = true;
try
{
_webAssembly = Assembly.Load(AssemblyRef.SystemWeb);
return _webAssembly != null;
}
catch (Exception e)
{
if (!EntityUtil.IsCatchableExceptionType(e))
{
throw; // StackOverflow, OutOfMemory, ...
}
// It is possible that we are operating in an environment where
// System.Web is simply not available (for instance, inside SQL
// Server). Instead of throwing or rethrowing, we simply fail
// gracefully
}
return false;
}
void InitializeWebAssembly()
{
if (!TryInitializeWebAssembly())
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext);
}
}
/// <summary>
/// This method accepts a string parameter that represents a path in a Web (specifically,
/// an ASP.NET) application -- one that starts with a '~' -- and resolves it to a
/// canonical file path.
/// </summary>
/// <remarks>
/// The implementation assumes that you cannot have file names that begin with the '~'
/// character. (This is a pretty reasonable assumption.) Additionally, the method does not
/// test for the existence of a directory or file resource after resolving the path.
///
internal string MapWebPath(string path)
{
Debug.Assert(path != null, "path == null");
path = PrivateMapWebPath(path);
if (path == null)
{
string errMsg = Strings.InvalidUseOfWebPath(EdmConstants.WebHomeSymbol);
throw EntityUtil.InvalidOperation(errMsg);
}
return path;
}
private string PrivateMapWebPath(string path)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(path.StartsWith(EdmConstants.WebHomeSymbol, StringComparison.Ordinal));
InitializeWebAssembly();
// Each managed application domain contains a static instance of the HostingEnvironment class, which
// provides access to application-management functions and application services. We'll try to invoke
// the static method MapPath() on that object.
//
try
{
Type hostingEnvType = _webAssembly.GetType("System.Web.Hosting.HostingEnvironment", true);
MethodInfo miMapPath = hostingEnvType.GetMethod("MapPath");
Debug.Assert(miMapPath != null, "Unpexpected missing member in type System.Web.Hosting.HostingEnvironment");
// Note:
// 1. If path is null, then the MapPath() method returns the full physical path to the directory
// containing the current application.
// 2. Any attempt to navigate out of the application directory (using "../..") will generate
// a (wrapped) System.Web.HttpException under ASP.NET (which we catch and re-throw).
//
return (string)miMapPath.Invoke(null, new object[] { path });
}
catch (TargetException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (ArgumentException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TargetInvocationException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TargetParameterCountException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (MethodAccessException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (MemberAccessException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TypeLoadException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
}
internal bool HasBuildManagerType()
{
Type buildManager;
return TryGetBuildManagerType(out buildManager);
}
private bool TryGetBuildManagerType(out Type buildManager)
{
InitializeWebAssembly();
buildManager = _webAssembly.GetType(BUILD_MANAGER_TYPE_NAME, false);
return buildManager != null;
}
internal IEnumerable<Assembly> GetBuildManagerReferencedAssemblies()
{
// We are interested in invoking the following method on the class
// System.Web.Compilation.BuildManager, which is available only in Orcas:
//
// public static ICollection GetReferencedAssemblies();
//
Type buildManager;
if (!TryGetBuildManagerType(out buildManager))
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToFindReflectedType(BUILD_MANAGER_TYPE_NAME, AssemblyRef.SystemWeb));
}
MethodInfo getRefAssembliesMethod = buildManager.GetMethod(
@"GetReferencedAssemblies",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public
);
if (getRefAssembliesMethod == null)
{
// eat this problem
return new List<Assembly>();
}
ICollection referencedAssemblies = null;
try
{
referencedAssemblies = (ICollection)getRefAssembliesMethod.Invoke(null, null);
if (referencedAssemblies == null)
{
return new List<Assembly>();
}
return referencedAssemblies.Cast<Assembly>();
}
catch (TargetException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (TargetInvocationException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
catch (MethodAccessException e)
{
throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.UnableToDetermineApplicationContext, e);
}
}
}
}

View File

@@ -0,0 +1,208 @@
//---------------------------------------------------------------------
// <copyright file="CacheForPrimitiveTypes.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.EntityModel;
using System.Diagnostics;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.IO;
using System.Data.Common;
using System.Globalization;
namespace System.Data.Metadata.Edm
{
internal class CacheForPrimitiveTypes
{
#region Fields
// The primitive type kind is a list of enum which the EDM model
// Every specific instantiation of the model should map their
// primitive types to the edm primitive types.
// In this class, primitive type is to be cached
// Key for the cache: primitive type kind
// Value for the cache: List<PrimitiveType>. A list is used because there an be multiple types mapping to the
// same primitive type kind. For example, sqlserver has multiple string types.
private List<PrimitiveType>[] _primitiveTypeMap = new List<PrimitiveType>[EdmConstants.NumPrimitiveTypes];
#endregion
#region Methods
/// <summary>
/// Add the given primitive type to the primitive type cache
/// </summary>
/// <param name="type">The primitive type to add</param>
internal void Add(PrimitiveType type)
{
// Get to the list
List<PrimitiveType> primitiveTypes = EntityUtil.CheckArgumentOutOfRange(_primitiveTypeMap, (int)type.PrimitiveTypeKind, "primitiveTypeKind");
// If there isn't a list for the given model type, create one and add it
if (primitiveTypes == null)
{
primitiveTypes = new List<PrimitiveType>();
primitiveTypes.Add(type);
_primitiveTypeMap[(int)type.PrimitiveTypeKind] = primitiveTypes;
}
else
{
primitiveTypes.Add(type);
}
}
/// <summary>
/// Try and get the mapped type for the given primitiveTypeKind in the given dataspace
/// </summary>
/// <param name="primitiveTypeKind">The primitive type kind of the primitive type to retrieve</param>
/// <param name="facets">The facets to use in picking the primitive type</param>
/// <param name="type">The resulting type</param>
/// <returns>Whether a type was retrieved or not</returns>
internal bool TryGetType(PrimitiveTypeKind primitiveTypeKind, IEnumerable<Facet> facets, out PrimitiveType type)
{
type = null;
// Now, see if we have any types for this model type, if so, loop through to find the best matching one
List<PrimitiveType> primitiveTypes = EntityUtil.CheckArgumentOutOfRange(_primitiveTypeMap, (int)primitiveTypeKind, "primitiveTypeKind");
if ((null != primitiveTypes) && (0 < primitiveTypes.Count))
{
if (primitiveTypes.Count == 1)
{
type = primitiveTypes[0];
return true;
}
if (facets == null)
{
FacetDescription[] facetDescriptions = EdmProviderManifest.GetInitialFacetDescriptions(primitiveTypeKind);
if (facetDescriptions == null)
{
type = primitiveTypes[0];
return true;
}
Debug.Assert(facetDescriptions.Length > 0);
facets = CacheForPrimitiveTypes.CreateInitialFacets(facetDescriptions);
}
Debug.Assert(type == null, "type must be null here");
bool isMaxLengthSentinel = false;
// Create a dictionary of facets for easy lookup
foreach (Facet facet in facets)
{
if ((primitiveTypeKind == PrimitiveTypeKind.String ||
primitiveTypeKind == PrimitiveTypeKind.Binary) &&
facet.Value != null &&
facet.Name == EdmProviderManifest.MaxLengthFacetName &&
Helper.IsUnboundedFacetValue(facet))
{
// MaxLength has the sentinel value. So this facet need not be added.
isMaxLengthSentinel = true;
continue;
}
}
int maxLength = 0;
// Find a primitive type with the matching constraint
foreach (PrimitiveType primitiveType in primitiveTypes)
{
if (isMaxLengthSentinel)
{
if (type == null)
{
type = primitiveType;
maxLength = Helper.GetFacet(primitiveType.FacetDescriptions, EdmProviderManifest.MaxLengthFacetName).MaxValue.Value;
}
else
{
int newMaxLength = Helper.GetFacet(primitiveType.FacetDescriptions, EdmProviderManifest.MaxLengthFacetName).MaxValue.Value;
if (newMaxLength > maxLength)
{
type = primitiveType;
maxLength = newMaxLength;
}
}
}
else
{
type = primitiveType;
break;
}
}
Debug.Assert(type != null);
return true;
}
return false;
}
private static Facet[] CreateInitialFacets(FacetDescription[] facetDescriptions)
{
Debug.Assert(facetDescriptions != null && facetDescriptions.Length > 0);
Facet[] facets = new Facet[facetDescriptions.Length];
for (int i = 0; i < facetDescriptions.Length; ++i)
{
switch (facetDescriptions[i].FacetName)
{
case DbProviderManifest.MaxLengthFacetName:
facets[i] = Facet.Create(facetDescriptions[i], TypeUsage.DefaultMaxLengthFacetValue);
break;
case DbProviderManifest.UnicodeFacetName:
facets[i] = Facet.Create(facetDescriptions[i], TypeUsage.DefaultUnicodeFacetValue);
break;
case DbProviderManifest.FixedLengthFacetName:
facets[i] = Facet.Create(facetDescriptions[i], TypeUsage.DefaultFixedLengthFacetValue);
break;
case DbProviderManifest.PrecisionFacetName:
facets[i] = Facet.Create(facetDescriptions[i], TypeUsage.DefaultPrecisionFacetValue);
break;
case DbProviderManifest.ScaleFacetName:
facets[i] = Facet.Create(facetDescriptions[i], TypeUsage.DefaultScaleFacetValue);
break;
default:
Debug.Assert(false, "Unexpected facet");
break;
}
}
return facets;
}
/// <summary>
/// Get the list of the primitive types for the given dataspace
/// </summary>
/// <returns></returns>
internal System.Collections.ObjectModel.ReadOnlyCollection<PrimitiveType> GetTypes()
{
List<PrimitiveType> primitiveTypes = new List<PrimitiveType>();
foreach (List<PrimitiveType> types in _primitiveTypeMap)
{
if (null != types)
{
primitiveTypes.AddRange(types);
}
}
return primitiveTypes.AsReadOnly();
}
#endregion
}
}

View File

@@ -0,0 +1,165 @@
//---------------------------------------------------------------------
// <copyright file="ClrPerspective.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
using System.Collections.Generic;
using System.Data.Mapping;
using System.Diagnostics;
/// <summary>
/// Internal helper class for query
/// </summary>
internal sealed class ClrPerspective : Perspective
{
private EntityContainer _defaultContainer;
#region Constructors
/// <summary>
/// Creates a new instance of perspective class so that query can work
/// ignorant of all spaces
/// </summary>
/// <param name="metadataWorkspace"></param>
internal ClrPerspective(MetadataWorkspace metadataWorkspace)
: base(metadataWorkspace, DataSpace.CSpace)
{
}
#endregion //Constructors
#region Methods
/// <summary>
/// Given a clrType attempt to return the corresponding target type from
/// the worksapce
/// </summary>
/// <param name="clrType">The clr type to resolve</param>
/// <param name="outTypeUsage">an out param for the typeUsage to be resolved to</param>
/// <returns>true if a TypeUsage can be found for the target type</returns>
internal bool TryGetType(Type clrType, out TypeUsage outTypeUsage)
{
return TryGetTypeByName(clrType.FullName,
false /*ignoreCase*/,
out outTypeUsage);
}
/// <summary>
/// Given the type in the target space and the member name in the source space,
/// get the corresponding member in the target space
/// For e.g. consider a Conceptual Type Foo with a member bar and a CLR type
/// XFoo with a member YBar. If one has a reference to Foo one can
/// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar
/// </summary>
/// <param name="type">The type in the target perspective</param>
/// <param name="memberName">the name of the member in the source perspective</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="outMember">returns the edmMember if a match is found</param>
/// <returns>true if a match is found, otherwise false</returns>
internal override bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember)
{
outMember = null;
Map map = null;
if (this.MetadataWorkspace.TryGetMap(type, DataSpace.OCSpace, out map))
{
ObjectTypeMapping objectTypeMap = map as ObjectTypeMapping;
if (objectTypeMap!=null)
{
ObjectMemberMapping objPropertyMapping = objectTypeMap.GetMemberMapForClrMember(memberName, ignoreCase);
if (null != objPropertyMapping)
{
outMember = objPropertyMapping.EdmMember;
return true;
}
}
}
return false;
}
/// <summary>
/// Look up a type in the target data space based upon the fullName
/// </summary>
/// <param name="fullName">fullName</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="typeUsage">The type usage object to return</param>
/// <returns>True if the retrieval succeeded</returns>
internal override bool TryGetTypeByName(string fullName, bool ignoreCase, out TypeUsage typeUsage)
{
typeUsage = null;
Map map = null;
// From ClrPerspective, we should not allow anything from SSpace. So make sure that the CSpace type does not
// have the Target attribute
if (this.MetadataWorkspace.TryGetMap(fullName, DataSpace.OSpace, ignoreCase, DataSpace.OCSpace, out map))
{
// Check if it's primitive type, if so, then use the MetadataWorkspace to get the mapped primitive type
if (map.EdmItem.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
{
// Reassign the variable with the provider primitive type, then create the type usage
PrimitiveType primitiveType = this.MetadataWorkspace.GetMappedPrimitiveType(((PrimitiveType)map.EdmItem).PrimitiveTypeKind, DataSpace.CSpace);
if (primitiveType != null)
{
typeUsage = EdmProviderManifest.Instance.GetCanonicalModelTypeUsage(primitiveType.PrimitiveTypeKind);
}
}
else
{
Debug.Assert(((GlobalItem)map.EdmItem).DataSpace == DataSpace.CSpace);
typeUsage = GetMappedTypeUsage(map);
}
}
return (null != typeUsage);
}
/// <summary>
/// get the default container
/// </summary>
/// <returns>The default container</returns>
internal override EntityContainer GetDefaultContainer()
{
return _defaultContainer;
}
internal void SetDefaultContainer(string defaultContainerName)
{
EntityContainer container = null;
if (!String.IsNullOrEmpty(defaultContainerName))
{
if (!MetadataWorkspace.TryGetEntityContainer(defaultContainerName, DataSpace.CSpace, out container))
{
throw EntityUtil.InvalidDefaultContainerName("defaultContainerName", defaultContainerName);
}
}
_defaultContainer = container;
}
/// <summary>
/// Given a map, dereference the EdmItem, ensure that it is
/// an EdmType and return a TypeUsage for the type, otherwise
/// return null.
/// </summary>
/// <param name="map">The OC map to use to get the EdmType</param>
/// <returns>A TypeUsage for the mapped EdmType or null if no EdmType was mapped</returns>
private static TypeUsage GetMappedTypeUsage(Map map)
{
TypeUsage typeUsage = null;
if (null != map)
{
MetadataItem item = map.EdmItem;
EdmType edmItem = item as EdmType;
if (null != item && edmItem!=null)
{
typeUsage = TypeUsage.Create(edmItem);
}
}
return typeUsage;
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
//---------------------------------------------------------------------
// <copyright file="CustomAssemblyResolver.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Reflection;
internal class CustomAssemblyResolver : MetadataArtifactAssemblyResolver
{
private Func<AssemblyName, Assembly> _referenceResolver;
private Func<IEnumerable<Assembly>> _wildcardAssemblyEnumerator;
internal CustomAssemblyResolver(Func<IEnumerable<Assembly>> wildcardAssemblyEnumerator, Func<AssemblyName, Assembly> referenceResolver)
{
Debug.Assert(wildcardAssemblyEnumerator != null);
Debug.Assert(referenceResolver != null);
_wildcardAssemblyEnumerator = wildcardAssemblyEnumerator;
_referenceResolver = referenceResolver;
}
internal override bool TryResolveAssemblyReference(AssemblyName refernceName, out Assembly assembly)
{
assembly = _referenceResolver(refernceName);
return assembly != null;
}
internal override IEnumerable<Assembly> GetWildcardAssemblies()
{
IEnumerable<Assembly> wildcardAssemblies = _wildcardAssemblyEnumerator();
if (wildcardAssemblies == null)
{
throw EntityUtil.InvalidOperation(Strings.WildcardEnumeratorReturnedNull);
}
return wildcardAssemblies;
}
}
}

View File

@@ -0,0 +1,45 @@
//---------------------------------------------------------------------
// <copyright file="DataSpace.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// DataSpace
/// </summary>
public enum DataSpace
{
/// <summary>
/// OSpace indicates the item in the clr space
/// </summary>
OSpace = 0,
/// <summary>
/// CSpace indicates the item in the CSpace - edm primitive types +
/// types defined in csdl
/// </summary>
CSpace = 1,
/// <summary>
/// SSpace indicates the item in the SSpace
/// </summary>
SSpace = 2,
/// <summary>
/// Mapping between OSpace and CSpace
/// </summary>
OCSpace = 3,
/// <summary>
/// Mapping between CSpace and SSpace
/// </summary>
CSSpace = 4
}
}

View File

@@ -0,0 +1,184 @@
//---------------------------------------------------------------------
// <copyright file="DefaultAssemblyResolver.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
namespace System.Data.Metadata.Edm
{
internal class DefaultAssemblyResolver : MetadataArtifactAssemblyResolver
{
internal override bool TryResolveAssemblyReference(AssemblyName refernceName, out Assembly assembly)
{
assembly = ResolveAssembly(refernceName);
return assembly != null;
}
internal override IEnumerable<Assembly> GetWildcardAssemblies()
{
return GetAllDiscoverableAssemblies();
}
internal Assembly ResolveAssembly(AssemblyName referenceName)
{
Assembly assembly = null;
// look in the already loaded assemblies
foreach (Assembly current in GetAlreadyLoadedNonSystemAssemblies())
{
if (AssemblyName.ReferenceMatchesDefinition(referenceName, new AssemblyName(current.FullName)))
{
return current;
}
}
// try to load this one specifically
if (assembly == null)
{
assembly = MetadataAssemblyHelper.SafeLoadReferencedAssembly(referenceName);
if (assembly != null)
{
return assembly;
}
}
// try all the discoverable ones
TryFindWildcardAssemblyMatch(referenceName, out assembly);
return assembly;
}
private bool TryFindWildcardAssemblyMatch(AssemblyName referenceName, out Assembly assembly)
{
Debug.Assert(referenceName != null);
foreach (Assembly current in GetAllDiscoverableAssemblies())
{
if (AssemblyName.ReferenceMatchesDefinition(referenceName, new AssemblyName(current.FullName)))
{
assembly = current;
return true;
}
}
assembly = null;
return false;
}
/// <summary>
/// Return all assemblies loaded in the current AppDomain that are not signed
/// with the Microsoft Key.
/// </summary>
/// <returns>A list of assemblies</returns>
private static IEnumerable<Assembly> GetAlreadyLoadedNonSystemAssemblies()
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
return assemblies.Where(a => a != null && !MetadataAssemblyHelper.ShouldFilterAssembly(a));
}
/// <summary>
/// This method returns a list of assemblies whose contents depend on whether we
/// are running in an ASP.NET environment. If we are indeed in a Web/ASP.NET
/// scenario, we pick up the assemblies that all page compilations need to
/// reference. If not, then we simply get the list of assemblies referenced by
/// the entry assembly.
/// </summary>
/// <returns>A list of assemblies</returns>
private static IEnumerable<Assembly> GetAllDiscoverableAssemblies()
{
Assembly assembly = Assembly.GetEntryAssembly();
HashSet<Assembly> assemblyList = new HashSet<Assembly>(
AssemblyComparer.Instance);
foreach (Assembly loadedAssembly in GetAlreadyLoadedNonSystemAssemblies())
{
assemblyList.Add(loadedAssembly);
}
AspProxy aspProxy = new AspProxy();
if (!aspProxy.IsAspNetEnvironment())
{
if (assembly == null)
{
return assemblyList;
}
assemblyList.Add(assembly);
foreach (Assembly referenceAssembly in MetadataAssemblyHelper.GetNonSystemReferencedAssemblies(assembly))
{
assemblyList.Add(referenceAssembly);
}
return assemblyList;
}
if (aspProxy.HasBuildManagerType())
{
IEnumerable<Assembly> referencedAssemblies = aspProxy.GetBuildManagerReferencedAssemblies();
// filter out system assemblies
if (referencedAssemblies != null)
{
foreach (Assembly referencedAssembly in referencedAssemblies)
{
if (MetadataAssemblyHelper.ShouldFilterAssembly(referencedAssembly))
{
continue;
}
assemblyList.Add(referencedAssembly);
}
}
}
return assemblyList.Where(a => a != null);
}
internal sealed class AssemblyComparer : IEqualityComparer<Assembly>
{
// use singleton
private AssemblyComparer() { }
private static AssemblyComparer _instance = new AssemblyComparer();
public static AssemblyComparer Instance{ get { return _instance; } }
/// <summary>
/// if two assemblies have the same full name, we will consider them as the same.
/// for example,
/// both of x and y have the full name as "{RES, Version=3.5.0.0, Culture=neutral, PublicKeyToken=null}",
/// although they are different instances since the ReflectionOnly field in them are different, we sitll
/// consider them as the same.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public bool Equals(Assembly x, Assembly y)
{
AssemblyName xname = new AssemblyName(x.FullName);
AssemblyName yname = new AssemblyName(y.FullName);
// return *true* when either the reference are the same
// *or* the Assembly names are commutative equal
return object.ReferenceEquals(x, y)
|| (AssemblyName.ReferenceMatchesDefinition(xname, yname)
&& AssemblyName.ReferenceMatchesDefinition(yname, xname));
}
public int GetHashCode(Assembly assembly)
{
return assembly.FullName.GetHashCode();
}
}
}
}

View File

@@ -0,0 +1,58 @@
//---------------------------------------------------------------------
// <copyright file="AssociationEndMember.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Data.Objects.DataClasses;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Represents a end of a Association Type
/// </summary>
public sealed class AssociationEndMember : RelationshipEndMember
{
#region Constructors
/// <summary>
/// Initializes a new instance of AssociationEndMember
/// </summary>
/// <param name="name">name of the association end member</param>
/// <param name="endRefType">Ref type that this end refers to </param>
/// <param name="multiplicity">multiplicity of the end</param>
internal AssociationEndMember(string name,
RefType endRefType,
RelationshipMultiplicity multiplicity)
: base(name, endRefType, multiplicity)
{
}
#endregion
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.AssociationEndMember; } }
private Func<RelationshipManager, RelatedEnd, RelatedEnd> _getRelatedEndMethod = null;
/// <summary>cached dynamic method to set a CLR property value on a CLR instance</summary>
internal Func<RelationshipManager, RelatedEnd, RelatedEnd> GetRelatedEnd
{
get { return _getRelatedEndMethod; }
set
{
System.Diagnostics.Debug.Assert(null != value, "clearing GetRelatedEndMethod");
// It doesn't matter which delegate wins, but only one should be jitted
Interlocked.CompareExchange(ref _getRelatedEndMethod, value, null);
}
}
}
}

View File

@@ -0,0 +1,92 @@
//---------------------------------------------------------------------
// <copyright file="AssociationSet.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class for representing an Association set
/// </summary>
public sealed class AssociationSet : RelationshipSet
{
#region Constructors
/// <summary>
/// Initializes a new instance of AssocationSet with the given name and the association type
/// </summary>
/// <param name="name">The name of the Assocation set</param>
/// <param name="associationType">The association type of the entities that this associationship set type contains</param>
internal AssociationSet(string name, AssociationType associationType)
: base(name, null, null, null, associationType)
{
}
#endregion
#region Fields
private readonly ReadOnlyMetadataCollection<AssociationSetEnd> _associationSetEnds =
new ReadOnlyMetadataCollection<AssociationSetEnd>(new MetadataCollection<AssociationSetEnd>());
#endregion
#region Properties
/// <summary>
/// Returns the association type associated with this association set
/// </summary>
public new AssociationType ElementType
{
get
{
return (AssociationType)base.ElementType;
}
}
/// <summary>
/// Returns the ends of the association set
/// </summary>
[MetadataProperty(BuiltInTypeKind.AssociationSetEnd, true)]
public ReadOnlyMetadataCollection<AssociationSetEnd> AssociationSetEnds
{
get
{
return _associationSetEnds;
}
}
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.AssociationSet; } }
#endregion
#region Methods
/// <summary>
/// Sets this item to be readonly, once this is set, the item will never be writable again.
/// </summary>
internal override void SetReadOnly()
{
if (!this.IsReadOnly)
{
base.SetReadOnly();
this.AssociationSetEnds.Source.SetReadOnly();
}
}
/// <summary>
/// Adds the given end to the collection of ends
/// </summary>
/// <param name="associationSetEnd"></param>
internal void AddAssociationSetEnd(AssociationSetEnd associationSetEnd)
{
this.AssociationSetEnds.Source.Add(associationSetEnd);
}
#endregion
}
}

View File

@@ -0,0 +1,169 @@
//---------------------------------------------------------------------
// <copyright file="AssociationSetEnd.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class representing a AssociationSet End
/// </summary>
public sealed class AssociationSetEnd : MetadataItem
{
#region Constructors
/// <summary>
/// Initializes a new instance of AssocationSetEnd
/// </summary>
/// <param name="entitySet">Entity set that this end refers to</param>
/// <param name="parentSet">The association set which this belongs to</param>
/// <param name="endMember">The end member of the association set which this is an instance of</param>
/// <exception cref="System.ArgumentNullException">Thrown if either the role,entitySet, parentSet or endMember arguments are null </exception>
internal AssociationSetEnd(EntitySet entitySet, AssociationSet parentSet, AssociationEndMember endMember)
{
_entitySet = EntityUtil.GenericCheckArgumentNull(entitySet, "entitySet");
_parentSet = EntityUtil.GenericCheckArgumentNull(parentSet, "parentSet");
_endMember = EntityUtil.GenericCheckArgumentNull(endMember, "endMember");
}
#endregion
#region Fields
private readonly EntitySet _entitySet;
private readonly AssociationSet _parentSet;
private readonly AssociationEndMember _endMember;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.AssociationSetEnd; } }
/// <summary>
/// The parent association set for this AssociationSetEnd.
/// </summary>
/// <exception cref="System.ArgumentNullException">Thrown if the value passed in for the setter is null </exception>
/// <exception cref="System.InvalidOperationException">Thrown if Setter is called when the AssociationSetEnd instance is in ReadOnly state</exception>
[MetadataProperty(BuiltInTypeKind.AssociationSet, false)]
public AssociationSet ParentAssociationSet
{
get
{
return _parentSet;
}
}
/// <summary>
/// The EndMember which this AssociationSetEnd corresponds to.
/// </summary>
/// <exception cref="System.ArgumentNullException">Thrown if the value passed in for the setter is null </exception>
/// <exception cref="System.InvalidOperationException">Thrown if Setter is called when the AssociationSetEnd instance is in ReadOnly state</exception>
[MetadataProperty(BuiltInTypeKind.AssociationEndMember, false)]
public AssociationEndMember CorrespondingAssociationEndMember
{
get
{
return _endMember;
}
}
/// <summary>
/// Name of the end
/// </summary>
[MetadataProperty(PrimitiveTypeKind.String, false)]
public string Name
{
get
{
return CorrespondingAssociationEndMember.Name;
}
}
/// <summary>
/// Name of the end role
/// </summary>
/// <exception cref="System.ArgumentNullException">Thrown if the value passed in for the setter is null </exception>
/// <exception cref="System.InvalidOperationException">Thrown if Setter is called when the AssociationSetEnd instance is in ReadOnly state</exception>
[MetadataProperty(PrimitiveTypeKind.String, false)]
[Obsolete("This property is going away, please use the Name property instead")]
public string Role
{
get
{
return Name;
}
}
/// <summary>
/// Returns the entity set referred by this end role
/// </summary>
[MetadataProperty(BuiltInTypeKind.EntitySet, false)]
public EntitySet EntitySet
{
get
{
return _entitySet;
}
}
/// <summary>
/// Gets the identity of this item
/// </summary>
internal override string Identity
{
get
{
return this.Name;
}
}
#endregion
#region Methods
/// <summary>
/// Overriding System.Object.ToString to provide better String representation
/// for this type.
/// </summary>
public override string ToString()
{
return Name;
}
/// <summary>
/// Sets this item to be readonly, once this is set, the item will never be writable again.
/// </summary>
internal override void SetReadOnly()
{
if (!IsReadOnly)
{
base.SetReadOnly();
AssociationSet parentAssociationSet = ParentAssociationSet;
if (parentAssociationSet != null)
{
parentAssociationSet.SetReadOnly();
}
AssociationEndMember endMember = CorrespondingAssociationEndMember;
if (endMember != null)
{
endMember.SetReadOnly();
}
EntitySet entitySet = EntitySet;
if (entitySet != null)
{
entitySet.SetReadOnly();
}
}
}
#endregion
}
}

View File

@@ -0,0 +1,136 @@
//---------------------------------------------------------------------
// <copyright file="AssociationType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Represents the EDM Association Type
/// </summary>
public sealed class AssociationType : RelationshipType
{
#region Constructors
/// <summary>
/// Initializes a new instance of Association Type with the given name, namespace, version and ends
/// </summary>
/// <param name="name">name of the association type</param>
/// <param name="namespaceName">namespace of the association type</param>
/// <param name="foreignKey">is this a foreign key (FK) relationship?</param>
/// <param name="dataSpace">dataSpace in which this AssociationType belongs to</param>
/// <exception cref="System.ArgumentNullException">Thrown if either the name, namespace or version attributes are null</exception>
internal AssociationType(string name,
string namespaceName,
bool foreignKey,
DataSpace dataSpace)
: base(name, namespaceName, dataSpace)
{
_referentialConstraints = new ReadOnlyMetadataCollection<ReferentialConstraint>(new MetadataCollection<ReferentialConstraint>());
_isForeignKey = foreignKey;
}
#endregion
#region Fields
private readonly ReadOnlyMetadataCollection<ReferentialConstraint> _referentialConstraints;
private FilteredReadOnlyMetadataCollection<AssociationEndMember, EdmMember> _associationEndMembers;
private readonly bool _isForeignKey;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.AssociationType; } }
/// <summary>
/// Returns the list of ends for this association type
/// </summary>
public ReadOnlyMetadataCollection<AssociationEndMember> AssociationEndMembers
{
get
{
Debug.Assert(IsReadOnly, "this is a wrapper around this.Members, don't call it during metadata loading, only call it after the metadata is set to read-only");
if (null == _associationEndMembers)
{
Interlocked.CompareExchange(ref _associationEndMembers,
new FilteredReadOnlyMetadataCollection<AssociationEndMember, EdmMember>(
this.Members, Helper.IsAssociationEndMember), null);
}
return _associationEndMembers;
}
}
/// <summary>
/// Returns the list of constraints for this association type
/// </summary>
[MetadataProperty(BuiltInTypeKind.ReferentialConstraint, true)]
public ReadOnlyMetadataCollection<ReferentialConstraint> ReferentialConstraints
{
get
{
return _referentialConstraints;
}
}
/// <summary>
/// Indicates whether this is a foreign key relationship.
/// </summary>
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
public bool IsForeignKey
{
get
{
return _isForeignKey;
}
}
#endregion
#region Methods
/// <summary>
/// Validates a EdmMember object to determine if it can be added to this type's
/// Members collection. If this method returns without throwing, it is assumed
/// the member is valid.
/// </summary>
/// <param name="member">The member to validate</param>
/// <exception cref="System.ArgumentException">Thrown if the member is not an AssociationEndMember</exception>
internal override void ValidateMemberForAdd(EdmMember member)
{
Debug.Assert(
(member is AssociationEndMember),
"Only members of type AssociationEndMember may be added to Association definitions.");
}
/// <summary>
/// Sets this item to be read-only, once this is set, the item will never be writable again.
/// </summary>
internal override void SetReadOnly()
{
if (!IsReadOnly)
{
base.SetReadOnly();
this.ReferentialConstraints.Source.SetReadOnly();
}
}
/// <summary>
/// Add the given referential constraint to the collection of referential constraints
/// </summary>
/// <param name="referentialConstraint"></param>
internal void AddReferentialConstraint(ReferentialConstraint referentialConstraint)
{
this.ReferentialConstraints.Source.Add(referentialConstraint);
}
#endregion
}
}

View File

@@ -0,0 +1,23 @@
//---------------------------------------------------------------------
// <copyright file="AttributeKind.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Kind of Item Attribute
/// </summary>
public enum PropertyKind
{
System,
Extended
}
}

View File

@@ -0,0 +1,228 @@
//---------------------------------------------------------------------
// <copyright file="BuiltInKind.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// List of all the built in types
/// </summary>
public enum BuiltInTypeKind
{
/// <summary>
/// Association Type Kind
/// </summary>
AssociationEndMember = 0,
/// <summary>
/// AssociationSetEnd Kind
/// </summary>
AssociationSetEnd,
/// <summary>
/// AssociationSet Kind
/// </summary>
AssociationSet,
/// <summary>
/// Association Type Kind
/// </summary>
AssociationType,
/// <summary>
/// EntitySetBase Kind
/// </summary>
EntitySetBase,
/// <summary>
/// Entity Type Base Kind
/// </summary>
EntityTypeBase,
/// <summary>
/// Collection Type Kind
/// </summary>
CollectionType,
/// <summary>
/// Collection Kind
/// </summary>
CollectionKind,
/// <summary>
/// Complex Type Kind
/// </summary>
ComplexType,
/// <summary>
/// Documentation Kind
/// </summary>
Documentation,
/// <summary>
/// DeleteAction Type Kind
/// </summary>
OperationAction,
/// <summary>
/// Edm Type Kind
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
EdmType,
/// <summary>
/// Entity Container Kind
/// </summary>
EntityContainer,
/// <summary>
/// Entity Set Kind
/// </summary>
EntitySet,
/// <summary>
/// Entity Type Kind
/// </summary>
EntityType,
/// <summary>
/// Enumeration Type Kind
/// </summary>
EnumType,
/// <summary>
/// Enum Member Kind
/// </summary>
EnumMember,
/// <summary>
/// Facet Kind
/// </summary>
Facet,
/// <summary>
/// EdmFunction Kind
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
EdmFunction,
/// <summary>
/// Function Parameter Kind
/// </summary>
FunctionParameter,
/// <summary>
/// Global Item Type Kind
/// </summary>
GlobalItem,
/// <summary>
/// Metadata Property Kind
/// </summary>
MetadataProperty,
/// <summary>
/// Navigation Property Kind
/// </summary>
NavigationProperty,
/// <summary>
/// Metadata Item Type Kind
/// </summary>
MetadataItem,
/// <summary>
/// EdmMember Type Kind
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
EdmMember,
/// <summary>
/// Parameter Mode Kind
/// </summary>
ParameterMode,
/// <summary>
/// Primitive Type Kind
/// </summary>
PrimitiveType,
/// <summary>
/// Primitive Type Kind Kind
/// </summary>
PrimitiveTypeKind,
/// <summary>
/// EdmProperty Type Kind
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
EdmProperty,
/// <summary>
/// ProviderManifest Type Kind
/// </summary>
ProviderManifest,
/// <summary>
/// Referential Constraint Type Kind
/// </summary>
ReferentialConstraint,
/// <summary>
/// Ref Type Kind
/// </summary>
RefType,
/// <summary>
/// RelationshipEnd Type Kind
/// </summary>
RelationshipEndMember,
/// <summary>
/// Relationship Multiplicity Type Kind
/// </summary>
RelationshipMultiplicity,
/// <summary>
/// Relationship Set Type Kind
/// </summary>
RelationshipSet,
/// <summary>
/// Relationship Type
/// </summary>
RelationshipType,
/// <summary>
/// Row Type Kind
/// </summary>
RowType,
/// <summary>
/// Simple Type Kind
/// </summary>
SimpleType,
/// <summary>
/// Structural Type Kind
/// </summary>
StructuralType,
/// <summary>
/// Type Information Kind
/// </summary>
TypeUsage,
//
//If you add anything below this, make sure you update the variable NumBuiltInTypes in EdmConstants
//
}
}

View File

@@ -0,0 +1,104 @@
//---------------------------------------------------------------------
// <copyright file="CollectionType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Represents the Edm Collection Type
/// </summary>
public sealed class CollectionType : EdmType
{
#region Constructors
/// <summary>
/// The constructor for constructing a CollectionType object with the element type it contains
/// </summary>
/// <param name="elementType">The element type that this collection type contains</param>
/// <exception cref="System.ArgumentNullException">Thrown if the argument elementType is null</exception>
internal CollectionType(EdmType elementType)
: this(TypeUsage.Create(elementType))
{
this.DataSpace = elementType.DataSpace;
}
/// <summary>
/// The constructor for constructing a CollectionType object with the element type (as a TypeUsage) it contains
/// </summary>
/// <param name="elementType">The element type that this collection type contains</param>
/// <exception cref="System.ArgumentNullException">Thrown if the argument elementType is null</exception>
internal CollectionType(TypeUsage elementType)
: base(GetIdentity(EntityUtil.GenericCheckArgumentNull(elementType, "elementType")),
EdmConstants.TransientNamespace, elementType.EdmType.DataSpace)
{
_typeUsage = elementType;
SetReadOnly();
}
#endregion
#region Fields
private readonly TypeUsage _typeUsage;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.CollectionType; } }
/// <summary>
/// The type of the element that this collection type contains
/// </summary>
[MetadataProperty(BuiltInTypeKind.TypeUsage, false)]
public TypeUsage TypeUsage
{
get
{
return _typeUsage;
}
}
#endregion
#region Methods
/// <summary>
/// Constructs the name of the collection type
/// </summary>
/// <param name="typeUsage">The typeusage for the element type that this collection type refers to</param>
/// <returns>The identity of the resulting collection type</returns>
private static string GetIdentity(TypeUsage typeUsage)
{
StringBuilder builder = new StringBuilder(50);
builder.Append("collection[");
typeUsage.BuildIdentity(builder);
builder.Append("]");
return builder.ToString();
}
/// <summary>
/// Override EdmEquals to support value comparison of TypeUsage property
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
internal override bool EdmEquals(MetadataItem item)
{
// short-circuit if this and other are reference equivalent
if (Object.ReferenceEquals(this, item)) { return true; }
// check type of item
if (null == item || BuiltInTypeKind.CollectionType != item.BuiltInTypeKind) { return false; }
CollectionType other = (CollectionType)item;
// compare type usage
return this.TypeUsage.EdmEquals(other.TypeUsage);
}
#endregion
}
}

View File

@@ -0,0 +1,148 @@
//---------------------------------------------------------------------
// <copyright file="ComplexType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Common;
using System.Threading;
using System.Diagnostics;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Represent the Edm Complex Type
/// </summary>
public class ComplexType : StructuralType
{
#region Constructors
/// <summary>
/// Initializes a new instance of Complex Type with the given properties
/// </summary>
/// <param name="name">The name of the complex type</param>
/// <param name="namespaceName">The namespace name of the type</param>
/// <param name="version">The version of this type</param>
/// <param name="dataSpace">dataSpace in which this ComplexType belongs to</param>
/// <exception cref="System.ArgumentNullException">If either name, namespace or version arguments are null</exception>
internal ComplexType(string name, string namespaceName, DataSpace dataSpace)
: base(name, namespaceName, dataSpace)
{
}
/// <summary>
/// Initializes a new instance of Complex Type - required for bootstraping code
/// </summary>
internal ComplexType()
{
// No initialization of item attributes in here, it's used as a pass thru in the case for delay population
// of item attributes
}
#endregion
#region Fields
private ReadOnlyMetadataCollection<EdmProperty> _properties;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.ComplexType; } }
/// <summary>
/// Returns just the properties from the collection
/// of members on this type
/// </summary>
public ReadOnlyMetadataCollection<EdmProperty> Properties
{
get
{
Debug.Assert(IsReadOnly, "this is a wrapper around this.Members, don't call it during metadata loading, only call it after the metadata is set to readonly");
if (null == _properties)
{
Interlocked.CompareExchange(ref _properties,
new FilteredReadOnlyMetadataCollection<EdmProperty, EdmMember>(
this.Members, Helper.IsEdmProperty), null);
}
return _properties;
}
}
#endregion
#region Methods
/// <summary>
/// Validates a EdmMember object to determine if it can be added to this type's
/// Members collection. If this method returns without throwing, it is assumed
/// the member is valid.
/// </summary>
/// <param name="member">The member to validate</param>
/// <exception cref="System.ArgumentException">Thrown if the member is not a EdmProperty</exception>
internal override void ValidateMemberForAdd(EdmMember member)
{
Debug.Assert(Helper.IsEdmProperty(member) || Helper.IsNavigationProperty(member),
"Only members of type Property may be added to ComplexType.");
}
#endregion
}
internal sealed class ClrComplexType : ComplexType
{
/// <summary>cached CLR type handle, allowing the Type reference to be GC'd</summary>
private readonly System.RuntimeTypeHandle _type;
/// <summary>cached dynamic method to construct a CLR instance</summary>
private Delegate _constructor;
private readonly string _cspaceTypeName;
/// <summary>
/// Initializes a new instance of Complex Type with properties from the type.
/// </summary>
/// <param name="clrType">The CLR type to construct from</param>
internal ClrComplexType(Type clrType, string cspaceNamespaceName, string cspaceTypeName)
: base(EntityUtil.GenericCheckArgumentNull(clrType, "clrType").Name, clrType.Namespace ?? string.Empty,
DataSpace.OSpace)
{
System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(cspaceNamespaceName) &&
!String.IsNullOrEmpty(cspaceTypeName), "Mapping information must never be null");
_type = clrType.TypeHandle;
_cspaceTypeName = cspaceNamespaceName + "." + cspaceTypeName;
this.Abstract = clrType.IsAbstract;
}
internal static ClrComplexType CreateReadonlyClrComplexType(Type clrType, string cspaceNamespaceName, string cspaceTypeName)
{
ClrComplexType type = new ClrComplexType(clrType, cspaceNamespaceName, cspaceTypeName);
type.SetReadOnly();
return type;
}
/// <summary>cached dynamic method to construct a CLR instance</summary>
internal Delegate Constructor
{
get { return _constructor; }
set
{
// It doesn't matter which delegate wins, but only one should be jitted
Interlocked.CompareExchange(ref _constructor, value, null);
}
}
/// <summary>
/// </summary>
internal override System.Type ClrType
{
get { return Type.GetTypeFromHandle(_type); }
}
internal string CSpaceTypeName { get { return _cspaceTypeName; } }
}
}

View File

@@ -0,0 +1,128 @@
//---------------------------------------------------------------------
// <copyright file="Documentation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Data.Common.Utils;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class representing the Documentation associated with an item
/// </summary>
public sealed class Documentation: MetadataItem
{
#region Fields
private string _summary = "";
private string _longDescription = "";
#endregion
#region Constructors
/// <summary>
/// Default constructor - primarily created for supporting usage of this Documentation class by SOM.
/// </summary>
internal Documentation()
{
}
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.Documentation; } }
/// <summary>
/// Gets the Summary for this Documentation instance.
/// </summary>
///
public string Summary
{
get
{
return _summary;
}
internal set
{
if (value != null)
_summary = value;
else
_summary = "";
}
}
/// <summary>
/// Gets the LongDescription for this Documentation instance.
/// </summary>
///
public string LongDescription
{
get
{
return _longDescription;
}
internal set
{
if (value != null)
_longDescription = value;
else
_longDescription = "";
}
}
/// <summary>
/// This property is required to be implemented for inheriting from MetadataItem. As there can be atmost one
/// instance of a nested-Documentation, return the constant "Documentation" as it's identity.
/// </summary>
internal override string Identity
{
get
{
return "Documentation";
}
}
/// <summary>
/// Returns true if this Documentation instance contains only null/empty summary and longDescription
/// </summary>
///
public bool IsEmpty
{
get
{
if (string.IsNullOrEmpty(_summary) && string.IsNullOrEmpty(_longDescription) )
{
return true;
}
return false;
}
}
#endregion
#region Methods
/// <summary>
/// </summary>
public override string ToString()
{
return _summary;
}
#endregion
}
}

View File

@@ -0,0 +1,233 @@
//---------------------------------------------------------------------
// <copyright file="EdmConstants.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Metadata.Edm
{
internal static class EdmConstants
{
// Namespace for all the system types
internal const string EdmNamespace = "Edm";
internal const string ClrPrimitiveTypeNamespace = "System";
internal const string TransientNamespace = "Transient";
// max number of primitive types
internal const int NumPrimitiveTypes = (int)System.Data.Metadata.Edm.PrimitiveTypeKind.GeographyCollection + 1;
// max number of primitive types
internal const int NumBuiltInTypes = (int)BuiltInTypeKind.TypeUsage + 1;
// MaxLength for the string types: Name, Namespace, Version
internal const int MaxLength = 256;
// Name of the built in types
internal const string AssociationEnd = "AssociationEnd";
internal const string AssociationSetType = "AssocationSetType";
internal const string AssociationSetEndType = "AssociationSetEndType";
internal const string AssociationType = "AssociationType";
internal const string BaseEntitySetType = "BaseEntitySetType";
internal const string CollectionType = "CollectionType";
internal const string ComplexType = "ComplexType";
internal const string DeleteAction = "DeleteAction";
internal const string DeleteBehavior = "DeleteBehavior";
internal const string Documentation = "Documentation";
internal const string EdmType = "EdmType";
internal const string ElementType = "ElementType";
internal const string EntityContainerType = "EntityContainerType";
internal const string EntitySetType = "EntitySetType";
internal const string EntityType = "EntityType";
internal const string EnumerationMember = "EnumMember";
internal const string EnumerationType = "EnumType";
internal const string Facet = "Facet";
internal const string Function = "EdmFunction";
internal const string FunctionParameter = "FunctionParameter";
internal const string GlobalItem = "GlobalItem";
internal const string ItemAttribute = "MetadataProperty";
internal const string ItemType = "ItemType";
internal const string Member = "EdmMember";
internal const string NavigationProperty = "NavigationProperty";
internal const string OperationBehavior = "OperationBehavior";
internal const string OperationBehaviors = "OperationBehaviors";
internal const string ParameterMode = "ParameterMode";
internal const string PrimitiveType = "PrimitiveType";
internal const string PrimitiveTypeKind = "PrimitiveTypeKind";
internal const string Property = "EdmProperty";
internal const string ProviderManifest = "ProviderManifest";
internal const string ReferentialConstraint = "ReferentialConstraint";
internal const string RefType = "RefType";
internal const string RelationshipEnd = "RelationshipEnd";
internal const string RelationshipMultiplicity = "RelationshipMultiplicity";
internal const string RelationshipSet = "RelationshipSet";
internal const string RelationshipType = "RelationshipType";
internal const string ReturnParameter = "ReturnParameter";
internal const string Role = "Role";
internal const string RowType = "RowType";
internal const string SimpleType = "SimpleType";
internal const string StructuralType = "StructuralType";
internal const string TypeUsage = "TypeUsage";
//Enum value of date time kind
internal const string Utc = "Utc";
internal const string Unspecified = "Unspecified";
internal const string Local = "Local";
//Enum value of multiplicity kind
internal const string One = "One";
internal const string ZeroToOne = "ZeroToOne";
internal const string Many = "Many";
//Enum value of Parameter Mode
internal const string In = "In";
internal const string Out = "Out";
internal const string InOut = "InOut";
//Enum value of DeleteAction Mode
internal const string None = "None";
internal const string Cascade = "Cascade";
internal const string Restrict = "Restrict";
//Enum Value of CollectionKind
internal const string NoneCollectionKind = "None";
internal const string ListCollectionKind = "List";
internal const string BagCollectionKind = "Bag";
//Enum Value of MaxLength (max length can be a single enum value, or a positive integer)
internal const string MaxMaxLength = "Max";
//Enum Value of SRID (srid can be a single enum value, or a positive integer)
internal const string VariableSrid = "Variable";
// Members of the built in types
internal const string AssociationSetEnds = "AssociationSetEnds";
internal const string Child = "Child";
internal const string DefaultValue = "DefaultValue";
internal const string Ends = "Ends";
internal const string EntitySet = "EntitySet";
internal const string AssociationSet = "AssociationSet";
internal const string EntitySets = "EntitySets";
internal const string Facets = "Facets";
internal const string FromProperties = "FromProperties";
internal const string FromRole = "FromRole";
internal const string IsParent = "IsParent";
internal const string KeyMembers = "KeyMembers";
internal const string Members = "Members";
internal const string Mode = "Mode";
internal const string Nullable = "Nullable";
internal const string Parameters = "Parameters";
internal const string Parent = "Parent";
internal const string Properties = "Properties";
internal const string ToProperties = "ToProperties";
internal const string ToRole = "ToRole";
internal const string ReferentialConstraints = "ReferentialConstraints";
internal const string RelationshipTypeName = "RelationshipTypeName";
internal const string ReturnType = "ReturnType";
internal const string ToEndMemberName = "ToEndMemberName";
internal const string CollectionKind = "CollectionKind";
// Name of the primitive types
internal const string Binary = "Binary";
internal const string Boolean = "Boolean";
internal const string Byte = "Byte";
internal const string DateTime = "DateTime";
internal const string Decimal = "Decimal";
internal const string Double = "Double";
internal const string Geometry = "Geometry";
internal const string GeometryPoint = "GeometryPoint";
internal const string GeometryLineString = "GeometryLineString";
internal const string GeometryPolygon = "GeometryPolygon";
internal const string GeometryMultiPoint = "GeometryMultiPoint";
internal const string GeometryMultiLineString = "GeometryMultiLineString";
internal const string GeometryMultiPolygon = "GeometryMultiPolygon";
internal const string GeometryCollection = "GeometryCollection";
internal const string Geography = "Geography";
internal const string GeographyPoint = "GeographyPoint";
internal const string GeographyLineString = "GeographyLineString";
internal const string GeographyPolygon = "GeographyPolygon";
internal const string GeographyMultiPoint = "GeographyMultiPoint";
internal const string GeographyMultiLineString = "GeographyMultiLineString";
internal const string GeographyMultiPolygon = "GeographyMultiPolygon";
internal const string GeographyCollection = "GeographyCollection";
internal const string Guid = "Guid";
internal const string Single = "Single";
internal const string SByte = "SByte";
internal const string Int16 = "Int16";
internal const string Int32 = "Int32";
internal const string Int64 = "Int64";
internal const string Money = "Money";
internal const string Null = "Null";
internal const string String = "String";
internal const string DateTimeOffset = "DateTimeOffset";
internal const string Time = "Time";
internal const string UInt16 = "UInt16";
internal const string UInt32 = "UInt32";
internal const string UInt64 = "UInt64";
internal const string Xml = "Xml";
// Name of the system defined attributes on edm type
internal const string Name = "Name";
internal const string Namespace = "Namespace";
internal const string Abstract = "Abstract";
internal const string BaseType = "BaseType";
internal const string Sealed = "Sealed";
internal const string ItemAttributes = "MetadataProperties";
internal const string Type = "Type";
// Name of SSDL specifc attributes for SQL Gen
internal const string Schema = "Schema";
internal const string Table = "Table";
// Name of the additional system defined attributes on item attribute
internal const string FacetType = "FacetType";
internal const string Value = "Value";
// Name of the additional system defined attributes on enum types
internal const string EnumMembers = "EnumMembers";
//
// Provider Manifest EdmFunction Attributes
//
internal const string BuiltInAttribute = "BuiltInAttribute";
internal const string StoreFunctionNamespace = "StoreFunctionNamespace";
internal const string ParameterTypeSemanticsAttribute = "ParameterTypeSemanticsAttribute";
internal const string ParameterTypeSemantics = "ParameterTypeSemantics";
internal const string NiladicFunctionAttribute = "NiladicFunctionAttribute";
internal const string IsComposableFunctionAttribute = "IsComposable";
internal const string CommandTextFunctionAttribyte = "CommandText";
internal const string StoreFunctionNameAttribute = "StoreFunctionNameAttribute";
/// <summary>
/// Used to denote application home directory in a Web/ASP.NET context
/// </summary>
internal const string WebHomeSymbol = "~";
// Name of Properties belonging to EDM's Documentation construct
internal const string Summary = "Summary";
internal const string LongDescription = "LongDescription";
internal static readonly Unbounded UnboundedValue = Unbounded.Instance;
internal class Unbounded
{
static readonly Unbounded _instance = new Unbounded();
private Unbounded() { }
static internal Unbounded Instance { get { return _instance; } }
public override string ToString() { return MaxMaxLength; }
}
internal static readonly Variable VariableValue = Variable.Instance;
internal class Variable
{
static readonly Variable _instance = new Variable();
private Variable() { }
static internal Variable Instance { get { return _instance; } }
public override string ToString() { return VariableSrid; }
}
}
}

View File

@@ -0,0 +1,452 @@
//---------------------------------------------------------------------
// <copyright file="EdmFunction.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class for representing a function
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public sealed class EdmFunction : EdmType
{
#region Constructors
internal EdmFunction(string name, string namespaceName, DataSpace dataSpace, EdmFunctionPayload payload)
: base(name, namespaceName, dataSpace)
{
//---- name of the 'schema'
//---- this is used by the SQL Gen utility and update pipeline to support generation of the correct function name in the store
_schemaName = payload.Schema;
_fullName = this.NamespaceName + "." + this.Name;
FunctionParameter[] returnParameters = payload.ReturnParameters;
Debug.Assert(returnParameters.All((returnParameter) => returnParameter != null), "All return parameters must be non-null");
Debug.Assert(returnParameters.All((returnParameter) => returnParameter.Mode == ParameterMode.ReturnValue), "Return parameter in a function must have the ParameterMode equal to ReturnValue.");
_returnParameters = new ReadOnlyMetadataCollection<FunctionParameter>(
returnParameters
.Select((returnParameter) => SafeLink<EdmFunction>.BindChild<FunctionParameter>(this, FunctionParameter.DeclaringFunctionLinker, returnParameter))
.ToList());
if (payload.IsAggregate.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.Aggregate, payload.IsAggregate.Value);
if (payload.IsBuiltIn.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.BuiltIn, payload.IsBuiltIn.Value);
if (payload.IsNiladic.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.NiladicFunction, payload.IsNiladic.Value);
if (payload.IsComposable.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsComposable, payload.IsComposable.Value);
if (payload.IsFromProviderManifest.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsFromProviderManifest, payload.IsFromProviderManifest.Value);
if (payload.IsCachedStoreFunction.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsCachedStoreFunction, payload.IsCachedStoreFunction.Value);
if (payload.IsFunctionImport.HasValue) SetFunctionAttribute(ref _functionAttributes, FunctionAttributes.IsFunctionImport, payload.IsFunctionImport.Value);
if (payload.ParameterTypeSemantics.HasValue)
{
_parameterTypeSemantics = payload.ParameterTypeSemantics.Value;
}
if (payload.StoreFunctionName != null)
{
_storeFunctionNameAttribute = payload.StoreFunctionName;
}
if (payload.EntitySets != null)
{
Debug.Assert(_returnParameters.Count == payload.EntitySets.Length, "The number of entity sets should match the number of return parameters");
_entitySets = new ReadOnlyMetadataCollection<EntitySet>(payload.EntitySets);
}
else
{
var list = new List<EntitySet>();
if (_returnParameters.Count != 0)
{
Debug.Assert(_returnParameters.Count == 1, "If there was more than one result set payload.EntitySets should not have been null");
list.Add(null);
}
_entitySets = new ReadOnlyMetadataCollection<EntitySet>(list);
}
if (payload.CommandText != null)
{
_commandTextAttribute = payload.CommandText;
}
if (payload.Parameters != null)
{
// validate the parameters
foreach (FunctionParameter parameter in payload.Parameters)
{
if (parameter == null)
{
throw EntityUtil.CollectionParameterElementIsNull("parameters");
}
Debug.Assert(parameter.Mode != ParameterMode.ReturnValue, "No function parameter can have ParameterMode equal to ReturnValue.");
}
// Populate the parameters
_parameters = new SafeLinkCollection<EdmFunction, FunctionParameter>(this, FunctionParameter.DeclaringFunctionLinker, new MetadataCollection<FunctionParameter>(payload.Parameters));
}
else
{
_parameters = new ReadOnlyMetadataCollection<FunctionParameter>(new MetadataCollection<FunctionParameter>());
}
}
#endregion
#region Fields
private readonly ReadOnlyMetadataCollection<FunctionParameter> _returnParameters;
private readonly ReadOnlyMetadataCollection<FunctionParameter> _parameters;
private readonly FunctionAttributes _functionAttributes = FunctionAttributes.Default;
private readonly string _storeFunctionNameAttribute;
private readonly ParameterTypeSemantics _parameterTypeSemantics;
private readonly string _commandTextAttribute;
private readonly string _schemaName;
private readonly ReadOnlyMetadataCollection<EntitySet> _entitySets;
private readonly string _fullName;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.EdmFunction; } }
/// <summary>
/// Returns the full name of this type, which is namespace + "." + name.
/// </summary>
public override string FullName
{
get
{
return _fullName;
}
}
/// <summary>
/// Gets the collection of parameters
/// </summary>
public ReadOnlyMetadataCollection<FunctionParameter> Parameters
{
get
{
return _parameters;
}
}
/// <summary>
/// Returns true if this is a C-space function and it has an eSQL body defined as DefiningExpression.
/// </summary>
internal bool HasUserDefinedBody
{
get
{
return this.IsModelDefinedFunction && !String.IsNullOrEmpty(this.CommandTextAttribute);
}
}
/// <summary>
/// For function imports, optionally indicates the entity set to which the result is bound.
/// If the function import has multiple result sets, returns the entity set to which the first result is bound
/// </summary>
[MetadataProperty(BuiltInTypeKind.EntitySet, false)]
internal EntitySet EntitySet
{
get
{
return _entitySets.Count != 0 ? _entitySets[0] : null;
}
}
/// <summary>
/// For function imports, indicates the entity sets to which the return parameters are bound.
/// The number of elements in the collection matches the number of return parameters.
/// A null element in the collection indicates that the corresponding are not bound to an entity set.
/// </summary>
[MetadataProperty(BuiltInTypeKind.EntitySet, true)]
internal ReadOnlyMetadataCollection<EntitySet> EntitySets
{
get
{
return _entitySets;
}
}
/// <summary>
/// Gets the return parameter of this function
/// </summary>
[MetadataProperty(BuiltInTypeKind.FunctionParameter, false)]
public FunctionParameter ReturnParameter
{
get
{
return _returnParameters.FirstOrDefault();
}
}
/// <summary>
/// Gets the return parameters of this function
/// </summary>
[MetadataProperty(BuiltInTypeKind.FunctionParameter, true)]
public ReadOnlyMetadataCollection<FunctionParameter> ReturnParameters
{
get
{
return _returnParameters;
}
}
[MetadataProperty(PrimitiveTypeKind.String, false)]
internal string StoreFunctionNameAttribute
{
get { return _storeFunctionNameAttribute; }
}
[MetadataProperty(typeof(ParameterTypeSemantics), false)]
internal ParameterTypeSemantics ParameterTypeSemanticsAttribute
{
get { return _parameterTypeSemantics; }
}
// Function attribute parameters
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool AggregateAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.Aggregate);
}
}
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool BuiltInAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.BuiltIn);
}
}
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool IsFromProviderManifest
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsFromProviderManifest);
}
}
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
internal bool NiladicFunctionAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.NiladicFunction);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Composable")]
[MetadataProperty(PrimitiveTypeKind.Boolean, false)]
public bool IsComposableAttribute
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsComposable);
}
}
[MetadataProperty(PrimitiveTypeKind.String, false)]
public string CommandTextAttribute
{
get
{
return _commandTextAttribute;
}
}
internal bool IsCachedStoreFunction
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsCachedStoreFunction);
}
}
internal bool IsModelDefinedFunction
{
get
{
return this.DataSpace == DataSpace.CSpace && !IsCachedStoreFunction && !IsFromProviderManifest && !IsFunctionImport;
}
}
internal bool IsFunctionImport
{
get
{
return GetFunctionAttribute(FunctionAttributes.IsFunctionImport);
}
}
[MetadataProperty(PrimitiveTypeKind.String, false)]
internal string Schema
{
get
{
return _schemaName;
}
}
#endregion
#region Methods
/// <summary>
/// Sets this item to be readonly, once this is set, the item will never be writable again.
/// </summary>
internal override void SetReadOnly()
{
if (!IsReadOnly)
{
base.SetReadOnly();
this.Parameters.Source.SetReadOnly();
foreach (FunctionParameter returnParameter in ReturnParameters)
{
returnParameter.SetReadOnly();
}
}
}
/// <summary>
/// Builds function identity string in the form of "functionName (param1, param2, ... paramN)".
/// </summary>
internal override void BuildIdentity(StringBuilder builder)
{
// If we've already cached the identity, simply append it
if (null != CacheIdentity)
{
builder.Append(CacheIdentity);
return;
}
EdmFunction.BuildIdentity(
builder,
FullName,
Parameters,
(param) => param.TypeUsage,
(param) => param.Mode);
}
/// <summary>
/// Builds identity based on the functionName and parameter types. All parameters are assumed to be <see cref="ParameterMode.In"/>.
/// Returns string in the form of "functionName (param1, param2, ... paramN)".
/// </summary>
internal static string BuildIdentity(string functionName, IEnumerable<TypeUsage> functionParameters)
{
StringBuilder identity = new StringBuilder();
BuildIdentity(
identity,
functionName,
functionParameters,
(param) => param,
(param) => ParameterMode.In);
return identity.ToString();
}
/// <summary>
/// Builds identity based on the functionName and parameters metadata.
/// Returns string in the form of "functionName (param1, param2, ... paramN)".
/// </summary>
internal static void BuildIdentity<TParameterMetadata>(StringBuilder builder,
string functionName,
IEnumerable<TParameterMetadata> functionParameters,
Func<TParameterMetadata, TypeUsage> getParameterTypeUsage,
Func<TParameterMetadata, ParameterMode> getParameterMode)
{
//
// Note: some callers depend on the format of the returned identity string.
//
// Start with the function name
builder.Append(functionName);
// Then add the string representing the list of parameters
builder.Append('(');
bool first = true;
foreach (TParameterMetadata parameter in functionParameters)
{
if (first) { first = false; }
else { builder.Append(","); }
builder.Append(Helper.ToString(getParameterMode(parameter)));
builder.Append(' ');
getParameterTypeUsage(parameter).BuildIdentity(builder);
}
builder.Append(')');
}
private bool GetFunctionAttribute(FunctionAttributes attribute)
{
return attribute == (attribute & _functionAttributes);
}
private static void SetFunctionAttribute(ref FunctionAttributes field, FunctionAttributes attribute, bool isSet)
{
if (isSet)
{
// make sure that attribute bits are set to 1
field |= attribute;
}
else
{
// make sure that attribute bits are set to 0
field ^= field & attribute;
}
}
#endregion
#region Nested types
[Flags]
private enum FunctionAttributes : byte
{
None = 0,
Aggregate = 1,
BuiltIn = 2,
NiladicFunction = 4,
IsComposable = 8,
IsFromProviderManifest = 16,
IsCachedStoreFunction = 32,
IsFunctionImport = 64,
Default = IsComposable,
}
#endregion
}
internal struct EdmFunctionPayload
{
public string Name;
public string NamespaceName;
public string Schema;
public string StoreFunctionName;
public string CommandText;
public EntitySet[] EntitySets;
public bool? IsAggregate;
public bool? IsBuiltIn;
public bool? IsNiladic;
public bool? IsComposable;
public bool? IsFromProviderManifest;
public bool? IsCachedStoreFunction;
public bool? IsFunctionImport;
public FunctionParameter[] ReturnParameters;
public ParameterTypeSemantics? ParameterTypeSemantics;
public FunctionParameter[] Parameters;
public DataSpace DataSpace;
}
}

View File

@@ -0,0 +1,151 @@
//---------------------------------------------------------------------
// <copyright file="EdmMember.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Represents the edm member class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public abstract class EdmMember : MetadataItem
{
/// <summary>
/// Initializes a new instance of EdmMember class
/// </summary>
/// <param name="name">name of the member</param>
/// <param name="memberTypeUsage">type information containing info about member's type and its facet</param>
internal EdmMember(string name, TypeUsage memberTypeUsage)
{
EntityUtil.CheckStringArgument(name, "name");
EntityUtil.GenericCheckArgumentNull(memberTypeUsage, "memberTypeUsage");
_name = name;
_typeUsage = memberTypeUsage;
}
private TypeUsage _typeUsage;
private string _name;
private StructuralType _declaringType;
/// <summary>
/// Returns the identity of the member
/// </summary>
internal override string Identity
{
get
{
return this.Name;
}
}
/// <summary>
/// Returns the name of the member
/// </summary>
[MetadataProperty(PrimitiveTypeKind.String, false)]
public String Name
{
get
{
return _name;
}
}
/// <summary>
/// Returns the declaring type of the member
/// </summary>
public StructuralType DeclaringType
{
get
{
return _declaringType;
}
}
/// <summary>
/// Returns the TypeUsage object containing the type information and facets
/// about the type
/// </summary>
[MetadataProperty(BuiltInTypeKind.TypeUsage, false)]
public TypeUsage TypeUsage
{
get
{
return _typeUsage;
}
}
/// <summary>
/// Overriding System.Object.ToString to provide better String representation
/// for this type.
/// </summary>
public override string ToString()
{
return Name;
}
/// <summary>
/// Sets the member to read only mode. Once this is done, there are no changes
/// that can be done to this class
/// </summary>
internal override void SetReadOnly()
{
if (!IsReadOnly)
{
base.SetReadOnly();
// TypeUsage is always readonly, no need to set it
}
}
/// <summary>
/// Change the declaring type without doing fixup in the member collection
/// </summary>
internal void ChangeDeclaringTypeWithoutCollectionFixup(StructuralType newDeclaringType)
{
_declaringType = newDeclaringType;
}
/// <summary>
/// Tells whether this member is marked as a Computed member in the EDM definition
/// </summary>
internal bool IsStoreGeneratedComputed
{
get
{
Facet item=null;
if (TypeUsage.Facets.TryGetValue(EdmProviderManifest.StoreGeneratedPatternFacetName, false, out item))
{
return ((StoreGeneratedPattern)item.Value) == StoreGeneratedPattern.Computed;
}
return false;
}
}
/// <summary>
/// Tells whether this member's Store generated pattern is marked as Identity in the EDM definition
/// </summary>
internal bool IsStoreGeneratedIdentity
{
get
{
Facet item = null;
if (TypeUsage.Facets.TryGetValue(EdmProviderManifest.StoreGeneratedPatternFacetName, false, out item))
{
return ((StoreGeneratedPattern)item.Value) == StoreGeneratedPattern.Identity;
}
return false;
}
}
}
}

View File

@@ -0,0 +1,148 @@
//---------------------------------------------------------------------
// <copyright file="EdmProperty.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Common;
using System.Threading;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Represent the edm property class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public sealed class EdmProperty : EdmMember
{
#region Constructors
/// <summary>
/// Initializes a new instance of the property class
/// </summary>
/// <param name="name">name of the property</param>
/// <param name="typeUsage">TypeUsage object containing the property type and its facets</param>
/// <exception cref="System.ArgumentNullException">Thrown if name or typeUsage arguments are null</exception>
/// <exception cref="System.ArgumentException">Thrown if name argument is empty string</exception>
internal EdmProperty(string name, TypeUsage typeUsage)
: base(name, typeUsage)
{
EntityUtil.CheckStringArgument(name, "name");
EntityUtil.GenericCheckArgumentNull(typeUsage, "typeUsage");
}
#endregion
#region Fields
/// <summary>Store the handle, allowing the PropertyInfo/MethodInfo/Type references to be GC'd</summary>
internal readonly System.RuntimeMethodHandle PropertyGetterHandle;
/// <summary>Store the handle, allowing the PropertyInfo/MethodInfo/Type references to be GC'd</summary>
internal readonly System.RuntimeMethodHandle PropertySetterHandle;
/// <summary>Store the handle, allowing the PropertyInfo/MethodInfo/Type references to be GC'd</summary>
internal readonly System.RuntimeTypeHandle EntityDeclaringType;
/// <summary>cached dynamic method to get the property value from a CLR instance</summary>
private Func<object,object> _memberGetter;
/// <summary>cached dynamic method to set a CLR property value on a CLR instance</summary>
private Action<object,object> _memberSetter;
#endregion
/// <summary>
/// Initializes a new OSpace instance of the property class
/// </summary>
/// <param name="name">name of the property</param>
/// <param name="typeUsage">TypeUsage object containing the property type and its facets</param>
/// <param name="propertyInfo">for the property</param>
/// <param name="entityDeclaringType">The declaring type of the entity containing the property</param>
internal EdmProperty(string name, TypeUsage typeUsage, System.Reflection.PropertyInfo propertyInfo, RuntimeTypeHandle entityDeclaringType)
: this(name, typeUsage)
{
System.Diagnostics.Debug.Assert(name == propertyInfo.Name, "different PropertyName");
if (null != propertyInfo)
{
System.Reflection.MethodInfo method;
method = propertyInfo.GetGetMethod(true); // return public or non-public getter
PropertyGetterHandle = ((null != method) ? method.MethodHandle : default(System.RuntimeMethodHandle));
method = propertyInfo.GetSetMethod(true); // return public or non-public getter
PropertySetterHandle = ((null != method) ? method.MethodHandle : default(System.RuntimeMethodHandle));
EntityDeclaringType = entityDeclaringType;
}
}
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.EdmProperty; } }
/// <summary>
/// Returns true if this property is nullable.
/// </summary>
/// <remarks>
/// Nullability in the conceptual model and store model is a simple indication of whether or not
/// the property is considered nullable. Nullability in the object model is more complex.
/// When using convention based mapping (as usually happens with POCO entities), a property in the
/// object model is considered nullable if and only if the underlying CLR type is nullable and
/// the property is not part of the primary key.
/// When using attribute based mapping (usually used with entities that derive from the EntityObject
/// base class), a property is considered nullable if the IsNullable flag is set to true in the
/// <see cref="System.Data.Objects.DataClasses.EdmScalarPropertyAttribute"/> attribute. This flag can
/// be set to true even if the underlying type is not nullable, and can be set to false even if the
/// underlying type is nullable. The latter case happens as part of default code generation when
/// a non-nullable property in the conceptual model is mapped to a nullable CLR type such as a string.
/// In such a case, the Entity Framework treats the property as non-nullable even though the CLR would
/// allow null to be set.
/// There is no good reason to set a non-nullable CLR type as nullable in the object model and this
/// should not be done even though the attribute allows it.
/// </remarks>
/// <exception cref="System.InvalidOperationException">Thrown if the setter is called when the EdmProperty instance is in ReadOnly state</exception>
public bool Nullable
{
get
{
return (bool)TypeUsage.Facets[DbProviderManifest.NullableFacetName].Value;
}
}
/// <summary>
/// Returns the default value for this property
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the setter is called when the EdmProperty instance is in ReadOnly state</exception>
public Object DefaultValue
{
get
{
return TypeUsage.Facets[DbProviderManifest.DefaultValueFacetName].Value;
}
}
/// <summary>cached dynamic method to get the property value from a CLR instance</summary>
internal Func<object,object> ValueGetter {
get { return _memberGetter; }
set
{
System.Diagnostics.Debug.Assert(null != value, "clearing ValueGetter");
// It doesn't matter which delegate wins, but only one should be jitted
Interlocked.CompareExchange(ref _memberGetter, value, null);
}
}
/// <summary>cached dynamic method to set a CLR property value on a CLR instance</summary>
internal Action<object,object> ValueSetter
{
get { return _memberSetter; }
set
{
System.Diagnostics.Debug.Assert(null != value, "clearing ValueSetter");
// It doesn't matter which delegate wins, but only one should be jitted
Interlocked.CompareExchange(ref _memberSetter, value, null);
}
}
}
}

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