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,151 @@
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; System.Data.Entity.Design Error Messages
;
EntityStoreGeneratorSchemaNotLoaded=The store metadata has not been generated yet. Call GenerateStoreMetadata first.
EntityModelGeneratorSchemaNotLoaded=The model metadata has not been generated yet. Call GenerateModelMetadata first.
StonglyTypedAccessToNullValue=The value for column '{0}' in table '{1}' is DBNull.
NoPrimaryKeyDefined=The table/view '{0}' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.
InvalidTypeForPrimaryKey=The table/view '{0}' has column '{1}' defined as a primary key, but the column type '{2}' is not a valid type for a key in the EDM. An attempt will be made to define the table/view as a read-only table/view.
CannotCreateEntityWithNoPrimaryKeyDefined=The table/view '{0}' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.
TableReferencedByAssociationWasNotFound=The table '{0}' is referenced by a relationship, but cannot be found.
TableReferencedByTvfWasNotFound=The return table of the function '{0}' is not defined. Either all columns have been excluded or the table has no columns. The function has been excluded. To use the function, you will need to review your schema, specify the return type of the function, and uncomment it.
UnsupportedDataType=The data type '{0}' is currently not supported for the target .NET Framework version; the column '{2}' in table '{1}' was excluded.
UnsupportedDataTypeUnknownType=The data type of the column '{0}' is currently not supported so the column '{0}' in table '{1}' was excluded.
UnsupportedFunctionReturnDataType=The function '{0}' has a return data type '{1}' that is currently not supported for the target .NET Framework version. The function was excluded.
UnsupportedFunctionParameterDataType=The function '{0}' has a parameter '{1}' at parameter index {2} that has a data type '{3}' which is currently not supported for the target .NET Framework version. The function was excluded.
UnsupportedDataTypeForTarget=The data type '{0}' is not supported for the target .NET Framework version. The column '{2}' in the table '{1}' was excluded from the model. To use the data type '{0}', target the .NET Framework 4.5 or higher.
UnsupportedFunctionReturnDataTypeForTarget=The function '{0}' returns the data type '{1}' that is not supported for the target .NET Framework version. The function was excluded from the model. To use the data type '{0}', target the .NET Framework 4.5 or higher.
UnsupportedFunctionParameterDataTypeForTarget=The function '{0}' has the parameter '{1}' at the parameter index {2} that has the data type '{3}' which is not supported for the target .NET Framework version. The function was excluded from the model. To use the data type '{0}', target the .NET Framework 4.5 or higher.
UnsupportedDbRelationship=The relationship '{0}' has columns that are not part of the key of the table on the primary side of the relationship. The relationship was excluded.
ParameterDirectionNotValid=The function '{0}' has a parameter '{1}' that has a parameter direction value '{2}', which is not valid. Please use 'IN', 'OUT', or 'INOUT'.
InvalidStringArgument=Parameter '{0}' is not valid. String arguments cannot be empty.
Serialization_UnknownGlobalItem=The GlobalItem of type '{0}' is not a serializable type.
ReservedNamespace=The namespace '{0}' is a system namespace, and cannot be used.
ColumnFacetValueOutOfRange=The facet '{0}' with a value '{1}' is outside the range {2}-{3} specified by the facet description. The column '{4}' in the table '{5}' was excluded.
AssociationMissingKeyColumn=The association between '{0}' and '{1}' will not be created because the key column '{2}' was not found to be part of the table definition (see previous warnings).
SingleStoreEntityContainerExpected=The StoreItemCollection collection must contain exactly one EntityContainer.
InvalidNonStoreEntityContainer=The EntityContainer '{0}' is not a store EntityContainer.
ExcludedColumnWasAKeyColumnEntityIsInvalid=The column '{0}' on the table/view '{1}' was excluded, and is a key column. The table/view has been excluded. Please fix the entity in the schema file, and uncomment.
ExcludedColumnWasAKeyColumnEntityIsReadOnly=The column '{0}' on the table/view '{1}' was excluded, and is a key column. The remaining key(s) were used and table/view has been created as read-only.
ModelGeneration_UnGeneratableType=The GlobalItem of type '{0}' has no model generation patterns defined.
DuplicateEntityContainerName=An EntityContainer with the name '{0}' already exists in the EdmItemCollection containing the EntityContainer '{1}'. Please choose a different model EntityContainer name.
ProviderFactoryReturnedNullFactory=The '{0}' DbProviderFactory returned a null value from the CreateConnection method.
ProviderSchemaErrors=The provider returned schema mapping information that is not valid.
InvalidNamespaceNameArgument=The namespaceName parameter '{0}' contains characters that are not valid.
InvalidEntityContainerNameArgument=The modelEntityContainerName parameter '{0}' contains characters that are not valid.
EntityClient_InvalidStoreProvider=The specified store provider '{0}' cannot be found in the configuration, or '{0}' is not valid.
DbProviderServicesInformationLocationPath=DbProviderServices://{0}/{1}
UnsupportedForeignKeyPattern=The relationship '{0}' uses the set of foreign keys '{1}' that are partially contained in the set of primary keys '{2}' of the table '{3}'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
UnsupportedQueryViewInEntityContainerMapping=The EntitySetMapping in EntityContainerMapping for entity container '{0}' contains a query view. Query views are not allowed in compile time view generation, so the view for this EntityContainerMapping will not be generated.
SharedForeignKey=Foreign key constraint '{0}' has been omitted from the storage model. Column '{1}' of table '{2}' is a foreign key participating in multiple relationships. A one-to-one Entity Model will not validate since data inconsistency is possible.
UnmappedFunctionImport=The function import '{0}' is not mapped to a store function. A function import needs to be mapped for successful execution.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; System.Data.EntityModel.EntityClassGenerator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CannotChangePropertyReturnType=The return data type of property '{0}' on the type '{1}' cannot be changed.
CannotChangePropertyReturnTypeToNull=The return data type of property '{0}' on the type '{1}' cannot be changed to null.
CodeGenSourceFilePathIsNotAFile=The parameter must specify a single file, not multiple.
InvalidAttributeSuppliedForType=The custom attribute supplied for type '{0}' is not valid.
InvalidMemberSuppliedForType=The additional member supplied for type '{0}' is not valid.
InvalidInterfaceSuppliedForType=The additional interface supplied for type '{0}' is not valid.
InvalidAttributeSuppliedForProperty=The custom attribute supplied for property '{0}' is not valid.
InvalidGetStatementSuppliedForProperty=The additional get statement supplied for property '{0}' is not valid.
InvalidSetStatementSuppliedForProperty=The additional Set statement supplied for property '{0}' is not valid.
PropertyExistsWithDifferentCase=The property '{0}' differs only in case from an existing property, and is not compatible with the current language option.
EntitySetExistsWithDifferentCase=The entity set '{0}' differs only in case from an existing entity set, and is not compatible with the current language option.
ItemExistsWithDifferentCase=The {0} '{1}' differs only in case from an existing {0}, and is not compatible with the current language option.
NullAdditionalSchema=The value in the parameter {0} at index {1} is null.
DuplicateClassName=The {0} '{1}' has the same name as the {2} '{1}'. Duplicate names are not allowed. You must change the name of either the {0} or the {2}.
TargetEntityFrameworkVersionToNewForEntityClassGenerator=The EntityClassGenerator is only for use with EntityFrameworkVersions.Version1 and the schemas provided have newer versions of the Model schema. Consider using EntityCodeGenerator or a template.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; System.Data.EntityModel.Emitters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MissingPropertyDocumentation=There are no comments for property {0} in the schema.
MissingComplexTypeDocumentation=There are no comments for ComplexType {0} in the schema.
MissingDocumentation=There are no comments for {0} in the schema.
MissingDocumentationNoName=There are no comments in the schema.
NamespaceComments=Original file name: {0}\nGeneration date: {1}\n
FactoryMethodSummaryComment=Create a new {0} object.
FactoryParamCommentGeneral=Initial value of {0}.
CtorSummaryComment=Initialize a new {0} object.
EmptyCtorSummaryComment=Initializes a new {0} object using the connection string found in the '{1}' section of the application configuration file.
GeneratedNavigationPropertyNameConflict=The NavigationProperty '{0}' on the type '{1}' is the source of a generated property '{2}' which conflicts with a member of the same name.
GeneratedPropertyAccessibilityConflict=Property '{0}' has '{1}' Get property and '{2}' Set property accessibility specified. {1} and {2} modifiers cannot be combined within a single Property.
EntityTypeAndSetAccessibilityConflict=EntityType '{0}' has '{1}' accessibility and EntitySet '{2}' has a get property with '{3}' accessibility. The get property of the EntitySet must not have less restrictive access than the containing EntityType has.
GeneratedFactoryMethodNameConflict=The member '{0}' on the type '{1}' conflicts with the generated factory method.
MetadataItemErrorsFoundDuringGeneration=Errors Found During Generation:
UnableToGenerateForeignKeyPropertiesForV1=Foreign keys may only be generated when targeting version 4.0 of the .NET Framework or higher.
UnableToGenerateFunctionImportParameterName=Unable to generate function import parameter name for the parameter '{0}' of the store function '{1}'. The store function will be ignored and the function import will not be generated.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; System.Data.Entity.Design.EntityViewGenerator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TypeComments=The type contains views for EntitySets and AssociationSets that were generated at design time.
GetViewAtMethodComments=The method returns the view for the index given.
ConstructorComments=The constructor stores the views for the extents and also the hash values generated based on the metadata and mapping closure and views.
IndividualViewComments=return view for {0}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; System.Data.Entity.Design.MetadataItemCollectionFactory
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TargetVersionSchemaVersionMismatch=The target Entity Framework version requires the edmx schema version {0} or lower. The specified schema is version {1}.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; System.Data.Entity.Design.PluralizationServices
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DuplicateEntryInUserDictionary=The {0} value '{1}' already exists in the user-defined dictionary.
UnsupportedLocaleForPluralizationServices=The culture '{0}' is not supported. Pluralization is currently only supported for the English language.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; CodeGeneration Templates
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Template_DuplicateTopLevelType=The type name '{0}' is used for both an EntityContainer and a type. Duplicates are not allowed, please change one of the names.
Template_ConflictingGeneratedNavPropName=The NavigationProperty '{0}' on the type '{1}' is the source of a generated property '{2}' which conflicts with a member of the same name.
Template_FactoryMethodNameConflict=The member '{0}' on the type '{1}' conflicts with the generated factory method.
Template_CaseInsensitiveTypeConflict=The Type '{0}' is not unique. This may be caused by the types only differing in case which is not compatible with the current language option.
Template_CaseInsensitiveEntitySetConflict=The EntitySet '{0}.{1}' differs only in case from an existing EntitySet, and is not compatible with the current language option.
Template_CaseInsensitiveMemberConflict=The Member '{0}.{1}' differs only in case from an existing Member, and is not compatible with the current language option.
Template_GenCommentAddToMethodCs=Deprecated Method for adding a new object to the {0} EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
Template_GenCommentAddToMethodVb=Deprecated Method for adding a new object to the {0} EntitySet. Consider using the .Add method of the associated ObjectSet(Of T) property instead.
Template_CommentNoDocumentation=No Metadata Documentation available.
Template_CommentFactoryMethodParam=Initial value of the {0} property.
Template_GeneratedCodeCommentLine1= This code was generated from a template.
Template_GeneratedCodeCommentLine2= Manual changes to this file may cause unexpected behavior in your application.
Template_GeneratedCodeCommentLine3= Manual changes to this file will be overwritten if the code is regenerated.
Template_ContextDefaultCtorComment=Initializes a new {0} object using the connection string found in the '{1}' section of the application configuration file.
Template_ContextCommonCtorComment=Initialize a new {0} object.
Template_FactoryMethodComment=Create a new {0} object.
Template_RegionRelationships=EDM Relationship Metadata
Template_RegionContexts=Contexts
Template_RegionObjectSetProperties=ObjectSet Properties
Template_RegionAddToMethods=AddTo Methods
Template_RegionFunctionImports=Function Imports
Template_RegionEntities=Entities
Template_RegionNavigationProperties=Navigation Properties
Template_RegionComplexTypes=ComplexTypes
Template_RegionFactoryMethod=Factory Method
Template_RegionPrimitiveProperties=Primitive Properties
Template_RegionSimpleProperties=Simple Properties
Template_RegionComplexProperties=Complex Properties
Template_RegionEnumTypes=Enums
Template_RegionConstructors=Constructors
Template_RegionPartialMethods=Partial Methods
Template_ReplaceVsItemTemplateToken=Please overwrite the replacement token '$edmxInputFile$' with the actual name of the .edmx file you would like to generate from.
Template_CurrentlyRunningTemplate=Currently Running Template
Template_UnsupportedSchema=The input file appears to be using a schema version not supported by this template. This may lead to compile errors. Please use 'Add New Generated Item' to add an updated template.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; EntityCodeGenerator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EdmSchemaNotValid=The EDM Schema argument is not valid.
EdmSchemaFileNotFound=Could not find file '{0}'.
EntityCodeGenTargetTooLow=The EntityCodeGenerator is not for targeting EntityFrameworkVersions.Version1. Consider using EntityClassGenerator or a template.
DefaultTargetVersionTooLow=The default target Entity Framework version requires the edmx schema version {0} or lower. The specified schema is version {1}. To avoid this warning specify the target Entity Framework version explicitly. You can do this by using the EdmGen.exe command-line tool with the targetVersion option, or by including the targetEntityFrameworkVersion parameter when calling the GenerateCode method.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copy from System.Data.Entity
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EntityClient_DoesNotImplementIServiceProvider=The store provider factory type '{0}' does not implement the IServiceProvider interface. Use a store provider that implements this interface.
EntityClient_ReturnedNullOnProviderMethod=A null was returned after calling the '{0}' method on a store provider instance of type '{1}'. The store provider might not be functioning correctly.

View File

@@ -0,0 +1,73 @@
//---------------------------------------------------------------------
// <copyright file="BuildProviderUtils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.Compilation;
using System.Web.Hosting;
namespace System.Data.Entity.Design.AspNet
{
/// <summary>
/// A place to put common methods used by our build providers
/// </summary>
///
internal class BuildProviderUtils
{
/// <summary>
/// Default constructor
/// </summary>
private BuildProviderUtils()
{
}
internal static void AddArtifactReference(AssemblyBuilder assemblyBuilder, BuildProvider prov, string virtualPath)
{
// add the artifact as a resource to the DLL
using (Stream input = VirtualPathProvider.OpenFile(virtualPath))
{
// derive the resource name
string name = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPath);
using (Stream resStream = assemblyBuilder.CreateEmbeddedResource(prov, name))
{
int byteRead = input.ReadByte();
while (byteRead != -1)
{
resStream.WriteByte((byte)byteRead);
byteRead = input.ReadByte();
}
}
}
}
/// <summary>
/// Transforms a virtual path string into a valid resource name.
/// </summary>
/// <param name="virtualPath"></param>
/// <returns></returns>
internal static string GetResourceNameForVirtualPath(string virtualPath)
{
string name = VirtualPathUtility.ToAppRelative(virtualPath);
Debug.Assert(name.StartsWith("~/", StringComparison.OrdinalIgnoreCase), "Expected app-relative path to start with ~/");
if (name.StartsWith("~/", StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(2);
}
name = name.Replace("/", ".");
Debug.Assert(name.StartsWith(".", StringComparison.OrdinalIgnoreCase) == false, "resource name unexpectedly starts with .");
return name;
}
}
}

View File

@@ -0,0 +1,100 @@
//---------------------------------------------------------------------
// <copyright file="EntityDesignerBuildProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Hosting;
using System.Web.Compilation;
using System.Xml;
using System.Data.Metadata.Edm;
namespace System.Data.Entity.Design.AspNet
{
/// <summary>
/// The ASP .NET Build provider for the CSDL in ADO .NET
/// </summary>
///
[BuildProviderAppliesTo(BuildProviderAppliesTo.Code)]
public class EntityDesignerBuildProvider : System.Web.Compilation.BuildProvider
{
/// <summary>
/// Default constructor
/// </summary>
public EntityDesignerBuildProvider()
{
}
/// <summary>
/// We want ASP .NET to always reset the app domain when we have to rebuild
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
public override BuildProviderResultFlags GetResultFlags(CompilerResults results)
{
return BuildProviderResultFlags.ShutdownAppDomainOnChange;
}
/// <summary>
/// Extract the CSDL, SSDL and MSL nodes from the EDMX file and store them
/// as embedded resources
/// </summary>
/// <param name="assemblyBuilder"></param>
public override void GenerateCode(AssemblyBuilder assemblyBuilder)
{
using (StreamReader edmxInputStream = new StreamReader(VirtualPathProvider.OpenFile(base.VirtualPath)))
{
// load up an XML document representing the edmx file
XmlElement conceptualSchemaElement;
XmlElement mappingElement;
XmlElement storageSchemaElement;
string embedAsResourcePropertyValue;
EntityDesignerUtils.ExtractConceptualMappingAndStorageNodes(edmxInputStream, out conceptualSchemaElement, out mappingElement, out storageSchemaElement, out embedAsResourcePropertyValue);
if (null == conceptualSchemaElement)
{
throw new XmlException("No Conceptual Schema node to embed as a resource", null, 0, 0);
}
if (null == storageSchemaElement)
{
throw new XmlException("No Storage Schema node to embed as a resource", null, 0, 0);
}
if (null == mappingElement)
{
throw new XmlException("No Mapping node to embed as a resource", null, 0, 0);
}
// construct output paths where the CSDL/MSL/SSDL resources will be placed
string virtualPathPrefix = base.VirtualPath.Replace(EntityDesignerUtils._edmxFileExtension, String.Empty);
string csdlResourceName = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPathPrefix + XmlConstants.CSpaceSchemaExtension);
string ssdlResourceName = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPathPrefix + XmlConstants.SSpaceSchemaExtension);
string mslResourceName = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPathPrefix + XmlConstants.CSSpaceSchemaExtension);
SetupEmbeddedResource(assemblyBuilder, this, conceptualSchemaElement, csdlResourceName);
SetupEmbeddedResource(assemblyBuilder, this, storageSchemaElement, ssdlResourceName);
SetupEmbeddedResource(assemblyBuilder, this, mappingElement, mslResourceName);
}
}
private static void SetupEmbeddedResource(AssemblyBuilder assemblyBuilder,
BuildProvider prov, XmlElement xmlElement, string resourceName)
{
using (Stream resStream = assemblyBuilder.CreateEmbeddedResource(prov, resourceName))
{
EntityDesignerUtils.OutputXmlElementToStream(xmlElement, resStream);
}
}
}
}

View File

@@ -0,0 +1,121 @@
//---------------------------------------------------------------------
// <copyright file="EntityModelBuildProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.Compilation;
using System.Xml;
using System.Data.Entity.Design;
using System.Data.Metadata.Edm;
namespace System.Data.Entity.Design.AspNet
{
/// <summary>
/// The ASP .NET Build provider for the CSDL in ADO .NET
/// </summary>
///
[BuildProviderAppliesTo(BuildProviderAppliesTo.Code)]
public class EntityModelBuildProvider : System.Web.Compilation.BuildProvider
{
/// <summary>
/// Default constructor
/// </summary>
public EntityModelBuildProvider()
{
}
/// <summary>
/// We want ASP .NET to always reset the app domain when we have to rebuild
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
public override BuildProviderResultFlags GetResultFlags(CompilerResults results)
{
return BuildProviderResultFlags.ShutdownAppDomainOnChange;
}
/// <summary>
///
/// </summary>
/// <param name="assemblyBuilder"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
public override void GenerateCode(AssemblyBuilder assemblyBuilder)
{
// look at the assembly builder to see which language we should use in the App_Code directory
EntityCodeGenerator generator = null;
if (assemblyBuilder.CodeDomProvider.FileExtension.ToLowerInvariant() == "cs")
{
generator = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode);
}
else
{
generator = new EntityCodeGenerator(LanguageOption.GenerateVBCode);
}
// generate the code for our CSDL file
IList<EdmSchemaError> errors = null;
using (XmlReader input = XmlReader.Create(VirtualPathProvider.OpenFile(base.VirtualPath)))
{
using (StringWriter output = new StringWriter(CultureInfo.InvariantCulture))
{
// Read from input and generate into output, put errors in a class member
var entityFrameworkVersion = GetEntityFrameworkVersion(BuildManager.TargetFramework.Version);
errors = generator.GenerateCode(input, output, entityFrameworkVersion);
if (errors.Count == 0)
{
output.Flush();
assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(output.ToString()));
}
}
}
// if there are errors, package this data into XmlExceptions and throw this
// if we are in VS, the ASP .NET stack will place this information in the error pane
// if we are in the ASP .NET runtime, it will use this information to build the error page
if (errors != null && errors.Count > 0)
{
XmlException inner = null;
XmlException outer = null;
foreach (EdmSchemaError error in errors)
{
outer = new XmlException(error.Message, inner, error.Line, error.Column);
inner = outer;
}
throw outer;
}
BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath);
}
private static Version GetEntityFrameworkVersion(Version targetFrameworkVersion)
{
Debug.Assert(targetFrameworkVersion != null, "targetFrameworkVersion should not be null.");
Debug.Assert(targetFrameworkVersion >= new Version(3, 5), "This assembly doesn't exist pre-3.5.");
if (targetFrameworkVersion < new Version(4, 0))
{
return EntityFrameworkVersions.Version1;
}
if (targetFrameworkVersion < new Version(4, 5))
{
return EntityFrameworkVersions.Version2;
}
return EntityFrameworkVersions.Version3;
}
}
}

View File

@@ -0,0 +1,56 @@
//---------------------------------------------------------------------
// <copyright file="MappingModelBuildProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Web;
using System.Web.Hosting;
using System.Web.Compilation;
namespace System.Data.Entity.Design.AspNet
{
/// <summary>
/// The ASP .NET Build provider for the MSL in ADO .NET
/// </summary>
///
[BuildProviderAppliesTo(BuildProviderAppliesTo.Code)]
public class MappingModelBuildProvider : System.Web.Compilation.BuildProvider
{
/// <summary>
/// Default constructor
/// </summary>
public MappingModelBuildProvider()
{
}
/// <summary>
/// We want ASP .NET to always reset the app domain when we have to rebuild
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
public override BuildProviderResultFlags GetResultFlags(CompilerResults results)
{
return BuildProviderResultFlags.ShutdownAppDomainOnChange;
}
/// <summary>
///
/// </summary>
/// <param name="assemblyBuilder"></param>
public override void GenerateCode(AssemblyBuilder assemblyBuilder)
{
BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath);
}
}
}

View File

@@ -0,0 +1,56 @@
//---------------------------------------------------------------------
// <copyright file="StorageModelBuildProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Web;
using System.Web.Hosting;
using System.Web.Compilation;
namespace System.Data.Entity.Design.AspNet
{
/// <summary>
/// The ASP .NET Build provider for the SSDL in ADO .NET
/// </summary>
///
[BuildProviderAppliesTo(BuildProviderAppliesTo.Code)]
public class StorageModelBuildProvider : System.Web.Compilation.BuildProvider
{
/// <summary>
/// Default constructor
/// </summary>
public StorageModelBuildProvider()
{
}
/// <summary>
/// We want ASP .NET to always reset the app domain when we have to rebuild
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
public override BuildProviderResultFlags GetResultFlags(CompilerResults results)
{
return BuildProviderResultFlags.ShutdownAppDomainOnChange;
}
/// <summary>
///
/// </summary>
/// <param name="assemblyBuilder"></param>
public override void GenerateCode(AssemblyBuilder assemblyBuilder)
{
BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath);
}
}
}

View File

@@ -0,0 +1,179 @@
//------------------------------------------------------------------------------
// <copyright file="EDesignUtil.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// @owner [....]
// @backupOwner [....]
//------------------------------------------------------------------------------
namespace System.Data.Entity.Design.Common {
using System;
using System.Data;
using System.Data.Metadata.Edm;
internal static class EDesignUtil {
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// Helper Functions
//
internal static string GetMessagesFromEntireExceptionChain(Exception e)
{
// get the full error message list from the inner exceptions
string message = e.Message;
int count = 0;
for (Exception inner = e.InnerException; inner != null; inner = inner.InnerException)
{
count++;
string indent = string.Empty.PadLeft(count, '\t');
message += Environment.NewLine + indent;
message += inner.Message;
}
return message;
}
static internal T CheckArgumentNull<T>(T value, string parameterName) where T : class
{
if (null == value)
{
throw ArgumentNull(parameterName);
}
return value;
}
static internal void CheckStringArgument(string value, string parameterName)
{
// Throw ArgumentNullException when string is null
CheckArgumentNull(value, parameterName);
// Throw ArgumentException when string is empty
if (value.Length == 0)
{
throw InvalidStringArgument(parameterName);
}
}
static internal LanguageOption CheckLanguageOptionArgument(LanguageOption value, string paramName)
{
if (value == LanguageOption.GenerateCSharpCode ||
value == LanguageOption.GenerateVBCode)
{
return value;
}
throw ArgumentOutOfRange(paramName);
}
static internal ArgumentException SingleStoreEntityContainerExpected(string parameterName)
{
ArgumentException e = new ArgumentException(Strings.SingleStoreEntityContainerExpected, parameterName);
return e;
}
static internal ArgumentException InvalidStoreEntityContainer(string entityContainerName, string parameterName)
{
ArgumentException e = new ArgumentException(Strings.InvalidNonStoreEntityContainer(entityContainerName), parameterName);
return e;
}
static internal ArgumentException InvalidStringArgument(string parameterName) {
ArgumentException e = new ArgumentException(Strings.InvalidStringArgument(parameterName));
return e;
}
static internal ArgumentException EdmReservedNamespace(string namespaceName) {
ArgumentException e = new ArgumentException(Strings.ReservedNamespace(namespaceName));
return e;
}
static internal ArgumentNullException ArgumentNull(string parameter) {
ArgumentNullException e = new ArgumentNullException(parameter);
return e;
}
static internal ArgumentException Argument(string parameter)
{
ArgumentException e = new ArgumentException(parameter);
return e;
}
static internal ArgumentException Argument(string message, Exception inner)
{
ArgumentException e = new ArgumentException(message, inner);
return e;
}
static internal InvalidOperationException InvalidOperation(string error)
{
InvalidOperationException e = new InvalidOperationException(error);
return e;
}
// SSDL Generator
static internal StrongTypingException StrongTyping(string error, Exception innerException) {
StrongTypingException e = new StrongTypingException(error, innerException);
return e;
}
static internal StrongTypingException StonglyTypedAccessToNullValue(string columnName, string tableName, Exception innerException) {
return StrongTyping(Strings.StonglyTypedAccessToNullValue(columnName, tableName), innerException);
}
static internal InvalidOperationException EntityStoreGeneratorSchemaNotLoaded() {
return InvalidOperation(Strings.EntityStoreGeneratorSchemaNotLoaded);
}
static internal InvalidOperationException EntityModelGeneratorSchemaNotLoaded() {
return InvalidOperation(Strings.EntityModelGeneratorSchemaNotLoaded);
}
static internal InvalidOperationException NonSerializableType(BuiltInTypeKind kind)
{
return InvalidOperation(Strings.Serialization_UnknownGlobalItem(kind));
}
static internal InvalidOperationException MissingGenerationPatternForType(BuiltInTypeKind kind)
{
return InvalidOperation(Strings.ModelGeneration_UnGeneratableType(kind));
}
static internal ArgumentException InvalidNamespaceNameArgument(string namespaceName)
{
return new ArgumentException(Strings.InvalidNamespaceNameArgument(namespaceName));
}
static internal ArgumentException InvalidEntityContainerNameArgument(string entityContainerName)
{
return new ArgumentException(Strings.InvalidEntityContainerNameArgument(entityContainerName));
}
static internal ArgumentException DuplicateEntityContainerName(string newModelEntityContainerName, string storeEntityContainer)
{
return new ArgumentException(Strings.DuplicateEntityContainerName(newModelEntityContainerName, storeEntityContainer));
}
static internal ProviderIncompatibleException ProviderIncompatible(string message)
{
return new ProviderIncompatibleException(message);
}
static internal ProviderIncompatibleException ProviderIncompatible(string message, Exception inner)
{
return new ProviderIncompatibleException(message, inner);
}
static internal ArgumentOutOfRangeException ArgumentOutOfRange(string paramName)
{
return new ArgumentOutOfRangeException(paramName);
}
internal static void CheckTargetEntityFrameworkVersionArgument(Version targetEntityFrameworkVersion, string parameterName)
{
EDesignUtil.CheckArgumentNull(targetEntityFrameworkVersion, parameterName);
if (!EntityFrameworkVersions.IsValidVersion(targetEntityFrameworkVersion))
{
throw EDesignUtil.Argument(parameterName);
}
}
}
}

View File

@@ -0,0 +1,338 @@
//---------------------------------------------------------------------
// <copyright file="MetadataUtil.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Data.Metadata.Edm;
using System.Xml;
using System.Data.Common;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Linq;
namespace System.Data.Entity.Design.Common
{
internal static class MetadataUtil
{
private const string s_defaultDelimiter = ", ";
internal static bool IsStoreType(GlobalItem item)
{
return item.DataSpace == DataSpace.SSpace;
}
internal static DbProviderServices GetProviderServices(DbProviderFactory factory)
{
EDesignUtil.CheckArgumentNull(factory, "factory");
// Special case SQL client so that it will work with System.Data from .NET 4.0 even without
// a binding redirect.
if (factory is SqlClientFactory)
{
return SqlProviderServices.Instance;
}
IServiceProvider serviceProvider = factory as IServiceProvider;
if (serviceProvider == null)
{
throw MetadataUtil.ProviderIncompatible(System.Data.Entity.Design.Strings.EntityClient_DoesNotImplementIServiceProvider(
factory.GetType().ToString()));
}
DbProviderServices providerServices = serviceProvider.GetService(typeof(DbProviderServices)) as DbProviderServices;
if (providerServices == null)
{
throw MetadataUtil.ProviderIncompatible(
System.Data.Entity.Design.Strings.EntityClient_ReturnedNullOnProviderMethod(
"GetService",
factory.GetType().ToString()));
}
return providerServices;
}
static internal ProviderIncompatibleException ProviderIncompatible(string error)
{
ProviderIncompatibleException e = new ProviderIncompatibleException(error);
return e;
}
/// <summary>
/// Check if all the SchemaErrors have the serverity of SchemaErrorSeverity.Warning
/// </summary>
/// <param name="schemaErrors"></param>
/// <returns></returns>
internal static bool CheckIfAllErrorsAreWarnings(IList<EdmSchemaError> schemaErrors)
{
int length = schemaErrors.Count;
for (int i = 0; i < length; ++i)
{
EdmSchemaError error = schemaErrors[i];
if (error.Severity != EdmSchemaErrorSeverity.Warning)
{
return false;
}
}
return true;
}
/// <summary>
/// This private static method checks a string to make sure that it is not empty.
/// Comparing with String.Empty is not sufficient since a string with nothing
/// but white space isn't considered "empty" by that rationale.
/// </summary>
internal static bool IsNullOrEmptyOrWhiteSpace(string value)
{
return IsNullOrEmptyOrWhiteSpace(value, 0);
}
internal static bool IsNullOrEmptyOrWhiteSpace(string value, int offset)
{
// don't use Trim(), which will copy the string, which may be large, just to test for emptyness
//return String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim());
if (null != value)
{
for (int i = offset; i < value.Length; ++i)
{
if (!Char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
// separate implementation from IsNullOrEmptyOrWhiteSpace(string, int) because that one will
// pick up the jit optimization to avoid boundary checks and the this won't is unknown (most likely not)
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // referenced by System.Data.Entity.Design.dll
internal static bool IsNullOrEmptyOrWhiteSpace(string value, int offset, int length)
{
// don't use Trim(), which will copy the string, which may be large, just to test for emptyness
//return String.IsNullOrEmpty(value) || String.IsNullOrEmpty(value.Trim());
if (null != value)
{
length = Math.Min(value.Length, length);
for (int i = offset; i < length; ++i)
{
if (!Char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
internal static string MembersToCommaSeparatedString(IEnumerable members)
{
StringBuilder builder = new StringBuilder();
builder.Append("{");
MetadataUtil.ToCommaSeparatedString(builder, members);
builder.Append("}");
return builder.ToString();
}
internal static void ToCommaSeparatedString(StringBuilder builder, IEnumerable list)
{
ToSeparatedStringPrivate(builder, list, s_defaultDelimiter, string.Empty, false);
}
// effects: Converts the list to a list of strings, sorts its (if
// toSort is true) and then converts to a string separated by
// "separator" with "nullValue" used for null values.
private static void ToSeparatedStringPrivate(StringBuilder stringBuilder, IEnumerable list, string separator,
string nullValue, bool toSort)
{
if (null == list)
{
return;
}
bool isFirst = true;
// Get the list of strings first
List<string> elementStrings = new List<string>();
foreach (object element in list)
{
string str;
// Get the element or its default null value
if (element == null)
{
str = nullValue;
}
else
{
str = FormatInvariant("{0}", element);
}
elementStrings.Add(str);
}
if (toSort == true)
{
// Sort the list
elementStrings.Sort(StringComparer.Ordinal);
}
// Now add the strings to the stringBuilder
foreach (string str in elementStrings)
{
if (false == isFirst)
{
stringBuilder.Append(separator);
}
stringBuilder.Append(str);
isFirst = false;
}
}
internal static string FormatInvariant(string format, params object[] args)
{
Debug.Assert(args.Length > 0, "Formatting utilities must be called with at least one argument");
return String.Format(CultureInfo.InvariantCulture, format, args);
}
/// <summary>
/// replace troublesome xml characters with equivalent entities
/// </summary>
/// <param name="text">text that make have characters troublesome in xml</param>
/// <returns>text with troublesome characters replaced with equivalent entities</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] // referenced by System.Data.Entity.Design.dll
internal static string Entityize(string text)
{
if (string.IsNullOrEmpty(text))
return "";
text = text.Replace("&", "&amp;");
text = text.Replace("<", "&lt;").Replace(">", "&gt;");
return text.Replace("\'", "&apos;").Replace("\"", "&quot;");
}
internal static bool TrySplitExtendedMetadataPropertyName(string name, out string xmlNamespaceUri, out string attributeName)
{
int pos = name.LastIndexOf(':');
if (pos < 0 || name.Length <= pos + 1)
{
Debug.Fail("the name is not in the form we expect");
xmlNamespaceUri = null;
attributeName = null;
return false;
}
xmlNamespaceUri = name.Substring(0, pos);
attributeName = name.Substring(pos + 1, (name.Length - 1) - pos);
return true;
}
static private readonly Type StackOverflowType = typeof(System.StackOverflowException);
static private readonly Type OutOfMemoryType = typeof(System.OutOfMemoryException);
static private readonly Type ThreadAbortType = typeof(System.Threading.ThreadAbortException);
static private readonly Type NullReferenceType = typeof(System.NullReferenceException);
static private readonly Type AccessViolationType = typeof(System.AccessViolationException);
static private readonly Type SecurityType = typeof(System.Security.SecurityException);
internal static bool IsCatchableExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != StackOverflowType) &&
(type != OutOfMemoryType) &&
(type != ThreadAbortType) &&
(type != NullReferenceType) &&
(type != AccessViolationType) &&
!SecurityType.IsAssignableFrom(type));
}
/// <summary>
/// Returns the single error message from the list of errors
/// </summary>
/// <param name="errors"></param>
/// <returns></returns>
static internal string CombineErrorMessage(IEnumerable<System.Data.Metadata.Edm.EdmSchemaError> errors)
{
Debug.Assert(errors != null);
StringBuilder sb = new StringBuilder(System.Environment.NewLine);
int count = 0;
foreach (System.Data.Metadata.Edm.EdmSchemaError error in errors)
{
//Don't append a new line at the beginning of the messages
if ((count++) != 0)
{
sb.Append(System.Environment.NewLine);
}
sb.Append(error.ToString());
}
Debug.Assert(count != 0, "Empty Error List");
return sb.ToString();
}
internal static void DisposeXmlReaders(IEnumerable<XmlReader> xmlReaders)
{
Debug.Assert(xmlReaders != null);
foreach (XmlReader xmlReader in xmlReaders)
{
((IDisposable)xmlReader).Dispose();
}
}
internal static bool IsCollectionType(GlobalItem item)
{
return (BuiltInTypeKind.CollectionType == item.BuiltInTypeKind);
}
internal static bool IsComplexType(EdmType type)
{
return (BuiltInTypeKind.ComplexType == type.BuiltInTypeKind);
}
internal static bool IsPrimitiveType(EdmType type)
{
return (BuiltInTypeKind.PrimitiveType == type.BuiltInTypeKind);
}
internal static bool IsEntitySet(EntitySetBase entitySetBase)
{
return BuiltInTypeKind.EntitySet == entitySetBase.BuiltInTypeKind;
}
internal static bool IsValidKeyType(Version entityFrameworkVersion, EdmType type)
{
var primitiveType = type as PrimitiveType;
if (primitiveType == null)
{
return false;
}
if (EntityFrameworkVersions.Version1 == entityFrameworkVersion)
{
return primitiveType.PrimitiveTypeKind != PrimitiveTypeKind.Binary;
}
else
{
// From V2 onwards, Binary key properties are supported
return true;
}
}
/// <summary>
/// determines if type is of EnumerationType.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
internal static bool IsEnumerationType(EdmType type)
{
return (BuiltInTypeKind.EnumType == type.BuiltInTypeKind);
}
}
}

View File

@@ -0,0 +1,110 @@
//---------------------------------------------------------------------
// <copyright file="UniqueIdentifierService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
namespace System.Data.Entity.Design.Common
{
/// <summary>
/// Service making names within a scope unique. Initialize a new instance
/// for every scope.
///
///
internal sealed class UniqueIdentifierService
{
internal UniqueIdentifierService(bool caseSensitive)
{
_knownIdentifiers = new Dictionary<string, bool>(caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
_identifierToAdjustedIdentifier = new Dictionary<object, string>();
_transform = s => s;
}
internal UniqueIdentifierService(bool caseSensitive, Func<string, string> transform)
{
Debug.Assert(transform != null, "use the other constructor if you don't want any transform");
_knownIdentifiers = new Dictionary<string, bool>(caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
_identifierToAdjustedIdentifier = new Dictionary<object, string>();
_transform = transform;
}
private readonly Dictionary<string, bool> _knownIdentifiers;
private readonly Dictionary<object, string> _identifierToAdjustedIdentifier;
private readonly Func<string, string> _transform;
/// <summary>
/// This method can be used in when you have an
/// identifier that you know can't be used, but you don't want
/// an adjusted version of it
/// </summary>
/// <param name="identifier"></param>
internal void RegisterUsedIdentifier(string identifier)
{
Debug.Assert(!_knownIdentifiers.ContainsKey(identifier), "don't register identifiers that already exist");
_knownIdentifiers.Add(identifier, true);
}
/// <summary>
/// Given an identifier, makes it unique within the scope by adding
/// a suffix (1, 2, 3, ...), and returns the adjusted identifier.
/// </summary>
/// <param name="identifier">Identifier. Must not be null or empty.</param>
/// <param name="value">Object associated with this identifier in case it is required to
/// retrieve the adjusted identifier. If not null, must not exist in the current scope already.</param>
/// <returns>Identifier adjusted to be unique within the scope.</returns>
internal string AdjustIdentifier(string identifier, object value)
{
Debug.Assert(!string.IsNullOrEmpty(identifier), "identifier is null or empty");
// find a unique name by adding suffix as necessary
int numberOfConflicts = 0;
string adjustedIdentifier = _transform(identifier);
while (_knownIdentifiers.ContainsKey(adjustedIdentifier))
{
++numberOfConflicts;
adjustedIdentifier = _transform(identifier) + numberOfConflicts.ToString(CultureInfo.InvariantCulture);
}
// remember the identifier in this scope
Debug.Assert(!_knownIdentifiers.ContainsKey(adjustedIdentifier), "we just made it unique");
_knownIdentifiers.Add(adjustedIdentifier, true);
if (null != value)
{
Debug.Assert(!_identifierToAdjustedIdentifier.ContainsKey(value), "should never register one value twice");
_identifierToAdjustedIdentifier.Add(value, adjustedIdentifier);
}
return adjustedIdentifier;
}
/// <summary>
/// Simple overload when you don't need to track back to an object
/// </summary>
/// <param name="identifier"></param>
/// <returns></returns>
internal string AdjustIdentifier(string identifier)
{
return AdjustIdentifier(identifier, null);
}
/// <summary>
/// Determines the adjusted name for an identifier if it has been registered in this scope.
/// </summary>
internal bool TryGetAdjustedName(object value, out string adjustedIdentifier)
{
return _identifierToAdjustedIdentifier.TryGetValue(value, out adjustedIdentifier);
}
}
}

View File

@@ -0,0 +1,28 @@
//---------------------------------------------------------------------
// <copyright file="DesignXmlConstants.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Entity.Design
{
internal static class DesignXmlConstants
{
internal const string EntityStoreSchemaGeneratorNamespace = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator";
internal const string EdmAnnotationNamespace = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";
// attributes
internal const string EntityStoreSchemaGeneratorTypeAttributeName = "Type";
internal const string EntityStoreSchemaGeneratorSchemaAttributeName = "Schema";
internal const string EntityStoreSchemaGeneratorNameAttributeName = "Name";
// attribute values
internal const string TypeValueTables = "Tables";
internal const string TypeValueViews = "Views";
internal const string StoreGeneratedPattern = "StoreGeneratedPattern";
internal const string LazyLoadingEnabled = "LazyLoadingEnabled";
internal const string AnnotationPrefix = "annotation";
}
}

View File

@@ -0,0 +1,156 @@
//---------------------------------------------------------------------
// <copyright file="EntityDesignerUtils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.IO;
using System.Text;
using System.Xml;
using System.Data.Metadata.Edm;
using System.Data.Mapping;
namespace System.Data.Entity.Design
{
internal static class EntityDesignerUtils
{
internal const string EdmxRootElementName = "Edmx";
internal const string EdmxNamespaceUriV1 = "http://schemas.microsoft.com/ado/2007/06/edmx";
internal const string EdmxNamespaceUriV2 = "http://schemas.microsoft.com/ado/2008/10/edmx";
internal const string EdmxNamespaceUriV3 = "http://schemas.microsoft.com/ado/2009/11/edmx";
private static readonly EFNamespaceSet v1Namespaces = new EFNamespaceSet
{
Edmx = EdmxNamespaceUriV1,
Csdl = XmlConstants.ModelNamespace_1,
Msl = StorageMslConstructs.NamespaceUriV1,
Ssdl = XmlConstants.TargetNamespace_1,
};
private static readonly EFNamespaceSet v2Namespaces = new EFNamespaceSet
{
Edmx = EdmxNamespaceUriV2,
Csdl = XmlConstants.ModelNamespace_2,
Msl = StorageMslConstructs.NamespaceUriV2,
Ssdl = XmlConstants.TargetNamespace_2,
};
private static readonly EFNamespaceSet v3Namespaces = new EFNamespaceSet
{
Edmx = EdmxNamespaceUriV3,
Csdl = XmlConstants.ModelNamespace_3,
Msl = StorageMslConstructs.NamespaceUriV3,
Ssdl = XmlConstants.TargetNamespace_3,
};
internal static readonly string _edmxFileExtension = ".edmx";
/// <summary>
/// Extract the Conceptual, Mapping and Storage nodes from an EDMX input streams, and extract the value of the metadataArtifactProcessing property.
/// </summary>
/// <param name="edmxInputStream"></param>
/// <param name="conceptualSchemaNode"></param>
/// <param name="mappingNode"></param>
/// <param name="storageSchemaNode"></param>
///
internal static void ExtractConceptualMappingAndStorageNodes(StreamReader edmxInputStream,
out XmlElement conceptualSchemaNode, out XmlElement mappingNode, out XmlElement storageSchemaNode, out string metadataArtifactProcessingValue)
{
// load up an XML document representing the edmx file
XmlDocument xmlDocument = new XmlDocument();
using (var reader = XmlReader.Create(edmxInputStream))
{
xmlDocument.Load(reader);
}
EFNamespaceSet set = v3Namespaces;
if (xmlDocument.DocumentElement.NamespaceURI == v2Namespaces.Edmx)
{
set = v2Namespaces;
}
else if (xmlDocument.DocumentElement.NamespaceURI == v1Namespaces.Edmx)
{
set = v1Namespaces;
}
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsMgr.AddNamespace("edmx", set.Edmx);
nsMgr.AddNamespace("edm", set.Csdl);
nsMgr.AddNamespace("ssdl", set.Ssdl);
nsMgr.AddNamespace("map", set.Msl);
// find the ConceptualModel Schema node
conceptualSchemaNode = (XmlElement)xmlDocument.SelectSingleNode(
"/edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/edm:Schema", nsMgr);
// find the StorageModel Schema node
storageSchemaNode = (XmlElement)xmlDocument.SelectSingleNode(
"/edmx:Edmx/edmx:Runtime/edmx:StorageModels/ssdl:Schema", nsMgr);
// find the Mapping node
mappingNode = (XmlElement)xmlDocument.SelectSingleNode(
"/edmx:Edmx/edmx:Runtime/edmx:Mappings/map:Mapping", nsMgr);
// find the Connection node
metadataArtifactProcessingValue = String.Empty;
XmlNodeList connectionProperties = xmlDocument.SelectNodes(
"/edmx:Edmx/edmx:Designer/edmx:Connection/edmx:DesignerInfoPropertySet/edmx:DesignerProperty", nsMgr);
if (connectionProperties != null)
{
foreach (XmlNode propertyNode in connectionProperties)
{
foreach (XmlAttribute a in propertyNode.Attributes)
{
// treat attribute names case-sensitive (since it is xml), but attribute value case-insensitive to be accommodating .
if (a.Name.Equals("Name", StringComparison.Ordinal) && a.Value.Equals("MetadataArtifactProcessing", StringComparison.OrdinalIgnoreCase))
{
foreach (XmlAttribute a2 in propertyNode.Attributes)
{
if (a2.Name.Equals("Value", StringComparison.Ordinal))
{
metadataArtifactProcessingValue = a2.Value;
break;
}
}
}
}
}
}
}
// utility method to ensure an XmlElement (containing the C, M or S element
// from the Edmx file) is sent out to a stream in the same format
internal static void OutputXmlElementToStream(XmlElement xmlElement, Stream stream)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
// set up output document
XmlDocument outputXmlDoc = new XmlDocument();
XmlNode importedElement = outputXmlDoc.ImportNode(xmlElement, true);
outputXmlDoc.AppendChild(importedElement);
// write out XmlDocument
XmlWriter writer = null;
try
{
writer = XmlWriter.Create(stream, settings);
outputXmlDoc.WriteTo(writer);
}
finally
{
if (writer != null) { writer.Close(); }
}
}
private struct EFNamespaceSet
{
public string Edmx;
public string Csdl;
public string Msl;
public string Ssdl;
}
}
}

View File

@@ -0,0 +1,235 @@
//---------------------------------------------------------------------
// <copyright file="EntityFrameworkVersions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.Data.Metadata.Edm;
using System.Data.Entity.Design.Common;
using System.IO;
using System.Data.Mapping;
using System.Data.EntityModel.SchemaObjectModel;
using System.Linq;
using System.Xml;
namespace System.Data.Entity.Design
{
public static class EntityFrameworkVersions
{
public static readonly Version Version1 = EntityFrameworkVersionsUtil.Version1;
public static readonly Version Version2 = EntityFrameworkVersionsUtil.Version2;
public static readonly Version Version3 = EntityFrameworkVersionsUtil.Version3;
internal static Version EdmVersion1_1 { get { return EntityFrameworkVersionsUtil.EdmVersion1_1; } }
/// <summary>
/// Returns the stream of the XSD corresponding to the frameworkVersion, and dataSpace passed in.
/// </summary>
/// <param name="entityFrameworkVersion">The version of the EntityFramework that you want the Schema XSD for.</param>
/// <param name="dataSpace">The data space of the schem XSD that you want.</param>
/// <returns>Stream version of the XSD</returns>
public static Stream GetSchemaXsd(Version entityFrameworkVersion, DataSpace dataSpace)
{
EDesignUtil.CheckTargetEntityFrameworkVersionArgument(entityFrameworkVersion, "entityFrameworkVersion");
string resourceName = null;
switch(dataSpace)
{
case DataSpace.CSpace:
resourceName = GetEdmSchemaXsdResourceName(entityFrameworkVersion);
break;
case DataSpace.CSSpace:
resourceName = GetMappingSchemaXsdResourceName(entityFrameworkVersion);
break;
case DataSpace.SSpace:
resourceName = GetStoreSchemaXsdResourceName(entityFrameworkVersion);
break;
default:
throw EDesignUtil.Argument("dataSpace");
}
Debug.Assert(!string.IsNullOrEmpty(resourceName), "Did you forget to map something new?");
Assembly dataEntity = typeof(EdmItemCollection).Assembly;
return dataEntity.GetManifestResourceStream(resourceName);
}
private static string GetStoreSchemaXsdResourceName(Version entityFrameworkVersion)
{
Debug.Assert(IsValidVersion(entityFrameworkVersion), "Did you forget to check for valid versions before calling this private method?");
Dictionary<string, XmlSchemaResource> map = new Dictionary<string, XmlSchemaResource>();
XmlSchemaResource.AddStoreSchemaResourceMapEntries(map, GetEdmVersion(entityFrameworkVersion));
return map[GetStoreSchemaNamespace(entityFrameworkVersion)].ResourceName;
}
private static string GetMappingSchemaXsdResourceName(Version entityFrameworkVersion)
{
Debug.Assert(IsValidVersion(entityFrameworkVersion), "Did you forget to check for valid versions before calling this private method?");
Dictionary<string, XmlSchemaResource> map = new Dictionary<string, XmlSchemaResource>();
XmlSchemaResource.AddMappingSchemaResourceMapEntries(map, GetEdmVersion(entityFrameworkVersion));
return map[GetMappingSchemaNamespace(entityFrameworkVersion)].ResourceName;
}
private static double GetEdmVersion(Version entityFrameworkVersion)
{
Debug.Assert(IsValidVersion(entityFrameworkVersion), "Did you add a new version or forget to check the version");
if (entityFrameworkVersion.Major == 1)
{
if (entityFrameworkVersion.Minor == 1)
{
return XmlConstants.EdmVersionForV1_1;
}
else
{
return XmlConstants.EdmVersionForV1;
}
}
else if (entityFrameworkVersion.Major == 2)
{
return XmlConstants.EdmVersionForV2;
}
else
{
Debug.Assert(entityFrameworkVersion == EntityFrameworkVersions.Version3, "did you add a new version?");
return XmlConstants.EdmVersionForV3;
}
}
private static string GetEdmSchemaXsdResourceName(Version entityFrameworkVersion)
{
Debug.Assert(ValidVersions.Contains(entityFrameworkVersion), "Did you forget to check for valid versions before calling this private method?");
Dictionary<string, XmlSchemaResource> map = new Dictionary<string, XmlSchemaResource>();
XmlSchemaResource.AddEdmSchemaResourceMapEntries(map, GetEdmVersion(entityFrameworkVersion));
return map[GetEdmSchemaNamespace(entityFrameworkVersion)].ResourceName;
}
internal static string GetSchemaNamespace(Version entityFrameworkVersion, DataSpace dataSpace)
{
Debug.Assert(IsValidVersion(entityFrameworkVersion), "Did you add a new version or forget to check the version");
Debug.Assert(dataSpace == DataSpace.CSpace ||
dataSpace == DataSpace.CSSpace ||
dataSpace == DataSpace.SSpace, "only support the three spaces with an xml file format");
switch (dataSpace)
{
case DataSpace.CSpace:
return GetEdmSchemaNamespace(entityFrameworkVersion);
case DataSpace.SSpace:
return GetStoreSchemaNamespace(entityFrameworkVersion);
default:
return GetMappingSchemaNamespace(entityFrameworkVersion);
}
}
private static string GetStoreSchemaNamespace(Version entityFrameworkVersion)
{
Debug.Assert(ValidVersions.Contains(entityFrameworkVersion), "Did you forget to check for valid versions before calling this private method?");
if (entityFrameworkVersion == EntityFrameworkVersions.Version1)
{
return XmlConstants.TargetNamespace_1;
}
else if (entityFrameworkVersion == EntityFrameworkVersions.Version2)
{
return XmlConstants.TargetNamespace_2;
}
else
{
Debug.Assert(entityFrameworkVersion == EntityFrameworkVersions.Version3, "did you add a new version?");
return XmlConstants.TargetNamespace_3;
}
}
private static string GetMappingSchemaNamespace(Version entityFrameworkVersion)
{
Debug.Assert(ValidVersions.Contains(entityFrameworkVersion), "Did you forget to check for valid versions before calling this private method?");
if (entityFrameworkVersion == EntityFrameworkVersions.Version1)
{
return StorageMslConstructs.NamespaceUriV1;
}
else if (entityFrameworkVersion == EntityFrameworkVersions.Version2)
{
return StorageMslConstructs.NamespaceUriV2;
}
else
{
Debug.Assert(entityFrameworkVersion == EntityFrameworkVersions.Version3, "did you add a new version?");
return StorageMslConstructs.NamespaceUriV3;
}
}
private static string GetEdmSchemaNamespace(Version entityFrameworkVersion)
{
Debug.Assert(ValidVersions.Contains(entityFrameworkVersion), "Did you forget to check for valid versions before calling this private method?");
if (entityFrameworkVersion == EntityFrameworkVersions.Version1)
{
return XmlConstants.ModelNamespace_1;
}
else if (entityFrameworkVersion == EntityFrameworkVersions.Version2)
{
return XmlConstants.ModelNamespace_2;
}
else
{
Debug.Assert(entityFrameworkVersion == EntityFrameworkVersions.Version3, "did you add a new version?");
return XmlConstants.ModelNamespace_3;
}
}
internal static Version Default = Version2;
internal static Version Latest = Version3;
internal static Version[] ValidVersions = new Version[] { Version1, Version2, Version3 };
internal static bool IsValidVersion(Version entityFrameworkVersion)
{
return ValidVersions.Contains(entityFrameworkVersion);
}
// this method will skip down to the first element, or to the end if it doesn't find one
internal static bool TryGetEdmxVersion(XmlReader reader, out Version entityFrameworkVersion)
{
// to make life simpler, we skip down to the first/root element, unless we're
// already there
if (!reader.EOF && reader.NodeType != XmlNodeType.Element)
{
while (reader.Read() && reader.NodeType != XmlNodeType.Element)
{
}
}
if (!reader.EOF &&
(reader.LocalName == EntityDesignerUtils.EdmxRootElementName))
{
return TryGetEdmxVersion(reader.NamespaceURI, out entityFrameworkVersion);
}
entityFrameworkVersion = default(Version);
return false;
}
internal static bool TryGetEdmxVersion(string xmlNamespaceName, out Version entityFrameworkVersion)
{
switch (xmlNamespaceName)
{
case EntityDesignerUtils.EdmxNamespaceUriV1:
entityFrameworkVersion = EntityFrameworkVersions.Version1;
return true;
case EntityDesignerUtils.EdmxNamespaceUriV2:
entityFrameworkVersion = EntityFrameworkVersions.Version2;
return true;
case EntityDesignerUtils.EdmxNamespaceUriV3:
entityFrameworkVersion = EntityFrameworkVersions.Version3;
return true;
default:
entityFrameworkVersion = default(Version);
return false;
}
}
}
}

View File

@@ -0,0 +1,41 @@
//---------------------------------------------------------------------
// <copyright file="EntityFrameworkVersionsUtil.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//---------------------------------------------------------------------
using System.Diagnostics;
namespace System.Data.Entity.Design
{
internal static class EntityFrameworkVersionsUtil
{
public static readonly Version Version1 = new Version(1, 0, 0, 0);
public static readonly Version Version2 = new Version(2, 0, 0, 0);
public static readonly Version Version3 = new Version(3, 0, 0, 0);
internal static Version EdmVersion1_1 { get { return new Version(1, 1, 0, 0); } }
internal static Version ConvertToVersion(double runtimeVersion)
{
if (runtimeVersion == 1.0 || runtimeVersion == 0.0)
{
return Version1;
}
else if (runtimeVersion == 1.1)
{
// this is not a valid EntityFramework version,
// but only a valid EdmVersion
return EdmVersion1_1;
}
else if (runtimeVersion == 2.0)
{
return Version2;
}
else
{
Debug.Assert(runtimeVersion == 3.0, "Did you add a new version?");
return Version3;
}
}
}
}

View File

@@ -0,0 +1,28 @@
//---------------------------------------------------------------------
// <copyright file="EntityStoreSchemaFilterEffect.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.Entity.Design
{
/// <summary>
/// The effect that the filter entry should have on the results
///
/// When a database object matchs the pattern for both an allow and exclude EntityStoreSchemaFilterEntry,
/// the database object will be excluded.
/// </summary>
public enum EntityStoreSchemaFilterEffect
{
/// <summary>Allow the entries that match the specified pattern.</summary>
Allow = 0,
/// <summary>Exclude the entries that match the specified pattern.</summary>
Exclude = 1,
}
}

View File

@@ -0,0 +1,105 @@
//---------------------------------------------------------------------
// <copyright file="EntityStoreSchemaFilterEntry.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Data.Entity.Design.Common;
namespace System.Data.Entity.Design
{
/// <summary>
/// This class represent a single filter entry
/// </summary>
public class EntityStoreSchemaFilterEntry
{
private string _catalog;
private string _schema;
private string _name;
private EntityStoreSchemaFilterObjectTypes _types;
private EntityStoreSchemaFilterEffect _effect;
/// <summary>
/// Creates a EntityStoreSchemaFilterEntry
/// </summary>
/// <param name="catalog">The pattern to use to select the appropriate catalog or null to not limit by catalog.</param>
/// <param name="schema">The pattern to use to select the appropriate schema or null to not limit by schema.</param>
/// <param name="name">The pattern to use to select the appropriate name or null to not limit by name.</param>
/// <param name="types">The type of objects to apply this filter to.</param>
/// <param name="effect">The effect that this filter should have on the results.</param>
public EntityStoreSchemaFilterEntry(string catalog, string schema, string name, EntityStoreSchemaFilterObjectTypes types, EntityStoreSchemaFilterEffect effect)
{
if (types == EntityStoreSchemaFilterObjectTypes.None)
{
throw EDesignUtil.Argument("types");
}
_catalog = catalog;
_schema = schema;
_name = name;
_types = types;
_effect = effect;
}
/// <summary>
/// Creates a EntityStoreSchemaFilterEntry
/// </summary>
/// <param name="catalog">The pattern to use to select the appropriate catalog or null to not limit by catalog.</param>
/// <param name="schema">The pattern to use to select the appropriate schema or null to not limit by schema.</param>
/// <param name="name">The pattern to use to select the appropriate name or null to not limit by name.</param>
public EntityStoreSchemaFilterEntry(string catalog, string schema, string name)
:this(catalog, schema, name, EntityStoreSchemaFilterObjectTypes.All, EntityStoreSchemaFilterEffect.Allow)
{
}
/// <summary>
/// Gets the pattern that will be used to select the appropriate catalog.
/// </summary>
public string Catalog
{
[DebuggerStepThroughAttribute]
get { return _catalog; }
}
/// <summary>
/// Gets the pattern that will be used to select the appropriate schema.
/// </summary>
public string Schema
{
[DebuggerStepThroughAttribute]
get { return _schema; }
}
/// <summary>
/// Gets the pattern that will be used to select the appropriate name.
/// </summary>
public string Name
{
[DebuggerStepThroughAttribute]
get { return _name; }
}
/// <summary>
/// Gets the types of objects that this filter applies to.
/// </summary>
public EntityStoreSchemaFilterObjectTypes Types
{
[DebuggerStepThroughAttribute]
get { return _types; }
}
/// <summary>
/// Gets the effect that this filter has on results.
/// </summary>
public EntityStoreSchemaFilterEffect Effect
{
[DebuggerStepThroughAttribute]
get { return _effect; }
}
}
}

View File

@@ -0,0 +1,35 @@
//---------------------------------------------------------------------
// <copyright file="EntityStoreSchemaFilterObjectTypes.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.Entity.Design
{
/// <summary>
/// The type of store object to apply this filter to
/// </summary>
[Flags]
public enum EntityStoreSchemaFilterObjectTypes
{
/// <summary>
/// The value that this enum will initilize to.
/// This is not a valid value to be use.
/// </summary>
None = 0x0000,
/// <summary>Apply this filter to table object types.</summary>
Table = 0x0001,
/// <summary>Apply this filter to view object types.</summary>
View = 0x0002,
/// <summary>Apply this filter to function object types.</summary>
Function = 0x0004,
/// <summary>Apply this filter to all possible object types.</summary>
All = Table | View | Function,
}
}

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