private void ProgressScript(ScriptViewModel model)
        {
            var folderViewModel = model.Parent;

            if (!ExecutedScripts.Contains(folderViewModel))
            {
                ExecutedScripts.Add(folderViewModel);
            }

            folderViewModel.Scripts.Add(model);
        }
Exemplo n.º 2
0
        public static bool RunSqlScriptOnConnection(string connectionString, ScriptViewModel script)
        {
            try
            {
                var filePath = script.Path;

                var scriptContents = File.ReadAllText(filePath);
                var sqlConnection = new SqlConnection(connectionString);
                var server = new Server(new ServerConnection(sqlConnection));
                server.ConnectionContext.ExecuteNonQuery(scriptContents);

                script.ErrorMessage = string.Empty;

                return true;
            }
            catch (ExecutionFailureException ex)
            {
                var sqlException = ex.InnerException as SqlException;
                if (sqlException != null)
                {
                    script.ErrorMessage = string.Format("At line {0}:\n{1}", sqlException.LineNumber, sqlException.Message);
                }
                else if (ex.InnerException != null)
                {
                    script.ErrorMessage = ex.InnerException.Message;
                }
                else
                    script.ErrorMessage = ex.Message;
            }
            catch (Exception ex)
            {
                script.ErrorMessage = ex.Message;
            }

            return false;
        }
        private async Task RunSelectedScriptsCommandExecute()
        {
            bool isError = false;

            try
            {
                if (string.IsNullOrWhiteSpace(ConnectionString))
                {
                    throw new Exception();
                }

                // ReSharper disable once ObjectCreationAsStatement
                new SqlConnectionStringBuilder {
                    ConnectionString = ConnectionString
                };
            }
            catch
            {
                MessageBox.Show(_parent, "Invalid connection string", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                isError = true;
            }

            // and here we try to establish the connection

            try
            {
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();
                }
            }
            catch
            {
                MessageBox.Show(_parent, "Cannot establish the connection to the server", "Error", MessageBoxButton.OK,
                                MessageBoxImage.Error);
                isError = true;
            }

            if (isError)
            {
                await Task.Yield();
            }

            await Task.Factory.StartNew(() =>
            {
                _scriptsQueue             = new ConcurrentQueue <ScriptViewModel>();
                _mreNoMoreScriptsExpected = new ManualResetEvent(false);

                CurrentScriptsCount = 0;
                TotalScriptsCount   = 0;
                HasTotalScriptsCountBeenDetermined = false;
                ExecutionInProgress = true;

                _cancellationTokenSource = new CancellationTokenSource();
                var token = _cancellationTokenSource.Token;

                var getScriptsTask = new Task(param =>
                {
                    var cancellationToken = (CancellationToken)param;

                    foreach (var scriptFolder in Scripts.Where(script => script.IsChecked))
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        var path = scriptFolder.FilePath;
                        var di   = new DirectoryInfo(path);
                        if (!di.Exists)
                        {
                            continue;
                        }

                        var sqlFiles = di.EnumerateFiles("*.sql").ToList();

                        if (!sqlFiles.Any())
                        {
                            continue;
                        }

                        _totalScriptsCountProgress.Report(sqlFiles.Count);

                        var folderViewModel = new FolderViewModel {
                            Path = path
                        };

                        foreach (var fileInfo in sqlFiles)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            var scriptPath      = fileInfo.FullName;
                            var scriptViewModel = new ScriptViewModel {
                                Parent = folderViewModel, Path = scriptPath
                            };
                            _scriptsQueue.Enqueue(scriptViewModel);
                        }
                    }
                }, token, token);

                var finishedProcessingTask = getScriptsTask.ContinueWith(continuation =>
                {
                    HasTotalScriptsCountBeenDetermined = true;
                    _mreNoMoreScriptsExpected.Set();
                }, token);

                var processScriptsTask = Task.Factory.StartNew(param =>
                {
                    var cancellationToken = (CancellationToken)param;

                    while (true)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        ScriptViewModel viewModel;
                        if (_scriptsQueue.TryDequeue(out viewModel))
                        {
                            SqlScriptRunner.RunSqlScriptOnConnection(ConnectionString, viewModel);
                            _currentScriptsCountProgress.Report(1);
                            _progressScript.Report(viewModel);
                        }
                        else
                        {
                            if (_mreNoMoreScriptsExpected.WaitOne(TimeSpan.Zero))
                            {
                                break;
                            }
                        }
                    }
                }, token, token);

                getScriptsTask.Start();

                try
                {
                    Task.WaitAll(finishedProcessingTask, processScriptsTask);
                }
                catch (AggregateException aex)
                {
                    aex.Handle(ex => ex is TaskCanceledException);
                }

                ExecutionInProgress = false;
            });
        }