Example #1
0
        public void Intercept(IInvocation invocation)
        {
            PropertyInfo property = invocation.TargetType.GetProperty("Connection");
            DbConnection conn     = (DbConnection)property.GetValue(invocation.InvocationTarget);
            MiniProfiler mp       = MiniProfiler.Current;

            if (mp == null)
            {
                mp = MiniProfiler.StartNew($"{invocation.TargetType}-{invocation.Method.Name}");
            }
            conn = new StackExchange.Profiling.Data.ProfiledDbConnection(conn, MiniProfiler.Current);
            property.SetValue(invocation.InvocationTarget, conn);
            invocation.Proceed();
            mp.Stop();
            if (mp.Root != null)
            {
                if (mp.Root.CustomTimings.ContainsKey("sql"))
                {
                    List <CustomTiming> list = mp.Root.CustomTimings["sql"];
                    StringBuilder       sb   = new StringBuilder();
                    sb.AppendLine($"【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}  {mp.Name}】");
                    foreach (var item in list)
                    {
                        if (item.ExecuteType == "Open" || item.ExecuteType == "Close")
                        {
                            continue;
                        }
                        sb.AppendLine($"{(item.Errored ? "【ERROR】" : "")}CommandString:{item.CommandString}\r\nExecuteType:{item.ExecuteType}\r\nDurationMilliseconds:{item.DurationMilliseconds}ms");
                    }
                    Console.WriteLine(sb);
                }
            }
        }
		public void TestProfiledSqlQuery()
		{
			var profiled = new ProfiledDbConnection((DbConnection)Connection(), MiniProfiler.Current);
			var result = profiled.QuerySql<int>("SELECT @p --MiniProfiler", new { p = 1 }).First();

			Assert.AreEqual((int)1, result);
		}
Example #3
0
        private void SelectTables()
        {
            var profiler = MiniProfiler.Current;
            var bareFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
            var providerFactory = new ProfiledDbProviderFactory(profiler, bareFactory);

            var connStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

            var bareConnection = new SqlConnection(connStr);

            var profiledConnection = new ProfiledDbConnection(bareConnection, profiler);

            var profiledCommand = providerFactory.CreateCommand();
            profiledCommand.Connection = profiledConnection;
            profiledCommand.CommandText = "SELECT * FROM sys.tables";

            using (profiler.Step("Open Connection"))
            {
                profiledConnection.Open();
            }

            using (profiler.Step("ExecuteNonQuery"))
            {
                profiledCommand.ExecuteNonQuery();
            }
        }
Example #4
0
 /// <summary>
 /// Initialises a new instance of the <see cref="ProfiledDbTransaction"/> class.
 /// </summary>
 /// <param name="transaction">The transaction.</param>
 /// <param name="connection">The connection.</param>
 public ProfiledDbTransaction(DbTransaction transaction, ProfiledDbConnection connection)
 {
     if (transaction == null) throw new ArgumentNullException("transaction");
     if (connection == null) throw new ArgumentNullException("connection");
     _transaction = transaction;
     _connection = connection;
 }
        public IDbConnection GetConnection()
        {
            var connection = new SqlConnection(_connectionString);
            var profiledConnection = new ProfiledDbConnection(connection, MiniProfiler.Current);

            profiledConnection.Open();

            return profiledConnection;
        }
 /// <summary>
 /// dispose the transaction and connection.
 /// </summary>
 /// <param name="disposing">false if being called from a <c>finalizer</c></param>
 protected override void Dispose(bool disposing)
 {
     if (disposing && _transaction != null)
     {
         _transaction.Dispose();
     }
     _transaction = null;
     _connection  = null;
     base.Dispose(disposing);
 }
Example #7
0
        public override DbConnection CreateConnection()
        {
            var sqliteConnection = new SqlCeConnection();
            DbConnection connection = sqliteConnection;

            if (IsProfiled)
            {
                connection = new ProfiledDbConnection(sqliteConnection, MiniProfiler.Current);
            }

            return connection;
        }
		public void TestProfiledStoredProcWithParameters()
		{
			using (var connection = ConnectionWithTransaction())
			{
				connection.ExecuteSql("CREATE PROC InsightTestProcMiniProfiler (@Value int = 5) AS SELECT Value=@Value");

				var profiled = new ProfiledDbConnection((DbConnection)connection, MiniProfiler.Current);
				var result = profiled.Query<int>("InsightTestProcMiniProfiler", new { Value = 1 }).First();

				Assert.AreEqual((int)1, result);
			}
		}
		public void TestProfiledStoredProcWithParameters()
		{
			using (SqlTransaction t = _connection.BeginTransaction())
			{
				_connection.ExecuteSql("CREATE PROC InsightTestProc (@Value int = 5) AS SELECT Value=@Value", transaction: t);

				var profiled = new ProfiledDbConnection(_connection, MiniProfiler.Current);
				var result = profiled.Query<int>("InsightTestProc", new { Value = 1 }, transaction: t).First();

				Assert.AreEqual((int)1, result);
			}
		}
 /// <summary>
 /// Initialises a new instance of the <see cref="ProfiledDbTransaction"/> class.
 /// </summary>
 /// <param name="transaction">The transaction.</param>
 /// <param name="connection">The connection.</param>
 public ProfiledDbTransaction(DbTransaction transaction, ProfiledDbConnection connection)
 {
     if (transaction == null)
     {
         throw new ArgumentNullException("transaction");
     }
     if (connection == null)
     {
         throw new ArgumentNullException("connection");
     }
     _transaction = transaction;
     _connection  = connection;
 }
Example #11
0
        /// <summary>
        /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect
        /// </summary>
        /// <param name="connectionString">The connection string to use for the connection</param>
        /// <param name="connectionTimeout">Milliseconds to wait to connect, optional</param>
        /// <returns>A READ UNCOMMITTED connection to the specified connection string</returns>
        public static async Task<DbConnection> GetOpenAsync(string connectionString, int? connectionTimeout = null)
        {
            var conn = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current);

            if (connectionTimeout.GetValueOrDefault(0) == 0)
            {
                await conn.OpenAsync();
                await conn.SetReadUncommitted();
            }
            else
            {
                // In the case of remote monitoring, the timeout will be at the NIC level, not responding to traffic,
                // in that scenario, connection timeouts don't really do much, because they're never reached, the timeout happens
                // before their timer starts.  Because of that, we need to spin up our own overall timeout
                using (MiniProfiler.Current.Step($"Opening Connection, Timeout: {conn.ConnectionTimeout}"))
                using (var tokenSource = new CancellationTokenSource())
                {
                    tokenSource.CancelAfter(connectionTimeout.Value);
                    try
                    {
                        await conn.OpenAsync(tokenSource.Token); // Throwing Null Refs
                        await conn.SetReadUncommitted();
                    }
                    catch (TaskCanceledException e)
                    {
                        conn.Close();
                        var csb = new SqlConnectionStringBuilder(connectionString);
                        var sqlException = $"Error opening connection to {csb.InitialCatalog} at {csb.DataSource}, timeout out at {connectionTimeout.ToComma()} ms";
                        throw new Exception(sqlException, e);
                    }
                    catch (SqlException e)
                    {
                        conn.Close();
                        var csb = new SqlConnectionStringBuilder(connectionString);
                        var sqlException = $"Error opening connection to {csb.InitialCatalog} at {csb.DataSource}: {e.Message}";
                        throw new Exception(sqlException, e);
                    }
                    if (conn.State == ConnectionState.Connecting)
                    {
                        tokenSource.Cancel();
                        var b = new SqlConnectionStringBuilder {ConnectionString = connectionString};
                        throw new TimeoutException($"Timeout expired connecting to {b.InitialCatalog} on {b.DataSource} on in the alloted {connectionTimeout.Value.ToComma()} ms");
                    }
                }
            }
            return conn;
        }
Example #12
0
        /// <summary>
        /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect
        /// </summary>
        /// <param name="connectionString">The connection string to use for the connection</param>
        /// <param name="connectionTimeout">Milliseconds to wait to connect, optional</param>
        /// <returns>A READ UNCOMMITTED connection to the specified connection string</returns>
        public static DbConnection GetOpen(string connectionString, int? connectionTimeout = null)
        {
            var conn = new ProfiledDbConnection(new MySqlConnection(connectionString), MiniProfiler.Current);
            Action<DbConnection> setReadUncommitted = c =>
            {
                using (var cmd = c.CreateCommand())
                {
                    cmd.CommandText = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
                    cmd.ExecuteNonQueryAsync();
                }
            };

            if (connectionTimeout.GetValueOrDefault(0) == 0)
            {
                conn.OpenAsync();
                setReadUncommitted(conn);
            }
            else
            {
                // In the case of remote monitoring, the timeout will be at the NIC level, not responding to traffic,
                // in that scenario, connection timeouts don't really do much, because they're never reached, the timeout happens
                // before their timer starts.  Because of that, we need to spin up our own overall timeout
                using (MiniProfiler.Current.Step("Opening Connection, Timeout: " + conn.ConnectionTimeout))
                    try
                    {
                        conn.Open();
                    }
                    catch (SqlException e)
                    {
                        var csb = new MySqlConnectionStringBuilder(connectionString);
                        var sqlException = string.Format("Error opening connection to {0} at {1} timeout was: {2} ms", csb.Server, csb.Database, connectionTimeout.ToString());
                        throw new Exception(sqlException, e);
                    }
                setReadUncommitted(conn);
                if (conn.State == ConnectionState.Connecting)
                {
                    var b = new MySqlConnectionStringBuilder { ConnectionString = connectionString };

                    throw new TimeoutException("Timeout expired connecting to " + b.Server + " on " +
                                                b.Database + " on in the alloted " +
                                                connectionTimeout.Value.ToString() + " ms");
                }
            }
            return conn;
        }
        protected System.Data.Common.DbCommand CreateDbCommand()
        {
            var connectionString = Constants.AdventureWorksConnectionString;
            var sqlConnection = new SqlConnection(connectionString);

            var connection = new StackExchange.Profiling.Data.ProfiledDbConnection
                (sqlConnection, MiniProfiler.Current);

            Request.RegisterForDispose(connection);

            var command = connection.CreateCommand();
            Request.RegisterForDispose(command);

            Logger.Log(new LogEventInfo(LogLevel.Error,"Controller","Connection Returned."));

            connection.Open();
            return command;
        }
Example #14
0
        /// <summary>
        /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect
        /// </summary>
        /// <param name="connectionString">The connection string to use for the connection</param>
        /// <param name="connectionTimeout">Milliseconds to wait to connect, optional</param>
        /// <returns>A READ UNCOMMITTED connection to the specified connection string</returns>
        public static async Task<DbConnection> GetOpenAsync(string connectionString, int? connectionTimeout = null)
        {
            var conn = new ProfiledDbConnection(new MySqlConnection(connectionString), MiniProfiler.Current);

            if (connectionTimeout.GetValueOrDefault(0) == 0)
            {
                await conn.OpenAsync();
                await SetReadUncommitted(conn);
            }
            else
            {
                // In the case of remote monitoring, the timeout will be at the NIC level, not responding to traffic,
                // in that scenario, connection timeouts don't really do much, because they're never reached, the timeout happens
                // before their timer starts.  Because of that, we need to spin up our own overall timeout
                using (MiniProfiler.Current.Step("Opening Connection, Timeout: " + conn.ConnectionTimeout))
                using (var tokenSource = new CancellationTokenSource())
                {
                    tokenSource.CancelAfter(connectionTimeout.Value);
                    try
                    {
                        await conn.OpenAsync(tokenSource.Token); // Throwing Null Refs
                    }
                    catch (SqlException e)
                    {
                        var csb = new MySqlConnectionStringBuilder(connectionString);
                        var sqlException = string.Format("Error opening connection to {0} at {1} timeout was: {2} ms", csb.Database, csb.Server, connectionTimeout.ToString());
                        throw new Exception(sqlException, e);
                    }
                    await SetReadUncommitted(conn);
                    if (conn.State == ConnectionState.Connecting)
                    {
                        tokenSource.Cancel();
                        var b = new MySqlConnectionStringBuilder { ConnectionString = connectionString };

                        throw new TimeoutException("Timeout expired connecting to " + b.Database + " on " +
                                                    b.Server + " on in the alloted " +
                                                    connectionTimeout.Value.ToString() + " ms");
                    }
                }
            }
            return conn;
        }
 public ProfiledSqlDbTransaction(SqlTransaction transaction, ProfiledDbConnection connection)
     : base(transaction, connection)
 {
     Transaction = transaction;
 }
Example #16
0
        /// <summary>
        /// The EF code first.
        /// </summary>
        /// <returns>the entity framework code first view.</returns>
        public ActionResult EFCodeFirst()
        {
            int count;
            int? newCount = null;

            EFContext context = null;
            using (MiniProfiler.Current.Step("EF Stuff"))
            {
                try
                {
                    using (MiniProfiler.Current.Step("Create Context"))
                        context = new EFContext();

                    // this is not correct, as the count from this assignment is never actually used
                    using (MiniProfiler.Current.Step("First count"))
                        count = context.People.Count();

                    using (MiniProfiler.Current.Step("Insertion"))
                    {
                        var p = new Person { Name = "sam" };
                        context.People.Add(p);
                        context.SaveChanges();
                    }

                    // this count is actually used.
                    using (MiniProfiler.Current.Step("Second count"))
                        count = context.People.Count();

                    const string sql = "Select count(*) from People";
                    using (MiniProfiler.Current.Step("Get Count from SqlQuery Method - no sql recorded"))
                    {
                        newCount = context.Database.SqlQuery<int>(sql).Single();
                    }
                    using (MiniProfiler.Current.Step("Get Count using ProfiledConnection - sql recorded"))
                    {
                        using (var conn = new ProfiledDbConnection(context.Database.Connection, MiniProfiler.Current))
                        {
                            conn.Open();
                            newCount = conn.Query<int>(sql).Single();
                            conn.Close();
                        }
                    }

                }
                finally
                {
                    if (context != null)
                    {
                        context.Dispose();
                    }
                }
            }

            return Content(string.Format("EF Code First complete - count: {0}, sqlQuery count {1}", count, newCount));
        }
Example #17
0
 /// <summary>
 /// Initialises a new instance of the <see cref="ProfiledDbTransaction"/> class.
 /// </summary>
 /// <param name="transaction">The transaction.</param>
 /// <param name="connection">The connection.</param>
 /// <exception cref="ArgumentNullException">Throws when the <paramref name="transaction"/> or <paramref name="connection"/> is <c>null</c>.</exception>
 public ProfiledDbTransaction(DbTransaction transaction, ProfiledDbConnection connection)
 {
     _transaction = transaction ?? throw new ArgumentNullException(nameof(transaction));
     _connection  = connection ?? throw new ArgumentNullException(nameof(connection));
 }
Example #18
0
 /// <summary>
 /// dispose the transaction and connection.
 /// </summary>
 /// <param name="disposing">false if being called from a <c>finalizer</c></param>
 protected override void Dispose(bool disposing)
 {
     if (disposing && _transaction != null)
     {
         _transaction.Dispose();
     }
     _transaction = null;
     _connection = null;
     base.Dispose(disposing);
 }
Example #19
0
    /// <summary>
    /// Méthodes ConfigureServices
    /// </summary>
    public void ConfigureServices(IServiceCollection services)
    {
        // contrôleur
        services.AddControllers(o =>
        {
            if (string.Equals(Configuration["MiniProfiler.Enable"], TrueString, OrdinalIgnoreCase))
            {
                o.Filters.Add <MiniProfilerAsyncLogger>();
            }
        })
        .AddOData(o =>
        {
            o.Select().Filter().OrderBy().SetMaxTop(100).Expand();
        })
        .AddJsonOptions(c =>
        {
            c.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
            c.JsonSerializerOptions.ReferenceHandler    = ReferenceHandler.IgnoreCycles;
        });

        // Forwarded headers
        services.AddErabliereAPIForwardedHeaders(Configuration);

        // Authentication
        if (string.Equals(Configuration["USE_AUTHENTICATION"], TrueString, OrdinalIgnoreCase))
        {
            if (Configuration["AzureAD__ClientId"] != null && Configuration["AzureAD:ClientId"] == null)
            {
                Configuration["AzureAD:ClientId"] = Configuration["AzureAD__ClientId"];
            }

            if (Configuration["AzureAD__TenantId"] != null && Configuration["AzureAD:TenantId"] == null)
            {
                Configuration["AzureAD:TenantId"] = Configuration["AzureAD__TenantId"];
            }

            if (string.IsNullOrWhiteSpace(Configuration["AzureAD:ClientId"]) == false)
            {
                services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
            }
            else
            {
                services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = Configuration["OIDC_AUTHORITY"];

                    options.ApiName = "erabliereapi";
                });
            }
        }
        else
        {
            services.AddSingleton <IAuthorizationHandler, AllowAnonymous>();
        }

        // Swagger
        services.AjouterSwagger(Configuration);

        // Cors
        if (string.Equals(Configuration["USE_CORS"], TrueString, OrdinalIgnoreCase))
        {
            services.AddCors();
        }

        // Automapper
        services.AjouterAutoMapperErabliereApiDonnee();

        // Database
        if (string.Equals(Configuration["USE_SQL"], TrueString, OrdinalIgnoreCase))
        {
            services.AddDbContext <ErabliereDbContext>(options =>
            {
                var connectionString = Configuration["SQL_CONNEXION_STRING"] ?? throw new InvalidOperationException("La variable d'environnement 'SQL_CONNEXION_STRING' à une valeur null.");

                if (string.Equals(Configuration["MiniProlifer.EntityFramework.Enable"], TrueString, OrdinalIgnoreCase))
                {
                    DbConnection connection = new SqlConnection(connectionString);

                    connection = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);

                    options.UseSqlServer(connection, o => o.EnableRetryOnFailure());
                }
                else
                {
                    options.UseSqlServer(connectionString, o => o.EnableRetryOnFailure());
                }

                if (string.Equals(Configuration["LOG_SQL"], "Console", OrdinalIgnoreCase))
                {
                    options.LogTo(Console.WriteLine, LogLevel.Information);
                }
            });
        }
        else
        {
            services.AddDbContext <ErabliereDbContext>(options =>
            {
                options.UseInMemoryDatabase(nameof(ErabliereDbContext));
            });
        }

        // HealthCheck
        services.AddHealthChecks()
        .AddCheck <MemoryUsageCheck>(nameof(MemoryUsageCheck), HealthStatus.Degraded, new[]
        {
            "live",
            "memory"
        });

        // MiniProfiler
        if (string.Equals(Configuration["MiniProfiler.Enable"], TrueString, OrdinalIgnoreCase))
        {
            var profilerBuilder = services.AddMiniProfiler(o =>
            {
                if (string.Equals(Configuration["MiniProlifer.EntityFramework.Enable"], TrueString, OrdinalIgnoreCase))
                {
                    o.SqlFormatter = new SqlServerFormatter();
                }
            });

            if (string.Equals(Configuration["MiniProlifer.EntityFramework.Enable"], TrueString, OrdinalIgnoreCase))
            {
                profilerBuilder.AddEntityFramework();
            }
        }

        // Prometheus
        services.AddSingleton <CollectorRegistry>(Metrics.DefaultRegistry);
    }
 public ProfiledTransactionWrapper(DbTransaction transaction, ProfiledDbConnection connection)
     : base(transaction, connection)
 {
     Transaction = transaction;
 }