Exemple #1
0
        internal UpdatedModelSummary(EFArtifact artifact)
        {
            _artifact = artifact;

            Debug.Assert(artifact != null, "Null artifact");

            if (artifact != null)
            {
                if (null != artifact.MappingModel() &&
                    null != artifact.MappingModel().FirstEntityContainerMapping)
                {
                    RecordEntityTypeIdentities(
                        artifact.MappingModel().FirstEntityContainerMapping);

                    // build the association summary
                    _associationSummary = AssociationSummary.ConstructAssociationSummary(artifact);
                }

                if (null != artifact.StorageModel() &&
                    null != artifact.StorageModel().FirstEntityContainer)
                {
                    var sec = artifact.StorageModel().FirstEntityContainer as StorageEntityContainer;
                    if (sec != null)
                    {
                        RecordStorageProperties(sec);
                    }
                }
            }
        }
        public static AssociationEnd GetFreshAssociationEnd(this EFArtifact artifact, string associationTypeName, int index)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(associationTypeName), "!string.IsNullOrWhiteSpace(associationTypeName)");

            return(GetFreshAssociation(artifact, associationTypeName).AssociationEnds()[index]);
        }
        public static FunctionImport GetFreshFunctionImport(this EFArtifact artifact, string functionImportName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(functionImportName), "!string.IsNullOrWhiteSpace(functionImportName)");

            return((FunctionImport)artifact.ConceptualModel().EntityContainers().Single().GetFirstNamedChildByLocalName(functionImportName));
        }
        public static ConceptualEntityType GetFreshConceptualEntity(this EFArtifact artifact, string entityTypeName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(entityTypeName), "!string.IsNullOrWhiteSpace(entityTypeName)");

            return(artifact.GetConceptualChildByName <ConceptualEntityType>(entityTypeName));
        }
        public static Association GetFreshAssociation(this EFArtifact artifact, string associationTypeName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(associationTypeName), "!string.IsNullOrWhiteSpace(associationTypeName)");

            return(artifact.GetConceptualChildByName <Association>(associationTypeName));
        }
        public static Function GetFreshStorageFunction(this EFArtifact artifact, string functionName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(functionName), "!string.IsNullOrWhiteSpace(functionName)");

            return(artifact.GetStorageChildByName <Function>(functionName));
        }
        public static StorageEntityType GetFreshStorageEntity(this EFArtifact artifact, string entityTypeName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(entityTypeName), "!string.IsNullOrWhiteSpace(entityTypeName)");

            return(artifact.GetStorageChildByName <StorageEntityType>(entityTypeName));
        }
        internal UpdatedModelSummary(EFArtifact artifact)
        {
            _artifact = artifact;

            Debug.Assert(artifact != null, "Null artifact");

            if (artifact != null)
            {
                if (null != artifact.MappingModel()
                    && null != artifact.MappingModel().FirstEntityContainerMapping)
                {
                    RecordEntityTypeIdentities(
                        artifact.MappingModel().FirstEntityContainerMapping);

                    // build the association summary
                    _associationSummary = AssociationSummary.ConstructAssociationSummary(artifact);
                }

                if (null != artifact.StorageModel()
                    && null != artifact.StorageModel().FirstEntityContainer)
                {
                    var sec = artifact.StorageModel().FirstEntityContainer as StorageEntityContainer;
                    if (sec != null)
                    {
                        RecordStorageProperties(sec);
                    }
                }
            }
        }
Exemple #9
0
        internal static void ProcessStoredProcedureReturnTypeInformation(
            EFArtifact artifact,
            Dictionary <EntityStoreSchemaFilterEntry, IDataSchemaProcedure> newFunctionSchemaProceduresMap, IList <Command> commands,
            bool shouldCreateComposableFunctionImports)
        {
            if (null == artifact)
            {
                Debug.Fail("null artifact");
                return;
            }

            if (null == newFunctionSchemaProceduresMap)
            {
                Debug.Fail("Null newFunctionSchemaProceduresMap for artifact " + artifact.Uri);
                return;
            }

            var sem = artifact.StorageModel();

            if (null == sem)
            {
                Debug.Fail("Null StorageEntityModel for artifact " + artifact.Uri);
                return;
            }

            var storageEntityContainerName = sem.FirstEntityContainer.LocalName.Value;

            if (string.IsNullOrWhiteSpace(storageEntityContainerName))
            {
                Debug.Fail("Null or whitespace StorageEntityContainerName for artifact " + artifact.Uri);
                return;
            }

            foreach (var entry in newFunctionSchemaProceduresMap.Keys)
            {
                var     schemaProcedure = newFunctionSchemaProceduresMap[entry];
                Command cmd             = null;
                if (null == schemaProcedure)
                {
                    // schemaProcedure information was not collected - so delete the Function
                    var dbObj = DatabaseObject.CreateFromEntityStoreSchemaFilterEntry(entry, storageEntityContainerName);
                    var func  = ModelHelper.FindFunction(sem, dbObj);
                    Debug.Assert(func != null, "Could not find Function to delete matching Database Object " + dbObj.ToString());
                    if (null != func)
                    {
                        cmd = func.GetDeleteCommand();
                    }
                }
                else
                {
                    cmd = new CreateMatchingFunctionImportCommand(schemaProcedure, shouldCreateComposableFunctionImports);
                }

                if (null != cmd)
                {
                    commands.Add(cmd);
                }
            }
        }
Exemple #10
0
 internal static void AddRule(CommandProcessorContext cpc, EFArtifact artifact, bool propagateNoneSGP)
 {
     if (null != artifact)
     {
         IIntegrityCheck check = new PropagateStoreGeneratedPatternToStorageModel(cpc, artifact, propagateNoneSGP);
         cpc.AddIntegrityCheck(check);
     }
 }
Exemple #11
0
 private static string GetReturnType(IRawDataSchemaProcedure procedure, EFArtifact artifact)
 {
     if (procedure.RawReturnValue != null)
     {
         return(GetParameterType(procedure.RawReturnValue, artifact));
     }
     return(null);
 }
 internal static void AddRule(CommandProcessorContext cpc, EFArtifact artifact)
 {
     if (artifact != null)
     {
         IIntegrityCheck check = new PropagateStoragePropertyFacetsToConceptualModel(cpc, artifact);
         cpc.AddIntegrityCheck(check);
     }
 }
 private EfiTransaction(EFArtifact artifact, string originatorId, bool createdXmlTxn, EfiTransactionContext context)
 {
     _artifact              = artifact;
     _changes               = new EfiChangeGroup(this);
     _createdXmlTxn         = createdXmlTxn;
     _originatorId          = originatorId;
     _efiTransactionContext = context != null ? context : new EfiTransactionContext();
 }
Exemple #14
0
        private static void UpdateMappingModel(EFArtifact existingArtifact, string oldStorageEntityContainerName)
        {
            // replaces the possible reference to the old S-side EntityContainer name
            ReplaceMappingContainerRef(existingArtifact, oldStorageEntityContainerName);

            // normalize and resolve the changes we just made above
            XmlModelHelper.NormalizeAndResolve(existingArtifact.MappingModel());
        }
Exemple #15
0
        private void LoadDesignerInfoAndDescriptors(EditingContext editingContext, EFArtifact artifact)
        {
            if (artifact != null &&
                artifact.DesignerInfo() != null)
            {
                DesignerInfo connectionDesignerInfo = null;
                DesignerInfo optionsDesignerInfo    = null;

                var foundConnectionDesignerInfo = artifact.DesignerInfo()
                                                  .TryGetDesignerInfo(ConnectionDesignerInfo.ElementName, out connectionDesignerInfo);

                if (foundConnectionDesignerInfo)
                {
                    var connectionDesigner = connectionDesignerInfo as ConnectionDesignerInfo;
                    Debug.Assert(connectionDesigner != null, "DesignerInfo with element name 'Connection' must be a ConnectionDesignerInfo");

                    if (connectionDesigner != null)
                    {
                        // if the owner of the edmx file is a website, then we can
                        // only have one possible value (EmbedInOutputAssembly) for metadata artifact processing
                        // however the item template just adds CopyToOutputDirectory, so we need to fix it
                        var project = VSHelpers.GetProjectForDocument(artifact.Uri.LocalPath, PackageManager.Package);
                        if (project != null)
                        {
                            var appType = VsUtils.GetApplicationType(Services.ServiceProvider, project);
                            if (appType == VisualStudioProjectSystem.Website)
                            {
                                var mapDefault = ConnectionManager.GetMetadataArtifactProcessingDefault();
                                if (connectionDesigner.MetadataArtifactProcessingProperty != null &&
                                    connectionDesigner.MetadataArtifactProcessingProperty.ValueAttr.Value != mapDefault)
                                {
                                    var cpc = new CommandProcessorContext(
                                        editingContext, EfiTransactionOriginator.PropertyWindowOriginatorId,
                                        Resources.Tx_ChangeMetadataArtifactProcessing);
                                    var cmd =
                                        new UpdateDefaultableValueCommand <string>(
                                            connectionDesigner.MetadataArtifactProcessingProperty.ValueAttr, mapDefault);
                                    CommandProcessor.InvokeSingleCommand(cpc, cmd);
                                }
                            }
                        }

                        _EFConnectionDesignerInfoDescriptor = new EFConnectionDesignerInfoDescriptor();
                        _EFConnectionDesignerInfoDescriptor.Initialize(connectionDesigner, editingContext);
                    }
                }

                var foundOptionsDesignerInfo = artifact.DesignerInfo()
                                               .TryGetDesignerInfo(OptionsDesignerInfo.ElementName, out optionsDesignerInfo);

                if (foundOptionsDesignerInfo)
                {
                    _EFOptionsDesignerInfoDescriptor = new EFOptionsDesignerInfoDescriptor();
                    _EFOptionsDesignerInfoDescriptor.Initialize(optionsDesignerInfo as OptionsDesignerInfo, editingContext);
                }
            }
        }
        public static T GetStorageChildByName <T>(this EFArtifact artifact, string childName)
            where T : EFNameableItem
        {
            Debug.Assert(artifact != null, "artifact != null");

            var storageModel = artifact.StorageModel();

            return((T)storageModel.GetFirstNamedChildByLocalName(childName));
        }
        public static ConceptualEntityContainer GetFreshConceptualEntityContainer(this EFArtifact artifact, string entityContainerName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(entityContainerName), "!string.IsNullOrWhiteSpace(entityContainerName)");

            return
                ((ConceptualEntityContainer)
                 artifact.ConceptualModel().EntityContainers().SingleOrDefault(e => e.Name.Value == entityContainerName));
        }
        internal static string GetMslFromArtifact(EFArtifact artifact)
        {
            Debug.Assert(artifact != null, "Artifact is null ");
            if (artifact != null)
            {
                return(GetSchemaFromRuntimeModelRoot(artifact.MappingModel()));
            }

            return(String.Empty);
        }
        public static EntitySetMapping GetFreshEntitySetMapping(this EFArtifact artifact, string entitySetName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(entitySetName), "!string.IsNullOrWhiteSpace(entitySetName)");

            return
                (artifact.MappingModel()
                 .EntityContainerMappings().Single()
                 .EntitySetMappings().SingleOrDefault(m => m.Name.RefName == entitySetName));
        }
        public static AssociationSetMapping GetFreshAssociationSetMapping(this EFArtifact artifact, string associationSetMappingName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(associationSetMappingName), "!string.IsNullOrWhiteSpace(associationSetName)");

            return(artifact
                   .MappingModel()
                   .EntityContainerMappings().Single()
                   .AssociationSetMappings().SingleOrDefault(asm => asm.Name.Target.LocalName.Value == associationSetMappingName));
        }
        public static FunctionImportMapping GetFreshFunctionMapping(this EFArtifact artifact, string functionImportName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(functionImportName), "!string.IsNullOrWhiteSpace(functionImportName)");

            return
                (artifact.MappingModel()
                 .EntityContainerMappings().Single()
                 .FunctionImportMappings().SingleOrDefault(m => m.FunctionImportName.RefName == functionImportName));
        }
            internal DispatchToExtensionsCommand(ModelBuilderSettings settings)
            {
                _settings       = settings;
                _artifact       = settings.Artifact;
                _fromDbDocument = ((EdmxModelBuilderEngine)settings.ModelBuilderEngine).Edmx;
                _projectItem    = VsUtils.GetProjectItemForDocument(_artifact.Uri.LocalPath, PackageManager.Package);

                // make a copy of the artifact before any chagnes are done to it.  This is the "original document" that will be passed to extensions
                _originalDocument = XDocument.Parse(_artifact.XDocument.ToString(), LoadOptions.PreserveWhitespace);
            }
Exemple #23
0
        public static EditingContext GetEditingContext(this EFArtifact artifact)
        {
            Debug.Assert(artifact != null, "artifact != null");

            var service        = new EFArtifactService(artifact);
            var editingContext = new EditingContext();

            editingContext.SetEFArtifactService(service);
            return(editingContext);
        }
        private void PropagateAllStoragePropertyFacets(EFArtifact artifact)
        {
            var sModel = artifact.StorageModel();

            if (null == sModel)
            {
                Debug.Fail("null StorageEntityModel");
                return;
            }

            var cModel = artifact.ConceptualModel();

            if (null == cModel)
            {
                Debug.Fail("null ConceptualEntityModel");
                return;
            }

            // loop over every S-side Property
            foreach (var sSideEntityType in sModel.EntityTypes())
            {
                foreach (var sSideProperty in sSideEntityType.Properties())
                {
                    // add every mapped C-side Property whose parent is a C-side EntityType (as opposed to a ComplexType)
                    var cSideProperties = new HashSet <Property>();
                    foreach (var scalarProp in sSideProperty.GetAntiDependenciesOfType <ScalarProperty>())
                    {
                        // only count mappings through EntitySetMapping and EntityTypeMapping (MappingFragment only
                        // appears as a child in these kinds of mappings). Mappings through e.g.
                        // AssociationSetMapping do not identify the C-side properties to be updated.
                        if (scalarProp.GetParentOfType(typeof(MappingFragment)) != null)
                        {
                            var cSideProperty = scalarProp.Name.Target;
                            if (null != cSideProperty &&
                                null != cSideProperty.GetParentOfType(typeof(EntityType)) &&
                                false == cSideProperties.Contains(cSideProperty))
                            {
                                cSideProperties.Add(cSideProperty);
                            }
                        }
                    }

                    // propagate the facets for this S-side Property to all the C-side Properties that are mapped to it
                    foreach (var mappedCSideProperty in cSideProperties)
                    {
                        // for each mapped C-side Property, loop over all the facet-synchronizers invoking them
                        foreach (var facetSynchronizer in _facetSynchronizers)
                        {
                            facetSynchronizer.Invoke(sSideProperty, mappedCSideProperty);
                        }
                    }
                }
            }
        }
 private static bool IsArtifactDesignerSafe(EFArtifact artifact)
 {
     // if the artifact needs to be reloaded, treat it as designer-unsafe for our purposes.
     // this should only be the case when editing in the xml editor, and our selection container
     // gets invoked.
     if (artifact.RequireDelayedReload)
     {
         return(false);
     }
     return(artifact.IsDesignerSafe);
 }
        public static EntityTypeMapping GetFreshEntityTypeMapping(this EFArtifact artifact, string entitySetName, string entityTypeName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(entityTypeName), "!string.IsNullOrWhiteSpace(entityTypeName)");

            var entitySetMapping = GetFreshEntitySetMapping(artifact, entitySetName);

            return(entitySetMapping != null
                       ? entitySetMapping.EntityTypeMappings().SingleOrDefault(m => m.TypeName.RefName == entityTypeName)
                       : null);
        }
Exemple #27
0
        internal static AssociationSummary ConstructAssociationSummary(EFArtifact artifact)
        {
            var ecm = artifact.MappingModel().FirstEntityContainerMapping;

            var summary = new AssociationSummary();

            if (!EdmFeatureManager.GetForeignKeysInModelFeatureState(artifact.SchemaVersion).IsEnabled())
            {
                if (ecm != null)
                {
                    // Foreign keys in the model are not supported for this EDMX version.
                    foreach (var asm in ecm.AssociationSetMappings())
                    {
                        var cSideAssociation = asm.TypeName.Target;

                        if (null != cSideAssociation)
                        {
                            var assocId = AssociationIdentityForAssociationSetMapping.CreateAssociationIdentity(asm);
                            if (null != assocId)
                            {
                                summary.Add(cSideAssociation, assocId);
                            }
                        }
                    }
                }
            }
            else
            {
                // Foreign keys in the model are supported for this EDMX version.
                foreach (var a in artifact.ConceptualModel().Associations())
                {
                    AssociationIdentity assocId = null;
                    if (a.IsManyToMany == false &&
                        a.ReferentialConstraint != null)
                    {
                        assocId = AssociationIdentityForReferentialConstraint.CreateAssociationIdentity(a.ReferentialConstraint);
                    }
                    else
                    {
                        var asm = ModelHelper.FindAssociationSetMappingForConceptualAssociation(a);
                        if (asm != null)
                        {
                            assocId = AssociationIdentityForAssociationSetMapping.CreateAssociationIdentity(asm);
                        }
                    }
                    if (null != assocId)
                    {
                        summary.Add(a, assocId);
                    }
                }
            }
            return(summary);
        }
        public static ScalarProperty GetFreshScalarProperty(
            this EFArtifact artifact, string entitySetName, string entityTypeName, string propertyName)
        {
            var entityTypeMapping = GetFreshEntityTypeMapping(artifact, entitySetName, entityTypeName);

            return(entityTypeMapping != null
                       ? entityTypeMapping
                   .MappingFragments()
                   .SelectMany(m => m.ScalarProperties())
                   .SingleOrDefault(p => p.Name.Target.LocalName.Value == propertyName)
                       : null);
        }
        public static Condition GetFreshCondition(this EFArtifact artifact, string entitySetName, string columnName)
        {
            Debug.Assert(artifact != null, "artifact != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(entitySetName), "!string.IsNullOrWhiteSpace(entitySetName)");
            Debug.Assert(!string.IsNullOrWhiteSpace(columnName), "!string.IsNullOrWhiteSpace(columnName)");

            return(artifact.MappingModel()
                   .EntityContainerMappings()
                   .Single()
                   .EntitySetMappings().Single(m => m.Name.RefName == entitySetName)
                   .EntityTypeMappings().SelectMany(t => t.MappingFragments())
                   .SelectMany(f => f.Conditions()).SingleOrDefault(c => c.ColumnName.RefName == columnName));
        }
        private static void ValidateArtifact(EntityDesignModelManager modelManager, EFArtifact artifact, WizardKind kind)
        {
            var       errorsFound     = false;
            Exception caughtException = null;

            try
            {
                VsUtils.EnsureProvider(artifact);
                var artifactSet = (EntityDesignArtifactSet)modelManager.GetArtifactSet(artifact.Uri);
                modelManager.ValidateAndCompileMappings(artifactSet, false); // just run the runtime's validation
                var errors = artifactSet.GetAllErrorsForArtifact(artifact);
                if (errors != null &&
                    errors.Count > 0)
                {
                    foreach (var error in errors)
                    {
                        if (error.IsError())
                        {
                            errorsFound = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                caughtException = e;
            }

            if (errorsFound || caughtException != null)
            {
                var message = string.Empty;
                if (kind == WizardKind.Generate)
                {
                    message = Resources.Extensibility_ExtensionMadeBadModel;
                }
                else if (kind == WizardKind.UpdateModel)
                {
                    message = Resources.Extensibility_ExtensionMadeBadModel_Update;
                }

                if (caughtException == null)
                {
                    throw new InvalidOperationException(message);
                }
                else
                {
                    throw new InvalidOperationException(message, caughtException);
                }
            }
        }
        internal static string GetDatabaseSchemaNameFromArtifact(EFArtifact artifact)
        {
            var databaseSchemaName = ModelHelper.GetDesignerPropertyValueFromArtifact(
                OptionsDesignerInfo.ElementName, OptionsDesignerInfo.AttributeDatabaseSchemaName, artifact);

            if (String.IsNullOrEmpty(databaseSchemaName))
            {
                // There is probably not a DesignerProperty under the DesignerInfoPropertySet or there may not even
                // be a DesignerInfoPropertySet under the DesignerInfo. In this case, we will just use the default value
                // of the database schema name
                databaseSchemaName = DefaultDatabaseSchemaName;
            }
            return(databaseSchemaName);
        }
        internal CreateEntityContainerMappingCommand(EFArtifact artifact)
        {
            Debug.Assert(artifact != null, "artifact should not be null");
            Debug.Assert(
                artifact.ConceptualModel().EntityContainerCount == 1,
                "conceptual model EntityContainer count (" + artifact.ConceptualModel().EntityContainerCount + ") should be 1");
            Debug.Assert(
                artifact.StorageModel().EntityContainerCount == 1,
                "storage model EntityContainer count (" + artifact.StorageModel().EntityContainerCount + ") should be 1");
            Debug.Assert(
                artifact.MappingModel().FirstEntityContainerMapping == null, "mapping model FirstEntityContainer should not be null");

            _artifact = artifact;
        }
 /// <summary>
 ///     Note:  If createTransactionImmediately is set to true, the caller is responsible for calling CommandProcessor's FinalizeTransaction().  This is a bit wonky.  User can spin up a CommandProcessor
 ///     with this context, and then invoke that method on that command processor.
 /// </summary>
 /// <param name="editingContext"></param>
 /// <param name="originatorId"></param>
 /// <param name="transactionName"></param>
 /// <param name="artifact"></param>
 /// <param name="transactionContext"></param>
 /// <param name="createTransactionImmediately"></param>
 internal CommandProcessorContext(
     EditingContext editingContext, string originatorId, string transactionName, EFArtifact artifact,
     EfiTransactionContext transactionContext, bool createTransactionImmediately)
 {
     _editingContext = editingContext;
     _originatorId = originatorId;
     _transactionName = transactionName;
     _artifact = artifact;
     _transactionContext = transactionContext;
     if (createTransactionImmediately)
     {
         _transaction = CreateTransaction();
     }
 }
        internal static bool IsStorageModelEmpty(EFArtifact artifact)
        {
            var result = false;

            var storageModel = artifact.StorageModel();
            if (storageModel != null)
            {
                var container = storageModel.FirstEntityContainer as StorageEntityContainer;
                if (container != null)
                {
                    var element = container.Children.OfType<EFElement>().FirstOrDefault<EFElement>();
                    if (element == null)
                    {
                        result = true;
                    }
                }
            }

            return result;
        }
        private void FindNewStorageEntitySetsWithSameName(
            EFArtifact artifact, out HashSet<StorageEntitySet> storageEntitySetsWithSameNameButDifferentIdentity)
        {
            storageEntitySetsWithSameNameButDifferentIdentity = new HashSet<StorageEntitySet>();

            if (null != artifact
                && null != artifact.StorageModel()
                && null != artifact.StorageModel().FirstEntityContainer)
            {
                // set up Dictionary of EntitySetName to EntitySet for new (DB-based) artifact
                var newEntitySetMap = new Dictionary<string, EntitySet>();
                foreach (var newEntitySet in artifact.StorageModel().FirstEntityContainer.EntitySets())
                {
                    newEntitySetMap.Add(newEntitySet.LocalName.Value, newEntitySet);
                }

                // now compare all names - if we find a local name match compare identities
                // if they have the same name but different identities then add to returned HashSet
                foreach (var existingEntitySet in _preExistingModel.AllTablesAndViewsDictionary)
                {
                    var existingEntitySetLocalName = existingEntitySet.Value;

                    EntitySet newEntitySet;
                    if (newEntitySetMap.TryGetValue(existingEntitySetLocalName, out newEntitySet))
                    {
                        var newStorageEntitySet = newEntitySet as StorageEntitySet;
                        if (null != newStorageEntitySet)
                        {
                            // we have a StorageEntitySet in the DB-based artifact which is the
                            // same as one in the pre-existing artifact. Now compare identities.
                            var newEntitySetIdentity = DatabaseObject.CreateFromEntitySet(newStorageEntitySet);
                            var existingEntitySetIdentity = existingEntitySet.Key;
                            if (!newEntitySetIdentity.Equals(existingEntitySetIdentity))
                            {
                                storageEntitySetsWithSameNameButDifferentIdentity.Add(newStorageEntitySet);
                            }
                        }
                    }
                }
            }
        }
        internal ExistingModelSummary(EFArtifact artifact)
        {
            _artifact = artifact;
            if (null == artifact)
            {
                Debug.Fail("Null artifact");
            }
            else
            {
                if (null != artifact.MappingModel()
                    && null != artifact.MappingModel().FirstEntityContainerMapping)
                {
                    RecordEntityTypeIdentities(
                        artifact.MappingModel().FirstEntityContainerMapping);

                    // build the association summary.
                    _associationSummary = AssociationSummary.ConstructAssociationSummary(artifact);
                }

                if (null != artifact.ConceptualModel())
                {
                    RecordInheritanceAndEntityTypeMappings(artifact.ConceptualModel());
                }

                if (null != artifact.StorageModel())
                {
                    RecordFunctions(artifact.StorageModel());

                    if (null != artifact.StorageModel().FirstEntityContainer)
                    {
                        var sec = artifact.StorageModel().FirstEntityContainer as StorageEntityContainer;
                        if (sec != null)
                        {
                            RecordStorageEntitySetsAndProperties(sec);
                        }
                    }
                }
            }
        }
 internal PropagateStoreGeneratedPatternToStorageModel(CommandProcessorContext cpc, EFArtifact artifact, bool propagateNoneSGP)
 {
     _cpc = cpc;
     _artifact = artifact;
     _propagateNoneSGP = propagateNoneSGP;
 }
        internal static CreateFunctionCommand GetCreateFunctionCommandFromDataSchemaProcedure(
            IRawDataSchemaProcedure procedure, EFArtifact artifact, Func<Command, CommandProcessorContext, bool> bindingAction = null)
        {
            CreateFunctionCommand createFunctionCommand = null;
            if (procedure.IsFunction)
            {
                createFunctionCommand = new CreateFunctionCommand
                    (
                    name: ModelHelper.CreateValidSimpleIdentifier(procedure.Name),
                    schemaName: procedure.Schema,
                    isNiladic: !procedure.RawParameters.Any(),
                    isAggregate: false, // figure out if there's some way to determine this from IDataSchemaProcedure
                    isBuiltIn: false,
                    isComposable: true, // figure out if there's some way to determine this from IDataSchemaProcedure
                    commandText: null,
                    returnType: GetReturnType(procedure, artifact),
                    storeFunctionName: procedure.Name,
                    parameterInfos: GetParameterInfos(procedure, artifact),
                    dataSchemaProcedure: procedure,
                    bindingAction: bindingAction
                    );
            }
            else
            {
                createFunctionCommand = new CreateFunctionCommand
                    (
                    name: ModelHelper.CreateValidSimpleIdentifier(procedure.Name),
                    storeFunctionName: procedure.Name,
                    schemaName: procedure.Schema,
                    commandText: null,
                    parameterInfos: GetParameterInfos(procedure, artifact),
                    dataSchemaProcedure: procedure,
                    bindingAction: bindingAction
                    );
            }

            return createFunctionCommand;
        }
 internal static bool SynchronizePropertyFacetsDefault(EFArtifact artifact)
 {
     return artifact != null && artifact.IsSqlFamilyProvider();
 }
        internal static AssociationSummary ConstructAssociationSummary(EFArtifact artifact)
        {
            var ecm = artifact.MappingModel().FirstEntityContainerMapping;

            var summary = new AssociationSummary();

            if (!EdmFeatureManager.GetForeignKeysInModelFeatureState(artifact.SchemaVersion).IsEnabled())
            {
                if (ecm != null)
                {
                    // Foreign keys in the model are not supported for this EDMX version.
                    foreach (var asm in ecm.AssociationSetMappings())
                    {
                        var cSideAssociation = asm.TypeName.Target;

                        if (null != cSideAssociation)
                        {
                            var assocId = AssociationIdentityForAssociationSetMapping.CreateAssociationIdentity(asm);
                            if (null != assocId)
                            {
                                summary.Add(cSideAssociation, assocId);
                            }
                        }
                    }
                }
            }
            else
            {
                // Foreign keys in the model are supported for this EDMX version.
                foreach (var a in artifact.ConceptualModel().Associations())
                {
                    AssociationIdentity assocId = null;
                    if (a.IsManyToMany == false
                        && a.ReferentialConstraint != null)
                    {
                        assocId = AssociationIdentityForReferentialConstraint.CreateAssociationIdentity(a.ReferentialConstraint);
                    }
                    else
                    {
                        var asm = ModelHelper.FindAssociationSetMappingForConceptualAssociation(a);
                        if (asm != null)
                        {
                            assocId = AssociationIdentityForAssociationSetMapping.CreateAssociationIdentity(asm);
                        }
                    }
                    if (null != assocId)
                    {
                        summary.Add(a, assocId);
                    }
                }
            }
            return summary;
        }
        private static IEnumerable<ParameterDefinition> GetParameterInfos(IRawDataSchemaProcedure procedure, EFArtifact artifact)
        {
            var parameterInfos = new List<ParameterDefinition>();

            foreach (var dataSchemaParam in procedure.RawParameters.Where(p => p != null && p.Direction != ParameterDirection.ReturnValue))
            {
                // -1 means that the type is unknown
                if (dataSchemaParam.ProviderDataType != -1)
                {
                    var info = new ParameterDefinition();
                    parameterInfos.Add(info);
                    info.Name = ModelHelper.CreateValidSimpleIdentifier(dataSchemaParam.Name);

                    switch (dataSchemaParam.Direction)
                    {
                        case ParameterDirection.Input:
                            info.Mode = Parameter.InOutMode.In.ToString();
                            break;
                        case ParameterDirection.InputOutput:
                            info.Mode = Parameter.InOutMode.InOut.ToString();
                            break;
                        case ParameterDirection.Output:
                            info.Mode = Parameter.InOutMode.Out.ToString();
                            break;
                        case ParameterDirection.ReturnValue:
                        default:
                            Debug.Fail("Could not determine parameter mode");
                            info.Mode = Parameter.InOutMode.Unknown.ToString();
                            break;
                    }
                    info.Type = GetParameterType(dataSchemaParam, artifact);
                }
            }
            return parameterInfos;
        }
 internal CommandProcessorContext(
     EditingContext editingContext, string originatorId, string transactionName, EFArtifact artifact,
     EfiTransactionContext transactionContext)
     : this(editingContext, originatorId, transactionName, artifact, transactionContext, false)
 {
 }
        private void FindNewStorageFunctionsWithSameName(
            EFArtifact artifact, out HashSet<Function> storageFunctionsWithSameNameButDifferentIdentity)
        {
            storageFunctionsWithSameNameButDifferentIdentity = new HashSet<Function>();

            if (null != artifact
                && null != artifact.StorageModel())
            {
                // set up Dictionary of EntitySetName to EntitySet for new (DB-based) artifact
                var newFunctionMap = new Dictionary<string, Function>();
                foreach (var newFunction in artifact.StorageModel().Functions())
                {
                    newFunctionMap.Add(newFunction.LocalName.Value, newFunction);
                }

                // now compare all names - if we find a local name match compare identities
                // if they have the same name but different identities then add to returned HashSet
                foreach (var existingFunction in _preExistingModel.AllFunctionsDictionary)
                {
                    var existingFunctionLocalName = existingFunction.Value;

                    Function newFunction;
                    if (newFunctionMap.TryGetValue(existingFunctionLocalName, out newFunction))
                    {
                        if (null != newFunction)
                        {
                            // we have a Function in the DB-based artifact which is the
                            // same as one in the pre-existing artifact. Now compare identities.
                            var newFunctionIdentity = DatabaseObject.CreateFromFunction(newFunction);
                            var existingFunctionIdentity = existingFunction.Key;
                            if (!newFunctionIdentity.Equals(existingFunctionIdentity))
                            {
                                storageFunctionsWithSameNameButDifferentIdentity.Add(newFunction);
                            }
                        }
                    }
                }
            }
        }
        private static string GetParameterType(IRawDataSchemaParameter parameter, EFArtifact artifact)
        {
            var type = ModelHelper.GetPrimitiveType(artifact.StorageModel(), parameter.NativeDataType, parameter.ProviderDataType);
            if (type != null)
            {
                return type.Name;
            }

            Debug.Fail(
                "Unable to find EDM primitive type for DB type:" + parameter.NativeDataType + ", provider data type:"
                + parameter.ProviderDataType);

            return null;
        }
 public EFArtifactService(EFArtifact artifact)
 {
     _artifact = artifact;
 }
 private static string GetReturnType(IRawDataSchemaProcedure procedure, EFArtifact artifact)
 {
     if (procedure.RawReturnValue != null)
     {
         return GetParameterType(procedure.RawReturnValue, artifact);
     }
     return null;
 }
 public EFArtifactSet CreateArtifactSet(EFArtifact artifact)
 {
     return new EntityDesignArtifactSet(artifact);
 }
        private EFObject EdmSchemaError2EFObject(EdmSchemaError error, EFArtifact defaultArtifactForError)
        {
            EFArtifact a = null;
            if (error.SchemaLocation != null)
            {
                a = _modelManager.GetArtifact(Utils.FileName2Uri(error.SchemaLocation));
            }

            if (a == null)
            {
                a = defaultArtifactForError;
            }

            return a.FindEFObjectForLineAndColumn(error.Line, error.Column);
        }
        /// <summary>
        ///     This method returns true if the passed-in error code is one that requires the document to be opened in the XML editor,
        ///     with no designer.
        /// </summary>
        internal static bool IsOpenInEditorError(ErrorInfo errorInfo, EFArtifact artifact)
        {
            if ((errorInfo.ErrorClass & ErrorClass.Runtime_All) == 0)
            {
                return false;
            }

            var o = artifact.FindEFObjectForLineAndColumn(errorInfo.GetLineNumber(), errorInfo.GetColumnNumber());

            if (errorInfo.ErrorCode == (int)MappingErrorCode.XmlSchemaValidationError
                && o is ModificationFunctionMapping)
            {
                // we don't trigger safe-mode for XSD errors on ModificationFunctionMapping, since these can be fixed in the designer
                return false;
            }

            if (errorInfo.ErrorCode == (int)ErrorCode.XmlError
                && o is ReferentialConstraintRole)
            {
                // we don't trigger safe-mode for XSD errors on referential constraint roles.  This is so we can leave the RC 
                // and the Role, even if it has no properties.
                return false;
            }

            if (errorInfo.ErrorCode == (int)MappingErrorCode.ConditionError
                && o is Condition)
            {
                // don't trigger safe-mode for errors based around condition validation
                return false;
            }

            if (errorInfo.ErrorCode == (int)ErrorCode.InvalidPropertyInRelationshipConstraint
                && o is ReferentialConstraint)
            {
                // don't trigger safe-mode for error about Principal not being exactly identical to the EntityType key,
                // since we can run into this problem just by adding new key Property to the EntityType that is Principal Role for some Referential Constraint
                return false;
            }

            if (errorInfo.ErrorCode == ErrorCodes.ESCHER_VALIDATOR_UNDEFINED_COMPLEX_PROPERTY_TYPE
                || (errorInfo.ErrorCode == (int)ErrorCode.NotInNamespace && o is ComplexConceptualProperty))
            {
                // don't trigger safe-mode for underfined/deleted complex property types, the user should be able to fix the problem in the designer.
                return false;
            }

            if (errorInfo.ErrorCode == (int)ErrorCode.XmlError)
            {
                var navigationProperty = o as NavigationProperty;
                if (navigationProperty != null)
                {
                    // we allow the user to have navigation properties not bound to any association via an AssociationEnd if the Name property is defined as it's still required.
                    return
                        string.IsNullOrEmpty(navigationProperty.LocalName.Value) /* invalid name */||
                        navigationProperty.Relationship.Status != BindingStatus.Undefined ||
                        navigationProperty.ToRole.Status != BindingStatus.Undefined ||
                        navigationProperty.FromRole.Status != BindingStatus.Undefined;
                }
            }

            return
                UnrecoverableRuntimeErrors.SchemaObjectModelErrorCodes.Any(c => c == (ErrorCode)errorInfo.ErrorCode) ||
                UnrecoverableRuntimeErrors.StorageMappingErrorCodes.Any(c => c == (MappingErrorCode)errorInfo.ErrorCode);
        }
 private static XmlReader CreateXmlReader(EFArtifact artifact, XElement xobject)
 {
     var baseReader = xobject.CreateReader();
     var lineNumberService = new XNodeReaderLineNumberService(artifact.XmlModelProvider, baseReader, artifact.Uri);
     return new XmlReaderProxy(baseReader, artifact.Uri, lineNumberService);
 }
 internal UpdateModelFromDatabaseCommand(EFArtifact newArtifactFromDB)
 {
     _newArtifactFromDB = newArtifactFromDB;
 }
            AddAssociationSetMappingForConceptualAssociation(
            CommandProcessorContext cpc, EFArtifact existingArtifact,
            Association assocInTempArtifact, Association assocInExistingArtifact,
            Dictionary<EntityType, EntityType> tempArtifactCEntityTypeToNewCEntityTypeInExistingArtifact)
        {
            // first find the AssociationSetMapping in the tempArtifact for this association
            var asmInTempArtifact =
                ModelHelper.FindAssociationSetMappingForConceptualAssociation(assocInTempArtifact);
            if (asmInTempArtifact == null)
            {
                if (!EdmFeatureManager.GetForeignKeysInModelFeatureState(existingArtifact.SchemaVersion).IsEnabled()
                    || assocInTempArtifact.IsManyToMany)
                {
                    // this is an error condition - we should have an association set mapping in this case, so assert and throw an exception
                    throw new UpdateModelFromDatabaseException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.UpdateFromDatabaseAssociationSetMappingCannotFind,
                            assocInTempArtifact.ToPrettyString()));
                }
                else
                {
                    // we don't expect an association set mapping here
                    return;
                }
            }

            // next find the S-side EntitySet in the tempArtifact for this AssociationSetMapping
            var storeEntitySetInTempArtifact = asmInTempArtifact.StoreEntitySet.Target;
            if (storeEntitySetInTempArtifact == null)
            {
                throw new UpdateModelFromDatabaseException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.UpdateFromDatabaseAssociationSetMappingCannotFindTempSSideEntitySet,
                        asmInTempArtifact.ToPrettyString()));
            }

            // now find the S-side EntitySet in the existingArtifact which matches this
            // Note: LocalName's will be the same as the SSDL has been replaced
            StorageEntitySet storeEntitySetInExistingArtifact = null;
            foreach (var es in existingArtifact.StorageModel().FirstEntityContainer.EntitySets())
            {
                if (es.LocalName.Value == storeEntitySetInTempArtifact.LocalName.Value)
                {
                    storeEntitySetInExistingArtifact = es as StorageEntitySet;
                    break;
                }
            }

            if (storeEntitySetInExistingArtifact == null)
            {
                throw new UpdateModelFromDatabaseException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.UpdateFromDatabaseAssociationSetMappingCannotFindMatchingSSideEntitySet,
                        storeEntitySetInTempArtifact.LocalName.Value));
            }

            // now create a new AssociationSetMapping in the existingArtifact using the data
            // accumulated above
            CloneAssociationSetMapping(
                cpc,
                asmInTempArtifact,
                existingArtifact.MappingModel().FirstEntityContainerMapping,
                assocInExistingArtifact.AssociationSet,
                assocInExistingArtifact,
                storeEntitySetInExistingArtifact,
                tempArtifactCEntityTypeToNewCEntityTypeInExistingArtifact
                );
        }
        /// <summary>
        ///     Clone the Association with its ReferentialConstraint (if available), AssociationSet
        ///     and AssociationSetMapping. If the ReferentialConstraint is available in the temp artifact
        ///     but we cannot find matching properties in the existing artifact then the whole Association
        ///     (and AssociationSet and AssociationSetMapping) will not be cloned, a warning message will
        ///     be issued but otherwise the process is not stopped.
        ///     But if the Association cannot be created for any other reason that's an error and an
        ///     UpdateModelFromDatabaseException will be thrown.
        /// </summary>
        /// <param name="cpc">CommandProcessorContext for the commands to be issued</param>
        /// <param name="existingArtifact">the existing artifact in which to make these changes</param>
        /// <param name="assocInTempArtifact">the Association in the temp artifact to be cloned</param>
        /// <param name="end1InTempArtifact">the end of the Association in the temp artifact to be cloned to be treated as End1</param>
        /// <param name="end2InTempArtifact">the end of the Association in the temp artifact to be cloned to be treated as End2</param>
        /// <param name="navProp1InTempArtifact">the NavigationProperty for End1 in the temp artifact to be cloned</param>
        /// <param name="navProp2InTempArtifact">the NavigationProperty for End2 in the temp artifact to be cloned</param>
        /// <param name="end1EntityTypeInExistingArtifact">the EntityType in the existing artifact matching the End1 target in the temp artifact</param>
        /// <param name="end2EntityTypeInExistingArtifact">the EntityType in the existing artifact matching the End2 target in the temp artifact</param>
        /// <param name="tempArtifactCEntityTypeToNewCEntityTypeInExistingArtifact">
        ///     a Dictionary mapping temp artifact EntityTypes which have
        ///     been identified as new to their equivalent in the existing artifact
        /// </param>
        private void CloneAssociation(
            CommandProcessorContext cpc, EFArtifact existingArtifact, Association assocInTempArtifact,
            AssociationEnd end1InTempArtifact, AssociationEnd end2InTempArtifact,
            NavigationProperty navProp1InTempArtifact, NavigationProperty navProp2InTempArtifact,
            ConceptualEntityType end1EntityTypeInExistingArtifact, ConceptualEntityType end2EntityTypeInExistingArtifact,
            Dictionary<EntityType, EntityType> tempArtifactCEntityTypeToNewCEntityTypeInExistingArtifact)
        {
            Association newAssocInExistingArtifact = null;
            AssociationEnd newAssocEnd1 = null;
            AssociationEnd newAssocEnd2 = null;
            if (assocInTempArtifact.ReferentialConstraint == null)
            {
                // if there is no ReferentialConstraint to clone then just try to 
                // create the Association and AssociationSet
                var cmd = new CreateConceptualAssociationCommand(
                    assocInTempArtifact.LocalName.Value,
                    end1EntityTypeInExistingArtifact, end1InTempArtifact.Multiplicity.Value, navProp1InTempArtifact.LocalName.Value,
                    end2EntityTypeInExistingArtifact, end2InTempArtifact.Multiplicity.Value, navProp2InTempArtifact.LocalName.Value,
                    true, false);
                CommandProcessor.InvokeSingleCommand(cpc, cmd);
                newAssocInExistingArtifact = cmd.CreatedAssociation;
                newAssocEnd1 = cmd.End1;
                newAssocEnd2 = cmd.End2;
            }
            else
            {
                // There is a ReferentialConstraint - so we need to check whether we can find matching properties
                // for the Principal and Dependent roles of the ReferentialConstraint. If we can't find
                // matching properties then log a warning message and return. Otherwise attempt to create
                // the Association (and its AssociationSet) followed by a matching ReferentialConstraint.
                //
                // Note: ShouldCreateAssociationGivenReferentialConstraint() produces 2 sets of information:
                // (1) the sets of matching properties to use if we can find matching properties for the Principal
                // and Dependent roles, and (2) the sets of property names to include in the error message if 
                // we cannot find matching properties for the Principal and Dependent roles.
                // If ShouldCreateAssociationGivenReferentialConstraint() returns true we use the first set of
                // information to create the ReferentialConstraint after having created the Association and
                // AssociationSet. If it returns false we use the second set of information to construct the
                // warning message.
                var refConstraintInTempArtifact = assocInTempArtifact.ReferentialConstraint;
                bool end1IsPrincipalEnd;
                List<Property> principalPropertiesInExistingArtifact;
                List<Property> dependentPropertiesInExistingArtifact;
                List<string> unfoundPrincipalProperties;
                List<string> unfoundDependentProperties;
                if (ShouldCreateAssociationGivenReferentialConstraint(
                    refConstraintInTempArtifact, end1InTempArtifact,
                    end2InTempArtifact, end1EntityTypeInExistingArtifact, end2EntityTypeInExistingArtifact, out end1IsPrincipalEnd,
                    out principalPropertiesInExistingArtifact, out dependentPropertiesInExistingArtifact,
                    out unfoundPrincipalProperties, out unfoundDependentProperties))
                {
                    // create the new Association and AssociationSet
                    var cmd = new CreateConceptualAssociationCommand(
                        assocInTempArtifact.LocalName.Value,
                        end1EntityTypeInExistingArtifact, end1InTempArtifact.Multiplicity.Value, navProp1InTempArtifact.LocalName.Value,
                        end2EntityTypeInExistingArtifact, end2InTempArtifact.Multiplicity.Value, navProp2InTempArtifact.LocalName.Value,
                        true, false);
                    CommandProcessor.InvokeSingleCommand(cpc, cmd);
                    newAssocInExistingArtifact = cmd.CreatedAssociation;
                    newAssocEnd1 = cmd.End1;
                    newAssocEnd2 = cmd.End2;

                    // Add in the ReferentialConstraint for the new Association
                    if (null != newAssocInExistingArtifact)
                    {
                        AddReferentialConstraintForAssociation(
                            cpc, cmd, end1IsPrincipalEnd, principalPropertiesInExistingArtifact, dependentPropertiesInExistingArtifact);
                    }
                }
                else
                {
                    // Unable to find matching properties for the Principal and Dependent roles of 
                    // the ReferentialConstraint. So log a warning message.
                    newAssocInExistingArtifact = null;
                    EntityType principalEndEntityType = end1IsPrincipalEnd
                                                            ? end1EntityTypeInExistingArtifact
                                                            : end2EntityTypeInExistingArtifact;
                    EntityType dependentEndEntityType = end1IsPrincipalEnd
                                                            ? end2EntityTypeInExistingArtifact
                                                            : end1EntityTypeInExistingArtifact;
                    LogWarningMessageForReferentialConstraintProperties(
                        assocInTempArtifact.LocalName.Value,
                        principalEndEntityType, dependentEndEntityType, unfoundPrincipalProperties, unfoundDependentProperties);

                    // having logged the warning message we do not need to attempt to create
                    // the AssociationSetMapping nor throw an exception due to the lack of the
                    // created Association - so just return
                    return;
                }
            }

            // if we have failed to create an Association at this stage that's a serious error
            // so throw an exception to indicate the failure
            if (null == newAssocInExistingArtifact)
            {
                throw new UpdateModelFromDatabaseException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.UpdateFromDatabaseCannotCreateAssociation,
                        assocInTempArtifact.ToPrettyString()));
            }

            // update OnDeleteActions to match temp artifact
            UpdateOnDeleteAction(cpc, newAssocEnd1, end1InTempArtifact);
            UpdateOnDeleteAction(cpc, newAssocEnd2, end2InTempArtifact);

            // add a new AssociationSetMapping for the new Association
            AddAssociationSetMappingForConceptualAssociation(
                cpc, existingArtifact, assocInTempArtifact,
                newAssocInExistingArtifact, tempArtifactCEntityTypeToNewCEntityTypeInExistingArtifact);
        }
 internal static void AddRule(CommandProcessorContext cpc, EFArtifact artifact, bool propagateNoneSGP)
 {
     if (null != artifact)
     {
         IIntegrityCheck check = new PropagateStoreGeneratedPatternToStorageModel(cpc, artifact, propagateNoneSGP);
         cpc.AddIntegrityCheck(check);
     }
 }