Пример #1
0
        private void Schemas_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (null == Schemas.SelectedValue)
                {
                    return;
                }

                var schemaName = Schemas.SelectedValue.ToString();

                if (String.IsNullOrEmpty(schemaName))
                {
                    return;
                }

                _currentSchema = _currentProject.GetSchema(schemaName);

                Tables.ItemsSource = _currentSchema.GetTables();
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });

                OutputWindowMessage.WriteMessage("Error selecting schema:");
                OutputWindowMessage.WriteMessage(ex.Message);
            }
        }
Пример #2
0
        private void DumpMergeText(MergeStatement merge)
        {
            //
            var script = merge.GetScript();

            OutputWindowMessage.WriteMessage("Script Parser: About to Parse Script: \r\n======================================\r\n{0}\r\n======================================\r\n", script);
        }
Пример #3
0
        private void WriteDeployFile(string projectFile, string procName, string procFile, string outputDir)
        {
            var script = GetFileContents(procFile);

            if (string.IsNullOrEmpty(script))
            {
                OutputWindowMessage.WriteMessage("Could not read script file: " + procFile);
                return;
            }

            var variables = new SsdtVariableProvider().GetVariables(projectFile);

            foreach (SqlCmdVariable v in variables)
            {
                script = script.Replace(v.Name, v.Value);
            }

            var outputScript = new StringBuilder();

            outputScript.AppendFormat(DeploymentScriptGenerator.BuildDeploy(script));

            string outputScriptPath = Path.Combine(outputDir,
                                                   string.Format("{0}.sql", DeploymentScriptGenerator.GetLastPartOfName(procName)));

            try
            {
                WriteFileContents(outputScriptPath, outputScript.ToString());
                OutputWindowMessage.WriteMessage("Written file: " + outputScriptPath);
            }
            catch (Exception e)
            {
                OutputWindowMessage.WriteMessage("Could not write file: " + outputScriptPath + " - error: " + e.Message);
            }
        }
Пример #4
0
        private void GenerateScript(object state)
        {
            try
            {
                var project = state as Project;

                var filename = GetSelectedSolutionExplorerFileName();

                if (String.IsNullOrEmpty(filename))
                {
                    OutputWindowMessage.WriteMessage("Couldn't GetConfig filename");
                    return;
                }

                if (!filename.EndsWith(".sql"))
                {
                    OutputWindowMessage.WriteMessage("This only works with .sql files - boo hoo hoo");
                    return;
                }

                var procname = ScriptProperties.GetScriptDetail(File.ReadAllText(filename)).Name;
                if (string.IsNullOrEmpty(procname))
                {
                    OutputWindowMessage.WriteMessage("Couldn't GetConfig proc name - boo hoo hoo");
                    return;
                }
                var settings = Config.Configuration.GetSettings(project);

                WriteDeployFile(project.FullName, procname, filename, settings.DeploymentFolder);
            }
            catch (Exception e)
            {
                OutputWindowMessage.WriteMessage("Unable to generate script: " + e.Message);
            }
        }
Пример #5
0
        public void Save(string scriptFile)
        {
            if (Data != null && Data.IsDirty())
            {
                if (DebugLogging.Enable)
                {
                    OutputWindowMessage.WriteMessage("Table: Saving change to table: \"{0}\" to scriptfile: \"{1}\"", Name, scriptFile);
                }

                //if detils of Merge.Blah are filled in then update the current Merge.MergeStatement with the new datatable and then get the script and overwrite the existing script..
                //if it is not filled in, we need to create a new one and build a new merge
                Data.AcceptChanges();

                if (Merge.MergeStatement == null)
                {
                    Merge.MergeStatement = new MergeStatementBuilder(Columns, SchemaName, Name, KeyColumns).Build();
                    Merge.File           = scriptFile;
                }

                Merge.MergeStatement.SetInlineTableData(Data, Columns);
                var script = Merge.MergeStatement.GetScript();

                string originalScript = null;
                using (var sr = new StreamReader(Merge.File))
                {
                    originalScript = sr.ReadToEnd();
                }

                string outputScript = null;

                if (!string.IsNullOrEmpty(Merge.OriginalScript))
                {
                    outputScript = originalScript.Replace(Merge.OriginalScript, "");
                }
                else
                {
                    outputScript = originalScript;
                }

                Merge.OriginalScript = script;

                outputScript = outputScript + "\r\nGO\r\n" + script;
                outputScript = outputScript.Replace("\r\nGO\r\n\r\nGO\r\n", "\r\nGO\r\n");

                using (var sw = new StreamWriter(Merge.File, false))
                {
                    sw.Write(outputScript);
                }

                Data.SetClean();

                if (DebugLogging.Enable)
                {
                    OutputWindowMessage.WriteMessage("Table: Saving change to table: \"{0}\" to scriptfile: \"{1}\" Completed", Name, scriptFile);
                }
            }
        }
Пример #6
0
        public List <ITable> GetDataTables()
        {
            var tables = new List <ITable>();



            using (var reader = GetScriptReader())
            {
                var parser = new TSql120Parser(true);

                IList <ParseError> errors;
                TSqlFragment       sqlFragment = parser.Parse(reader, out errors);

                if (errors.Count > 0)
                {
                    if (DebugLogging.Enable)
                    {
                        OutputWindowMessage.WriteMessage("Script Parser: Script file: \"{0}\" contains errors:", _path);
                    }

                    foreach (var error in errors)
                    {
                        OutputWindowMessage.WriteWarning(_path, error.Line, "Script Parser: Error in {0} error: {1}", _path, error.Message);
                    }

                    ContainsErrors = true;
                }

                var visitor = new MergeVisitor();
                sqlFragment.Accept(visitor);

                foreach (var merge in visitor.Merges)
                {
                    try
                    {
                        if (DebugLogging.Enable)
                        {
                            DumpMergeText(merge);
                        }
                        tables.Add(new MergeStatementParser(merge).GetDescriptor(_path, _project));
                    }
                    catch (MergeStatamentParsingException msp)
                    {
                        OutputWindowMessage.WriteMessage("Unable to read table from the script file: \"{1}\" - error message: \"{1}\" ", _path);
                    }
                }
            }

            if (ContainsErrors)
            {
                OutputWindowMessage.WriteMessage("Errors were encountered parsing the script file - correct errors to save changes");
            }

            return(tables);
        }
Пример #7
0
 private void Save_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         _solution.Save();
     }
     catch (Exception ex)
     {
         OutputWindowMessage.WriteMessage("Error saving the changes: {0}", ex.Message);
     }
 }
Пример #8
0
        private void ShowToolsOptions(object sender, EventArgs e)
        {
            try
            {
                var project = GetCurrentProject();

                Config.Configuration.ShowConfig(project);
            }
            catch (Exception)
            {
                OutputWindowMessage.WriteMessage("Configuration Failed");
            }
        }
Пример #9
0
        private StreamReader GetScriptReader()
        {
            var tempPath = _path + ".tmp";

            try
            {
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
            }
            catch (Exception e)
            {
                OutputWindowMessage.WriteMessage("Unable to delete temporary file path: \"{0}\" - error message: \"{1}\" ", tempPath, e.Message);
            }

            bool haveSkipped = false;

            using (var reader = new StreamReader(_path))
                using (var writer = new StreamWriter(tempPath))
                {
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        if (!line.Trim().StartsWith(":r", StringComparison.OrdinalIgnoreCase))
                        {
                            writer.WriteLine(line);
                        }
                        else
                        {
                            if (line.Length > 2)
                            {
                                writer.WriteLine("--{0}", line.Substring(2));
                            }

                            haveSkipped = true;
                        }
                    }
                }

            if (haveSkipped)
            {
                return(new StreamReader(tempPath));
            }

            return(new StreamReader(_path));
        }
Пример #10
0
        private void button1_Save(object sender, RoutedEventArgs e)
        {
            //need to finish off saving back to the files (need a radio button with pre/post deploy (not changeable when read from file) - futrue feature
            //need a check to write files on window closing
            //need lots of tests
            try
            {
                _solution.Save();
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });

                OutputWindowMessage.WriteMessage("Error saving solution files:");
                OutputWindowMessage.WriteMessage(ex.Message);
            }
        }
Пример #11
0
        private string GetSelectedSolutionExplorerFileName()
        {
            var dte = GetService(typeof(SDTE)) as DTE;

            try
            {
                var filename = dte.SelectedItems.Item(1).ProjectItem.FileNames[0];

                return(filename);
            }
            catch (Exception ex)
            {
                OutputWindowMessage.WriteMessage(string.Format("error: " + ex));
            }

            return(null);
        }
Пример #12
0
 private void DeploySingleFileCallback(object sender, EventArgs e)
 {
     try
     {
         var project  = GetCurrentProject();
         var settings = Config.Configuration.GetSettings(project);
         if (null == settings)
         {
             OutputWindowMessage.WriteMessage("Cancelled");
             return;
         }
         ThreadPool.QueueUserWorkItem(DeploySingleFile, project);
     }
     catch (Exception)
     {
         OutputWindowMessage.WriteMessage("Deploying file Failed");
     }
 }
Пример #13
0
        private void DoRefresh()
        {
            Dispatcher.Invoke(() => { DebugLogging.Enable = Logging.IsChecked.Value; });
            try
            {
                if (_currentDataGridDirty)
                {
                    if (!CheckSaveChanges())
                    {
                        return;
                    }
                }

                var cursor = Cursors.Arrow;

                Dispatcher.Invoke(() =>
                {
                    cursor = Cursor;
                    RefreshButton.IsEnabled = false;
                    Projects.ItemsSource    = null;
                    Schemas.ItemsSource     = null;
                    Tables.ItemsSource      = null;
                    DataGrid.DataContext    = null;

                    Cursor = Cursors.Wait;
                });

                _solution = new SolutionParser(new ProjectEnumerator(), new DacParserBuilder(), this);

                Dispatcher.Invoke(() =>
                {
                    Projects.ItemsSource = _solution.GetProjects();
                    Cursor = cursor;
                    RefreshButton.IsEnabled = true;
                });
            }
            catch (Exception e)
            {
                Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });

                OutputWindowMessage.WriteMessage("Error Enumerating projects:");
                OutputWindowMessage.WriteMessage(e.Message);
            }
        }
Пример #14
0
        private void GenerateScriptCallback(object sender, EventArgs e)
        {
            try
            {
                var project  = GetCurrentProject();
                var settings = Config.Configuration.GetSettings(project);
                if (null == settings)
                {
                    OutputWindowMessage.WriteMessage("Cancelled");
                    return;
                }

                ThreadPool.QueueUserWorkItem(GenerateScript, project);
            }
            catch (Exception ex)
            {
                OutputWindowMessage.WriteMessage("Unable to generate script error: " + ex.Message);
            }
        }
Пример #15
0
        private void BuildSearchCondition(MergeSpecification specification)
        {
            if (_keyColumns.Count > 1)
            {
                BuildMultiKeySearchCondition(specification);
                return;
            }

            if (_keyColumns.Count == 0)
            {
                OutputWindowMessage.WriteMessage("The table: {0} does not contain a primary key so it isn't possible to work out what the columns the merge should check.",
                                                 _targetTableName);

                CreateSearchConditionForTableWithNoKeys((specification.SearchCondition = new BooleanComparisonExpression()) as BooleanComparisonExpression);
                return;
            }

            CreateSearchCondition(_keyColumns[0], (specification.SearchCondition = new BooleanComparisonExpression()) as BooleanComparisonExpression);
        }
Пример #16
0
        public SolutionParser(ProjectEnumerator projectEnumerator, DacParserBuilder dacParserBuilder, IStatus statusDisplay)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            statusDisplay.SetStatus("Finding Sql Projects...");
            var projects = projectEnumerator.EnumerateProjects();

            int count = 1;

            if (DebugLogging.Enable)
            {
                OutputWindowMessage.WriteMessage("Solution: Found {0} projects", projects.Count);
            }

            foreach (var project in projects)
            {
                statusDisplay.SetStatus(string.Format("Enumerating project {0} of {1} - project: {2}", count++, projects.Count, project.Name));

                if (!File.Exists(project.DacPath))
                {
                    if (DebugLogging.Enable)
                    {
                        OutputWindowMessage.WriteMessage("Solution: Did not find dacpac for project - path: {0}", project.DacPath);
                    }
                    continue;
                }

                var dac = dacParserBuilder.Build(project.DacPath);

                _projectList.Add(project.Name);
                _projects.Add(project.Name, new VsProject(project.PreDeployScriptPath, project.PostDeployScriptPath, dac.GetTableDefinitions(), project.Name, File.GetLastWriteTime(project.DacPath)));
            }

            stopwatch.Stop();
            statusDisplay.SetStatus(string.Format("Complete...Process took {0} seconds", stopwatch.ElapsedMilliseconds / 1000));

            if (DebugLogging.Enable)
            {
                OutputWindowMessage.WriteMessage("Solution: Enumerate Complete...Process took {0} seconds", stopwatch.ElapsedMilliseconds / 1000);
            }
        }
Пример #17
0
        private void Import_OnClick(object sender, RoutedEventArgs e)
        {
            if (_currentTable == null)
            {
                MessageBox.Show("Please choose a table in the drop down list", "MergeUi");
                return;
            }
            try
            {
                new Importer().GetData(_currentTable);
            }
            catch (Exception ex)
            {
                SetStatus("Error see output window");

                OutputWindowMessage.WriteMessage("Error importing data (table={0}):", _currentTable.Name);
                OutputWindowMessage.WriteMessage(ex.Message);
            }

            Table.DataContext = _currentTable.Data.DefaultView;
        }
Пример #18
0
        private void Projects_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (null == Projects.SelectedValue)
                {
                    return;
                }

                var projectName = Projects.SelectedValue.ToString();

                if (String.IsNullOrEmpty(projectName))
                {
                    return;
                }

                Schemas.ItemsSource = null;
                Tables.ItemsSource  = null;

                _currentProject = _solution.GetProject(projectName);

                if (string.IsNullOrEmpty(_currentProject.GetScript(ScriptType.PreDeploy)) &&
                    string.IsNullOrEmpty(_currentProject.GetScript(ScriptType.PostDeploy)))
                {
                    MessageBox.Show(
                        "The project needs a post deploy script - add one anywhere in the project and refresh", "MergeUi");
                    return;
                }

                LastBuildTime.Text  = string.Format("Last Dacpac Build Time: {0}", _currentProject.GetLastBuildTime());
                Schemas.ItemsSource = _currentProject.GetSchemas();
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window "; });

                OutputWindowMessage.WriteMessage("Error reading project: {0}", ex.Message);
            }
        }
Пример #19
0
        private void Tables_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (null == Tables.SelectedValue)
                {
                    return;
                }

                var tableName = Tables.SelectedValue.ToString();

                if (String.IsNullOrEmpty(tableName))
                {
                    return;
                }

                _currentTable = _currentSchema.GetTable(tableName);

                if (_currentTable.Data == null)
                {
                    _currentTable.Data = new DataTableBuilder(tableName, _currentTable.Columns).Get();
                }

                DataGrid.DataContext = _currentTable.Data.DefaultView;
                //TODO -= check for null and start adding a datatable when building the table (maybe need a lazy loading)
                //we also need a repository of merge statements which is the on disk representation so we can grab those
                //if they exist or just create a new one - then save them back and
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error Enumerating projects: " + ex.Message; });

                OutputWindowMessage.WriteMessage("Error selecting table ({0}-):",
                                                 _currentTable == null ? "null" : _currentTable.Name,
                                                 Tables.SelectedValue == null ? "selected = null" : Tables.SelectedValue.ToString());
                OutputWindowMessage.WriteMessage(ex.Message);
            }
        }
Пример #20
0
        private void DeploySingleFile(object state)
        {
            try
            {
                var project = state as Project;

                var variables = new SsdtVariableProvider().GetVariables(project.FullName);

                var settings = Config.Configuration.GetSettings(project);

                var filename = GetSelectedSolutionExplorerFileName();

                if (String.IsNullOrEmpty(filename))
                {
                    OutputWindowMessage.WriteMessage("Couldn't GetConfig filename");
                    return;
                }

                if (!filename.EndsWith(".sql"))
                {
                    OutputWindowMessage.WriteMessage("Single file deploy only works with .sql files - boo hoo hoo");
                    return;
                }

                var procname = ScriptProperties.GetScriptDetail(File.ReadAllText(filename)).Name;

                if (string.IsNullOrEmpty(procname))
                {
                    OutputWindowMessage.WriteMessage("Couldn't GetConfig proc name - boo hoo hoo");
                    return;
                }

                var fileContents = GetFileContents(filename);

                foreach (SqlCmdVariable v in variables)
                {
                    fileContents = fileContents.Replace(v.Name, v.Value);
                }


                if (!DtcAvailable())
                {
                    OutputWindowMessage.WriteMessage("Unable to deploy file, deploy uses msdtc to protect changes. Please ensure the service is enabled and running");
                    return;
                }

                using (var scope = new TransactionScope())
                {
                    try
                    {
                        var script  = DeploymentScriptGenerator.BuildDeploy(fileContents);
                        var batches = script.Split(new string[] { "\r\nGO\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var batch in batches)
                        {
                            new SqlGateway(settings.ConnectionString).Execute(batch);
                        }

                        scope.Complete();


                        OutputWindowMessage.WriteMessage(string.Format("Deployed File: {0}\r\n", filename));
                    }
                    catch (NullReferenceException)
                    {
                        OutputWindowMessage.WriteMessage(string.Format("Unable to deploy file {0}\r\n", filename));
                    }
                    catch (Exception ex)
                    {
                        OutputWindowMessage.WriteMessage(string.Format("Unable to deploy file {0} error : {1}\r\n",
                                                                       filename, ex.Message));
                    }
                }
            }
            catch (Exception e)
            {
                OutputWindowMessage.WriteMessage("Deploying file Failed: " + e.Message);
            }
        }