Exemple #1
0
        // internal for testing, settings parameter to allow testing without messing with the static variable
        internal void RunFinished(ModelBuilderSettings settings, string targetDirectory)
        {
            // null indicates an error when generating code
            if (_generatedCode == null)
            {
                return;
            }

            var project = settings.Project;

            var filesToSave = _generatedCode.Skip(1)
                              .ToDictionary(kvp => Path.Combine(targetDirectory, kvp.Key), kvp => (object)kvp.Value);

            try
            {
                _vsUtils.WriteCheckoutTextFilesInProject(filesToSave);
            }
            finally
            {
                // even if saving fails we actually might have created some files
                // and we should add them to the project
                AddFilesToProject(project, filesToSave.Keys);
            }

            _configFileUtils =
                _configFileUtils ??
                new ConfigFileUtils(
                    project,
                    PackageManager.Package,
                    settings.VSApplicationType);

            UpdateConfigFile(settings);
        }
Exemple #2
0
    public void LoadCustomPreset()
    {
        if (!Directory.Exists(PhysicalConfigurable.CustomDefaultConfigFileDirectory))
        {
            StartCoroutine(ShowNotification(notificationImportFailed));
            return;
        }

        bool corrupt;
        bool missing;

        ConfigFileUtils.CheckForInvalidCustomDefault(fileDropdown.options[fileDropdown.value].text, out corrupt, out missing);

        if (corrupt)
        {
            StartCoroutine(ShowNotification(notificationImportCorrupt));
            return;
        }

        if (missing)
        {
            StartCoroutine(ShowNotification(notificationImportMissing));
        }
        else
        {
            StartCoroutine(ShowNotification(notificationImport));
        }

        ConfigFileUtils.LoadCustomDefaultsOnAllConfigFiles(fileDropdown.options[fileDropdown.value].text);
    }
        public void InterpolateConfigFromDict()
        {
            string     expected;
            FileStream fileStream = new FileStream("expectedconfig.cfg", FileMode.Open);

            using (StreamReader reader = new StreamReader(fileStream))
            {
                expected = reader.ReadToEnd();
            }

            fileStream = new FileStream("csgoconfig.cfg", FileMode.Open);
            string template;

            using (StreamReader reader = new StreamReader(fileStream))
            {
                template = reader.ReadToEnd();
            }

            var values = new Dictionary <string, string>()
            {
                { "![ServerName]", "Test Server" },
                { "![RconPassword]", "password" },
                { "![TestVar1]", "thing1" },
                { "![TestVar2]", "thing2" },
                { "![TestVar3]", "thing3" }
            };
            var result = ConfigFileUtils.InterpolateConfigFromDict(values, template);

            Assert.Equal(expected, result);
        }
Exemple #4
0
 // testing only
 internal OneEFWizard(ConfigFileUtils configFileUtils = null, IVsUtils vsUtils = null, IErrorListHelper errorListHelper = null, ModelGenErrorCache errorCache = null,
                      List <KeyValuePair <string, string> > generatedCode = null)
 {
     _configFileUtils = configFileUtils;
     _generatedCode   = generatedCode ?? new List <KeyValuePair <string, string> >();
     _vsUtils         = vsUtils;
     _errorListHelper = errorListHelper;
     _errorCache      = errorCache;
 }
Exemple #5
0
 public DmatekFileModel()
 {
     configUtils = new ConfigFileUtils();
     configUtils.setCurrentApplicationPatn();
     configUtils.getFile(configUtils.CurrentPath, "cixin.tmetk");
     if (mID_Versions == null)
     {
         mID_Versions = new List <ID_Version>();
     }
     dmatekRead();
 }
        public string InterpolateCommandline(GameServer gameServer)
        {
            string outputCommandline = gameServer.CommandLine;
            var    variables         = ConfigFileUtils.GetVariablesFromGameServer(gameServer);

            foreach (KeyValuePair <string, string> kv in variables)
            {
                _logger.LogDebug($"Attempting to insert {kv.Key} into commandline with value {kv.Value}");
                outputCommandline = outputCommandline.Replace(kv.Key, kv.Value);
            }

            return(outputCommandline);
        }
        public void TestMethod04_InsertTowerTemplate()
        {
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                Filter = "Lcp Files (*.lcp)|*.lcp",
            };

            if (saveFileDialog.ShowDialog() != true)
            {
                return;
            }

            ConfigFileUtils.InsertTowerTemplates(saveFileDialog.FileName, new List <TowerTemplateStorageInfo>
            {
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回交流轻冰区(三跨验算)",
                    TowerType = "直线塔"
                },
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回交流轻冰区",
                    TowerType = "直线塔"
                },
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回交流轻中冰区",
                    TowerType = "直转塔"
                },
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回直流轻中冰区(8分裂)",
                    TowerType = "直转塔"
                },
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回交流轻中冰区",
                    TowerType = "转角塔"
                },
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回交流轻中冰区",
                    TowerType = "分支塔"
                },
                new TowerTemplateStorageInfo()
                {
                    Name      = "单回交流轻中冰区",
                    TowerType = "终端塔"
                },
            });
        }
        public void TestMethod05_UpdateTowerTemplate()
        {
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                Filter = "Lcp Files (*.lcp)|*.lcp",
            };

            if (saveFileDialog.ShowDialog() != true)
            {
                return;
            }

            ConfigFileUtils.UpdateTowerTemplateName(saveFileDialog.FileName, "单回交流轻冰区(三跨验算)1", "直线塔", "单回交流轻冰区(三跨验算)2", "直转塔");
        }
Exemple #9
0
    public void SaveCustomPreset()
    {
        if (nameInput.text == "")
        {
            StartCoroutine(ShowInvalidName());
            return;
        }

        ConfigFileUtils.SaveCustomDefaults(nameInput.text);
        LoadFilesIntoDropdown();

        // show the user that they exported the files
        StartCoroutine(ShowExportSuccess());
    }
Exemple #10
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;
        }
Exemple #11
0
        internal static void SqlDatabaseFileUpgradeService_OnUpgradeProject(
            IVsHierarchy hierarchy, string databaseFile, string newConnectionString, IVsUpgradeLogger logger)
        {
            if (PackageManager.Package != null &&
                PackageManager.Package.ModelManager != null)
            {
                var project = VSHelpers.GetProject(hierarchy);

                // skip the step if it is a miscellaneous project or if the project is using IIS
                // (projects using IIS should not be upgraded - see bug 812074)
                if (project != null &&
                    !VsUtils.IsMiscellaneousProject(project) &&
                    !IsUsingIIS(project))
                {
                    // update the config file as needed
                    var configFileUtils = new ConfigFileUtils(project, PackageManager.Package);
                    UpdateConfigForSqlDbFileUpgrade(configFileUtils, project, logger);
                }
            }
        }
Exemple #12
0
 internal static void UpdateConfigForSqlDbFileUpgrade(ConfigFileUtils configFileUtils, Project project, IVsUpgradeLogger logger)
 {
     try
     {
         var configXmlDoc = configFileUtils.LoadConfig();
         if (configXmlDoc != null) // check config file exists
         {
             if (ConnectionManager.UpdateSqlDatabaseFileDataSourceInConnectionStrings(configXmlDoc))
             {
                 configFileUtils.SaveConfig(configXmlDoc);
             }
         }
     }
     catch (Exception ex)
     {
         // if there were errors above then do not try to change the files on disk - just log the message and return
         var errMsg = String.Format(
             CultureInfo.CurrentCulture, Resources.ErrorDuringSqlDatabaseFileUpgrade, configFileUtils.GetConfigPath(), ex.Message);
         logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg);
     }
 }
Exemple #13
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);
        }
        public void GetVariablesFromGameServerShould()
        {
            var gameServer = new GameServerFactory().GetGameServer();
            var expected   = new Dictionary <string, string>()
            {
                { "![GameId]", "0" },
                { "![IpAddress]", "192.168.1.50" },
                { "![GamePort]", "29365" },
                { "![QueryPort]", "0" },
                { "![ServerName]", "Test Server" },
                { "![IsEnabled]", "True" },
                { "![HomeDirectory]", @"C:\dev\Server1" },
                { "![CommandLine]", "-game csgo -console -usercon" },
                { "![Slots]", "0" },
                { "![RconPassword]", "password" },
                { "![TestVar1]", "thing1" },
                { "![TestVar2]", "thing2" },
                { "![TestVar3]", "thing3" }
            };

            var result = ConfigFileUtils.GetVariablesFromGameServer(gameServer);

            Assert.Equal(expected, result);
        }
        public async Task Invoke(int gameServerId)
        {
            var gameServer = _repository.Single(DataItemPolicy <GameServer> .ById(gameServerId));

            _repository.List(GameServerConfigFilePolicy.ByServerId(gameServer.Id));
            foreach (var gameServerGameConfigFile in gameServer.GameConfigFiles)
            {
                _logger.LogDebug($"Processing config {gameServerGameConfigFile.FilePath} for game server {gameServer.Id}");
                var variables = ConfigFileUtils.GetVariablesFromGameServer(gameServer);
                if (File.Exists(Path.Combine(gameServer.HomeDirectory, gameServerGameConfigFile.FilePath)))
                {
                    _logger.LogDebug($"Found existing config ({gameServerGameConfigFile.FilePath})");
                    FileStream fileStream = new FileStream(Path.Combine(gameServer.HomeDirectory, gameServerGameConfigFile.FilePath), FileMode.Open);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        gameServerGameConfigFile.FileContent = reader.ReadToEnd();
                    }

                    _repository.Update(gameServerGameConfigFile);
                }

                var config = ConfigFileUtils.InterpolateConfigFromDict(variables, gameServerGameConfigFile.FileContent);
                try
                {
                    using (StreamWriter file =
                               new StreamWriter(Path.Combine(gameServer.HomeDirectory, gameServerGameConfigFile.FilePath)))
                    {
                        file.Write(config);
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError($"Failed to write {gameServerGameConfigFile.FilePath} for server {gameServer.Id}");
                }
            }
        }
        public void RunFinished()
        {
            if (_edmxItem == null)
            {
                return;
            }

            var fileExtension = Path.GetExtension(_edmxItem.FileNames[1]);

            Debug.Assert(
                _activeSolutionProject.Equals(_edmxItem.ContainingProject),
                "ActiveSolutionProject is not the EDMX file's containing project");
            using (new VsUtils.HourglassHelper())
            {
                var    package = PackageManager.Package;
                Window window  = null;

                try
                {
                    ConfigFileUtils.UpdateConfig(_modelBuilderSettings);

                    // save the model generated in the wizard UI.
                    if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                    {
                        var writingModelWatch = new Stopwatch();
                        writingModelWatch.Start();
                        var mbe = _modelBuilderSettings.ModelBuilderEngine;

                        if (!string.Equals(fileExtension, EntityDesignArtifact.EXTENSION_EDMX, StringComparison.OrdinalIgnoreCase))
                        {
                            // convert the file if this isn't EDMX
                            var edmxFileInfo      = new FileInfo(_edmxItem.FileNames[1]);
                            var conversionContext = new ModelConversionContextImpl(
                                _edmxItem.ContainingProject,
                                _edmxItem,
                                edmxFileInfo,
                                _modelBuilderSettings.TargetSchemaVersion,
                                mbe.Model);
                            VSArtifact.DispatchToConversionExtensions(
                                EscherExtensionPointManager.LoadModelConversionExtensions(),
                                fileExtension,
                                conversionContext,
                                loading: false);
                            File.WriteAllText(edmxFileInfo.FullName, conversionContext.OriginalDocument);
                        }
                        else
                        {
                            // we need to use XmlWriter to output so that XmlDeclaration is preserved.
                            using (var modelWriter = XmlWriter.Create(
                                       _edmxItem.FileNames[1],
                                       new XmlWriterSettings {
                                Indent = true
                            }))
                            {
                                mbe.Model.WriteTo(modelWriter);
                            }
                        }

                        writingModelWatch.Stop();
                        VsUtils.LogOutputWindowPaneMessage(
                            _edmxItem.ContainingProject,
                            string.Format(
                                CultureInfo.CurrentCulture,
                                Properties.Resources.WritingModelTimeMsg,
                                writingModelWatch.Elapsed));

                        // now add errors
                        ErrorListHelper.LogWizardErrors(mbe.Errors, _edmxItem);
                    }

                    // set the ItemType for the generated .edmx file
                    if (_modelBuilderSettings.VSApplicationType != VisualStudioProjectSystem.Website &&
                        string.Equals(
                            fileExtension,
                            EntityDesignArtifact.EXTENSION_EDMX,
                            StringComparison.OrdinalIgnoreCase))
                    {
                        _edmxItem.Properties.Item(ItemTypePropertyName).Value = EntityDeployBuildActionName;
                    }

                    // now open created file in VS using default viewer
                    try
                    {
                        window = _edmxItem.Open(Constants.vsViewKindPrimary);
                        Debug.Assert(window != null, "Unable to get window for created edmx file");
                    }
                    catch (ObjectDisposedException)
                    {
                        PackageManager.Package.ModelGenErrorCache.RemoveErrors(_edmxItem.get_FileNames(1));
                    }
                }
                finally
                {
                    package.ModelGenErrorCache.RemoveErrors(_edmxItem.FileNames[1]);
                }

                // Construct an editing context and make all final edits that require the file is opened.
                var edmxFileUri    = new Uri(_edmxItem.FileNames[1]);
                var designArtifact =
                    package.ModelManager.GetNewOrExistingArtifact(
                        edmxFileUri, new VSXmlModelProvider(package, package)) as EntityDesignArtifact;
                Debug.Assert(
                    designArtifact != null,
                    "artifact should be of type EntityDesignArtifact but received type " + designArtifact.GetType().FullName);
                Debug.Assert(
                    designArtifact.StorageModel != null, "designArtifact StorageModel cannot be null for Uri " + edmxFileUri.AbsolutePath);
                Debug.Assert(
                    designArtifact.ConceptualModel != null,
                    "designArtifact ConceptualModel cannot be null for Uri " + edmxFileUri.AbsolutePath);

                if (designArtifact != null &&
                    designArtifact.StorageModel != null &&
                    designArtifact.ConceptualModel != null)
                {
                    var designerSafeBeforeAddingTemplates = designArtifact.IsDesignerSafe;

                    var editingContext =
                        package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(designArtifact.Uri);
                    Debug.Assert(editingContext != null, "Null EditingContext for artifact " + edmxFileUri.AbsolutePath);
                    if (editingContext != null)
                    {
                        // Add DbContext templates when generation is GenerateFromDatabase. (connection is configured)
                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase)
                        {
                            new DbContextCodeGenerator().AddDbContextTemplates(
                                _edmxItem,
                                _modelBuilderSettings.UseLegacyProvider);
                        }

                        // Create FunctionImports for every new Function
                        var cp = PrepareCommandsAndIntegrityChecks(_modelBuilderSettings, editingContext, designArtifact);

                        if (DbContextCodeGenerator.TemplateSupported(_edmxItem.ContainingProject, package))
                        {
                            // Add command setting CodeGenerationStrategy to "None" for EmptyModel. (connection is not yet configured)
                            // NOTE: For EmptyModel, the templates will be added after the connection is configured.
                            //       (i.e. during "Generate Database from Model" or "Refresh from Database")
                            if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.EmptyModel)
                            {
                                var cmd = EdmUtils.SetCodeGenStrategyToNoneCommand(designArtifact);
                                if (cmd != null)
                                {
                                    if (cp == null)
                                    {
                                        var cpc = new CommandProcessorContext(
                                            editingContext,
                                            EfiTransactionOriginator.CreateNewModelId,
                                            Resources.Tx_SetCodeGenerationStrategy);
                                        cp = new CommandProcessor(cpc, cmd);
                                    }
                                    else
                                    {
                                        cp.EnqueueCommand(cmd);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // Templates not supported, add reference to SDE. (.NET Framework 3.5)
                            VsUtils.AddProjectReference(_edmxItem.ContainingProject, "System.Data.Entity");
                        }

                        if (cp != null)
                        {
                            cp.Invoke();
                        }

                        // save the artifact to make it look as though updates were part of creation
                        _edmxItem.Save();

                        if (_modelBuilderSettings.GenerationOption == ModelGenerationOption.GenerateFromDatabase &&
                            !designerSafeBeforeAddingTemplates)
                        {
                            // If the artifact became safe after adding references we need to reload it (this can happen
                            // on .NET Framework 4 where we would originally create a v3 edmx if the user selected EF6 -
                            // the artifact will be flagged as invalid since there is no runtime which could handle v3
                            // but after we added references to EF6 the artifacts becomes valid and need to be reloaded).
                            designArtifact.DetermineIfArtifactIsDesignerSafe();
                            if (designArtifact.IsDesignerSafe)
                            {
                                Debug.Assert(!designArtifact.IsDirty, "Reloading dirty artifact - changes will be lost.");

                                // Since the artifact was originally not valid we did not create the diagram for it.
                                // Using ReloadDocData will cause the diagram to be recreated. Note we don't need to
                                // reload the artifact itself since it has not changed.
                                ((DocData)
                                 VSHelpers.GetDocData(package, designArtifact.Uri.LocalPath)).ReloadDocData(0);
                            }
                        }
                    }

                    if (window != null)
                    {
                        window.Activate();
                    }
                }
            }
        }
        public Task <CommandResponseGameServer> Handle(CreateServerCommand request, CancellationToken cancellationToken)
        {
            _logger.LogDebug($"Running Handler CreateServerCommandHandler");
            var response   = new CommandResponseGameServer();
            var gameServer = request.gameServer;
            var game       = _repository.Single(DataItemPolicy <Game> .ById(gameServer.GameId));

            if (game == null)
            {
                response.status  = CommandResponseStatusEnum.Error;
                response.message = $"Unable to locate game with ID {gameServer.GameId}";
                _mediator.Publish(new ServerInstallStatusNotification("error", $"Unable to locate game with ID {gameServer.GameId}"));
                return(Task.FromResult(response));
            }

            var configFiles = _repository.List(GameDefaultConfigPolicy.ByGameId(game.Id));

            gameServer.GameConfigFiles = new List <GameServerConfigFile>();
            var variables = ConfigFileUtils.GetVariablesFromGameServer(gameServer);

            foreach (var configFile in configFiles)
            {
                gameServer.GameConfigFiles.Add(new GameServerConfigFile()
                {
                    Description           = configFile.Description,
                    FileContent           = configFile.Template,
                    FilePath              = configFile.FilePath,
                    GameServer            = gameServer,
                    GameDefaultConfigFile = configFile
                });
            }


            gameServer.GamePort               = _portProvider.GetNextAvailablePort(game.GamePort, gameServer.IpAddress, game.PortIncrement);
            gameServer.QueryPort              = _portProvider.GetNextAvailablePort(game.QueryPort, gameServer.IpAddress, game.PortIncrement);
            gameServer.HomeDirectory          = Path.Combine(_dirProvider.GetBaseInstallDirectory(), gameServer.Guid.ToString());
            gameServer.GameServerCurrentStats = new GameServerCurrentStats();

            gameServer.GameServerCurrentStats.Status = ServerStatusStates.Installing;
            try
            {
                _repository.Create(gameServer);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                response.status  = CommandResponseStatusEnum.Success;
                response.message = e.ToString();
                _mediator.Publish(new ServerInstallStatusNotification("error", e.ToString()));
                return(Task.FromResult(response));
            }

            try
            {
                _serverManager.InstallGameServer(gameServer);
                _mediator.Publish(new ServerInstallStatusNotification("installing", $"Game server install started for server {gameServer.Guid}"));
                response.status  = CommandResponseStatusEnum.Success;
                response.message = "Game server now installing";
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                response.status  = CommandResponseStatusEnum.Error;
                response.message = e.ToString();
                _mediator.Publish(new ServerInstallStatusNotification("error", e.ToString()));
            }



            return(Task.FromResult(response));
        }
 protected override void CommitValuesToFile()
 {
     ConfigFileUtils.SaveAllConfigFiles();
 }
        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();
        }
Exemple #20
0
        internal static void SqlCeUpgradeService_OnUpgradeProject(IVsHierarchy hierarchy, IVsUpgradeLogger logger)
        {
            if (PackageManager.Package != null &&
                PackageManager.Package.ModelManager != null)
            {
                // since this is about retargeting EDMX files on disk, no need to process other file extensions from any converters
                var fileFinder = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx);
                fileFinder.FindInProject(hierarchy);

                var project = VSHelpers.GetProject(hierarchy);

                // skip the step if it is a miscellaneous project.
                if (project != null &&
                    !VsUtils.IsMiscellaneousProject(project))
                {
                    IDictionary <string, object> documentMap = new Dictionary <string, object>();
                    foreach (var vsFileInfo in fileFinder.MatchingFiles)
                    {
                        try
                        {
                            var projectItem = VsUtils.GetProjectItem(hierarchy, vsFileInfo.ItemId);

                            // Dev 10 bug 648969: skip the process for astoria edmx file.
                            if (EdmUtils.IsDataServicesEdmx(projectItem.get_FileNames(1)))
                            {
                                continue;
                            }

                            // Check whether project item is a linked item
                            var isLinkItem = VsUtils.IsLinkProjectItem(projectItem);

                            if (!isLinkItem)
                            {
                                var doc = MetadataConverterDriver.SqlCeInstance.Convert(SafeLoadXmlFromPath(vsFileInfo.Path));
                                if (doc != null)
                                {
                                    documentMap.Add(vsFileInfo.Path, doc);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            var errMsg = String.Format(
                                CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, vsFileInfo.Path, ex.Message);
                            logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, vsFileInfo.Path, errMsg);
                            return;
                        }
                    }

                    if (documentMap.Count > 0)
                    {
                        VsUtils.WriteCheckoutXmlFilesInProject(documentMap);
                    }

                    // now update the config file as needed
                    var configFileUtils = new ConfigFileUtils(project, PackageManager.Package);
                    try
                    {
                        var configXmlDoc = configFileUtils.LoadConfig();
                        if (configXmlDoc != null) // check config file exists
                        {
                            if (ConnectionManager.UpdateSqlCeProviderInConnectionStrings(configXmlDoc))
                            {
                                configFileUtils.SaveConfig(configXmlDoc);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var errMsg = String.Format(
                            CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, configFileUtils.GetConfigPath(), ex.Message);
                        logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg);
                    }
                }
            }
        }