Beispiel #1
0
        public void OnDeactivate_creates_and_verifies_model_path()
        {
            var modelBuilderSettings = new ModelBuilderSettings
            {
                NewItemFolder = @"C:\temp",
                ModelName     = "myModel"
            };

            var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality);
            var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object)
            {
                CallBase = true
            };

            mockWizardPageStart
            .Protected()
            .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>())
            .Returns(false);

            mockWizardPageStart.Object.OnDeactivate();

            mockWizardPageStart
            .Protected()
            .Verify("VerifyModelFilePath", Times.Once(), @"C:\temp\myModel.edmx");
        }
        public void OnDeactivate_generates_model()
        {
            var mockModelBuilderEngine = new Mock <ModelBuilderEngine>();

            mockModelBuilderEngine.Setup(e => e.Model).Returns(new XDocument());

            var mockSettings = new Mock <ModelBuilderSettings> {
                CallBase = true
            };

            mockSettings.Setup(s => s.DesignTimeConnectionString).Returns("fakeConnString");
            mockSettings.Object.ModelBuilderEngine = mockModelBuilderEngine.Object;

            var wizard = new ModelBuilderWizardForm(mockSettings.Object, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality);

            var mockWizardPageBase = new Mock <WizardPageBase>(wizard, new Mock <IServiceProvider>().Object)
            {
                CallBase = true
            };

            mockWizardPageBase.Setup(p => p.MovingNext).Returns(true);

            mockWizardPageBase.Object.OnDeactivate();

            mockModelBuilderEngine
            .Verify(m => m.GenerateModel(It.IsAny <EdmxHelper>(), It.IsAny <ModelBuilderSettings>(), It.IsAny <ModelBuilderEngineHostContext>()), Times.Once());
        }
Beispiel #3
0
        public void OnDeactivate_updates_model_settings_if_model_file_does_not_exist_for_empty_model()
        {
            var modelBuilderSettings = new ModelBuilderSettings
            {
                NewItemFolder         = @"C:\temp",
                ModelName             = "myModel",
                ReplacementDictionary = new Dictionary <string, string>(),
                TargetSchemaVersion   = EntityFrameworkVersion.Version3
            };

            var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality);
            var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object)
            {
                CallBase = true
            };

            mockWizardPageStart
            .Protected()
            .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>())
            .Returns(true);
            mockWizardPageStart
            .Protected()
            .Setup <int>("GetSelectedOptionIndex")
            .Returns(WizardPageStart.GenerateEmptyModelIndex);

            mockWizardPageStart.Object.OnDeactivate();

            Assert.Equal(ModelGenerationOption.EmptyModel, modelBuilderSettings.GenerationOption);
            Assert.False(wizard.FileAlreadyExistsError);
            Assert.Equal(@"C:\temp\myModel.edmx", modelBuilderSettings.ModelPath);
            Assert.True(modelBuilderSettings.ReplacementDictionary.Any());
            Assert.Null(modelBuilderSettings.ModelBuilderEngine);
        }
Beispiel #4
0
        internal WizardPageSelectTables(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            Logo          = ModelWizard.Properties.Resources.PageIcon;
            Headline      = ModelWizard.Properties.Resources.SelectTablesPage_Title;
            Id            = "WizardPageSelectTablesId";
            ShowInfoPanel = false;

            labelPrompt.Text = ModelWizard.Properties.Resources.WhichDatabaseObjectsLabel;
            labelPrompt.Font = LabelFont;

            HelpKeyword = null;

            Debug.Assert(
                Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformAllFunctionality,
                "Unexpected wizard mode in WizardPageSelectTables");

            _stopwatch = new Stopwatch();

            _isNetFx35 = NetFrameworkVersioningHelper.TargetNetFrameworkVersion(Wizard.Project, ServiceProvider) <
                         NetFrameworkVersioningHelper.NetFrameworkVersion4;

            InitializeModelOptions();

            _bgWorkerPopulateTree = new BackgroundWorker();
            _bgWorkerPopulateTree.WorkerSupportsCancellation = true;
            _bgWorkerPopulateTree.RunWorkerCompleted        += bgWorkerPopulateTree_RunWorkerCompleted;
            _bgWorkerPopulateTree.DoWork += bgWorkerPopulateTree_DoWork;
        }
        internal WizardPageSelectTables(ModelBuilderWizardForm wizard, IServiceProvider serviceProvider)
            : base(wizard, serviceProvider)
        {
            InitializeComponent();

            Logo          = ModelWizard.Properties.Resources.PageIcon;
            Headline      = ModelWizard.Properties.Resources.SelectTablesPage_Title;
            Id            = selectTablesPageId;
            ShowInfoPanel = false;

            labelPrompt.Text = ModelWizard.Properties.Resources.WhichDatabaseObjectsLabel;
            labelPrompt.Font = LabelFont;

            HelpKeyword = null;

            Debug.Assert(
                Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformAllFunctionality, "Unexpected wizard mode in WizardPageSelectTables");
            InitializeModelOptions(
                chkPluralize, chkIncludeForeignKeys, chkCreateFunctionImports,
                toolTip, Wizard.Project, Wizard.ServiceProvider,
                IncludeForeignKeysArea_OnMouseMove, IncludeForeignKeysArea_OnMouseLeave);

            _stopwatch = new Stopwatch();

            _bgWorkerPopulateTree = new BackgroundWorker();
            _bgWorkerPopulateTree.WorkerSupportsCancellation = true;
            _bgWorkerPopulateTree.RunWorkerCompleted        += bgWorkerPopulateTree_RunWorkerCompleted;
            _bgWorkerPopulateTree.DoWork += bgWorkerPopulateTree_DoWork;
        }
        internal WizardPageSelectTables(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            Logo = ModelWizard.Properties.Resources.PageIcon;
            Headline = ModelWizard.Properties.Resources.SelectTablesPage_Title;
            Id = "WizardPageSelectTablesId";
            ShowInfoPanel = false;

            labelPrompt.Text = ModelWizard.Properties.Resources.WhichDatabaseObjectsLabel;
            labelPrompt.Font = LabelFont;

            HelpKeyword = null;

            Debug.Assert(
                Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformAllFunctionality, 
                "Unexpected wizard mode in WizardPageSelectTables");

            _stopwatch = new Stopwatch();

            _isNetFx35 = NetFrameworkVersioningHelper.TargetNetFrameworkVersion(Wizard.Project, ServiceProvider) <
                NetFrameworkVersioningHelper.NetFrameworkVersion4;

            InitializeModelOptions();

            _bgWorkerPopulateTree = new BackgroundWorker();
            _bgWorkerPopulateTree.WorkerSupportsCancellation = true;
            _bgWorkerPopulateTree.RunWorkerCompleted += bgWorkerPopulateTree_RunWorkerCompleted;
            _bgWorkerPopulateTree.DoWork += bgWorkerPopulateTree_DoWork;
        }
        public void OnActivate_result_depends_on_FileAlreadyExistsError()
        {
            var wizard             = new ModelBuilderWizardForm(new ModelBuilderSettings(), ModelBuilderWizardForm.WizardMode.PerformAllFunctionality);
            var wizardPageDbConfig = new WizardPageDbConfig(wizard, new Mock <IServiceProvider>().Object);

            wizard.FileAlreadyExistsError = true;
            Assert.False(wizardPageDbConfig.OnActivate());

            wizard.FileAlreadyExistsError = false;
            Assert.True(wizardPageDbConfig.OnActivate());
        }
        public WizardPageBase(ModelBuilderWizardForm wizard, IServiceProvider serviceProvider)
            : base(wizard)
        {
            _wizard = wizard;
            // Set the default font to VS shell font.
            var vsFont = VSHelpers.GetVSFont(serviceProvider);

            if (vsFont != null)
            {
                Font = vsFont;
            }
        }
        public WizardPageBase(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            _wizard = wizard;

            // Set the default font to VS shell font.
            var vsFont = VSHelpers.GetVSFont(wizard.ServiceProvider);
            if (vsFont != null)
            {
                Font = vsFont;
            }
        }
        internal WizardPageDbGenSummary(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            Logo = Properties.Resources.PageIcon;
            Headline = Properties.Resources.DbGenSummary_Title;
            Id = "WizardPageGenerateDatabaseScriptId";
            ShowInfoPanel = false;

            HelpKeyword = null;

            _addedDbConfigPage = false;
        }
        internal WizardPageDbGenSummary(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            Logo          = Properties.Resources.PageIcon;
            Headline      = Properties.Resources.DbGenSummary_Title;
            Id            = "WizardPageGenerateDatabaseScriptId";
            ShowInfoPanel = false;

            HelpKeyword = null;

            _addedDbConfigPage = false;
        }
Beispiel #12
0
        public WizardPageStart(ModelBuilderWizardForm wizard, IServiceProvider serviceProvider)
            : base(wizard, serviceProvider)
        {
            InitializeComponent();

            components = new Container();

            Logo          = Resources.PageIcon;
            Headline      = Resources.StartPage_Title;
            Id            = "WizardPageStartId";
            ShowInfoPanel = false;

            labelPrompt.Text = Resources.StartPage_PromptLabelText;
            labelPrompt.Font = LabelFont;

            // Load new ImageList with glyphs from resources
            var imageList = new ImageList(components)
            {
                ColorDepth       = ColorDepth.Depth32Bit,
                ImageSize        = new Size(32, 32),
                TransparentColor = Color.Magenta
            };

            imageList.Images.Add("database.bmp", Resources.Database);
            imageList.Images.Add("EmptyModel.bmp", Resources.EmptyModel);

#if VS12
            // scale images as appropriate for screen resolution
            DpiHelper.LogicalToDeviceUnits(ref imageList);
#endif

            // Re-create ListView and add the list items so we are sure to use our string resources)
            listViewModelContents.Clear();
            listViewModelContents.ShowItemToolTips = true;
            listViewModelContents.LargeImageList   = imageList;

            listViewModelContents.Items.AddRange(
                new[]
            {
                new ListViewItem(Resources.GenerateFromDatabaseOption, "database.bmp"),
                new ListViewItem(Resources.EmptyModelOption, "EmptyModel.bmp")
            });

            // Always select the first item
            listViewModelContents.MultiSelect       = false;
            listViewModelContents.Items[0].Selected = true;

            listViewModelContents.Focus();
        }
Beispiel #13
0
        internal WizardPageDbConfig(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            _configFileUtils =
                new ConfigFileUtils(wizard.Project, wizard.ServiceProvider, wizard.ModelBuilderSettings.VSApplicationType);

            _identifierUtil =
                new CodeIdentifierUtils(wizard.ModelBuilderSettings.VSApplicationType, VsUtils.GetLanguageForProject(wizard.Project));

            Headline      = Resources.DbConfigPage_Title;
            Logo          = Resources.PageIcon;
            Id            = "WizardPageDbConfigId";
            ShowInfoPanel = false;

            sensitiveInfoTextBox.Text        = Resources.SensitiveDataInfoText;
            disallowSensitiveInfoButton.Text = Resources.DisallowSensitiveDataInfoText;
            allowSensitiveInfoButton.Text    = Resources.AllowSensitiveDataInfoText;
            if (VsUtils.IsWebProject(wizard.ModelBuilderSettings.VSApplicationType))
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveConnectionLabelASP;
            }
            else
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveConnectionLabel;
            }

            // make the App/Web.Config connection name entry non-editable for 'Update Model' and 'Generate Database' scenarios
            if (ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables == Wizard.Mode ||
                ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary == Wizard.Mode ||
                ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly == Wizard.Mode)
            {
                textBoxAppConfigConnectionName.Enabled = false;
            }

            newDBConnectionButton.Text      = Resources.NewDatabaseConnectionBtn;
            newDBConnectionButton.BackColor = SystemColors.Control;
            newDBConnectionButton.ForeColor = SystemColors.ControlText;
            lblEntityConnectionString.Text  = Resources.ConnectionStringLabel;
            lblPagePrompt.Text = Resources.WhichDataConnectionLabel;
            lblPagePrompt.Font = LabelFont;

            sensitiveInfoTextBox.Enabled        = false;
            disallowSensitiveInfoButton.Enabled = false;
            allowSensitiveInfoButton.Enabled    = false;
            HelpKeyword = null;
        }
        internal WizardPageRuntimeConfig(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            Logo        = Resources.PageIcon;
            Headline    = Resources.RuntimeConfigPage_Title;
            Id          = "WizardPageRuntimeConfig";
            HelpKeyword = null;

            promptLabel.Font = LabelFont;
            promptLabel.Text = Resources.RuntimeConfig_Prompt;

            VSHelpers.AssignLinkLabelColor(notificationLinkLabel);
            notificationLabel.Text = Resources.RuntimeConfig_LearnMore;
        }
        internal WizardPageRuntimeConfig(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            Logo = Resources.PageIcon;
            Headline = Resources.RuntimeConfigPage_Title;
            Id = "WizardPageRuntimeConfig";
            HelpKeyword = null;

            promptLabel.Font = LabelFont;
            promptLabel.Text = Resources.RuntimeConfig_Prompt;

            VSHelpers.AssignLinkLabelColor(notificationLinkLabel);
            notificationLabel.Text = Resources.RuntimeConfig_LearnMore;
        }
        internal WizardPageDbConfig(ModelBuilderWizardForm wizard)
            : base(wizard)
        {
            InitializeComponent();

            _configFileUtils =
                new ConfigFileUtils(wizard.Project, wizard.ServiceProvider, wizard.ModelBuilderSettings.VSApplicationType);

            _identifierUtil =
                new CodeIdentifierUtils(wizard.ModelBuilderSettings.VSApplicationType, VsUtils.GetLanguageForProject(wizard.Project));

            Headline = Resources.DbConfigPage_Title;
            Logo = Resources.PageIcon;
            Id = "WizardPageDbConfigId";
            ShowInfoPanel = false;

            sensitiveInfoTextBox.Text = Resources.SensitiveDataInfoText;
            disallowSensitiveInfoButton.Text = Resources.DisallowSensitiveDataInfoText;
            allowSensitiveInfoButton.Text = Resources.AllowSensitiveDataInfoText;
            if (VsUtils.IsWebProject(wizard.ModelBuilderSettings.VSApplicationType))
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveConnectionLabelASP;
            }
            else
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveConnectionLabel;
            }

            // make the App/Web.Config connection name entry non-editable for 'Update Model' and 'Generate Database' scenarios
            if (ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables == Wizard.Mode
                || ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary == Wizard.Mode
                || ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly == Wizard.Mode)
            {
                textBoxAppConfigConnectionName.Enabled = false;
            }

            newDBConnectionButton.Text = Resources.NewDatabaseConnectionBtn;
            lblEntityConnectionString.Text = Resources.ConnectionStringLabel;
            lblPagePrompt.Text = Resources.WhichDataConnectionLabel;
            lblPagePrompt.Font = LabelFont;

            sensitiveInfoTextBox.Enabled = false;
            disallowSensitiveInfoButton.Enabled = false;
            allowSensitiveInfoButton.Enabled = false;
            HelpKeyword = null;
        }
Beispiel #17
0
        public void OnDeactivate_updates_model_settings_if_model_file_does_not_exist_for_generate_from_database()
        {
            var modelBuilderSettings = new ModelBuilderSettings
            {
                NewItemFolder         = @"C:\temp",
                ModelName             = "myModel",
                ReplacementDictionary = new Dictionary <string, string>(),
                TargetSchemaVersion   = EntityFrameworkVersion.Version3,
                VsTemplatePath        = "fake.vstemplate"
            };

            var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality);
            var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object)
            {
                CallBase = true
            };

            mockWizardPageStart
            .Protected()
            .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>())
            .Returns(true);
            mockWizardPageStart
            .Protected()
            .Setup <int>("GetSelectedOptionIndex")
            .Returns(WizardPageStart.GenerateFromDatabaseIndex);
            mockWizardPageStart
            .Protected()
            .Setup <string>("GetEdmxTemplateContent", ItExpr.IsAny <string>())
            .Returns("vstemplate contents");

            mockWizardPageStart.Object.OnDeactivate();

            Assert.Equal(ModelGenerationOption.GenerateFromDatabase, modelBuilderSettings.GenerationOption);
            Assert.False(wizard.FileAlreadyExistsError);
            Assert.Equal(@"C:\temp\myModel.edmx", modelBuilderSettings.ModelPath);
            // replacement dictionary updated lazily
            Assert.False(modelBuilderSettings.ReplacementDictionary.Any());
            Assert.NotNull(modelBuilderSettings.ModelBuilderEngine);

            mockWizardPageStart
            .Protected()
            .Verify("GetEdmxTemplateContent", Times.Once(), "fake.vstemplate");
        }
Beispiel #18
0
        internal static bool ValidateNamespace(TextBox modelNamespaceTextBox, ModelBuilderSettings modelBuilderSettings)
        {
            if (!EdmUtils.IsValidModelNamespace(modelNamespaceTextBox.Text))
            {
                var s = ModelWizard.Properties.Resources.ConnectionStringNonValidIdentifier;
                VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, s, modelNamespaceTextBox.Text));
                modelNamespaceTextBox.Focus();
                return(false);
            }

            // the Model Namespace and the Entity Container name must differ
            if (ModelBuilderWizardForm.ModelNamespaceAndEntityContainerNameSame(modelBuilderSettings))
            {
                var s = ModelWizard.Properties.Resources.NamespaceAndEntityContainerSame;
                VsUtils.ShowErrorDialog(String.Format(CultureInfo.CurrentCulture, s, modelBuilderSettings.AppConfigConnectionPropertyName));
                modelNamespaceTextBox.Focus();
                return(false);
            }
            return(true);
        }
        internal WizardPageDbConfig(ModelBuilderWizardForm wizard, IServiceProvider serviceProvider)
            : base(wizard, serviceProvider)
        {
            InitializeComponent();

            Headline      = Resources.DbConfigPage_Title;
            Logo          = Resources.PageIcon;
            Id            = "WizardPageDbConfigId";
            ShowInfoPanel = false;

            sensitiveInfoTextBox.Text        = Resources.SensitiveDataInfoText;
            disallowSensitiveInfoButton.Text = Resources.DisallowSensitiveDataInfoText;
            allowSensitiveInfoButton.Text    = Resources.AllowSensitiveDataInfoText;
            if (wizard.ModelBuilderSettings.SaveToWebConfig)
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveEntityConnectionLabelASP;
            }
            else
            {
                checkBoxSaveInAppConfig.Text = Resources.SaveEntityConnectionLabel;
            }

            // make the App/Web.Config connection name entry non-editable for 'Update Model' and 'Generate Database' scenarios
            if (ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables == Wizard.Mode ||
                ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary == Wizard.Mode ||
                ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly == Wizard.Mode)
            {
                textBoxAppConfigConnectionName.Enabled = false;
            }

            newDBConnectionButton.Text     = Resources.NewDatabaseConnectionBtn;
            lblEntityConnectionString.Text = Resources.EntityConnectionStringLabel;
            lblPagePrompt.Text             = Resources.WhichDataConnectionLabel;
            lblPagePrompt.Font             = LabelFont;

            sensitiveInfoTextBox.Enabled        = false;
            disallowSensitiveInfoButton.Enabled = false;
            allowSensitiveInfoButton.Enabled    = false;
            HelpKeyword = null;
        }
Beispiel #20
0
        public void OnDeactivate_does_not_update_settings_if_model_file_already_exists()
        {
            var modelBuilderSettings = new ModelBuilderSettings
            {
                NewItemFolder = @"C:\temp",
                ModelName     = "myModel"
            };

            var wizard = new ModelBuilderWizardForm(modelBuilderSettings, ModelBuilderWizardForm.WizardMode.PerformAllFunctionality);
            var mockWizardPageStart = new Mock <WizardPageStart>(wizard, new Mock <IServiceProvider>().Object)
            {
                CallBase = true
            };

            mockWizardPageStart
            .Protected()
            .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>())
            .Returns(false);

            mockWizardPageStart.Object.OnDeactivate();

            Assert.Null(modelBuilderSettings.ModelPath);
            Assert.True(wizard.FileAlreadyExistsError);
        }
Beispiel #21
0
        private static Mock <WizardPageStart> CreateMockWizardPageStart(ModelBuilderWizardForm mockWizard, int itemIndex,
                                                                        ConfigFileUtils configFileUtils = null)
        {
            var mockWizardPageStart = new Mock <WizardPageStart>(mockWizard, configFileUtils)
            {
                CallBase = true
            };

            mockWizardPageStart
            .Protected()
            .Setup <bool>("AnyItemSelected")
            .Returns(true);

            mockWizardPageStart
            .Protected()
            .Setup <bool>("VerifyModelFilePath", ItExpr.IsAny <string>())
            .Returns(true);

            mockWizardPageStart
            .Protected()
            .Setup <int>("GetSelectedOptionIndex")
            .Returns(itemIndex);
            return(mockWizardPageStart);
        }
        internal static void GenerateDatabaseScriptFromModel(EntityDesignArtifact artifact)
        {
            VsUtils.EnsureProvider(artifact);

            var project = VSHelpers.GetProjectForDocument(artifact.Uri.LocalPath, PackageManager.Package);
            var sp = Services.ServiceProvider;
            ModelBuilderWizardForm form;
            ModelBuilderWizardForm.WizardMode startMode;
            ModelBuilderSettings settings;

            // Start the hourglass, especially because we'll be incurring a perf hit from validating
            using (new VsUtils.HourglassHelper())
            {
                // Before running the Generate Database wizard, we have to make sure that the C-Side validates
                VisualStudioEdmxValidator.LoadAndValidateFiles(artifact.Uri);

                if (
                    artifact.ArtifactSet.GetAllErrors()
                        .Count(ei => ei.ErrorClass == ErrorClass.Runtime_CSDL || ei.ErrorClass == ErrorClass.Escher_CSDL) > 0)
                {
                    VsUtils.ShowErrorDialog(Resources.DatabaseCreation_ValidationFailed);
                    return;
                }

                // set up ModelBuilderSettings
                settings = SetupSettingsAndModeForDbPages(
                    sp, project, artifact, false,
                    ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary,
                    ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly, out startMode);

                form = new ModelBuilderWizardForm(sp, settings, startMode);
            }

            var originalSchemaVersion = settings.TargetSchemaVersion;

            try
            {
                // start the ModelBuilderWizardForm; this will start the workflow in another thread.
                form.Start();
            }
            catch (Exception e)
            {
                VsUtils.ShowErrorDialog(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ModelObjectItemWizard_UnexpectedExceptionHasOccurred,
                        e.Message));
                return;
            }

            // if Wizard was cancelled or the user hit 'X' to close window
            // no need for any further action
            if (form.WizardCancelled
                || !form.WizardFinished)
            {
                return;
            }

            // If database was configured, add DbContext templates
            if (startMode == ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndDBGenSummary)
            {
                var edmxItem = VsUtils.GetProjectItemForDocument(artifact.Uri.LocalPath, sp);
                new DbContextCodeGenerator().AddDbContextTemplates(edmxItem, settings.UseLegacyProvider);

                // We need to reload the artifact if we updated the edmx as part of generating
                // model from the database.
                if (settings.TargetSchemaVersion != originalSchemaVersion)
                {
                    artifact.ReloadArtifact();
                }
            }
        }
        internal override bool OnWizardFinish()
        {
            using (new VsUtils.HourglassHelper())
            {
                UpdateSettingsFromGui();
            }

            //
            // validate app config connection name
            //
            if (checkBoxSaveInAppConfig.Checked)
            {
                var id = textBoxAppConfigConnectionName.Text;
                if (!EscherAttributeContentValidator.IsValidCsdlEntityContainerName(id) ||
                    !_identifierUtil.IsValidIdentifier(id))
                {
                    VsUtils.ShowErrorDialog(
                        string.Format(CultureInfo.CurrentCulture, Resources.ConnectionStringNonValidIdentifier, id));
                    textBoxAppConfigConnectionName.Focus();
                    _isFocusSet = true;
                    return(false);
                }

                // only check that the connection string name is new if started in
                // 'PerformAllFunctionality' mode
                if (ModelBuilderWizardForm.WizardMode.PerformAllFunctionality == Wizard.Mode)
                {
                    string connectionString;
                    if (ConnectionManager.GetExistingConnectionStrings(_configFileUtils).TryGetValue(id, out connectionString) &&
                        !string.Equals(textBoxConnectionString.Text, connectionString, StringComparison.Ordinal))
                    {
                        VsUtils.ShowErrorDialog(
                            string.Format(CultureInfo.CurrentCulture, Resources.ConnectionStringDuplicateIdentifer, id));
                        textBoxAppConfigConnectionName.Focus();
                        _isFocusSet = true;
                        return(false);
                    }
                }
            }

            // the Model Namespace and the Entity Container name must differ
            if (ModelBuilderWizardForm.ModelNamespaceAndEntityContainerNameSame(Wizard.ModelBuilderSettings))
            {
                var s = Resources.NamespaceAndEntityContainerSame;
                VsUtils.ShowErrorDialog(
                    String.Format(CultureInfo.CurrentCulture, s, Wizard.ModelBuilderSettings.AppConfigConnectionPropertyName));
                textBoxAppConfigConnectionName.Focus();
                _isFocusSet = true;
                return(false);
            }

            try
            {
                // this might cause dataConnection to include some sensitive data into connectionString
                // the Open function also can cause DDEX to put up a prompt for the username/password for an existing connection
                // that does not have any saved password information.
                _dataConnection.Open();

                if (!IsDataValid)
                {
                    sensitiveInfoTextBox.Enabled        = true;
                    allowSensitiveInfoButton.Checked    = false;
                    allowSensitiveInfoButton.Enabled    = true;
                    disallowSensitiveInfoButton.Checked = false;
                    disallowSensitiveInfoButton.Enabled = true;

                    var result = VsUtils.ShowMessageBox(
                        PackageManager.Package,
                        Resources.SensitiveDataInfoText,
                        OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_THIRD,
                        OLEMSGICON.OLEMSGICON_QUERY);

                    switch (result)
                    {
                    case DialogResult.Yes:
                        allowSensitiveInfoButton.Checked = true;
                        break;

                    case DialogResult.No:
                        disallowSensitiveInfoButton.Checked = true;
                        break;

                    default:
                        Wizard.OnValidationStateChanged(this);
                        return(false);
                    }
                }
            }
            catch (DataConnectionOpenCanceledException)
            {
                return(false);
            }
            catch (Exception e)
            {
                // show error dialog
                ModelBuilderWizardForm.ShowDatabaseConnectionErrorDialog(e);

                return(false);
            }
            finally
            {
                if (_dataConnection.State != DataConnectionState.Closed)
                {
                    _dataConnection.Close();
                }
            }

            return(true);
        }
Beispiel #24
0
        protected void bgWorkerPopulateTree_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
        {
            try
            {
                _stopwatch.Stop();

                if (args.Cancelled)
                {
                    return;
                }

                if (args.Error != null)
                {
                    // show error dialog
                    ModelBuilderWizardForm.ShowDatabaseConnectionErrorDialog(args.Error);

                    Visited = false;
                    Wizard.OnPrevious();
                }
                else
                {
                    using (new VsUtils.HourglassHelper())
                    {
                        // No errors, populate nodes in TreeView - create the nodes accordingly
                        var result       = (ICollection <EntityStoreSchemaFilterEntry>[])args.Result;
                        var tableEntries = result[0];
                        var viewEntries  = result[1];
                        var sprocEntries = result[2];

                        CreateTreeForNewModel(tableEntries, viewEntries, sprocEntries);

                        // if there are Sproc entries then enable the Create Function Imports box and by default set to checked
                        if (sprocEntries != null && sprocEntries.Count > 0)
                        {
                            chkCreateFunctionImports.Enabled = true;
                            chkCreateFunctionImports.Checked = true;
                        }

                        // Hide status message
                        databaseObjectTreeView.HideStatus();

                        // Set focus to TreeView
                        databaseObjectTreeView.TreeViewControl.SelectedNode = databaseObjectTreeView.TreeViewControl.Nodes[0];
                        databaseObjectTreeView.Focus();

                        _initializedDataConnection      = Wizard.ModelBuilderSettings.DesignTimeConnectionString;
                        _initializedUsingLegacyProvider = Wizard.ModelBuilderSettings.UseLegacyProvider;
                        _initializedGenerationOption    = Wizard.ModelBuilderSettings.GenerationOption;
                        modelNamespaceTextBox.Enabled   = Wizard.ModelBuilderSettings.GenerationOption != ModelGenerationOption.CodeFirstFromDatabase;
                    }
                }

                // Enable wizard navigation
                Wizard.OnValidationStateChanged(this);
            }
            catch (Exception e)
            {
                databaseObjectTreeView.ShowStatus(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        ModelWizard.Properties.Resources.SelectTablesPage_ErrorRetrievingTablesText, e.Message));
                Wizard.EnableButton(ButtonType.Cancel, true);
            }
        }
        internal static void UpdateModelFromDatabase(EntityDesignArtifact artifact)
        {
            VsUtils.EnsureProvider(artifact);

            var serviceProvider = Services.ServiceProvider;
            var project = VSHelpers.GetProjectForDocument(artifact.Uri.LocalPath, serviceProvider);

            // set up ModelBuilderSettings for startMode=PerformDatabaseConfigAndSelectTables
            ModelBuilderWizardForm.WizardMode startMode;
            var settings =
                SetupSettingsAndModeForDbPages(
                    serviceProvider, project, artifact, true,
                    ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables,
                    ModelBuilderWizardForm.WizardMode.PerformSelectTablesOnly, out startMode);
            settings.WizardKind = WizardKind.UpdateModel;

            // use existing storage namespace as new storage namespace
            if (null != artifact.StorageModel()
                && null != artifact.StorageModel().Namespace
                && !string.IsNullOrEmpty(artifact.StorageModel().Namespace.Value))
            {
                settings.StorageNamespace = artifact.StorageModel().Namespace.Value;
            }

            // use existing model namespace as new model namespace (this only affects the temporary
            // artifact but there is a situation where the C-side EntityContainer has been given the
            // same name as the default model namespace where not setting this causes the temporary
            // artifact to be unreadable because of symbol clashes)
            if (null != artifact.ConceptualModel()
                && null != artifact.ConceptualModel().Namespace
                && !string.IsNullOrEmpty(artifact.ConceptualModel().Namespace.Value))
            {
                settings.ModelNamespace = artifact.ConceptualModel().Namespace.Value;
            }
            
            settings.ModelBuilderEngine = new UpdateModelFromDatabaseModelBuilderEngine();

            // call the ModelBuilderWizardForm
            var form = new ModelBuilderWizardForm(serviceProvider, settings, startMode);

            try
            {
                form.Start();
            }
            catch (Exception e)
            {
                VsUtils.ShowErrorDialog(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ModelObjectItemWizard_UnexpectedExceptionHasOccurred,
                        e.Message));
                return;
            }

            // if Wizard was cancelled or the user hit 'X' to close window
            // no need for any further action
            if (form.WizardCancelled
                || !form.WizardFinished)
            {
                return;
            }

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

            // use form.ModelBuilderSettings to look at accumulated info and
            // take appropriate action
            var editingContext = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(artifact.Uri);
            var shouldReloadArtifact = ProcessAccumulatedInfo(editingContext, artifact, settings);

            // If database was configured, add DbContext templates
            if (startMode == ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables)
            {
                var edmxItem = VsUtils.GetProjectItemForDocument(artifact.Uri.LocalPath, serviceProvider);
                new DbContextCodeGenerator().AddDbContextTemplates(edmxItem, settings.UseLegacyProvider);
            }

            // We can reload only after we added EF references to the project otherwise we would get a watermark
            // saying that the schema version does not match the referenced EF version which would not be true.
            // If we reload becuase there was an extension that potentially modified the artifact then it does not matter.
            if (shouldReloadArtifact)
            {
                artifact.ReloadArtifact();
                artifact.IsDirty = true;
            }
        }
Beispiel #26
0
        internal WizardPageUpdateFromDatabase(ModelBuilderWizardForm wizard, IServiceProvider serviceProvider)
            : base(wizard, serviceProvider)
        {
            InitializeComponent();

            Logo          = Resources.PageIcon;
            Headline      = Resources.SelectTablesPage_Title;
            Id            = "WizardPageUpdateFromDatabaseId";
            ShowInfoPanel = false;

            _bgWorkerPopulateTree = new BackgroundWorker();
            _bgWorkerPopulateTree.WorkerSupportsCancellation = true;
            _bgWorkerPopulateTree.RunWorkerCompleted        += bgWorkerPopulateTree_RunWorkerCompleted;
            _bgWorkerPopulateTree.DoWork += bgWorkerPopulateTree_DoWork;

            AddTabPage.Select();

            HelpKeyword = null;

            Debug.Assert(
                Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables ||
                Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformSelectTablesOnly,
                "Unexpected wizard mode " + Wizard.Mode);

            //
            //  Get the optionsDesignerInfo from the artifact
            //
            OptionsDesignerInfo optionsDesignerInfo = null;
            var artifact = Wizard.ModelBuilderSettings.Artifact;

            Debug.Assert(artifact != null, "Expected non-null artifact");
            if (artifact != null)
            {
                DesignerInfo designerInfo;
                if (artifact.DesignerInfo().TryGetDesignerInfo(OptionsDesignerInfo.ElementName, out designerInfo))
                {
                    Debug.Assert(designerInfo != null, "expected non-null designerInfo");
                    optionsDesignerInfo = designerInfo as OptionsDesignerInfo;
                    Debug.Assert(optionsDesignerInfo != null, "expected non-null optionsDesignerInfo");
                }
            }

            //
            // set up pluralization checkbox.  We only support english pluralization for this release, so default this checked in this case
            //
            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "en")
            {
                // default to checked.
                toolTip.SetToolTip(chkPluralize, Resources.PluralizeCheckBoxToolTipText);
                chkPluralize.Enabled = true;
                chkPluralize.Checked = true;

                // read value from designer properties
                if (optionsDesignerInfo != null)
                {
                    chkPluralize.Checked = TryReadDesignerProperty(optionsDesignerInfo.CheckPluralizationInWizard, true);
                }
            }
            else
            {
                // even if non-english, we still want the option available, just not checked by default
                chkPluralize.Enabled = true;
                chkPluralize.Checked = false;

                // read value from designer properties
                if (optionsDesignerInfo != null)
                {
                    chkPluralize.Checked = TryReadDesignerProperty(optionsDesignerInfo.CheckPluralizationInWizard, false);
                }
                toolTip.SetToolTip(chkPluralize, Resources.PluralizeCheckBoxDisabledToolTipText);
            }

            // foreign keys are supported by any version of EF that runs on .NET Framework 4 or newer
            if (NetFrameworkVersioningHelper.TargetNetFrameworkVersion(Wizard.Project, Wizard.ServiceProvider) >=
                NetFrameworkVersioningHelper.NetFrameworkVersion4)
            {
                chkIncludeForeignKeys.Checked = true;
                chkIncludeForeignKeys.Enabled = true;
                toolTip.SetToolTip(
                    chkIncludeForeignKeys,
                    Resources.SelectTablesPage_IncludeForeignKeysToolTip);

                // try to read value from designer properties
                if (optionsDesignerInfo != null)
                {
                    chkIncludeForeignKeys.Checked =
                        TryReadDesignerProperty(optionsDesignerInfo.CheckIncludeForeignKeysInModel, true);
                }
            }
            else
            {
                toolTip.SetToolTip(chkIncludeForeignKeys, Design.Resources.DisabledFeatureTooltip);
                chkIncludeForeignKeys.Parent.MouseMove  += IncludeForeignKeysArea_OnMouseMove;
                chkIncludeForeignKeys.Parent.MouseLeave += IncludeForeignKeysArea_OnMouseLeave;
                chkIncludeForeignKeys.Enabled            = false;
                chkIncludeForeignKeys.Checked            = false;
            }

            // assume we have no Stored Procs and so default the Create Function Imports checkbox to unchecked and not enabled
            chkCreateFunctionImports.Enabled = false;
            chkCreateFunctionImports.Checked = false;

            _stopwatch = new Stopwatch();
        }
        public WizardPageStart(ModelBuilderWizardForm wizard, ConfigFileUtils configFileUtils = null)
            : base(wizard)
        {
            InitializeComponent();

            _codeFirstAllowed = CodeFirstAllowed(Wizard.ModelBuilderSettings);
            _configFileUtils  = configFileUtils
                                ?? new ConfigFileUtils(wizard.Project, wizard.ServiceProvider, wizard.ModelBuilderSettings.VSApplicationType);

            components = new Container();

            Logo          = Resources.PageIcon;
            Headline      = Resources.StartPage_Title;
            Id            = "WizardPageStartId";
            ShowInfoPanel = false;

            labelPrompt.Text = Resources.StartPage_PromptLabelText;
            labelPrompt.Font = LabelFont;

            // Load new ImageList with glyphs from resources
            var imageList = new ImageList(components)
            {
                ColorDepth       = ColorDepth.Depth32Bit,
                ImageSize        = new Size(32, 32),
                TransparentColor = Color.Magenta
            };

            imageList.Images.Add("database.png", Resources.Database);
            imageList.Images.Add("EmptyModel.png", Resources.EmptyModel);
            imageList.Images.Add("EmptyModelCodeFirst.png", Resources.EmptyModelCodeFirst);
            imageList.Images.Add("CodeFirstFromDatabase.png", Resources.CodeFirstFromDatabase);

#if VS12ORNEWER
            // scale images as appropriate for screen resolution
            DpiHelper.LogicalToDeviceUnits(ref imageList);
#endif

            // Re-create ListView and add the list items so we are sure to use our string resources)
            listViewModelContents.Clear();
            listViewModelContents.ShowItemToolTips = true;
            listViewModelContents.LargeImageList   = imageList;

            listViewModelContents.Items.AddRange(
                new[]
            {
                new ListViewItem(Resources.GenerateFromDatabaseOption, "database.png"),
                new ListViewItem(Resources.EmptyModelOption, "EmptyModel.png"),
            });

            if (NetFrameworkVersioningHelper.TargetNetFrameworkVersion(wizard.ModelBuilderSettings.Project, Wizard.ServiceProvider) >=
                NetFrameworkVersioningHelper.NetFrameworkVersion4)
            {
                listViewModelContents.Items.Add(new ListViewItem(Resources.EmptyModelCodeFirstOption, "EmptyModelCodeFirst.png"));
                listViewModelContents.Items.Add(new ListViewItem(Resources.CodeFirstFromDatabaseOption, "CodeFirstFromDatabase.png"));
            }

            // Always select the first item
            listViewModelContents.MultiSelect       = false;
            listViewModelContents.Items[0].Selected = true;

            listViewModelContents.Focus();
        }
        public WizardPageStart(ModelBuilderWizardForm wizard, ConfigFileUtils configFileUtils = null)
            : base(wizard)
        {
            InitializeComponent();

            _codeFirstAllowed = CodeFirstAllowed(Wizard.ModelBuilderSettings);
            _configFileUtils = configFileUtils
                               ?? new ConfigFileUtils(wizard.Project, wizard.ServiceProvider, wizard.ModelBuilderSettings.VSApplicationType);

            components = new Container();

            Logo = Resources.PageIcon;
            Headline = Resources.StartPage_Title;
            Id = "WizardPageStartId";
            ShowInfoPanel = false;

            labelPrompt.Text = Resources.StartPage_PromptLabelText;
            labelPrompt.Font = LabelFont;

            // Load new ImageList with glyphs from resources
            var imageList = new ImageList(components)
            {
                ColorDepth = ColorDepth.Depth32Bit,
                ImageSize = new Size(32, 32),
                TransparentColor = Color.Magenta
            };

            imageList.Images.Add("database.png", Resources.Database);
            imageList.Images.Add("EmptyModel.png", Resources.EmptyModel);
            imageList.Images.Add("EmptyModelCodeFirst.png", Resources.EmptyModelCodeFirst);
            imageList.Images.Add("CodeFirstFromDatabase.png", Resources.CodeFirstFromDatabase);

#if VS12ORNEWER
            // scale images as appropriate for screen resolution
            DpiHelper.LogicalToDeviceUnits(ref imageList);
#endif

            // Re-create ListView and add the list items so we are sure to use our string resources)
            listViewModelContents.Clear();
            listViewModelContents.ShowItemToolTips = true;
            listViewModelContents.LargeImageList = imageList;

            listViewModelContents.Items.AddRange(
                new[]
                {
                    new ListViewItem(Resources.GenerateFromDatabaseOption, "database.png"),
                    new ListViewItem(Resources.EmptyModelOption, "EmptyModel.png"),
                });

            if (NetFrameworkVersioningHelper.TargetNetFrameworkVersion(wizard.ModelBuilderSettings.Project, Wizard.ServiceProvider) >=
                NetFrameworkVersioningHelper.NetFrameworkVersion4)
            {
                listViewModelContents.Items.Add(new ListViewItem(Resources.EmptyModelCodeFirstOption, "EmptyModelCodeFirst.png"));
                listViewModelContents.Items.Add(new ListViewItem(Resources.CodeFirstFromDatabaseOption, "CodeFirstFromDatabase.png"));
            }

            // Always select the first item
            listViewModelContents.MultiSelect = false;
            listViewModelContents.Items[0].Selected = true;

            listViewModelContents.Focus();
        }
        private static Mock<WizardPageStart> CreateMockWizardPageStart(ModelBuilderWizardForm mockWizard, int itemIndex, 
            ConfigFileUtils configFileUtils = null)
        {
            var mockWizardPageStart = new Mock<WizardPageStart>(mockWizard, configFileUtils) { CallBase = true };
            mockWizardPageStart
                .Protected()
                .Setup<bool>("AnyItemSelected")
                .Returns(true);

            mockWizardPageStart
                .Protected()
                .Setup<bool>("VerifyModelFilePath", ItExpr.IsAny<string>())
                .Returns(true);

            mockWizardPageStart
                .Protected()
                .Setup<int>("GetSelectedOptionIndex")
                .Returns(itemIndex);
            return mockWizardPageStart;
        }
        public void RunStarted(
            object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind,
            object[] customParams)
        {
            // the dte is the handle into the VS environment
            var dte = (DTE2)automationObject;
            var serviceProvider = new ServiceProvider((IOleServiceProvider)dte);

            // get the current project that the wizard is running in
            var project = VsUtils.GetActiveProject(dte);
            Debug.Assert(project != null, "Unable to retrieve ActiveSolutionProject from DTE");

            EnsureCanStartWizard(project, serviceProvider);

            // get file name the user chose 
            string modelName;
            replacementsDictionary.TryGetValue("$rootname$", out modelName);

            Debug.Assert(modelName != null, "Unable to get $rootname$ from replacementsDictionary");

            modelName = SanitizeModelName(modelName);

            PopluateReplacementDictionary(project, replacementsDictionary, modelName);

            _modelBuilderSettings = new ModelBuilderSettings
            {
                VSApplicationType = VsUtils.GetApplicationType(serviceProvider, project),
                WizardKind = WizardKind.Generate,
                TargetSchemaVersion =
                    EdmUtils.GetEntityFrameworkVersion(project, serviceProvider, useLatestIfNoEF: false),
                NewItemFolder = GetFolderNameForNewItems(dte, project),
                Project = project,
                ModelName = modelName,
                VsTemplatePath = customParams[0] as string,
                ReplacementDictionary = replacementsDictionary
            };

            var form = new ModelBuilderWizardForm(
                serviceProvider,
                _modelBuilderSettings,
                ModelBuilderWizardForm.WizardMode.PerformAllFunctionality)
            {
                FileAlreadyExistsError = false
            };

            try
            {
                form.Start();
            }
            catch (Exception ex)
            {
                VsUtils.ShowErrorDialog(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ModelObjectItemWizard_UnexpectedExceptionHasOccurred,
                        ex.Message));

                ClearErrors();

                throw new WizardCancelledException();
            }


            // the form.FileAlreadyExistsError flag is set in the WizardPageStart. We do it because if we 
            // threw this exception directly from the WizardPageStart it would be swallowed and the
            // "Add New Item" dialog would not show up. Throwing the exception from here will make
            // the "Add New Item" dialog re-appear which allows the user to enter a different model name.
            if (form.FileAlreadyExistsError)
            {
                Marshal.ThrowExceptionForHR(VSConstants.E_ABORT);
            }

            // if they cancelled or they didn't cancel, and we didn't log that Finish was pressed, 
            // they must have hit the X or an exception happened so cancel
            if (form.WizardCancelled
                || !form.WizardFinished)
            {
                ClearErrors();
                throw new WizardCancelledException();
            }

            Debug.Assert(ReferenceEquals(_modelBuilderSettings, form.ModelBuilderSettings));
        }
        protected static ModelBuilderSettings SetupSettingsAndModeForDbPages(
            IServiceProvider serviceProvider,
            Project project,
            EFArtifact artifact,
            bool checkDatabaseConnection,
            ModelBuilderWizardForm.WizardMode noConnectionMode,
            ModelBuilderWizardForm.WizardMode existingConnectionMode,
            out ModelBuilderWizardForm.WizardMode startMode)
        {
            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;
            var settings = new ModelBuilderSettings
            {
                VSApplicationType = VsUtils.GetApplicationType(serviceProvider, project),
                AppConfigConnectionPropertyName = entityContainerName,
                Artifact = artifact,
                UseLegacyProvider = ModelHelper.GetDesignerPropertyValueFromArtifactAsBool(
                    OptionsDesignerInfo.ElementName,
                    OptionsDesignerInfo.AttributeUseLegacyProvider,
                    OptionsDesignerInfo.UseLegacyProviderDefault,
                    artifact),
                TargetSchemaVersion = artifact.SchemaVersion,
                Project = project,
                ModelPath = artifact.Uri.LocalPath,
                ProviderManifestToken = artifact.GetProviderManifestToken()
            };

            // 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.

            // 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 = serviceProvider.GetService(typeof(IVsDataConnectionManager)) as IVsDataConnectionManager;
                        Debug.Assert(dataConnectionManager != null, "Could not find IVsDataConnectionManager");

                        var dataProviderManager = serviceProvider.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, serviceProvider);

                                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(
                        serviceProvider,
                        project,
                        runtimeProviderName,
                        runtimeProviderConnectionString,
                        runtimeProviderConnectionString,
                        false);
                    settings.InitialCatalog = initialCatalog;
                    settings.AppConfigConnectionPropertyName = entityContainerName;
                    settings.SaveConnectionStringInAppConfig = false;

                    VsUtils.EnsureProvider(runtimeProviderName, settings.UseLegacyProvider, project, serviceProvider);
                }
            }

            return settings;
        }
Beispiel #32
0
        protected void bgWorkerPopulateTree_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
        {
            try
            {
                _stopwatch.Stop();

                if (args.Cancelled)
                {
                    return;
                }

                if (args.Error != null)
                {
                    // show error dialog
                    var errMsg = ModelBuilderWizardForm.ShowDatabaseConnectionErrorDialog(args.Error);

                    Visited = false;

                    // if database config could be at fault revert to database config page
                    // otherwise just show the error message in the wizard and enable the cancel button
                    if (ModelBuilderWizardForm.WizardMode.PerformDatabaseConfigAndSelectTables == Wizard.Mode)
                    {
                        Wizard.OnPrevious();
                    }
                    else
                    {
                        ShowStatus(errMsg);
                        Wizard.EnableButton(ButtonType.Cancel, true);
                    }
                }
                else
                {
                    // No errors, populate nodes in TreeViews
                    var result       = (ICollection <EntityStoreSchemaFilterEntry>[])args.Result;
                    var tableEntries = result[0];
                    var viewEntries  = result[1];
                    var sprocEntries = result[2];

                    // First find all tables, views and storedProc's which exist in the current model (before update from DB)
                    // (value is not used - but list is in sorted order to ensure they show up correctly on the wizard)
                    SortedDictionary <DatabaseObject, int> existingTables;
                    SortedDictionary <DatabaseObject, int> existingViews;
                    SortedDictionary <DatabaseObject, int> existingStoredProcs;
                    GetExistingTablesViewsAndSprocs(
                        Wizard.ModelBuilderSettings.Artifact,
                        out existingTables, out existingViews, out existingStoredProcs);

                    // now create the tree nodes
                    string storageEntityContainerName = null;
                    if (null != Wizard.ModelBuilderSettings.Artifact &&
                        null != Wizard.ModelBuilderSettings.Artifact.StorageModel() &&
                        null != Wizard.ModelBuilderSettings.Artifact.StorageModel().FirstEntityContainer &&
                        null != Wizard.ModelBuilderSettings.Artifact.StorageModel().FirstEntityContainer.LocalName &&
                        null != Wizard.ModelBuilderSettings.Artifact.StorageModel().FirstEntityContainer.LocalName.Value)
                    {
                        storageEntityContainerName =
                            Wizard.ModelBuilderSettings.Artifact.StorageModel().FirstEntityContainer.LocalName.Value;
                    }
                    CreateAddRefreshAndDeleteTreeNodes(
                        tableEntries,
                        viewEntries,
                        sprocEntries,
                        existingTables,
                        existingViews,
                        existingStoredProcs,
                        storageEntityContainerName);

                    // Hide status message
                    HideStatus();

                    // Enable tab pages and make Description fields visible
                    AddUpdateDeleteTabControl.Enabled = true;
                    DescriptionTextBox.Visible        = true;

                    // Set focus to TreeView
                    var currentTreeView = CurrentTreeView;
                    if (null != currentTreeView)
                    {
                        currentTreeView.FocusAndSetFirstNodeSelected();
                    }

                    TreeViewsInitialized       = true;
                    _initializedDataConnection = Wizard.ModelBuilderSettings.DesignTimeConnectionString;
                }

                // Enable wizard navigation
                Wizard.OnValidationStateChanged(this);
            }
            catch (Exception e)
            {
                ShowStatus(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        Resources.SelectTablesPage_ErrorRetrievingTablesText,
                        e.Message));
                Wizard.EnableButton(ButtonType.Cancel, true);
            }
        }