Search code examples
c#console-applicationmvc-mini-profiler

How to store MIniProfiler data using Console application


I have implement one console application and added Miniprofiler to this application.

Now I want to store Miniprofiler data to database. I have execute the script to create tables to database. You can find script here!

I have reviewed answer on this

But How can I store the profiler values to related tables?

In MVC below line is used to store values:

MiniProfiler.Settings.Storage = new SqlServerStorage("<your connection string>");

How can I store these values from the Console application?


Solution

  • The above works fully, and records the expected data to the MiniProfilers and MiniProfilerTimings tables. The key bits in the setup code are:

    • specifying a storage provider (you already had this)
    • specifying a profiler provider (singleton in my case)
    • start/stop the profiler around the work
    • save the profiler after the work

    Code:

    using StackExchange.Profiling;
    using StackExchange.Profiling.Storage;
    using System;
    using System.Threading;
    //using StackExchange.Profiling.Helpers.Dapper; // only for table creation
    //using System.Data.SqlClient; // only for table creation
    
    static class Program
    {
        static void Main()
        {
            const string ConnectionString = "Initial Catalog=MiniProf;Data Source=.;Integrated Security=true;";
    
            //using(var conn = new SqlConnection(ConnectionString))
            //{
            //    conn.Open();
            //    conn.Execute(SqlServerStorage.TableCreationScript);
            //}
            MiniProfiler.Settings.Storage = new SqlServerStorage(ConnectionString);
            MiniProfiler.Settings.ProfilerProvider = new SingletonProfilerProvider();
            MiniProfiler.Settings.ProfilerProvider.Start(ProfileLevel.Info);
            DoStuff();
            MiniProfiler.Settings.ProfilerProvider.Stop(false);
    
            MiniProfiler.Settings.Storage.Save(MiniProfiler.Current);
        }
        static void DoStuff()
        {
            using (MiniProfiler.Current.Step("DoStuff"))
            {
                for (int i = 0; i < 5; i++)
                {
                    using (MiniProfiler.Current.Step("Loop iteration"))
                    {
                        Thread.Sleep(200);
                        Console.Write(".");
                    }
                }
            }
            Console.WriteLine();
        }
    }