src/Misc/EFTools/EntityDesign/VisualStudio/ModelWizard/ModelObjectItemWizard.cs
/// <summary>
///     This method is called at the end of a template wizard run
///     This lets us run custom wizard logic when the wizard has completed all tasks
///     We set up project item dependencies here for files added by the .vstemplate
/// </summary>
This method is called at the end of a template wizard run
This lets us run custom wizard logic when the wizard has completed all tasks
We set up project item dependencies here for files added by the .vstemplate
This method is called at the end of a template wizard run This lets us run custom wizard logic when the wizard has completed all tasks We set up project item dependencies here for files added by the . vstemplate
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
        public void RunFinished()
        {
            if (_edmxItem == null)
            {
                if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModelCodeFirst
                    || _modelBuilderSettings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase)
                {
                    Debug.Assert(
                        _modelBuilderSettings.ModelBuilderEngine == null ^
                        _modelBuilderSettings.GenerationOption == ModelGenerationOption.CodeFirstFromDatabase,
                        "Model should be null for Empty Model and not null CodeFirst from database");
                    AddCodeFirstItems();
                }
                return;
            }
            var fileExtension = Path.GetExtension(_edmxItem.FileNames[1]);
            Debug.Assert(
                _modelBuilderSettings.Project.Equals(_edmxItem.ContainingProject),
                "ActiveSolutionProject is not the EDMX file's containing project");
            using (new VsUtils.HourglassHelper())
            {
                var package = PackageManager.Package;
                Window window = null;
                try
                {
                    ConfigFileHelper.UpdateConfig(_modelBuilderSettings);
                    if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                    {
                        var writingModelWatch = new Stopwatch();
                        writingModelWatch.Start();
                        var modelEdmx = ((EdmxModelBuilderEngine)_modelBuilderSettings.ModelBuilderEngine).Edmx;
                        if (!string.Equals(fileExtension, EntityDesignArtifact.ExtensionEdmx, StringComparison.OrdinalIgnoreCase))
                        {
                            var edmxFileInfo = new FileInfo(_edmxItem.FileNames[1]);
                            var conversionContext = new ModelConversionContextImpl(
                                _edmxItem.ContainingProject,
                                _edmxItem,
                                edmxFileInfo,
                                _modelBuilderSettings.TargetSchemaVersion,
                                modelEdmx);
                            VSArtifact.DispatchToConversionExtensions(
                                EscherExtensionPointManager.LoadModelConversionExtensions(),
                                fileExtension,
                                conversionContext,
                                loading: false);
                            File.WriteAllText(edmxFileInfo.FullName, conversionContext.OriginalDocument);
                        }
                        else
                        {
                            using (var modelWriter = XmlWriter.Create(
                                _edmxItem.FileNames[1],
                                new XmlWriterSettings { Indent = true }))
                            {
                                modelEdmx.WriteTo(modelWriter);
                            }
                        }
                        writingModelWatch.Stop();
                        VsUtils.LogOutputWindowPaneMessage(
                            _edmxItem.ContainingProject,
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Properties.Resources.WritingModelTimeMsg,
                                writingModelWatch.Elapsed));
                    }
                    if (_modelBuilderSettings.VSApplicationType != VisualStudioProjectSystem.Website
                        && string.Equals(
                            fileExtension,
                            EntityDesignArtifact.ExtensionEdmx,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        _edmxItem.Properties.Item(ItemTypePropertyName).Value = EntityDeployBuildActionName;
                    }
                    window = _edmxItem.Open(Constants.vsViewKindPrimary);
                    Debug.Assert(window != null, "Unable to get window for created edmx file");
                }
                finally
                {
                    package.ModelGenErrorCache.RemoveErrors(_edmxItem.FileNames[1]);
                }
                var edmxFileUri = new Uri(_edmxItem.FileNames[1]);
                var designArtifact =
                    package.ModelManager.GetNewOrExistingArtifact(
                        edmxFileUri, new VSXmlModelProvider(package, package)) as EntityDesignArtifact;
                Debug.Assert(
                    designArtifact != null,
                    "artifact should be of type EntityDesignArtifact but received type " + designArtifact.GetType().FullName);
                Debug.Assert(
                    designArtifact.StorageModel != null, "designArtifact StorageModel cannot be null for Uri " + edmxFileUri.AbsolutePath);
                Debug.Assert(
                    designArtifact.ConceptualModel != null,
                    "designArtifact ConceptualModel cannot be null for Uri " + edmxFileUri.AbsolutePath);
                if (designArtifact != null
                    && designArtifact.StorageModel != null
                    && designArtifact.ConceptualModel != null)
                {
                    var designerSafeBeforeAddingTemplates = designArtifact.IsDesignerSafe;
                    var editingContext =
                        package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(designArtifact.Uri);
                    Debug.Assert(editingContext != null, "Null EditingContext for artifact " + edmxFileUri.AbsolutePath);
                    if (editingContext != null)
                    {
                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                        {
                            new DbContextCodeGenerator().AddDbContextTemplates(
                                _edmxItem,
                                _modelBuilderSettings.UseLegacyProvider);
                        }
                        var cp = PrepareCommandsAndIntegrityChecks(_modelBuilderSettings, editingContext, designArtifact);
                        if (DbContextCodeGenerator.TemplateSupported(_edmxItem.ContainingProject, package))
                        {
                            if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModel)
                            {
                                var cmd = EdmUtils.SetCodeGenStrategyToNoneCommand(designArtifact);
                                if (cmd != null)
                                {
                                    if (cp == null)
                                    {
                                        var cpc = new CommandProcessorContext(
                                            editingContext,
                                            EfiTransactionOriginator.CreateNewModelId,
                                            Resources.Tx_SetCodeGenerationStrategy);
                                        cp = new CommandProcessor(cpc, cmd);
                                    }
                                    else
                                    {
                                        cp.EnqueueCommand(cmd);
                                    }
                                }
                            }
                        }
                        else
                        {
                            VsUtils.AddProjectReference(_edmxItem.ContainingProject, "System.Data.Entity");
                        }
                        if (cp != null)
                        {
                            cp.Invoke();
                        }
                        _edmxItem.Save();
                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase
                            && !designerSafeBeforeAddingTemplates)
                        {
                            designArtifact.DetermineIfArtifactIsDesignerSafe();
                            if (designArtifact.IsDesignerSafe)
                            {
                                Debug.Assert(!designArtifact.IsDirty, "Reloading dirty artifact - changes will be lost.");
                                ((DocData)
                                 VSHelpers.GetDocData(package, designArtifact.Uri.LocalPath)).ReloadDocData(0);
                            }
                        }
                    }
                    if (window != null)
                    {
                        window.Activate();
                    }
                }
            }
        }
[ SuppressMessage ( " " , " " ) ] [ SuppressMessage ( " " , " " ) ] public void RunFinished ( ) { if ( _edmxItem == null ) { if ( _modelBuilderSettings . GenerationOption == ModelGenerationOption . EmptyModelCodeFirst || _modelBuilderSettings . GenerationOption == ModelGenerationOption . CodeFirstFromDatabase ) { Debug . Assert ( _modelBuilderSettings . ModelBuilderEngine == null ^ _modelBuilderSettings . GenerationOption == ModelGenerationOption . CodeFirstFromDatabase , " " ) ; AddCodeFirstItems ( ) ; } return ; } var fileExtension = Path . GetExtension ( _edmxItem . FileNames [ 1 ] ) ; Debug . Assert ( _modelBuilderSettings . Project . Equals ( _edmxItem . ContainingProject ) , " " ) ; using ( new VsUtils . HourglassHelper ( ) ) { var package = PackageManager . Package ; Window window = null ; try { ConfigFileHelper . UpdateConfig ( _modelBuilderSettings ) ; if ( _modelBuilderSettings . GenerationOption == ModelGenerationOption . GenerateFromDatabase ) { var writingModelWatch = new Stopwatch ( ) ; writingModelWatch . Start ( ) ; var modelEdmx = ( ( EdmxModelBuilderEngine ) _modelBuilderSettings . ModelBuilderEngine ) . Edmx ; if ( ! string . Equals ( fileExtension , EntityDesignArtifact . ExtensionEdmx , StringComparison . OrdinalIgnoreCase ) ) { var edmxFileInfo = new FileInfo ( _edmxItem . FileNames [ 1 ] ) ; var conversionContext = new ModelConversionContextImpl ( _edmxItem . ContainingProject , _edmxItem , edmxFileInfo , _modelBuilderSettings . TargetSchemaVersion , modelEdmx ) ; VSArtifact . DispatchToConversionExtensions ( EscherExtensionPointManager . LoadModelConversionExtensions ( ) , fileExtension , conversionContext , loading : false ) ; File . WriteAllText ( edmxFileInfo . FullName , conversionContext . OriginalDocument ) ; } else { using ( var modelWriter = XmlWriter . Create ( _edmxItem . FileNames [ 1 ] , new XmlWriterSettings { Indent = true } ) ) { modelEdmx . WriteTo ( modelWriter ) ; } } writingModelWatch . Stop ( ) ; VsUtils . LogOutputWindowPaneMessage ( _edmxItem . ContainingProject , string . Format ( CultureInfo . CurrentCulture , Properties . Resources . WritingModelTimeMsg , writingModelWatch . Elapsed ) ) ; } if ( _modelBuilderSettings . VSApplicationType != VisualStudioProjectSystem . Website && string . Equals ( fileExtension , EntityDesignArtifact . ExtensionEdmx , StringComparison . OrdinalIgnoreCase ) ) { _edmxItem . Properties . Item ( ItemTypePropertyName ) . Value = EntityDeployBuildActionName ; } window = _edmxItem . Open ( Constants . vsViewKindPrimary ) ; Debug . Assert ( window != null , " " ) ; } finally { package . ModelGenErrorCache . RemoveErrors ( _edmxItem . FileNames [ 1 ] ) ; } var edmxFileUri = new Uri ( _edmxItem . FileNames [ 1 ] ) ; var designArtifact = package . ModelManager . GetNewOrExistingArtifact ( edmxFileUri , new VSXmlModelProvider ( package , package ) ) as EntityDesignArtifact ; Debug . Assert ( designArtifact != null , " " + designArtifact . GetType ( ) . FullName ) ; Debug . Assert ( designArtifact . StorageModel != null , " " + edmxFileUri . AbsolutePath ) ; Debug . Assert ( designArtifact . ConceptualModel != null , " " + edmxFileUri . AbsolutePath ) ; if ( designArtifact != null && designArtifact . StorageModel != null && designArtifact . ConceptualModel != null ) { var designerSafeBeforeAddingTemplates = designArtifact . IsDesignerSafe ; var editingContext = package . DocumentFrameMgr . EditingContextManager . GetNewOrExistingContext ( designArtifact . Uri ) ; Debug . Assert ( editingContext != null , " " + edmxFileUri . AbsolutePath ) ; if ( editingContext != null ) { if ( _modelBuilderSettings . GenerationOption == ModelGenerationOption . GenerateFromDatabase ) { new DbContextCodeGenerator ( ) . AddDbContextTemplates ( _edmxItem , _modelBuilderSettings . UseLegacyProvider ) ; } var cp = PrepareCommandsAndIntegrityChecks ( _modelBuilderSettings , editingContext , designArtifact ) ; if ( DbContextCodeGenerator . TemplateSupported ( _edmxItem . ContainingProject , package ) ) { if ( _modelBuilderSettings . GenerationOption == ModelGenerationOption . EmptyModel ) { var cmd = EdmUtils . SetCodeGenStrategyToNoneCommand ( designArtifact ) ; if ( cmd != null ) { if ( cp == null ) { var cpc = new CommandProcessorContext ( editingContext , EfiTransactionOriginator . CreateNewModelId , Resources . Tx_SetCodeGenerationStrategy ) ; cp = new CommandProcessor ( cpc , cmd ) ; } else { cp . EnqueueCommand ( cmd ) ; } } } } else { VsUtils . AddProjectReference ( _edmxItem . ContainingProject , " " ) ; } if ( cp != null ) { cp . Invoke ( ) ; } _edmxItem . Save ( ) ; if ( _modelBuilderSettings . GenerationOption == ModelGenerationOption . GenerateFromDatabase && ! designerSafeBeforeAddingTemplates ) { designArtifact . DetermineIfArtifactIsDesignerSafe ( ) ; if ( designArtifact . IsDesignerSafe ) { Debug . Assert ( ! designArtifact . IsDirty , " " ) ; ( ( DocData ) VSHelpers . GetDocData ( package , designArtifact . Uri . LocalPath ) ) . ReloadDocData ( 0 ) ; } } } if ( window != null ) { window . Activate ( ) ; } } } }
This method is called at the end of a template wizard run
This lets us run custom wizard logic when the wizard has completed all tasks
We set up project item dependencies here for files added by the .vstemplate
This method is called at the end of a template wizard run This lets us run custom wizard logic when the wizard has completed all tasks We set up project item dependencies here for files added by the . vstemplate
// save the model generated in the wizard UI. // convert the file if this isn't EDMX // we need to use XmlWriter to output so that XmlDeclaration is preserved. // set the ItemType for the generated .edmx file // now open created file in VS using default viewer // Construct an editing context and make all final edits that require the file is opened. // Add DbContext templates when generation is GenerateFromDatabase. (connection is configured) // Create FunctionImports for every new Function // Add command setting CodeGenerationStrategy to "None" for EmptyModel. (connection is not yet configured) // NOTE: For EmptyModel, the templates will be added after the connection is configured. //       (i.e. during "Generate Database from Model" or "Refresh from Database") // Templates not supported, add reference to SDE. (.NET Framework 3.5) // save the artifact to make it look as though updates were part of creation // If the artifact became safe after adding references we need to reload it (this can happen  // on .NET Framework 4 where we would originally create a v3 edmx if the user selected EF6 -  // the artifact will be flagged as invalid since there is no runtime which could handle v3  // but after we added references to EF6 the artifacts becomes valid and need to be reloaded).  // Since the artifact was originally not valid we did not create the diagram for it.  // Using ReloadDocData will cause the diagram to be recreated. Note we don't need to  // reload the artifact itself since it has not changed.