internal GatherAndReturnSprocInfo(IList <EntityStoreSchemaFilterEntry> newFunctionEntries, ModelBuilderSettings modelBuilderSettings)
 {
     Debug.Assert(null != newFunctionEntries, "newFunctionEntries should not be null");
     Debug.Assert(null != modelBuilderSettings, "modelBuilderSettings should not be null");
     _newFunctionEntries   = newFunctionEntries;
     _modelBuilderSettings = modelBuilderSettings;
 }
Exemplo n.º 2
0
        internal static ICollection <EntityStoreSchemaFilterEntry> GetTablesFilterEntries(
            ModelBuilderSettings settings, DoWorkEventArgs args)
        {
            var entries = ExecuteDatabaseMetadataQuery(SelectTablesESqlQuery, EntityStoreSchemaFilterObjectTypes.Table, settings, args);

            return(entries);
        }
        private static void UpdateAppConfig(ICollection <string> metadataFiles, ModelBuilderSettings settings)
        {
            if (settings.SaveConnectionStringInAppConfig)
            {
                var statusMessage = string.Empty;

                try
                {
                    var manager = PackageManager.Package.ConnectionManager;
                    manager.AddConnectionString(
                        settings.Project,
                        metadataFiles,
                        settings.AppConfigConnectionPropertyName,
                        settings.AppConfigConnectionString,
                        settings.DesignTimeConnectionString,
                        settings.RuntimeProviderInvariantName,
                        settings.IsSql9OrNewer);
                    statusMessage = String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.Engine_AppConfigSuccess,
                        VsUtils.AppConfigFileName);
                }
                catch (Exception e)
                {
                    statusMessage = String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.Engine_AppConfigException,
                        e.Message);
                }
                VsUtils.LogOutputWindowPaneMessage(settings.Project, statusMessage);
            }
        }
Exemplo n.º 4
0
        private static void UpdateConfig(ICollection <string> metadataFiles, ModelBuilderSettings settings)
        {
            var statusMessage =
                VsUtils.IsWebProject(settings.VSApplicationType)
                    ? String.Format(CultureInfo.CurrentCulture, Resources.Engine_WebConfigSuccess, VsUtils.WebConfigFileName)
                    : String.Format(CultureInfo.CurrentCulture, Resources.Engine_AppConfigSuccess, VsUtils.AppConfigFileName);

            try
            {
                var manager = PackageManager.Package.ConnectionManager;
                manager.AddConnectionString(
                    settings.Project,
                    settings.VSApplicationType,
                    metadataFiles,
                    settings.AppConfigConnectionPropertyName,
                    settings.AppConfigConnectionString,
                    settings.RuntimeProviderInvariantName);
            }
            catch (Exception e)
            {
                statusMessage =
                    String.Format(
                        CultureInfo.CurrentCulture,
                        VsUtils.IsWebProject(settings.VSApplicationType)
                                ? Resources.Engine_WebConfigException
                                : Resources.Engine_AppConfigException,
                        e.Message);
            }
            VsUtils.LogOutputWindowPaneMessage(settings.Project, statusMessage);
        }
        /// <summary>
        ///     Updates app. or web.config to include connection strings, registers the build provider
        ///     for WebSite projects and the assembly for WebApp projects
        /// </summary>
        internal static void UpdateConfig(ModelBuilderSettings settings)
        {
            var metadataFileNames =
                ConnectionManager.GetMetadataFileNamesFromArtifactFileName(settings.Project, settings.ModelPath, PackageManager.Package);

            if (settings.GenerationOption == ModelGenerationOption.GenerateFromDatabase ||
                settings.GenerationOption == ModelGenerationOption.GenerateDatabaseScript)
            {
                if (settings.SaveConnectionStringInAppConfig &&
                    !settings.SaveToWebConfig)
                {
                    // save connection string in App Config
                    UpdateAppConfig(metadataFileNames, settings);
                }
                else if (settings.SaveConnectionStringInAppConfig &&
                         settings.SaveToWebConfig)
                {
                    // save connection string in Web Config
                    UpdateWebConfig(metadataFileNames, settings);
                }
            }

            var containingProject = settings.Project;

            // regardless of GenerationOption we always need to register the build
            // provider for web site projects and the assembly for web app projects
            if (settings.VSApplicationType == VisualStudioProjectSystem.Website)
            {
                RegisterBuildProvidersInWebConfig(containingProject);
            }

            // Ensure that System.Data.Entity.Design reference assemblies are added in the web.config.
            if (settings.VSApplicationType == VisualStudioProjectSystem.WebApplication ||
                settings.VSApplicationType == VisualStudioProjectSystem.Website)
            {
                // Get the correct assembly name based on target framework
                var projectHierarchy = VsUtils.GetVsHierarchy(containingProject, Services.ServiceProvider);
                Debug.Assert(projectHierarchy != null, "Could not get the IVsHierarchy from the EnvDTE.Project");
                if (projectHierarchy != null)
                {
                    var targetInfo = PackageManager.Package.GetService(typeof(SVsFrameworkMultiTargeting)) as IVsFrameworkMultiTargeting;
                    var openScope  = PackageManager.Package.GetService(typeof(SVsSmartOpenScope)) as IVsSmartOpenScope;
                    Debug.Assert(targetInfo != null, "Unable to get IVsFrameworkMultiTargeting from service provider");
                    var targetFrameworkMoniker = VsUtils.GetTargetFrameworkMonikerForProject(containingProject, PackageManager.Package);
                    if ((targetInfo != null) &&
                        (openScope != null) &&
                        settings.VSApplicationType == VisualStudioProjectSystem.Website)
                    {
                        var provider = new VsTargetFrameworkProvider(targetInfo, targetFrameworkMoniker, openScope);
                        var dataEntityDesignAssembly = provider.GetReflectionAssembly(new AssemblyName("System.Data.Entity.Design"));
                        if (dataEntityDesignAssembly != null)
                        {
                            RegisterAssemblyInWebConfig(containingProject, dataEntityDesignAssembly.FullName);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        public ModelGenerator(ModelBuilderSettings settings, string storeModelNamespace)
        {
            Debug.Assert(settings != null, "settings != null");
            Debug.Assert(
                !string.IsNullOrWhiteSpace(storeModelNamespace),
                "namespace must not be null or empty string.");

            _settings            = settings;
            _storeModelNamespace = storeModelNamespace;
        }
Exemplo n.º 7
0
            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);
            }
Exemplo n.º 8
0
 private static string GetStoreNamespace(ModelBuilderSettings settings)
 {
     return
         (string.IsNullOrEmpty(settings.StorageNamespace)
             ? String.Format(
              CultureInfo.CurrentCulture,
              Resources.SelectTablesPage_DefaultStorageNamespaceFormat,
              settings.ModelNamespace)
             : settings.StorageNamespace);
 }
Exemplo n.º 9
0
        public virtual void GenerateModel(ModelBuilderSettings settings, IVsUtils vsUtils = null,
                                          ModelBuilderEngineHostContext hostContext       = null)
        {
            if (settings.GenerationOption == ModelGenerationOption.GenerateFromDatabase &&
                String.IsNullOrEmpty(settings.DesignTimeConnectionString))
            {
                throw new ArgumentOutOfRangeException(Resources.Engine_EmptyConnStringErrorMsg);
            }

            var generatingModelWatch = Stopwatch.StartNew();

            hostContext = hostContext ?? new VSModelBuilderEngineHostContext(settings);
            vsUtils     = vsUtils ?? new VsUtilsWrapper();

            // Clear out the ModelGenErrorCache before ModelGen begins
            PackageManager.Package.ModelGenErrorCache.RemoveErrors(settings.ModelPath);

            var errors = new List <EdmSchemaError>();

            try
            {
                var storeModelNamespace = GetStoreNamespace(settings);
                Model = GenerateModels(storeModelNamespace, settings, errors);

                ProcessModel(Model, storeModelNamespace, settings, hostContext, errors);

                hostContext.LogMessage(
                    FormatMessage(
                        errors.Any()
                            ? Resources.Engine_ModelGenErrors
                            : Resources.Engine_ModelGenSuccess,
                        Path.GetFileName(settings.ModelPath)));

                if (errors.Any())
                {
                    PackageManager.Package.ModelGenErrorCache.AddErrors(settings.ModelPath, errors);
                }
            }
            catch (Exception e)
            {
                hostContext.LogMessage(FormatMessage(Resources.Engine_ModelGenException, e));
                // The exception we re-throw will get swallowed in the message pump and therefore we need to show the message box here.
                // It will also prevent the form.WizardFinished from being set to true which will cause cancelling the wizard and
                // therefore block adding new project items to the project as well as ModelObjectItemWizardFrom.RunFinished method.
                vsUtils.ShowErrorDialog(FormatMessage(Resources.Engine_ModelGenExceptionMessageBox, e.GetType().Name, e.Message));
                throw;
            }
            finally
            {
                generatingModelWatch.Stop();

                hostContext.LogMessage(FormatMessage(Resources.LoadingDBMetadataTimeMsg, settings.LoadingDBMetadataTime));
                hostContext.LogMessage(FormatMessage(Resources.GeneratingModelTimeMsg, generatingModelWatch.Elapsed));
            }
        }
Exemplo n.º 10
0
        protected virtual void UpdateDesignerInfo(EdmxHelper edmxHelper, ModelBuilderSettings settings)
        {
            Debug.Assert(edmxHelper != null);

            edmxHelper.UpdateDesignerOptionProperty(
                OptionsDesignerInfo.AttributeEnablePluralization, settings.UsePluralizationService);
            edmxHelper.UpdateDesignerOptionProperty(
                OptionsDesignerInfo.AttributeIncludeForeignKeysInModel, settings.IncludeForeignKeysInModel);
            edmxHelper.UpdateDesignerOptionProperty(
                OptionsDesignerInfo.AttributeUseLegacyProvider, settings.UseLegacyProvider);
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Generates EDMX file.
        /// </summary>
        public void GenerateModel(ModelBuilderSettings settings)
        {
            if (settings.GenerationOption == ModelGenerationOption.GenerateFromDatabase &&
                String.IsNullOrEmpty(settings.DesignTimeConnectionString))
            {
                throw new ArgumentOutOfRangeException(Resources.Engine_EmptyConnStringErrorMsg);
            }

            InitializeModelContents(settings.TargetSchemaVersion);

            GenerateModel(new EdmxHelper(Model), settings, new VSModelBuilderEngineHostContext(settings));
        }
Exemplo n.º 12
0
        private static FileInfo ConstructTempEdmxFile(ModelBuilderSettings settings)
        {
            var tempFilePath = Path.GetTempFileName().Replace(".tmp", EntityDesignArtifact.ExtensionEdmx);

            using (var fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
            {
                using (var sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.Write(((EdmxModelBuilderEngine)settings.ModelBuilderEngine).Edmx.ToString());
                }
            }
            return(new FileInfo(tempFilePath));
        }
Exemplo n.º 13
0
        internal static ICollection <EntityStoreSchemaFilterEntry> GetFunctionsFilterEntries(
            ModelBuilderSettings settings, DoWorkEventArgs args)
        {
            ICollection <EntityStoreSchemaFilterEntry> entries;

            if (EdmFeatureManager.GetComposableFunctionImportFeatureState(settings.TargetSchemaVersion).IsEnabled())
            {
                entries = ExecuteDatabaseMetadataQuery(
                    SelectFunctionsESqlQuery, EntityStoreSchemaFilterObjectTypes.Function, settings, args);
            }
            else
            {
                entries = ExecuteDatabaseMetadataQuery(
                    SelectFunctionsESqlQueryBeforeV3, EntityStoreSchemaFilterObjectTypes.Function, settings, args);
            }

            return(entries);
        }
Exemplo n.º 14
0
        internal virtual void GenerateModel(EdmxHelper edmxHelper, ModelBuilderSettings settings, ModelBuilderEngineHostContext hostContext)
        {
            var generatingModelWatch = Stopwatch.StartNew();

            // Clear out the ModelGenErrorCache before ModelGen begins
            PackageManager.Package.ModelGenErrorCache.RemoveErrors(settings.ModelPath);

            var errors = new List <EdmSchemaError>();

            try
            {
                var storeModelNamespace = GetStoreNamespace(settings);
                var model = GenerateModels(storeModelNamespace, settings, errors);

                edmxHelper.UpdateEdmxFromModel(model, storeModelNamespace, settings.ModelNamespace, errors);

                // load extensions that want to update model after the wizard has run.
                hostContext.DispatchToModelGenerationExtensions();

                UpdateDesignerInfo(edmxHelper, settings);

                hostContext.LogMessage(
                    FormatMessage(
                        errors.Any()
                        ? Resources.Engine_ModelGenErrors
                        : Resources.Engine_ModelGenSuccess,
                        Path.GetFileName(settings.ModelPath)));

                if (errors.Any())
                {
                    PackageManager.Package.ModelGenErrorCache.AddErrors(settings.ModelPath, errors);
                }
            }
            catch (Exception e)
            {
                hostContext.LogMessage(FormatMessage(Resources.Engine_ModelGenException, e));
            }

            generatingModelWatch.Stop();

            hostContext.LogMessage(FormatMessage(Resources.LoadingDBMetadataTimeMsg, settings.LoadingDBMetatdataTime));
            hostContext.LogMessage(FormatMessage(Resources.GeneratingModelTimeMsg, generatingModelWatch.Elapsed));
        }
Exemplo n.º 15
0
 // internal virtual to allow mocking
 internal virtual DbModel GenerateModels(string storeModelNamespace, ModelBuilderSettings settings, List <EdmSchemaError> errors)
 {
     return(new ModelGenerator(settings, storeModelNamespace).GenerateModel(errors));
 }
Exemplo n.º 16
0
 protected override void UpdateDesignerInfo(EdmxHelper edmxHelper, ModelBuilderSettings settings)
 {
     // in the update model case, there is no need to fix up the designer info
     // since it would only be applied to the temporary artifact and then ignored
 }
Exemplo n.º 17
0
        // internal virtual to allow mocking
        protected override void ProcessModel(DbModel model, string storeModelNamespace, ModelBuilderSettings settings,
                                             ModelBuilderEngineHostContext hostContext, List <EdmSchemaError> errors)
        {
            Edmx = XDocument.Parse(_initialModelContentsFactory.GetInitialModelContents(settings.TargetSchemaVersion));

            var edmxHelper = new EdmxHelper(Edmx);

            edmxHelper.UpdateEdmxFromModel(model, storeModelNamespace, settings.ModelNamespace, errors);

            // load extensions that want to update model after the wizard has run.
            hostContext.DispatchToModelGenerationExtensions();

            UpdateDesignerInfo(edmxHelper, settings);
        }
Exemplo n.º 18
0
 internal void UpdateDesignerInfoInvoker(EdmxHelper edmxHelper, ModelBuilderSettings settings)
 {
     UpdateDesignerInfo(edmxHelper, settings);
 }
Exemplo n.º 19
0
 public void InvokeProcessModel(DbModel model, string storeModelNamespace, ModelBuilderSettings settings,
                                ModelBuilderEngineHostContext hostContext, List <EdmSchemaError> errors)
 {
     ProcessModel(model, storeModelNamespace, settings, hostContext, errors);
 }
Exemplo n.º 20
0
        /// <summary>
        ///     Helper method used to show the ProgressDialog and collect return type information about sprocs
        /// </summary>
        /// <param name="owner">Window that owns the dialog</param>
        /// <param name="newFunctionEntries">list of Functions for which we should collect information</param>
        /// <param name="modelBuilderSettings">ModelBuilderSettings where collected information will be stored</param>
        internal static DialogResult ShowProgressDialog(
            IWin32Window owner, IList <EntityStoreSchemaFilterEntry> newFunctionEntries, ModelBuilderSettings modelBuilderSettings)
        {
            var args = new GatherAndReturnSprocInfo(newFunctionEntries, modelBuilderSettings);

            using (var pd = new ProgressDialog(
                       Design.Resources.RetrievingSprocReturnTypeProgressDialogTitle,
                       Design.Resources.RetrievingSprocReturnTypeProgressDialogDescription,
                       Design.Resources.RetrievingSprocReturnTypeProgressDialogInitialStatus, GatherAndStoreSchemaProcedureInformation, args))
            {
                return(pd.ShowDialog(owner));
            }
        }
Exemplo n.º 21
0
        internal static void SetupSettingsAndModeForDbPages(
            IServiceProvider sp,
            Project project,
            EFArtifact artifact,
            bool checkDatabaseConnection,
            ModelBuilderWizardForm.WizardMode noConnectionMode,
            ModelBuilderWizardForm.WizardMode existingConnectionMode,
            out ModelBuilderWizardForm.WizardMode startMode,
            out ModelBuilderSettings settings)
        {
            var conceptualEntityModel = artifact.ConceptualModel();

            Debug.Assert(conceptualEntityModel != null, "Null Conceptual Entity Model");
            var entityContainer = conceptualEntityModel.FirstEntityContainer as ConceptualEntityContainer;

            Debug.Assert(entityContainer != null, "Null Conceptual Entity Container");
            var entityContainerName = entityContainer.LocalName.Value;

            // set up ModelBuilderSettings for startMode=noConnectionMode
            startMode = noConnectionMode;
            settings  = new ModelBuilderSettings();
            var appType = VsUtils.GetApplicationType(sp, project);

            settings.VSApplicationType = appType;
            settings.AppConfigConnectionPropertyName = entityContainerName;
            settings.Artifact          = artifact;
            settings.UseLegacyProvider = ModelHelper.GetDesignerPropertyValueFromArtifactAsBool(
                OptionsDesignerInfo.ElementName,
                OptionsDesignerInfo.AttributeUseLegacyProvider,
                OptionsDesignerInfo.UseLegacyProviderDefault,
                artifact);
            settings.TargetSchemaVersion = artifact.SchemaVersion;
            settings.Project             = project;
            settings.ModelPath           = artifact.Uri.LocalPath;

            // Get the provider manifest token from the existing SSDL.
            // We don't want to attempt to get it from provider services since this requires a connection
            // which will severely impact the performance of Model First in disconnected scenarios.
            settings.ProviderManifestToken = DatabaseGenerationEngine.GetProviderManifestTokenDisconnected(artifact);

            // Change startMode and settings appropriately depending on whether there is an existing connection string and whether we can/should connect
            // to the database
            var connectionString = ConnectionManager.GetConnectionStringObject(project, entityContainerName);

            if (connectionString != null)
            {
                var ecsb = connectionString.Builder;
                var runtimeProviderName                = ecsb.Provider;
                var runtimeProviderConnectionString    = ecsb.ProviderConnectionString;
                var designTimeProviderConnectionString = connectionString.GetDesignTimeProviderConnectionString(project);
                var initialCatalog = String.Empty;

                if (checkDatabaseConnection)
                {
                    // This path will check to make sure that we can connect to an existing database before changing the start mode to 'existingConnection'
                    IVsDataConnection dataConnection = null;
                    try
                    {
                        var dataConnectionManager = sp.GetService(typeof(IVsDataConnectionManager)) as IVsDataConnectionManager;
                        Debug.Assert(dataConnectionManager != null, "Could not find IVsDataConnectionManager");

                        var dataProviderManager = sp.GetService(typeof(IVsDataProviderManager)) as IVsDataProviderManager;
                        Debug.Assert(dataProviderManager != null, "Could not find IVsDataProviderManager");

                        if (dataConnectionManager != null &&
                            dataProviderManager != null)
                        {
                            // this will either get an existing connection or attempt to create a new one
                            dataConnection = DataConnectionUtils.GetDataConnection(
                                dataConnectionManager,
                                dataProviderManager,
                                connectionString.DesignTimeProviderInvariantName,
                                designTimeProviderConnectionString);
                            Debug.Assert(
                                dataConnection != null,
                                "Could not find the IVsDataConnection; an exception should have been thrown if this was the case");
                            if (dataConnection != null)
                            {
                                VsUtils.EnsureProvider(runtimeProviderName, settings.UseLegacyProvider, project, sp);

                                if (CanCreateAndOpenConnection(
                                        new StoreSchemaConnectionFactory(),
                                        runtimeProviderName,
                                        connectionString.DesignTimeProviderInvariantName,
                                        designTimeProviderConnectionString))
                                {
                                    startMode      = existingConnectionMode;
                                    initialCatalog = DataConnectionUtils.GetInitialCatalog(dataProviderManager, dataConnection);
                                }
                            }
                        }
                    }
                    catch
                    {
                        // do nothing - we will go to WizardPageDbConfig which is
                        // what we want if the DB connection fails
                    }
                    finally
                    {
                        // Close the IVsDataConnection
                        if (dataConnection != null)
                        {
                            try
                            {
                                dataConnection.Close();
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                else
                {
                    // This path will just parse the existing connection string in order to change the start mode. This is ideal for features
                    // that do not need a database connection -- the information in the connection string is enough.
                    startMode      = existingConnectionMode;
                    initialCatalog = DataConnectionUtils.GetInitialCatalog(
                        connectionString.DesignTimeProviderInvariantName, designTimeProviderConnectionString);
                }

                if (startMode == existingConnectionMode)
                {
                    // the invariant name and connection string came from app.config, so they are "runtime" invariant names and not "design-time"
                    // (Note: it is OK for InitialCatalog to be null at this stage e.g. from a provider who do not support the concept of Initial Catalog)
                    settings.SetInvariantNamesAndConnectionStrings(
                        project,
                        runtimeProviderName,
                        runtimeProviderConnectionString,
                        runtimeProviderConnectionString,
                        false);
                    settings.InitialCatalog = initialCatalog;
                    settings.AppConfigConnectionPropertyName = entityContainerName;
                    settings.SaveConnectionStringInAppConfig = false;

                    VsUtils.EnsureProvider(runtimeProviderName, settings.UseLegacyProvider, project, sp);
                }
            }
        }
Exemplo n.º 22
0
 protected abstract void ProcessModel(
     DbModel model, string storeModelNamespace, ModelBuilderSettings settings,
     ModelBuilderEngineHostContext hostContext, List <EdmSchemaError> errors);
Exemplo n.º 23
0
        private static ICollection <EntityStoreSchemaFilterEntry> ExecuteDatabaseMetadataQuery(
            string esqlQuery, EntityStoreSchemaFilterObjectTypes types, ModelBuilderSettings settings, DoWorkEventArgs args)
        {
            var filterEntries = new List <EntityStoreSchemaFilterEntry>();

            EntityConnection ec = null;

            try
            {
                Version actualEntityFrameworkConnectionVersion;
                ec = new StoreSchemaConnectionFactory().Create(
                    DependencyResolver.Instance,
                    settings.RuntimeProviderInvariantName,
                    settings.DesignTimeConnectionString,
                    settings.TargetSchemaVersion,
                    out actualEntityFrameworkConnectionVersion);

                // if the provider does not support V3 and we are querying for Functions then switch to the pre-V3 query
                if (actualEntityFrameworkConnectionVersion < EntityFrameworkVersion.Version3 &&
                    SelectFunctionsESqlQuery.Equals(esqlQuery, StringComparison.Ordinal))
                {
                    esqlQuery = SelectFunctionsESqlQueryBeforeV3;
                }

                using (var command = new EntityCommand(null, ec, DependencyResolver.Instance))
                {
                    // NOTE:  DO NOT set the command.CommandTimeout value.  Some providers don't support a non-zero value, and will throw (eg, SqlCE provider).
                    // The System.Data.SqlClient's default value is 15, so we will still get a timeout for sql server.

                    command.CommandType = CommandType.Text;
                    command.CommandText = esqlQuery;
                    ec.Open();
                    DbDataReader reader = null;
                    try
                    {
                        reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
                        while (reader.Read())
                        {
                            if (args != null &&
                                args.Cancel)
                            {
                                break;
                            }

                            if (reader.FieldCount == 3)
                            {
                                // the types coming back through the reader may not be a string
                                // (eg, SqlCE returns System.DbNull for catalogName & schemaName), so cast carefully
                                var catalogName = reader.GetValue(0) as String;
                                var schemaName  = reader.GetValue(1) as String;
                                var name        = reader.GetValue(2) as String;

                                if (String.IsNullOrEmpty(name) == false)
                                {
                                    filterEntries.Add(
                                        new EntityStoreSchemaFilterEntry(
                                            catalogName, schemaName, name, types, EntityStoreSchemaFilterEffect.Allow));
                                }
                            }
                            else
                            {
                                Debug.Fail("Unexpected field count in reader");
                            }
                        }
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            try
                            {
                                reader.Close();
                                reader.Dispose();
                            }
                            catch (Exception)
                            {
                                Debug.Fail(
                                    "Could not close the DbDataReader in ExecuteDatabaseMetadataQuery(). If this is the result of a connection to a database file, it will leave a read lock on the file.");
                            }
                        }
                    }
                }
            }
            finally
            {
                if (ec != null)
                {
                    try
                    {
                        ec.Close();
                        ec.Dispose();
                    }
                    catch (Exception)
                    {
                        Debug.Fail(
                            "Could not close the EntityConnection in ExecuteDatabaseMetadataQuery(). If this is a connection to a database file, it will leave a read lock on the file.");
                    }
                }
            }

            return(filterEntries);
        }
 internal DatabaseConnectionSsdlAggregator(ModelBuilderSettings settings)
 {
     _settings = settings;
 }
Exemplo n.º 25
0
        private static bool ProcessAccumulatedInfo(
            EditingContext editingContext, EntityDesignArtifact existingArtifact, ModelBuilderSettings settings)
        {
            var schemaVersionChanged = existingArtifact.SchemaVersion != settings.TargetSchemaVersion;

            EntityDesignModelManager tempModelManager = null;
            FileInfo tempEdmxFile    = null;
            Uri      tempEdmxFileUri = null;

            try
            {
                // set up new temporary ModelManager
                // NOTE:  use an EFArtifact with VSArtifactSet.  This is so we get the in-vs behavior of artifact sets,
                // but don't rely on VS loading the model into the RDT, etc..
                tempModelManager = new EntityDesignModelManager(new EFArtifactFactory(), new VSArtifactSetFactory());

                tempEdmxFile    = ConstructTempEdmxFile(settings);
                tempEdmxFileUri = new Uri(tempEdmxFile.FullName, UriKind.Absolute);
                var tempArtifactBasedOnDatabase = tempModelManager.GetNewOrExistingArtifact(tempEdmxFileUri, new VanillaXmlModelProvider());

                // if a model generation extension has changed the model, ensure that it is
                // valid before we start to process it
                if (settings.HasExtensionChangedModel)
                {
                    ValidateArtifact(tempModelManager, tempArtifactBasedOnDatabase, WizardKind.Generate);
                }

                // Note: later we want the diagram shapes and connectors to be created in the current active diagram
                // so set TransactionContext appropriately.
                EfiTransactionContext transactionContext = null;
                var contextItem = editingContext.Items.GetValue <DiagramManagerContextItem>();
                if (contextItem != null &&
                    contextItem.DiagramManager != null)
                {
                    var activeDiagram = contextItem.DiagramManager.ActiveDiagram;
                    if (activeDiagram != null)
                    {
                        transactionContext = new EfiTransactionContext();
                        transactionContext.Add(
                            EfiTransactionOriginator.TransactionOriginatorDiagramId, new DiagramContextItem(activeDiagram.DiagramId));
                    }
                }

                // clear search if active (Note: in Model.Tests it is OK for below to be null)
                var explorerInfo = editingContext.Items.GetValue <ExplorerWindow.ExplorerInfo>();
                if (explorerInfo != null)
                {
                    var explorerFrame = explorerInfo._explorerFrame;
                    if (explorerFrame != null)
                    {
                        if (explorerFrame.SearchIsActive)
                        {
                            explorerFrame.ResetSearchCommand.Execute(null);
                        }
                    }
                }

                var cpc = new CommandProcessorContext(
                    editingContext, EfiTransactionOriginator.UpdateModelFromDatabaseId,
                    Resources.Tx_UpdateModelFromDatabase, null, transactionContext);

                if (schemaVersionChanged)
                {
                    // changing namespaces must be done in a separate transaction otherwise XmlEditor
                    // will not pick-up changes made to xml after namespaces are changed
                    CommandProcessor.InvokeSingleCommand(
                        cpc,
                        new RetargetXmlNamespaceCommand(existingArtifact, settings.TargetSchemaVersion));
                }

                // Update the existing artifact based on tempArtifactBasedOnDatabase
                var commands = new List <Command>();
                var cmd      = new UpdateModelFromDatabaseCommand(tempArtifactBasedOnDatabase);
                commands.Add(cmd);

                // set up our post event to clear out the error list
                cmd.PostInvokeEvent +=
                    (o, e) =>
                {
                    var errorList =
                        ErrorListHelper.GetSingleDocErrorList(e.CommandProcessorContext.Artifact.Uri);
                    if (errorList != null)
                    {
                        errorList.Clear();
                    }
                };

                DesignerInfo designerInfo;
                if (existingArtifact.DesignerInfo().TryGetDesignerInfo(OptionsDesignerInfo.ElementName, out designerInfo))
                {
                    var optionsDesignerInfo = designerInfo as OptionsDesignerInfo;
                    Debug.Assert(optionsDesignerInfo != null, "expected non-null optionsDesignerInfo");
                    if (optionsDesignerInfo != null)
                    {
                        // pluralization checkbox
                        AddUpdateDesignerPropertyCommand(
                            optionsDesignerInfo.CheckPluralizationInWizard,
                            OptionsDesignerInfo.AttributeEnablePluralization,
                            settings.UsePluralizationService, optionsDesignerInfo, commands);

                        // include FKs in model checkbox
                        AddUpdateDesignerPropertyCommand(
                            optionsDesignerInfo.CheckIncludeForeignKeysInModel,
                            OptionsDesignerInfo.AttributeIncludeForeignKeysInModel,
                            settings.IncludeForeignKeysInModel, optionsDesignerInfo, commands);

                        // ensure UseLegacyProvider is set
                        AddUpdateDesignerPropertyCommand(
                            optionsDesignerInfo.UseLegacyProvider,
                            OptionsDesignerInfo.AttributeUseLegacyProvider,
                            settings.UseLegacyProvider, optionsDesignerInfo, commands);
                    }
                }

                // create a new FunctionImport for every new Function created (whether composable or not)
                // (or delete Functions if ProgressDialog did not finish successfully)
                // Note: this must take place as a DelegateCommand as ProcessStoredProcedureReturnTypeInformation()
                // can depend on finding the existing Functions to delete. And it won't find them until the
                // ReplaceSsdlCommand within UpdateModelFromDatabaseCommand has executed.
                var createMatchingFunctionImportsDelegateCommand = new DelegateCommand(
                    () =>
                {
                    var functionImportCommands = new List <Command>();
                    ProgressDialogHelper.ProcessStoredProcedureReturnTypeInformation(
                        existingArtifact, settings.NewFunctionSchemaProcedures, functionImportCommands, true);

                    if (functionImportCommands.Count > 0)
                    {
                        new CommandProcessor(cpc, functionImportCommands)
                        .Invoke();
                    }
                });
                commands.Add(createMatchingFunctionImportsDelegateCommand);

                // if needed, create a command to dispatch any extensions
                if (EscherExtensionPointManager.LoadModelGenerationExtensions().Length > 0)
                {
                    var dispatchCommand = new DispatchToExtensionsCommand(settings);
                    commands.Add(dispatchCommand);
                }

                // do all the work here in one transaction
                new CommandProcessor(cpc, commands)
                .Invoke();

                // if an extension has changed the model, do a full reload
                if (schemaVersionChanged || settings.HasExtensionChangedModel)
                {
                    return(true);
                }
                else
                {
                    // reset the is-designer safe flag - this can be set incorrectly when the document is reloaded after ssdl has been updated,
                    // but csdl & msl haven't.  Here, the model is correct, but we need to get views to refresh themselves after we
                    // reset the is-designer-safe flag.
                    // Perf note: reloading the artifact can take some time - so only reload if IsDesignerSafe has changed
                    var isDesignerSafeBefore = existingArtifact.IsDesignerSafe;
                    existingArtifact.DetermineIfArtifactIsDesignerSafe();
                    var isDesignerSafeAfter = existingArtifact.IsDesignerSafe;
                    if (isDesignerSafeAfter != isDesignerSafeBefore)
                    {
                        existingArtifact.FireArtifactReloadedEvent();
                    }
                }
            }
            finally
            {
                // remove tempArtifactBasedOnDatabase to dispose EFObject's properly
                if (tempEdmxFileUri != null &&
                    tempModelManager != null)
                {
                    tempModelManager.ClearArtifact(tempEdmxFileUri);
                }

                // dispose of our temp model manager
                if (tempModelManager != null)
                {
                    tempModelManager.Dispose();
                }

                // delete temporary file
                if (tempEdmxFile != null &&
                    tempEdmxFile.Exists)
                {
                    try
                    {
                        tempEdmxFile.Delete();
                    }
                    catch (IOException)
                    {
                        // do nothing if delete fails
                    }
                }
            }

            return(false);
        }
        internal static bool UpdateEdmxAndEnvironment(ModelBuilderSettings settings)
        {
            var artifact = settings.Artifact as EntityDesignArtifact;

            if (artifact == null)
            {
                Debug.Fail("In trying to UpdateEdmxAndEnvironment(), No Artifact was found in the ModelBuilderSettings");
                return(false);
            }

            // Update the app. or web.config, register build providers etc
            ConfigFileHelper.UpdateConfig(settings);

            if (settings.SsdlStringReader != null &&
                settings.MslStringReader != null)
            {
                // Create the XmlReaders for the ssdl and msl text
                var ssdlXmlReader = XmlReader.Create(settings.SsdlStringReader);
                var mslXmlReader  = XmlReader.Create(settings.MslStringReader);

                // Set up our post event to clear out the error list
                var cmd = new ReplaceSsdlAndMslCommand(ssdlXmlReader, mslXmlReader);
                cmd.PostInvokeEvent += (o, e) =>
                {
                    var errorList = ErrorListHelper.GetSingleDocErrorList(e.CommandProcessorContext.Artifact.Uri);
                    if (errorList != null)
                    {
                        errorList.Clear();
                    }
                };

                // Update the model (all inside 1 transaction so we don't get multiple undo's/redo's)
                var editingContext =
                    PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(settings.Artifact.Uri);
                var cpc = new CommandProcessorContext(
                    editingContext,
                    EfiTransactionOriginator.GenerateDatabaseScriptFromModelId, Resources.Tx_GenerateDatabaseScriptFromModel);
                var cp = new CommandProcessor(cpc, cmd);
                var addUseLegacyProviderCommand = ModelHelper.CreateSetDesignerPropertyValueCommandFromArtifact(
                    cpc.Artifact,
                    OptionsDesignerInfo.ElementName,
                    OptionsDesignerInfo.AttributeUseLegacyProvider,
                    settings.UseLegacyProvider.ToString());
                if (addUseLegacyProviderCommand != null)
                {
                    cp.EnqueueCommand(addUseLegacyProviderCommand);
                }

                // When the user had a v2 edmx file (it can happen when creating a new empty model in a project targeting
                // .NET Framework 4 and the project does not have refereces to any of EF dlls) and selected EF6 in
                // the "create database from model" wizard we need to update the artifact to use v3 schemas otherwise
                // there will be a watermark saying that the edmx is not correct for the EF version and needs to be updated.
                // We only want to run this command if the version really changed to avoid the overhead.
                if (artifact.SchemaVersion != settings.TargetSchemaVersion)
                {
                    cp.EnqueueCommand(new RetargetXmlNamespaceCommand(artifact, settings.TargetSchemaVersion));
                }

                cp.Invoke();
            }

            // First let's get the canonical file path since DTE needs this
            if (!string.IsNullOrEmpty(settings.DdlFileName) &&
                settings.DdlStringReader != null)
            {
                var canonicalFilePath = string.Empty;
                try
                {
                    var fi = new FileInfo(settings.DdlFileName);
                    canonicalFilePath = fi.FullName;
                }
                catch (Exception e)
                {
                    Debug.Fail(
                        "We should have caught this exception '" + e.Message + "' immediately after the user clicked the 'Finish' button");
                    VsUtils.ShowErrorDialog(
                        String.Format(
                            CultureInfo.CurrentCulture, ModelWizard.Properties.Resources.ErrorCouldNotParseDdlFileName, settings.DdlFileName,
                            e.Message));
                    return(false);
                }

                // Output the DDL file, catch any Exceptions, display them, and revert
                // back to the last page of the wizard.
                try
                {
                    OutputDdl(canonicalFilePath, settings.DdlStringReader);
                }
                catch (Exception e)
                {
                    if (e.InnerException == null)
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(
                                CultureInfo.CurrentCulture, Resources.DatabaseCreation_ErrorWritingDdl, canonicalFilePath, e.Message));
                    }
                    else
                    {
                        VsUtils.ShowErrorDialog(
                            String.Format(
                                CultureInfo.CurrentCulture, Resources.DatabaseCreation_ErrorWritingDdlWithInner, canonicalFilePath,
                                e.Message, e.InnerException.Message));
                    }
                    return(false);
                }

                // Add DDL file to the project if it is inside the project
                string relativePath;
                if (VsUtils.TryGetRelativePathInProject(settings.Project, canonicalFilePath, out relativePath))
                {
                    AddDDLFileToProject(settings.Project, canonicalFilePath);
                }

                // Open the DDL file if it is not already open
                IVsUIHierarchy hier;
                uint           itemId;
                IVsWindowFrame frame;
                if (VsShellUtilities.IsDocumentOpen(
                        Services.ServiceProvider, canonicalFilePath, Guid.Empty, out hier, out itemId, out frame) == false)
                {
                    VsShellUtilities.OpenDocument(Services.ServiceProvider, canonicalFilePath);
                }
            }

            return(true);
        }
Exemplo n.º 27
0
 protected override void ProcessModel(DbModel model, string storeModelNamespace, ModelBuilderSettings settings,
                                      ModelBuilderEngineHostContext hostContext, List <EdmSchemaError> errors)
 {
     ValidateModel(model, errors);
 }
Exemplo n.º 28
0
 internal VSModelBuilderEngineHostContext(ModelBuilderSettings settings)
 {
     _settings = settings;
 }