Beispiel #1
0
        internal static string GetInitialCatalog(IVsDataProviderManager dataProviderManager, IVsDataConnection dataConnection)
        {
            string initialCatalog = null;

            var invariantName = GetProviderInvariantName(dataProviderManager, dataConnection.Provider);
            var props         = GetConnectionProperties(dataProviderManager, dataConnection);

            if (props != null)
            {
                if (props.ContainsKey(LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME)
                    &&
                    !string.IsNullOrEmpty(props[LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME] as string))
                {
                    //sql client with "AttachDbFileName" parameter in the connection string.
                    object o = null;
                    props.TryGetValue(LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME, out o);
                    initialCatalog = o as String;
                    if (initialCatalog != null)
                    {
                        initialCatalog = Path.GetFileNameWithoutExtension(initialCatalog);
                    }
                }
                else if (LocalDataUtil.IsSqlMobileConnectionString(invariantName))
                {
                    // sql CE
                    object o = null;
                    props.TryGetValue(LocalDataUtil.CONNECTION_PROPERTY_DATA_SOURCE, out o);
                    initialCatalog = o as String;
                    if (initialCatalog != null)
                    {
                        initialCatalog = Path.GetFileNameWithoutExtension(initialCatalog);
                    }
                }
                else
                {
                    object o = null;
                    props.TryGetValue("Database", out o);
                    initialCatalog = o as String;
                }
            }

            // save the default catalog
            if (string.IsNullOrEmpty(initialCatalog))
            {
                var sourceInformation = dataConnection.GetService(typeof(IVsDataSourceInformation)) as IVsDataSourceInformation;
                Debug.Assert(
                    sourceInformation != null,
                    "Could not find the IVsDataSourceInformation for this IVsDataConnection to determine the default catalog");
                if (sourceInformation != null)
                {
                    initialCatalog = sourceInformation["DefaultCatalog"] as string;
                    // Note: it is valid for initialCatalog to be null for certain providers which do not support that concept
                }
            }

            return(initialCatalog);
        }
        private bool CopyFileIntoProjectAndConvertConnectionString(string filePath)
        {
            try
            {
                // File is not in the project and user wants to convert it.
                var serviceProvider         = Wizard.ServiceProvider;
                var project                 = Wizard.Project;
                var vsTrackProjectDocuments = serviceProvider.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments3;

                if (null == vsTrackProjectDocuments)
                {
                    Debug.Fail("Could not get IVsTrackProjectDocuments3 from service provider.");
                }
                else
                {
                    // releases any read locks on this file so we can read it
                    vsTrackProjectDocuments.HandsOffFiles((uint)__HANDSOFFMODE.HANDSOFFMODE_ReadAccess, 1, new[] { filePath });
                }

                ProjectItem dbProjectItem = null;
                var         targetProjectItemCollection = LocalDataUtil.GetDefaultCollectionForLocalDataFile(Wizard.ServiceProvider, project);
                dbProjectItem = VsUtils.BringDatabaseFileIntoProject(serviceProvider, project, targetProjectItemCollection, filePath);

                if (dbProjectItem == null)
                {
                    var errmsg = string.Format(CultureInfo.CurrentCulture, Resources.LocalDataErrorAddingFile, filePath, project.UniqueName);
                    throw new FileCopyException(errmsg);
                }

                var newFilePath = (string)dbProjectItem.Properties.Item("FullPath").Value;

                // now re-target the connection string at the copied file
                return(RetargetConnectionString(newFilePath));
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    // User canceled a checkout prompt.
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
        private string ConvertConnectionStringToNewPath(
            string providerInvariantName, string filePathKey, string oldConnectionString, string newFilePath, bool useDataDirectoryMacro)
        {
            if (string.IsNullOrEmpty(filePathKey))
            {
                Debug.Fail("requires non-null, non-empty filePathKey");
                return(oldConnectionString);
            }

            if (LocalDataUtil.IsSqlMobileConnectionString(providerInvariantName))
            {
                // DbConnectionString does not support SQL Mobile
                return(GenerateNewSqlMobileConnectionString(oldConnectionString, newFilePath, useDataDirectoryMacro));
            }

            var dbConnectionStringBuilder = new DbConnectionStringBuilder();

            dbConnectionStringBuilder.ConnectionString = oldConnectionString;
            object filePathObject;

            dbConnectionStringBuilder.TryGetValue(filePathKey, out filePathObject);
            var filePath = filePathObject as string;

            if (string.IsNullOrEmpty(filePath))
            {
                Debug.Fail("could not find filePath for filePathKey=" + filePathKey);
                return(oldConnectionString);
            }

            // replace old path with new one
            dbConnectionStringBuilder.Remove(filePathKey);
            if (useDataDirectoryMacro)
            {
                dbConnectionStringBuilder.Add(filePathKey, DataDirectoryMacro + Path.DirectorySeparatorChar + Path.GetFileName(newFilePath));
            }
            else
            {
                dbConnectionStringBuilder.Add(filePathKey, newFilePath);
            }

            return(dbConnectionStringBuilder.ConnectionString);
        }
Beispiel #4
0
        internal static string GetInitialCatalog(string providerName, string providerConnectionString)
        {
            var dbsb = new DbConnectionStringBuilder();

            dbsb.ConnectionString = providerConnectionString;
            var initialCatalog = String.Empty;

            if (dbsb.ContainsKey(LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME)
                &&
                !string.IsNullOrEmpty(dbsb[LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME] as string))
            {
                //sql client with "AttachDbFileName" parameter in the connection string.
                object o = null;
                dbsb.TryGetValue(LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME, out o);
                initialCatalog = o as String;
                if (initialCatalog != null)
                {
                    initialCatalog = Path.GetFileNameWithoutExtension(initialCatalog);
                }
            }
            else if (LocalDataUtil.IsSqlMobileConnectionString(providerName))
            {
                // sql CE
                object o = null;
                dbsb.TryGetValue(LocalDataUtil.CONNECTION_PROPERTY_DATA_SOURCE, out o);
                initialCatalog = o as String;
                if (initialCatalog != null)
                {
                    initialCatalog = Path.GetFileNameWithoutExtension(initialCatalog);
                }
            }
            else
            {
                object o = null;
                dbsb.TryGetValue("Initial Catalog", out o);
                initialCatalog = o as String;
            }

            return(initialCatalog);
        }
        public override void OnActivated()
        {
            base.OnActivated();

            _onWorkflowCleanup = false;

            Debug.Assert(
                !Wizard.MovingNext || _workflowInstance == null,
                "Possible memory leak: We should have destroyed the old workflow instance when activating WizardPageDbGenSummary");

            if (_workflowInstance == null)
            {
                if (LocalDataUtil.IsSqlMobileConnectionString(Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName))
                {
                    _ddlFileExtension = DatabaseGenerationEngine._sqlceFileExtension;
                }
                else
                {
                    _ddlFileExtension = DatabaseGenerationEngine._ddlFileExtension;
                }

                // Add in the DbConfig page before if we have found a connection
                if (Wizard.Mode == ModelBuilderWizardForm.WizardMode.PerformDBGenSummaryOnly &&
                    _addedDbConfigPage == false)
                {
                    Wizard.InsertPageBefore(Id, new WizardPageDbConfig(Wizard));
                    _addedDbConfigPage = true;
                }

                // Display the default path for the DDL
                var artifactProjectItem = VsUtils.GetProjectItemForDocument(
                    Wizard.ModelBuilderSettings.Artifact.Uri.LocalPath, PackageManager.Package);
                if (artifactProjectItem != null)
                {
                    txtSaveDdlAs.Text = DatabaseGenerationEngine.CreateDefaultDdlFileName(artifactProjectItem) + _ddlFileExtension;
                }

                // Disable all buttons except for Previous and Cancel
                Wizard.EnableButton(ButtonType.Previous, true);
                Wizard.EnableButton(ButtonType.Next, false);
                Wizard.EnableButton(ButtonType.Finish, false);
                Wizard.EnableButton(ButtonType.Cancel, true);

                // Display a status message
                ShowStatus(Properties.Resources.DbGenSummary_StatusDeterminingDDL);

                // Extract the XML from the EDMX file and convert it into an EdmItemCollection for the workflow
                EdmItemCollection edm = null;
                using (new VsUtils.HourglassHelper())
                {
                    IList <EdmSchemaError> schemaErrors;
                    edm = Wizard.ModelBuilderSettings.Artifact.GetEdmItemCollectionFromArtifact(out schemaErrors);

                    Debug.Assert(
                        edm != null && schemaErrors.Count == 0,
                        "EdmItemCollection schema errors found; we should have performed validation on the EdmItemCollection before instantiating the wizard.");
                }

                var existingSsdl = Wizard.ModelBuilderSettings.Artifact.GetSsdlAsString();
                var existingMsl  = Wizard.ModelBuilderSettings.Artifact.GetMslAsString();

                // Attempt to get the workflow path, template path, and database schema name from the artifact. If we don't find them, we'll use defaults.
                var workflowPath       = DatabaseGenerationEngine.GetWorkflowPathFromArtifact(Wizard.ModelBuilderSettings.Artifact);
                var templatePath       = DatabaseGenerationEngine.GetTemplatePathFromArtifact(Wizard.ModelBuilderSettings.Artifact);
                var databaseSchemaName = DatabaseGenerationEngine.GetDatabaseSchemaNameFromArtifact(Wizard.ModelBuilderSettings.Artifact);

                // Save off the SynchronizationContext so we can post methods to the UI event queue when
                // responding to workflow events (since they are executed in a separate thread)
                _synchronizationContext = SynchronizationContext.Current;

                // Invoke the Pipeline/Workflow. The Workflow engine will automatically wrap this in a background thread
                try
                {
                    using (new VsUtils.HourglassHelper())
                    {
                        var resolvedWorkflowFileInfo = DatabaseGenerationEngine.ResolveAndValidateWorkflowPath(
                            Wizard.Project,
                            workflowPath);

                        var resolvedDefaultPath = VsUtils.ResolvePathWithMacro(
                            null, DatabaseGenerationEngine.DefaultWorkflowPath,
                            new Dictionary <string, string>
                        {
                            { ExtensibleFileManager.EFTOOLS_USER_MACRONAME, ExtensibleFileManager.UserEFToolsDir.FullName },
                            { ExtensibleFileManager.EFTOOLS_VS_MACRONAME, ExtensibleFileManager.VSEFToolsDir.FullName }
                        });

                        // Display a security warning if the workflow path specified is different from the default
                        if (!resolvedWorkflowFileInfo.FullName.Equals(
                                Path.GetFullPath(resolvedDefaultPath), StringComparison.OrdinalIgnoreCase))
                        {
                            var displayCustomWorkflowWarning = true;
                            try
                            {
                                var customWorkflowWarningString = EdmUtils.GetUserSetting(RegKeyNameCustomWorkflowWarning);
                                if (false == String.IsNullOrEmpty(customWorkflowWarningString) &&
                                    false == Boolean.TryParse(customWorkflowWarningString, out displayCustomWorkflowWarning))
                                {
                                    displayCustomWorkflowWarning = true;
                                }
                                if (displayCustomWorkflowWarning)
                                {
                                    var cancelledDuringCustomWorkflowWarning = DismissableWarningDialog
                                                                               .ShowWarningDialogAndSaveDismissOption(
                                        Resources.DatabaseCreation_CustomWorkflowWarningTitle,
                                        Resources.DatabaseCreation_WarningCustomWorkflow,
                                        RegKeyNameCustomWorkflowWarning,
                                        DismissableWarningDialog.ButtonMode.OkCancel);
                                    if (cancelledDuringCustomWorkflowWarning)
                                    {
                                        HandleError(
                                            String.Format(
                                                CultureInfo.CurrentCulture, Resources.DatabaseCreation_CustomWorkflowCancelled,
                                                resolvedWorkflowFileInfo.FullName), false);
                                        return;
                                    }
                                }
                            }
                            catch (SecurityException e)
                            {
                                // We should at least alert the user of why this is failing so they can take steps to fix it.
                                VsUtils.ShowMessageBox(
                                    Services.ServiceProvider,
                                    String.Format(
                                        CultureInfo.CurrentCulture, Resources.ErrorReadingWritingUserSetting,
                                        RegKeyNameCustomWorkflowWarning, e.Message),
                                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                                    OLEMSGICON.OLEMSGICON_WARNING);
                            }
                        }

                        _workflowInstance = DatabaseGenerationEngine.CreateDatabaseScriptGenerationWorkflow(
                            _synchronizationContext,
                            Wizard.Project,
                            Wizard.ModelBuilderSettings.Artifact.Uri.LocalPath,
                            resolvedWorkflowFileInfo,
                            templatePath,
                            edm,
                            existingSsdl,
                            existingMsl,
                            databaseSchemaName,
                            Wizard.ModelBuilderSettings.InitialCatalog,
                            Wizard.ModelBuilderSettings.RuntimeProviderInvariantName,
                            Wizard.ModelBuilderSettings.AppConfigConnectionString,
                            Wizard.ModelBuilderSettings.ProviderManifestToken,
                            Wizard.ModelBuilderSettings.Artifact.SchemaVersion,
                            _workflowInstance_WorkflowCompleted,
                            _workflowInstance_UnhandledException);
                    }

                    Wizard.ModelBuilderSettings.WorkflowInstance = _workflowInstance;

                    _workflowInstance.Run();
                }
                catch (Exception e)
                {
                    HandleError(e.Message, true);

                    if (_workflowInstance != null)
                    {
                        CleanupWorkflow();
                    }
                }
            }
        }
        // <summary>
        //     Changes connection string to point to new file path
        // </summary>
        // <param name="newFilePath">New file path</param>
        // <returns>whether successful</returns>
        private bool RetargetConnectionString(string newFilePath)
        {
            // compute the Design and Runtime Connection String values based on the new file path
            // Note: newAppConfigConnectionString should use the |DataDirectory| macro because
            // that is what's displayed on screen and interpreted at runtime, but newConnectionString
            // should not use the macro as it will be used by the wizard at the next step to create
            // a working DB connection
            var filePathKey = LocalDataUtil.GetFilePathKey(
                Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                Wizard.ModelBuilderSettings.DesignTimeConnectionString);
            var newConnectionString = ConvertConnectionStringToNewPath(
                Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName, filePathKey,
                Wizard.ModelBuilderSettings.DesignTimeConnectionString, newFilePath, false);
            var newAppConfigConnectionString = ConvertConnectionStringToNewPath(
                Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName, filePathKey,
                Wizard.ModelBuilderSettings.AppConfigConnectionString, newFilePath, true);

            // update the DataConnection itself with the new path
            var oldProvider = DataConnectionUtils.GetVsProvider(_dataProviderManager, _dataConnection);

            if (null == oldProvider)
            {
                Debug.Fail("Could not find VS Provider for DataConnection " + _dataConnection.DisplayConnectionString);
                return(false);
            }

            if (null == _dataConnectionManager)
            {
                Debug.Fail("this._dataConnectionManager is null - cannot construct new DataConnection");
                return(false);
            }

            var dataConnection = _dataConnectionManager.GetConnection(oldProvider.Guid, newConnectionString, false);

            if (null == dataConnection)
            {
                Debug.Fail(
                    "DataConnectionManager could not get a connection for provider " + oldProvider.Guid + ", newConnectionString "
                    + newConnectionString);
                return(false);
            }

            // update this WizardPage's DataConnection and also set the DataSourceComboBoxItem's
            // dataConnection to this so that this connection is used if the user re-selects this
            // item from the drop-down
            SetDataConnection(dataConnection);
            var currentDataSourceComboBoxItem = dataSourceComboBox.SelectedItem as DataSourceComboBoxItem;

            Debug.Assert(null != currentDataSourceComboBoxItem, "Currently selected should not be null");
            if (null != currentDataSourceComboBoxItem)
            {
                currentDataSourceComboBoxItem.ResetDataConnection(dataConnection);
            }

            // update the Design and Runtime Connection String values stored in ModelBuilderSettings
            // these connection strings & invariant names are coming from the ddex provider, so these are "design-time"
            Wizard.ModelBuilderSettings.SetInvariantNamesAndConnectionStrings(ServiceProvider,
                                                                              Wizard.Project, Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName, newConnectionString,
                                                                              newAppConfigConnectionString, true);
            return(true);
        }
        // <summary>
        //     Prompts the user to copy the database file into the project if appropriate
        // </summary>
        // <returns>whether wizard should continue to next page</returns>
        private bool PromptConvertLocalConnection()
        {
            // first check whether connection is Local
            if (!LocalDataUtil.IsLocalDbFileConnectionString(
                    Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                    Wizard.ModelBuilderSettings.DesignTimeConnectionString))
            {
                return(true);
            }

            // if connection is Local but has already been copied into the project should not prompt
            var filePath = LocalDataUtil.GetLocalDbFilePath(
                Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                Wizard.ModelBuilderSettings.DesignTimeConnectionString);

            if (!string.IsNullOrEmpty(filePath))
            {
                var projectItemCollection = LocalDataUtil.GetDefaultCollectionForLocalDataFile(Wizard.ServiceProvider, Wizard.Project);
                var targetPath            = VsUtils.ConstructTargetPathForDatabaseFile(
                    Wizard.Project, projectItemCollection, Path.GetFileName(filePath));
                if (File.Exists(targetPath))
                {
                    return(true);
                }
            }

            // Special case -- Check if this is a SQL Mobile Device
            if (LocalDataUtil.IsSqlMobileDeviceConnectionString(
                    Wizard.ModelBuilderSettings.DesignTimeProviderInvariantName,
                    Wizard.ModelBuilderSettings.DesignTimeConnectionString))
            {
                // For mobile devices, if the connection starts with 'Mobile Device' it means that the connection
                // refers to a location on the device itself. Do not perform conversion.
                return(true);
            }

            // ask user if they want to copy
            var result = VsUtils.ShowMessageBox(
                Wizard.ServiceProvider,
                Resources.LocalDataConvertConnectionText,
                OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                OLEMSGICON.OLEMSGICON_QUERY);

            if (DialogResult.Yes != result)
            {
                return(true);
            }

            try
            {
                return(CopyFileIntoProjectAndConvertConnectionString(filePath));
            }
            catch (FileCopyException e)
            {
                var errMsgWithInnerExceptions = VsUtils.ConstructInnerExceptionErrorMessage(e);
                var errMsg = string.Format(
                    CultureInfo.CurrentCulture, Resources.LocalDataExceptionCopyingFile, e.GetType().FullName, filePath,
                    errMsgWithInnerExceptions);
                VsUtils.ShowErrorDialog(errMsg);
                return(false);
            }
        }
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        var rect = EditorGUILayout.GetControlRect();

        /*----------- uuid suffix -------------*/
        uuidSuffix = LocalDataUtil.Get(GameManager.PREFS_UUID_SUFFIX, "");
        uuidSuffix = EditorGUILayout.TextField("UUID SUFFIX", uuidSuffix);
        LocalDataUtil.Set(GameManager.PREFS_UUID_SUFFIX, uuidSuffix);


        /*----------- custom ip -----------------*/
        m_selected  = LocalDataUtil.Get(PREFS_SELECTED_CUSTOM_ADDRESS, (int)0);
        rect        = EditorGUILayout.GetControlRect();
        rect.width -= 40f;
        m_selected  = EditorGUI.Popup(rect, "Main Server Address", m_selected, dataList.serverIPDescriptions);
        LocalDataUtil.Set(PREFS_SELECTED_CUSTOM_ADDRESS, m_selected);
        serverAddress = dataList.serverIPs[m_selected];
        LocalDataUtil.Set(GameManager.PREFS_SERVER_ADDRESS, serverAddress);


        rect.x    += rect.width;
        rect.width = 20f;
        if (GUI.Button(rect, "+"))
        {
            currentIP = !currentIP;
            tempName  = "";
            tempValue = "";
        }
        rect.x += 20f;
        if (GUI.Button(rect, "-"))
        {
            if (m_selected > 0 && m_selected < dataList.serverIPs.Length)
            {
                var ips   = dataList.serverIPs.ToListFromPool();
                var names = dataList.serverIPDescriptions.ToListFromPool();
                ips.RemoveAt(m_selected);
                names.RemoveAt(m_selected);
                dataList.serverIPs            = ips.ToArray();
                dataList.serverIPDescriptions = names.ToArray();
                ips.ReleaseToPool();
                names.ReleaseToPool();
                m_selected = 0;
                LocalDataUtil.Set(PREFS_SELECTED_CUSTOM_ADDRESS, m_selected);
                SaveFile();
            }
        }

        if (currentIP)
        {
            tempName  = EditorGUILayout.TextField("New Name", tempName).Trim();
            tempValue = EditorGUILayout.TextField("New IP", tempValue).Trim();
            rect      = EditorGUILayout.GetControlRect();
            if (GUI.Button(rect, "save"))
            {
                currentIP = false;
                var newips = dataList.serverIPs.ToListFromPool();
                if (!newips.Contains(tempValue))
                {
                    var newnames = dataList.serverIPDescriptions.ToListFromPool();
                    newnames.Add(tempName);
                    newips.Add(tempValue);
                    dataList.serverIPs            = newips.ToArray();
                    dataList.serverIPDescriptions = newnames.ToArray();
                    newnames.ReleaseToPool();
                    SaveFile();
                }
                newips.ReleaseToPool();
            }
        }


        /*-------------- Trigger Heartbeat Timeout -------------*/
        if (Application.isPlaying && GUILayout.Button("Trigger Heartbeat Timeout(Main)"))
        {
            if (NetworkManager.instance != null && NetworkManager.instance.main != null)
            {
                NetworkManager.instance.main.heartbeat.TestTriggerTimeout();
            }
        }

        if (Application.isPlaying && GUILayout.Button("Trigger Heartbeat Timeout(Battle)"))
        {
            if (NetworkManager.instance != null && NetworkManager.instance.battle != null)
            {
                NetworkManager.instance.battle.heartbeat.TestTriggerTimeout();
            }
        }
    }
 void SaveFile()
 {
     File.WriteAllText(EditorConfig.CONFIG_PATH + "GameManagerToolConfig.json", LocalDataUtil.ToJson(dataList, true));
 }
 void Awake()
 {
     dataList = LocalDataUtil.FromJson <DataList>(File.ReadAllText(EditorConfig.CONFIG_PATH + "GameManagerToolConfig.json"));
 }