public IDataReader Execute(CommandBehavior behavior)
        {
            Exception exception = null;

            _startDate = LocalTime.Default.Now;
            _startTick = Stopwatch.GetTimestamp();

            try
            {
                _reader = _command.ExecuteReader(behavior);
            }
            catch (Exception e)
            {
                exception = e;
                throw;
            }
            finally
            {
                var ticks    = Stopwatch.GetTimestamp() - _startTick;
                var duration = StopwatchTimeSpan.ToInt32(ticks, 1000);
                var filter   = _connection.Filter;
                _contains = exception != null || filter == null ||
                            filter.Contains(_connection.UserName, _connection.HostName, _command);

                if (_contains)
                {
                    _connection.CommandExeucte(_command, _startDate, duration, exception);
                    _logged = true;
                }
            }

            return(this);
        }
        void IResultWriter.AfterCloseReader(int affectedRows)
        {
            var duration = Stopwatch.GetTimestamp() - _beforeExecuteReaderTimestamp;
            var now      = LocalTime.Default.Now;
            var affected = affectedRows >= 0
                ? $"{affectedRows} row(s) affected."
                : null;
            var message = $"Command[{_commandCount - 1}] completed in {StopwatchTimeSpan.ToString(duration, 3)} seconds. {affected}";

            _addInfoMessage(new InfoMessage(now, InfoMessageSeverity.Verbose, null, message));

            if (_query != null)
            {
                var directory = _fileName != null?Path.GetDirectoryName(_fileName) : Path.GetTempPath();

                var results = _query.Results.EmptyIfNull().Zip(_results, ToResult).ToReadOnlyCollection();
                var query   = new DbRequest(directory, _query.Name, _query.Using, _query.Namespace, _commandText, 0, _parameters, results);

                var queryBuilder     = new DbRequestBuilder(query);
                var csharpSourceCode = queryBuilder.Build();

                var path = Path.Combine(query.Directory, $"{query.Name}.generated.cs");
                File.WriteAllText(path, csharpSourceCode, Encoding.UTF8);

                _query       = null;
                _parameters  = null;
                _commandText = null;
                _results     = null;
            }
        }
        void IResultWriter.FirstRowReadEnd(string[] dataTypeNames)
        {
            var duration = Stopwatch.GetTimestamp() - _firstRowReadBeginTimestamp;
            var message  = $"First row read completed in {StopwatchTimeSpan.ToString(duration, 3)} seconds.";

            _addInfoMessage(new InfoMessage(LocalTime.Default.Now, InfoMessageSeverity.Verbose, null, message));
        }
示例#4
0
        void IResultWriter.AfterCloseReader(int affectedRows)
        {
            var duration      = Stopwatch.GetTimestamp() - _beforeExecuteReaderTimestamp;
            var header        = StopwatchTimeSpan.ToString(duration, 3);
            var stringBuilder = new StringBuilder();

            stringBuilder.Append($"Command[{_commandCount - 1}] completed.");
            if (affectedRows >= 0)
            {
                stringBuilder.Append($" {affectedRows} row(s) affected.");
            }
            var message = stringBuilder.ToString();

            _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));

            if (_query != null)
            {
                var directory = _fileName != null?Path.GetDirectoryName(_fileName) : Path.GetTempPath();

                var results = _query.Results.EmptyIfNull().Zip(_results, ToResult).ToReadOnlyList();
                var query   = new DbRequest(directory, _query.Name, _query.Using, _query.Namespace, _commandText, 0, _parameters, results);

                var queryBuilder     = new DbRequestBuilder(query);
                var csharpSourceCode = queryBuilder.Build();

                var path = Path.Combine(query.Directory, $"{query.Name}.generated.cs");
                File.WriteAllText(path, csharpSourceCode, Encoding.UTF8);

                _query       = null;
                _parameters  = null;
                _commandText = null;
                _results     = null;
            }
        }
示例#5
0
        private void OnInfoMessage(object sender, SqlInfoMessageEventArgs e)
        {
            var clock        = ClockAggregateRepository.Singleton.Get();
            var localTime    = clock.GetLocalTimeFromCurrentEnvironmentTickCount();
            var infoMessages = SqlServerProvider.ToInfoMessages(e.Errors, localTime);

            if (e.Errors.Count > 0)
            {
                var error = e.Errors[0];
                if (error.Number == SqlErrorNumber.PercentProcessed)
                {
                    var elapsed            = Stopwatch.GetTimestamp() - _createCommandTimestamp;
                    var index              = error.Message.IndexOf(' ');
                    var percentString      = error.Message.Substring(0, index);
                    var percent            = int.Parse(percentString);
                    var remainingPercent   = 100 - percent;
                    var estimated          = (long)Math.Round(100.0 / percent * elapsed);
                    var estimatedRemaining = remainingPercent * elapsed / percent;
                    var infoMessage        = new InfoMessage(localTime, InfoMessageSeverity.Verbose, null,
                                                             $"Estimated time: {StopwatchTimeSpan.ToString(estimated, 0)} remaining time: {StopwatchTimeSpan.ToString(estimatedRemaining, 0)}");
                    infoMessages.Add(infoMessage);
                }
            }

            InvokeInfoMessage(infoMessages);
        }
    void IResultWriter.BeforeExecuteReader(AsyncDataAdapterCommand asyncDataAdapterCommand)
    {
        _beforeExecuteReaderTimestamp = Stopwatch.GetTimestamp();
        ++_commandCount;

        var        command    = asyncDataAdapterCommand.Command;
        const long duration   = 0;
        var        header     = $"{StopwatchTimeSpan.ToString(duration, 3)} Command[{_commandCount-1}]";
        var        message    = $"Before executing reader at line {asyncDataAdapterCommand.LineIndex + 1}...\r\n{command.CommandText}";
        var        parameters = command.Parameters;

        if (!parameters.IsNullOrEmpty())
        {
            message += "\r\n" + command.Parameters.ToLogString();
        }

        _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));

        _query = asyncDataAdapterCommand.Query;
        if (_query != null)
        {
            _fileName    = asyncDataAdapterCommand.FileName;
            _parameters  = asyncDataAdapterCommand.Parameters;
            _commandText = asyncDataAdapterCommand.CommandText;
            _results     = new List <Result>();
        }
    }
示例#7
0
    public void Add(int value, long timestamp)
    {
        Assert.IsTrue(value >= 0);
        var newTaskCount = _currentTaskCount + value;

        Assert.IsTrue(newTaskCount <= _taskCount);

        var newRatio         = (double)newTaskCount / _taskCount;
        var newPercentDouble = _startPercent + newRatio * (_endPercent - _startPercent);

        var elapsedTimeAmount         = timestamp - _startTimestamp;
        var estimatedTimeAmount       = (long)(elapsedTimeAmount / newRatio);
        var estimatedTimeAmountString = StopwatchTimeSpan.ToString(estimatedTimeAmount, 3);

        System.Diagnostics.Debug.WriteLine(
            $"newTaskCount: {newTaskCount}, newPercentDouble: {newPercentDouble}, elapsed:  {StopwatchTimeSpan.ToString(elapsedTimeAmount, 3)} estimatedTimeAmount: {estimatedTimeAmountString}");

        var newPercent = (int)newPercentDouble;
        var changed    = _currentPercent < newPercent;

        _currentPercent   = newPercent;
        _currentTaskCount = newTaskCount;
        if (changed)
        {
            _handleEvent(new ProgressChangedEvent(newTaskCount, newPercent));
        }
    }
        void IResultWriter.End()
        {
            var duration = Stopwatch.GetTimestamp() - _beginTimestamp;
            var message  = $"Query completed {_commandCount} command(s) in {StopwatchTimeSpan.ToString(duration, 3)} seconds.";

            _addInfoMessage(new InfoMessage(LocalTime.Default.Now, InfoMessageSeverity.Verbose, null, message));
        }
    void IResultWriter.FirstRowReadEnd(string[] dataTypeNames)
    {
        var duration = Stopwatch.GetTimestamp() - _firstRowReadBeginTimestamp;
        var header   = $"{StopwatchTimeSpan.ToString(duration, 3)} Command[{_commandCount-1}]";
        var message  = $"Result[{_tableCount - 1}] first row read completed.";

        _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));
    }
示例#10
0
        void IResultWriter.AfterExecuteReader(int fieldCount)
        {
            var duration = Stopwatch.GetTimestamp() - _beforeExecuteReaderTimestamp;
            var message  = $"Command[{_commandCount - 1}] started in {StopwatchTimeSpan.ToString(duration, 3)} seconds. Field count: {fieldCount}";

            _addInfoMessage(new InfoMessage(LocalTime.Default.Now, InfoMessageSeverity.Verbose, null, message));
            _tableCount = 0;
        }
示例#11
0
        void IResultWriter.End()
        {
            var duration = Stopwatch.GetTimestamp() - _beginTimestamp;
            var header   = StopwatchTimeSpan.ToString(duration, 3);
            var message  = $"Query completed {_commandCount} command(s).";

            _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));
        }
示例#12
0
    void IResultWriter.WriteTableEnd()
    {
        var duration = Stopwatch.GetTimestamp() - _writeTableBeginTimestamp;
        var header   = $"{StopwatchTimeSpan.ToString(duration, 3)} Command[{_commandCount-1}]";
        var message  =
            $"Result[{_tableCount - 1}] finished. Table[{_tableCount - 1},{_query?.Results[_tableCount - 1]}] has {SingularOrPlural(_fieldCount, "column", "columns")}, {SingularOrPlural(_rowCount, "row", "rows")}.";

        _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));
    }
示例#13
0
        void IResultWriter.WriteTableEnd()
        {
            var duration = Stopwatch.GetTimestamp() - _writeTableBeginTimestamp;
            var header   = StopwatchTimeSpan.ToString(duration, 3);
            var message  =
                $"Command[{_commandCount - 1}] result[{_tableCount - 1}] finished. Table[{_tableCount - 1},{_query?.Results[_tableCount - 1]}] has {_fieldCount} column(s), {_rowCount} row(s).";

            _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));
        }
示例#14
0
        private void Flush()
        {
            while (_queue.Count > 0)
            {
                ISqlLogItem[] array;

                lock (_queue)
                {
                    array = new ISqlLogItem[_queue.Count];
                    _queue.CopyTo(array, 0);
                    _queue.Clear();
                }

                var sb = new StringBuilder();

                for (var i = 0; i < array.Length; i++)
                {
                    var item        = array[i];
                    var commandText = item.CommandText;
                    sb.Append(commandText);
                }

                var  cmdText = sb.ToString();
                long ticks   = 0;

                try
                {
                    var command = _connection.CreateCommand();
                    command.CommandText    = cmdText;
                    command.CommandTimeout = 259200;
                    ticks = Stopwatch.GetTimestamp();
                    command.ExecuteNonQuery();
                    ticks = Stopwatch.GetTimestamp() - ticks;
                }
                catch (Exception e)
                {
                    Log.Write(LogLevel.Error, e.ToString());
                }
                finally
                {
                    var seconds = (double)ticks / Stopwatch.Frequency;
                    var speed   = (int)(array.Length / seconds);

                    Log.Trace(
                        "SqlLog.Flush() called. Count: {0}, Elapsed: {1}, Speed: {2} item/sec\r\n{3}",
                        array.Length,
                        StopwatchTimeSpan.ToString(ticks, 3),
                        speed,
                        cmdText);
                }
            }
        }
示例#15
0
        private void Connect()
        {
            var connectionForm = new ConnectionForm(_statusBar, _colorTheme);

            if (connectionForm.ShowDialog() == DialogResult.OK)
            {
                var connectionProperties = connectionForm.ConnectionProperties;

                var queryForm = new QueryForm(this, MdiChildren.Length, connectionProperties.Provider, connectionProperties.ConnectionString,
                                              connectionProperties.Connection, _statusBar, _colorTheme);

                queryForm.MdiParent = this;

                if (SelectedFont != null)
                {
                    queryForm.Font = SelectedFont;
                }

                queryForm.FormClosing += queryForm_FormClosing;

                switch (WindowState)
                {
                case FormWindowState.Normal:
                    var width  = Math.Max(ClientSize.Width + 70, 100);
                    var height = Math.Max(ClientSize.Height - 120, 50);
                    queryForm.ClientSize = new Size(width, height);
                    break;

                case FormWindowState.Maximized:
                    //queryForm.WindowState = FormWindowState.Maximized;
                    break;

                default:
                    break;
                }

                var message = $@"Connection opened in {StopwatchTimeSpan.ToString(connectionForm.Duration, 3)} seconds.
ServerVersion: {connectionProperties.Connection.ServerVersion}";

                var infoMessage = InfoMessageFactory.Create(InfoMessageSeverity.Verbose, null, message);
                queryForm.AddInfoMessage(infoMessage);

                queryForm.Show();

                if (WindowState == FormWindowState.Maximized)
                {
                    queryForm.WindowState = FormWindowState.Maximized;
                }
            }
        }
        private void ConnectionAfterOpen(object sender, AfterOpenDbConnectionEventArgs e)
        {
            var duration = e.Timestamp - _beforeOpen.Timestamp;

            if (e.Exception != null)
            {
                Log.Write(LogLevel.Error, "Opening connection finished in {0} seconds. Exception:\r\n{1}", StopwatchTimeSpan.ToString(duration, 3), e.Exception.ToLogString());
            }
            else
            {
                Log.Trace("Opening connection finished in {0} seconds.", StopwatchTimeSpan.ToString(duration, 3));
            }

            _beforeOpen = null;
        }
示例#17
0
    void IResultWriter.AfterExecuteReader(int fieldCount)
    {
        var duration      = Stopwatch.GetTimestamp() - _beforeExecuteReaderTimestamp;
        var header        = $"{StopwatchTimeSpan.ToString(duration, 3)} Command[{_commandCount-1}]";
        var stringBuilder = new StringBuilder();

        stringBuilder.Append($"Executing reader...");
        if (fieldCount > 0)
        {
            stringBuilder.Append($" Field count: {fieldCount}");
        }
        var message = stringBuilder.ToString();

        _addInfoMessage(InfoMessageFactory.Create(InfoMessageSeverity.Verbose, header, message));

        _tableCount = 0;
        _fieldCount = fieldCount;
    }
    private void ManagePoolDequeuers(object state)
    {
        if (_pool.QueuedItemCount > 0)
        {
            var addableThreadCount = _pool.MaxThreadCount - _pool.Dequeuers.Count;
            var count = Math.Min(addableThreadCount, 5);

            for (var i = 0; i < count; i++)
            {
                var callback = _waitCallbackFactory.CreateWaitCallback();
                var dequeuer = new WorkerThreadPoolDequeuer(callback);
                _pool.Dequeuers.Add(dequeuer);
                dequeuer.Thread.Start();
            }
        }
        else
        {
            var timestamp = Stopwatch.GetTimestamp();
            var dequeuers = new List <WorkerThreadPoolDequeuer>();
            var threads   = new WorkerThreadCollection();

            foreach (var dequeuer in _pool.Dequeuers)
            {
                var milliseconds = StopwatchTimeSpan.ToInt32(timestamp - dequeuer.LastActivityTimestamp, 1000);

                if (milliseconds >= 10000)
                {
                    dequeuers.Add(dequeuer);
                    threads.Add(dequeuer.Thread);
                }
            }

            foreach (var dequeuer in dequeuers)
            {
                _pool.Dequeuers.Remove(dequeuer);
            }

            var stopEvent = new ManualResetEvent(false);
            threads.Stop(stopEvent);
            stopEvent.WaitOne();
        }
    }
        private void menuItemScriptObject_Click(object sender, EventArgs e)
        {
            var    stopwatch        = Stopwatch.StartNew();
            var    connectionString = _database.Databases.Server.ConnectionString;
            string text;

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                text = SqlDatabase.GetSysComments(connection, _database.Name, _owner, _name);
            }

            Clipboard.SetText(text);

            var queryForm = (QueryForm)DataCommanderApplication.Instance.MainForm.ActiveMdiChild;

            queryForm.SetStatusbarPanelText(
                $"Copying stored prcoedure script to clipboard finished in {StopwatchTimeSpan.ToString(stopwatch.ElapsedTicks, 3)} seconds.",
                SystemColors.ControlText);
        }
    private void ScriptObjectMenuItem_Click(object sender, EventArgs e)
    {
        var    stopwatch        = Stopwatch.StartNew();
        var    connectionString = _database.Databases.Server.ConnectionString;
        string text;

        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            text = SqlDatabase.GetSysComments(connection, _database.Name, _owner, _name);
        }

        if (text != null)
        {
            var queryForm = (IQueryForm)sender;
            queryForm.ClipboardSetText(text);

            queryForm.SetStatusbarPanelText(
                $"Copying stored prcoedure script to clipboard finished in {StopwatchTimeSpan.ToString(stopwatch.ElapsedTicks, 3)} seconds.",
                SystemColors.ControlText);
        }
    }
    private void ConnectionAfterRead(object sender, AfterReadEventArgs e)
    {
        var duration = e.Timestamp - _beforeExecuteReader.Timestamp;

        Log.Trace("{0} row(s) read in {1} seconds.", e.RowCount, StopwatchTimeSpan.ToString(duration, 3));
    }
 private static string ToString(LoggedDbCommandInfo command, long duration) =>
 $"Executing command started in {StopwatchTimeSpan.ToString(duration, 3)} seconds.\r\ncommandId: {command.CommandId},connectionState: {command.ConnectionState},database: {command.Database},executionType: {command.ExecutionType},commandType: {command.CommandType},commandTimeout: {command.CommandTimeout}\r\ncommandText: {command.CommandText}\r\nparameters:\r\n{command.Parameters}";
示例#23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xmlReader"></param>
        /// <param name="configFilename"></param>
        /// <param name="sectionName"></param>
        /// <param name="fileNames"></param>
        /// <returns></returns>
        public ConfigurationNode Read(
            XmlReader xmlReader,
            string configFilename,
            string sectionName,
            StringCollection fileNames)
        {
            Log.Trace("ConfigurationReader.Read({0},{1})...", configFilename, sectionName);
            var startTick = Stopwatch.GetTimestamp();

            _xmlReader   = xmlReader;
            _fileName    = configFilename;
            _sectionName = sectionName;
            ConfigurationNode node    = null;
            string            message = null;

            try
            {
                var found = FindSection(sectionName);

                if (found)
                {
                    var nodeType = xmlReader.MoveToContent();

                    if (nodeType == XmlNodeType.Element)
                    {
                        InitCultureInfo();
                        _enableFileSystemWatcher = StringHelper.ParseBoolean(xmlReader["enableFileSystemWatcher"], false);
                        node = new ConfigurationNode(null);
                        Read(node, fileNames);

                        if (_enableFileSystemWatcher && fileNames != null && !fileNames.Contains(configFilename))
                        {
                            fileNames.Add(configFilename);
                        }
                    }
                    else
                    {
                        message = $"RootNode not found. fileName: {_fileName}, sectionName: {sectionName}";
                        AddError(ErrorType.Error, message, null);
                    }
                }
                else
                {
                    message = $"RootNode not found. fileName: {_fileName}, sectionName: {sectionName}";
                    AddError(ErrorType.Information, message, null);
                }
            }
            catch (Exception e)
            {
                AddError(ErrorType.Error, null, e);
            }

            var ticks = Stopwatch.GetTimestamp() - startTick;

            message = $"{configFilename} loaded successfully in {StopwatchTimeSpan.ToString(ticks, 3)}.";
            LogLevel logLevel;
            var      source = _errors.Where(e => e.Type == ErrorType.Error);

            if (source.Any())
            {
                logLevel = LogLevel.Error;
            }
            else
            {
                var enumerable = _errors.Where(e => e.Type == ErrorType.Warning);
                logLevel = enumerable.Any() ? LogLevel.Warning : LogLevel.Trace;
            }

            Log.Write(logLevel, "ConfigurationReader.Read finished.\r\nthis.errors.Count: {0}\r\n{1}", _errors.Count, _errors.ToString());
            return(node);
        }
示例#24
0
        private void ScriptTable_Click(object sender, EventArgs e)
        {
            using (new CursorManager(Cursors.WaitCursor))
            {
                var queryForm = (QueryForm)DataCommanderApplication.Instance.MainForm.ActiveMdiChild;
                queryForm.SetStatusbarPanelText("Copying table script to clipboard...",
                                                queryForm.ColorTheme != null ? queryForm.ColorTheme.ForeColor : SystemColors.ControlText);
                var stopwatch = Stopwatch.StartNew();

                var connectionString = DatabaseNode.Databases.Server.ConnectionString;
                var csb = new SqlConnectionStringBuilder(connectionString);

                var connectionInfo = new SqlConnectionInfo();
                connectionInfo.ApplicationName       = csb.ApplicationName;
                connectionInfo.ConnectionTimeout     = csb.ConnectTimeout;
                connectionInfo.DatabaseName          = csb.InitialCatalog;
                connectionInfo.EncryptConnection     = csb.Encrypt;
                connectionInfo.MaxPoolSize           = csb.MaxPoolSize;
                connectionInfo.MinPoolSize           = csb.MinPoolSize;
                connectionInfo.PacketSize            = csb.PacketSize;
                connectionInfo.Pooled                = csb.Pooling;
                connectionInfo.ServerName            = csb.DataSource;
                connectionInfo.UseIntegratedSecurity = csb.IntegratedSecurity;
                connectionInfo.WorkstationId         = csb.WorkstationID;
                if (!csb.IntegratedSecurity)
                {
                    connectionInfo.UserName = csb.UserID;
                    connectionInfo.Password = csb.Password;
                }

                var connection = new ServerConnection(connectionInfo);
                connection.Connect();
                var server   = new Server(connection);
                var database = server.Databases[DatabaseNode.Name];
                var table    = database.Tables[_name, _owner];

                var options = new ScriptingOptions();
                options.Indexes                = true;
                options.Permissions            = true;
                options.IncludeDatabaseContext = false;
                options.Default                = true;
                options.AnsiPadding            = true;
                options.DriAll                = true;
                options.ExtendedProperties    = true;
                options.ScriptBatchTerminator = true;
                options.SchemaQualify         = true;
                options.SchemaQualifyForeignKeysReferences = true;

                var stringCollection = table.Script(options);
                var sb = new StringBuilder();
                foreach (var s in stringCollection)
                {
                    sb.AppendLine(s);
                    sb.AppendLine("GO");
                }

                Clipboard.SetText(sb.ToString());
                stopwatch.Stop();
                queryForm.SetStatusbarPanelText(
                    $"Copying table script to clipboard finished in {StopwatchTimeSpan.ToString(stopwatch.ElapsedTicks, 3)} seconds.",
                    queryForm.ColorTheme != null ? queryForm.ColorTheme.ForeColor : SystemColors.ControlText);
            }
        }
示例#25
0
        void IResultWriter.WriteTableEnd()
        {
            var duration = Stopwatch.GetTimestamp() - _writeTableBeginTimestamp;
            var message  =
                $"Reading {_rowCount} row(s) from command[{_commandCount - 1}] into table[{_tableCount - 1},{_query?.Results[_tableCount - 1]}] finished in {StopwatchTimeSpan.ToString(duration, 3)} seconds.";

            _addInfoMessage(new InfoMessage(LocalTime.Default.Now, InfoMessageSeverity.Verbose, null, message));
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            var ticks = _stopwatch.ElapsedTicks;

            _tbTimer.Text = StopwatchTimeSpan.ToString(ticks, 0);
        }