public int OnClose(ref uint pgrfSaveOptions)
        {
            if (!Properties.Settings.Default.PromptToSaveChangedScript)
            {
                return(Microsoft.VisualStudio.VSConstants.S_OK);
            }
            // Check if your content is dirty here, then
            var window = _control as SqlEditorControl;

            if (window != null && window.IsDirty && !_mustClose)
            {
                // Prompt a dialog
                DialogResult res = EnvDteHelper.ShowMessageBox("This script has been modified. Do you want to save the changes ?", OLEMSGBUTTON.OLEMSGBUTTON_YESNOCANCEL, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_QUERY);
                // If the users wants to save
                if (res == DialogResult.Yes)
                {
                    window.SaveScript(true);
                }
                if (res == DialogResult.Cancel)
                {
                    // If "cancel" is clicked, abort the close
                    return(Microsoft.VisualStudio.VSConstants.E_ABORT);
                }
                if (res == DialogResult.No)
                {
                    _mustClose = true;
                }
            }
            return(Microsoft.VisualStudio.VSConstants.S_OK);
        }
示例#2
0
        public void DropSubscription(object sender, ExecutedRoutedEventArgs e)
        {
            if (EnvDteHelper.ShowMessageBox("Do you really want to remove replication metadata from the SQL Server Compact database?", Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO, Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }
            var menuInfo = menuItem.CommandParameter as MenuCommandParameters;

            if (menuInfo == null)
            {
                return;
            }
            try
            {
                SqlCeReplicationHelper.DropPublication(menuInfo.DatabaseInfo.ConnectionString, menuInfo.Name);
                if (_parentWindow != null && _parentWindow.Content != null)
                {
                    ExplorerControl control = _parentWindow.Content as ExplorerControl;
                    control.BuildDatabaseTree();
                }
                Helpers.DataConnectionHelper.LogUsage("SubscriptionDrop");
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, menuInfo.DatabaseInfo.DatabaseType, false);
            }
        }
        public void DropScope(object sender, ExecutedRoutedEventArgs e)
        {
            if (EnvDteHelper.ShowMessageBox("Do you really want to deprovision this scope?", Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO, Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }
            var menuInfo = menuItem.CommandParameter as MenuCommandParameters;

            if (menuInfo == null)
            {
                return;
            }
            try
            {
                SyncFxHelper.DeprovisionSqlCeScope(menuInfo.DatabaseInfo.ConnectionString, menuInfo.Name);
                EnvDteHelper.ShowMessage("Scope deprovisioned");
                if (_parentWindow != null && _parentWindow.Content != null)
                {
                    ExplorerControl control = _parentWindow.Content as ExplorerControl;
                    control.BuildDatabaseTree();
                }
                Helpers.DataConnectionHelper.LogUsage("SyncScopeDrop");
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, menuInfo.DatabaseInfo.DatabaseType);
            }
        }
 private bool TestConnection(bool showMessage)
 {
     try
     {
         if (_createDb)
         {
             if (!System.IO.File.Exists(dataSourceTextBox.Text))
             {
                 var engineHelper = Helpers.RepositoryHelper.CreateEngineHelper(DbType);
                 engineHelper.CreateDatabase(_connectionString);
             }
         }
         using (Helpers.RepositoryHelper.CreateRepository(new DatabaseInfo {
             ConnectionString = _connectionString, DatabaseType = DbType
         }))
         {
             if (showMessage)
             {
                 EnvDteHelper.ShowMessage("Connection OK!");
             }
             else
             {
                 DialogResult = true;
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         if (ex.Message.Contains("Please upgrade using SqlCeEngine.Upgrade() method") && DbType == DatabaseType.SQLCE40)
         {
             if (EnvDteHelper.ShowMessageBox("This database file is from an earlier version,\n\rwould you like to Upgrade it?\n\r(A copy of the original file will be named .bak)"
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.Yes)
             {
                 var bakFile = dataSourceTextBox.Text + ".bak";
                 var go      = true;
                 try
                 {
                     if (System.IO.File.Exists(bakFile))
                     {
                         if (EnvDteHelper.ShowMessageBox(string.Format("{0} already exists, do you wish to overwrite it?", bakFile)
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.Yes)
                         {
                             System.IO.File.Delete(bakFile);
                         }
                         else
                         {
                             go = false;
                         }
                     }
                     if (go)
                     {
                         System.IO.File.Copy(dataSourceTextBox.Text, dataSourceTextBox.Text + ".bak");
                         var helper = new SqlCeScripting.SqlCeHelper4();
                         helper.UpgradeTo40(_connectionString);
                         DialogResult = true;
                     }
                 }
                 catch (Exception ex2)
                 {
                     DataConnectionHelper.SendError(ex2, DbType, false);
                     return(false);
                 }
             }
         }
         else
         {
             DataConnectionHelper.SendError(ex, DbType, false);
             return(false);
         }
     }
     return(true);
 }
        public void GenerateDataContextInProject(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }

            var isDesktop = (bool)((MenuItem)sender).Tag;

            if (package == null)
            {
                return;
            }
            var dte = package.GetServiceHelper(typeof(DTE)) as DTE;

            if (dte == null)
            {
                return;
            }
            if (dte.Mode == vsIDEMode.vsIDEModeDebug)
            {
                EnvDteHelper.ShowError("Cannot generate code while debugging");
                return;
            }

            var helper = Helpers.RepositoryHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType);

            if (!helper.IsV35DbProviderInstalled())
            {
                EnvDteHelper.ShowError("This feature requires the SQL Server Compact 3.5 SP2 DbProvider to be properly installed");
                return;
            }

            var dteH = new EnvDteHelper();

            var project = dteH.GetProject(dte);

            if (project == null)
            {
                EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the DataContext to be placed");
                return;
            }
            if (!isDesktop && !dteH.AllowedWpProjectKinds.Contains(new Guid(project.Kind)))
            {
                EnvDteHelper.ShowError("The selected project type does not support Windows Phone (please let me know if I am wrong)");
                return;
            }
            if (isDesktop && !dteH.AllowedProjectKinds.Contains(new Guid(project.Kind)))
            {
                EnvDteHelper.ShowError("The selected project type does not support LINQ to SQL (please let me know if I am wrong)");
                return;
            }
            if (project.Properties.Item("TargetFrameworkMoniker") == null)
            {
                EnvDteHelper.ShowError("The selected project type does not support Windows Phone - missing TargetFrameworkMoniker");
                return;
            }
            if (!isDesktop)
            {
                if (project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "Silverlight,Version=v4.0,Profile=WindowsPhone71" ||
                    project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "WindowsPhone,Version=v8.0" ||
                    project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "WindowsPhone,Version=v8.1"
                    )
                {
                }
                else
                {
                    EnvDteHelper.ShowError("The selected project type does not support Windows Phone 7.1/8.0 - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                    return;
                }
            }
            if (isDesktop && !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework"))
            {
                EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value);
                return;
            }
            if (!isDesktop && databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35)
            {
                EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now");
                return;
            }

            var sqlMetalPath = ProbeSqlMetalRegPaths();

            if (string.IsNullOrEmpty(sqlMetalPath))
            {
                EnvDteHelper.ShowError("Could not find SQLMetal file location");
                return;
            }

            var sdfFileName = string.Empty;

            try
            {
                using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                {
                    var tables        = repository.GetAllTableNames();
                    var pks           = repository.GetAllPrimaryKeys();
                    var checkedTables = string.Empty;
                    foreach (var tableName in tables)
                    {
                        var pk = pks.Where(k => k.TableName == tableName).FirstOrDefault();
                        if (pk.TableName == null)
                        {
                            checkedTables += tableName + Environment.NewLine;
                        }
                    }
                    if (!string.IsNullOrEmpty(checkedTables))
                    {
                        var message = string.Format("The tables below do not have Primary Keys defined,{0}and will not be generated properly:{1}{2}", Environment.NewLine, Environment.NewLine, checkedTables);
                        EnvDteHelper.ShowError(message);
                    }
                    var dbInfo = repository.GetDatabaseInfo();
                    foreach (var kvp in dbInfo)
                    {
                        if (kvp.Key == "Database")
                        {
                            sdfFileName = kvp.Value;
                            break;
                        }
                    }
                    sdfFileName = Path.GetFileName(sdfFileName);
                }

                var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption);
                if (fileNameWithoutExtension != null)
                {
                    var model = fileNameWithoutExtension.Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty);
                    model = model + "Context";
                    var dcDialog = new DataContextDialog();
                    dcDialog.ModelName   = model;
                    dcDialog.IsDesktop   = isDesktop;
                    dcDialog.ProjectName = project.Name;
                    dcDialog.NameSpace   = project.Properties.Item("DefaultNamespace").Value.ToString();
                    if (EnvDteHelper.VbProject == new Guid(project.Kind))
                    {
                        dcDialog.CodeLanguage = "VB";
                    }
                    else
                    {
                        dcDialog.CodeLanguage = "C#";
                    }
                    var result = dcDialog.ShowModal();
                    if (!result.HasValue || result.Value != true || string.IsNullOrWhiteSpace(dcDialog.ModelName))
                    {
                        return;
                    }
                    if (dcDialog.AddRowversionColumns)
                    {
                        AddRowVersionColumns(databaseInfo);
                    }

                    var sdfPath = databaseInfo.DatabaseInfo.ConnectionString;

                    //If version 4.0, create a 3.5 schema sdf, and use that as connection string
                    if (isDesktop && databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40)
                    {
                        var tempFile = Path.GetTempFileName();
                        using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                        {
                            var generator = DataConnectionHelper.CreateGenerator(repository, tempFile, databaseInfo.DatabaseInfo.DatabaseType);
                            generator.ScriptDatabaseToFile(Scope.Schema);
                        }
                        if (sdfFileName != null)
                        {
                            sdfPath = Path.Combine(Path.GetTempPath(), sdfFileName);
                        }
                        using (Stream stream = new MemoryStream(Resources.SqlCe35AddinStore))
                        {
                            // Create a FileStream object to write a stream to a file
                            using (var fileStream = File.Create(sdfPath, (int)stream.Length))
                            {
                                // Fill the bytes[] array with the stream data
                                var bytesInStream = new byte[stream.Length];
                                stream.Read(bytesInStream, 0, bytesInStream.Length);
                                // Use FileStream object to write to the specified file
                                fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                            }
                        }
                        var info = new DatabaseInfo
                        {
                            ConnectionString = "Data Source=" + sdfPath,
                            DatabaseType     = DatabaseType.SQLCE35
                        };
                        using (var repository = Helpers.RepositoryHelper.CreateRepository(info))
                        {
                            var script = File.ReadAllText(tempFile);
                            repository.ExecuteSql(script);
                        }
                        sdfPath = info.ConnectionString;
                    }

                    var versionNumber = GetVersionTableNumber(databaseInfo.DatabaseInfo, isDesktop);

                    model = dcDialog.ModelName;
                    var dcPath = Path.Combine(Path.GetTempPath(), model + ".cs");
                    if (dcDialog.CodeLanguage == "VB")
                    {
                        dcPath = Path.Combine(Path.GetTempPath(), model + ".vb");
                    }
                    var parameters = " /provider:SQLCompact /code:\"" + dcPath + "\"";
                    parameters += " /conn:\"" + sdfPath + "\"";
                    parameters += " /context:" + model;
                    if (dcDialog.Pluralize)
                    {
                        parameters += " /pluralize";
                    }
                    if (!string.IsNullOrWhiteSpace(dcDialog.NameSpace))
                    {
                        parameters += " /namespace:" + dcDialog.NameSpace;
                    }
                    var dcH = new DataContextHelper();

                    var sqlmetalResult = dcH.RunSqlMetal(sqlMetalPath, parameters);
                    if (!File.Exists(dcPath))
                    {
                        EnvDteHelper.ShowError("Error during SQL Metal run: " + sqlmetalResult);
                        return;
                    }

                    if (!isDesktop)
                    {
                        using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                        {
                            if (dcDialog.CodeLanguage == "VB")
                            {
                                DataContextHelper.FixDataContextVB(dcPath, model, dcDialog.NameSpace, sdfFileName, repository);
                            }
                            else
                            {
                                DataContextHelper.FixDataContextCS(dcPath, model, dcDialog.NameSpace, sdfFileName, repository);
                            }
                        }
                    }
                    if (dcDialog.MultipleFiles)
                    {
                        var classes     = DataContextHelper.SplitIntoMultipleFiles(dcPath, dcDialog.NameSpace, model);
                        var projectPath = project.Properties.Item("FullPath").Value.ToString();

                        foreach (var item in classes)
                        {
                            var fileName = Path.Combine(projectPath, item.Key + ".cs");
                            if (File.Exists(fileName))
                            {
                                File.Delete(fileName);
                            }
                            File.WriteAllText(fileName, item.Value);
                            var classItem = dteH.GetProjectDataContextClass(project, fileName);
                            if (classItem != null)
                            {
                                classItem.Delete();
                            }
                            project.ProjectItems.AddFromFile(fileName);
                        }
                    }
                    else
                    {
                        var extension = ".cs";
                        if (dcDialog.CodeLanguage == "VB")
                        {
                            extension = ".vb";
                        }
                        var dcItem = dteH.GetProjectDc(project, model, extension);
                        if (dcItem == null)
                        {
                            project.ProjectItems.AddFromFileCopy(dcPath);
                        }
                        else
                        {
                            if (EnvDteHelper.ShowMessageBox("The Data Context class already exists in the project, do you wish to replace it?", OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, OLEMSGICON.OLEMSGICON_QUERY) == System.Windows.Forms.DialogResult.Yes)
                            {
                                dcItem.Delete();
                                project.ProjectItems.AddFromFileCopy(dcPath);
                            }
                        }
                    }
                    EnvDteHelper.AddReference(project, "System.Data.Linq");
                    if (dcDialog.AddConnectionStringBuilder)
                    {
                        var projectPath = project.Properties.Item("FullPath").Value.ToString();

                        var fileName = "LocalDatabaseConnectionStringBuilder.cs";

                        var filePath = Path.Combine(projectPath, fileName);
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                        using (Stream stream = new MemoryStream(Resources.LocalDatabaseConnectionStringBuilder))
                        {
                            // Create a FileStream object to write a stream to a file
                            using (var fileStream = File.Create(filePath, (int)stream.Length))
                            {
                                // Fill the bytes[] array with the stream data
                                var bytesInStream = new byte[stream.Length];
                                stream.Read(bytesInStream, 0, bytesInStream.Length);
                                // Use FileStream object to write to the specified file
                                fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                            }
                        }
                        project.ProjectItems.AddFromFile(filePath);
                    }

                    // Creates __Version table and adds one row if desired
                    if (dcDialog.AddVersionTable)
                    {
                        using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo))
                        {
                            var list = repository.GetAllTableNames();
                            if (!list.Contains("__VERSION"))
                            {
                                repository.ExecuteSql(string.Format(@"
                                CREATE TABLE [__VERSION] (
                                  [SchemaVersion] int NOT NULL
                                , [DateUpdated] datetime NOT NULL DEFAULT (GETDATE())
                                );
                                GO
                                CREATE INDEX [IX_SchemaVersion] ON [__VERSION] ([SchemaVersion] DESC);
                                GO
                                INSERT INTO [__VERSION] ([SchemaVersion]) VALUES ({0});
                                GO", versionNumber));
                            }
                        }
                    }
                    DataConnectionHelper.LogUsage("DatabaseCreateDC");
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
        public void UpgradeTo40(object sender, ExecutedRoutedEventArgs e)
        {
            if (EnvDteHelper.ShowMessageBox("This will upgrade the 3.5 database to 4.0 format, and leave a renamed backup of the 3.5 database. Do you wish to proceed?",
                                            OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, OLEMSGICON.OLEMSGICON_QUERY) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            if (!Helpers.RepositoryHelper.IsV40Installed())
            {
                EnvDteHelper.ShowError("The SQL Server Compact 4.0 runtime is not installed, cannot upgrade. Install the 4.0 runtime.");
                return;
            }
            try
            {
                var databaseInfo = ValidateMenuInfo(sender);
                if (databaseInfo == null)
                {
                    return;
                }

                var helper = new SqlCeHelper4();
                var path   = helper.PathFromConnectionString(databaseInfo.DatabaseInfo.ConnectionString);

                if (!File.Exists(path))
                {
                    EnvDteHelper.ShowError(string.Format("Database file in path: {0} could not be found", path));
                    return;
                }
                var path1 = Path.GetDirectoryName(path);
                if (path1 != null)
                {
                    var newFile = Path.Combine(path1, Path.GetFileNameWithoutExtension(path) + "_35" + Path.GetExtension(path));
                    if (File.Exists(newFile))
                    {
                        for (var i = 0; i < 100; i++)
                        {
                            newFile = Path.Combine(path1, Path.GetFileNameWithoutExtension(newFile) + "_" + i.ToString() + "." + Path.GetExtension(newFile));
                            if (!File.Exists(newFile))
                            {
                                break;
                            }
                        }
                    }

                    if (File.Exists(newFile))
                    {
                        EnvDteHelper.ShowError("Could not create unique file name...");
                        return;
                    }
                    File.Copy(path, newFile);
                    helper.UpgradeTo40(databaseInfo.DatabaseInfo.ConnectionString);
                    EnvDteHelper.ShowMessage(string.Format("Database upgraded, version 3.5 database backed up to: {0}", newFile));
                }
                if (databaseInfo.DatabaseInfo.FromServerExplorer)
                {
                    DataConnectionHelper.RemoveDataConnection(package, databaseInfo.DatabaseInfo.ConnectionString, new Guid(Resources.SqlCompact35Provider));
                }
                else
                {
                    DataConnectionHelper.RemoveDataConnection(databaseInfo.DatabaseInfo.ConnectionString);
                }
                DataConnectionHelper.SaveDataConnection(databaseInfo.DatabaseInfo.ConnectionString, DatabaseType.SQLCE40, package);
                var control = _parentWindow.Content as ExplorerControl;
                if (control != null)
                {
                    control.BuildDatabaseTree();
                }
                DataConnectionHelper.LogUsage("DatabaseUpgrade40");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35);
            }
        }