SQL distributed cache created on Asp.net core startup












0















I was wondering if there is a way to create the SQL distributed cache on startup of the ASP.NET Core 2.1 application.



I know I can run this command
dotnet sql-cache create <connection string> <schema> <table name> but this is a manual process. I want to automate this process on startup.



Is this possible?



Thanks










share|improve this question























  • By startup I assume you meand during deployment? There's no reason to create the cache each time a web site starts, it should already be there. Why don't you use the same deployment technique you use for your other databases? If the cache table is stored in the same database as the application's tables all you need to do is include it in the deployment scripts

    – Panagiotis Kanavos
    Nov 22 '18 at 8:37


















0















I was wondering if there is a way to create the SQL distributed cache on startup of the ASP.NET Core 2.1 application.



I know I can run this command
dotnet sql-cache create <connection string> <schema> <table name> but this is a manual process. I want to automate this process on startup.



Is this possible?



Thanks










share|improve this question























  • By startup I assume you meand during deployment? There's no reason to create the cache each time a web site starts, it should already be there. Why don't you use the same deployment technique you use for your other databases? If the cache table is stored in the same database as the application's tables all you need to do is include it in the deployment scripts

    – Panagiotis Kanavos
    Nov 22 '18 at 8:37
















0












0








0








I was wondering if there is a way to create the SQL distributed cache on startup of the ASP.NET Core 2.1 application.



I know I can run this command
dotnet sql-cache create <connection string> <schema> <table name> but this is a manual process. I want to automate this process on startup.



Is this possible?



Thanks










share|improve this question














I was wondering if there is a way to create the SQL distributed cache on startup of the ASP.NET Core 2.1 application.



I know I can run this command
dotnet sql-cache create <connection string> <schema> <table name> but this is a manual process. I want to automate this process on startup.



Is this possible?



Thanks







c# sql-server asp.net-core






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 14:58









Gavin HowGavin How

254




254













  • By startup I assume you meand during deployment? There's no reason to create the cache each time a web site starts, it should already be there. Why don't you use the same deployment technique you use for your other databases? If the cache table is stored in the same database as the application's tables all you need to do is include it in the deployment scripts

    – Panagiotis Kanavos
    Nov 22 '18 at 8:37





















  • By startup I assume you meand during deployment? There's no reason to create the cache each time a web site starts, it should already be there. Why don't you use the same deployment technique you use for your other databases? If the cache table is stored in the same database as the application's tables all you need to do is include it in the deployment scripts

    – Panagiotis Kanavos
    Nov 22 '18 at 8:37



















By startup I assume you meand during deployment? There's no reason to create the cache each time a web site starts, it should already be there. Why don't you use the same deployment technique you use for your other databases? If the cache table is stored in the same database as the application's tables all you need to do is include it in the deployment scripts

– Panagiotis Kanavos
Nov 22 '18 at 8:37







By startup I assume you meand during deployment? There's no reason to create the cache each time a web site starts, it should already be there. Why don't you use the same deployment technique you use for your other databases? If the cache table is stored in the same database as the application's tables all you need to do is include it in the deployment scripts

– Panagiotis Kanavos
Nov 22 '18 at 8:37














2 Answers
2






active

oldest

votes


















2














Here are two options:



Options1



Since we could run command to create the table, we could run the command from code by Process.



    public static IServiceCollection ConfigureSqlCacheFromCommand(this IServiceCollection services)
{
var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();

var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c dotnet sql-cache create "{options.Value.ConnectionString}" { options.Value.SchemaName } { options.Value.TableName }",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Normal,
RedirectStandardInput = true,
RedirectStandardError = true
}
};
process.Start();
string input = process.StandardError.ReadToEnd();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return services;
}


Option2



For dotnet sql-cache command, it also calls dotnet-sql-cache, and you could implement the code to create the table programmly.



        private static int CreateTableAndIndexes(SqlServerCacheOptions options)
{
using (var connection = new SqlConnection(options.ConnectionString))
{
connection.Open();

var sqlQueries = new SqlQueries(options.SchemaName, options.TableName);
var command = new SqlCommand(sqlQueries.TableInfo, connection);

using (var reader = command.ExecuteReader(CommandBehavior.SingleRow))
{
if (reader.Read())
{
return 1;
}
}
using (var transaction = connection.BeginTransaction())
{
try
{
command = new SqlCommand(sqlQueries.CreateTable, connection, transaction);

command.ExecuteNonQuery();

command = new SqlCommand(
sqlQueries.CreateNonClusteredIndexOnExpirationTime,
connection,
transaction);

command.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
return 1;
}
}
}
return 0;
}


For calling CreateTableAndIndexes, you could implement this extension method:



        public static IServiceCollection ConfigureSqlCache(this IServiceCollection services)
{
var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();
int result = CreateTableAndIndexes(options.Value);
return services;
}


For configuring in Startup.cs



        services.AddDistributedSqlServerCache(options => {
options.ConnectionString = @"Server=localhostMSSQLSERVER01;Database=IISWindows;Trusted_Connection=True;";
options.TableName = "CacheFromCommand";
options.SchemaName = "dbo";
});

//services.ConfigureSqlCache();
services.ConfigureSqlCacheFromCommand();


Note




  • SqlQueries is from SqlQueries.


  • install package Microsoft.Extensions.CommandLineUtils.


  • Register ConfigureSqlCache after services.AddDistributedSqlServerCache






share|improve this answer































    0














    How do you want to automate this? I am sure but there are many ways to add a distributed cache.



    You can see the samples the following link:



    https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414801%2fsql-distributed-cache-created-on-asp-net-core-startup%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Here are two options:



      Options1



      Since we could run command to create the table, we could run the command from code by Process.



          public static IServiceCollection ConfigureSqlCacheFromCommand(this IServiceCollection services)
      {
      var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();

      var process = new Process()
      {
      StartInfo = new ProcessStartInfo
      {
      FileName = "cmd.exe",
      Arguments = $"/c dotnet sql-cache create "{options.Value.ConnectionString}" { options.Value.SchemaName } { options.Value.TableName }",
      RedirectStandardOutput = true,
      UseShellExecute = false,
      CreateNoWindow = false,
      WindowStyle = ProcessWindowStyle.Normal,
      RedirectStandardInput = true,
      RedirectStandardError = true
      }
      };
      process.Start();
      string input = process.StandardError.ReadToEnd();
      string result = process.StandardOutput.ReadToEnd();
      process.WaitForExit();
      return services;
      }


      Option2



      For dotnet sql-cache command, it also calls dotnet-sql-cache, and you could implement the code to create the table programmly.



              private static int CreateTableAndIndexes(SqlServerCacheOptions options)
      {
      using (var connection = new SqlConnection(options.ConnectionString))
      {
      connection.Open();

      var sqlQueries = new SqlQueries(options.SchemaName, options.TableName);
      var command = new SqlCommand(sqlQueries.TableInfo, connection);

      using (var reader = command.ExecuteReader(CommandBehavior.SingleRow))
      {
      if (reader.Read())
      {
      return 1;
      }
      }
      using (var transaction = connection.BeginTransaction())
      {
      try
      {
      command = new SqlCommand(sqlQueries.CreateTable, connection, transaction);

      command.ExecuteNonQuery();

      command = new SqlCommand(
      sqlQueries.CreateNonClusteredIndexOnExpirationTime,
      connection,
      transaction);

      command.ExecuteNonQuery();
      transaction.Commit();
      }
      catch (Exception ex)
      {
      transaction.Rollback();
      return 1;
      }
      }
      }
      return 0;
      }


      For calling CreateTableAndIndexes, you could implement this extension method:



              public static IServiceCollection ConfigureSqlCache(this IServiceCollection services)
      {
      var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();
      int result = CreateTableAndIndexes(options.Value);
      return services;
      }


      For configuring in Startup.cs



              services.AddDistributedSqlServerCache(options => {
      options.ConnectionString = @"Server=localhostMSSQLSERVER01;Database=IISWindows;Trusted_Connection=True;";
      options.TableName = "CacheFromCommand";
      options.SchemaName = "dbo";
      });

      //services.ConfigureSqlCache();
      services.ConfigureSqlCacheFromCommand();


      Note




      • SqlQueries is from SqlQueries.


      • install package Microsoft.Extensions.CommandLineUtils.


      • Register ConfigureSqlCache after services.AddDistributedSqlServerCache






      share|improve this answer




























        2














        Here are two options:



        Options1



        Since we could run command to create the table, we could run the command from code by Process.



            public static IServiceCollection ConfigureSqlCacheFromCommand(this IServiceCollection services)
        {
        var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();

        var process = new Process()
        {
        StartInfo = new ProcessStartInfo
        {
        FileName = "cmd.exe",
        Arguments = $"/c dotnet sql-cache create "{options.Value.ConnectionString}" { options.Value.SchemaName } { options.Value.TableName }",
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = false,
        WindowStyle = ProcessWindowStyle.Normal,
        RedirectStandardInput = true,
        RedirectStandardError = true
        }
        };
        process.Start();
        string input = process.StandardError.ReadToEnd();
        string result = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        return services;
        }


        Option2



        For dotnet sql-cache command, it also calls dotnet-sql-cache, and you could implement the code to create the table programmly.



                private static int CreateTableAndIndexes(SqlServerCacheOptions options)
        {
        using (var connection = new SqlConnection(options.ConnectionString))
        {
        connection.Open();

        var sqlQueries = new SqlQueries(options.SchemaName, options.TableName);
        var command = new SqlCommand(sqlQueries.TableInfo, connection);

        using (var reader = command.ExecuteReader(CommandBehavior.SingleRow))
        {
        if (reader.Read())
        {
        return 1;
        }
        }
        using (var transaction = connection.BeginTransaction())
        {
        try
        {
        command = new SqlCommand(sqlQueries.CreateTable, connection, transaction);

        command.ExecuteNonQuery();

        command = new SqlCommand(
        sqlQueries.CreateNonClusteredIndexOnExpirationTime,
        connection,
        transaction);

        command.ExecuteNonQuery();
        transaction.Commit();
        }
        catch (Exception ex)
        {
        transaction.Rollback();
        return 1;
        }
        }
        }
        return 0;
        }


        For calling CreateTableAndIndexes, you could implement this extension method:



                public static IServiceCollection ConfigureSqlCache(this IServiceCollection services)
        {
        var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();
        int result = CreateTableAndIndexes(options.Value);
        return services;
        }


        For configuring in Startup.cs



                services.AddDistributedSqlServerCache(options => {
        options.ConnectionString = @"Server=localhostMSSQLSERVER01;Database=IISWindows;Trusted_Connection=True;";
        options.TableName = "CacheFromCommand";
        options.SchemaName = "dbo";
        });

        //services.ConfigureSqlCache();
        services.ConfigureSqlCacheFromCommand();


        Note




        • SqlQueries is from SqlQueries.


        • install package Microsoft.Extensions.CommandLineUtils.


        • Register ConfigureSqlCache after services.AddDistributedSqlServerCache






        share|improve this answer


























          2












          2








          2







          Here are two options:



          Options1



          Since we could run command to create the table, we could run the command from code by Process.



              public static IServiceCollection ConfigureSqlCacheFromCommand(this IServiceCollection services)
          {
          var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();

          var process = new Process()
          {
          StartInfo = new ProcessStartInfo
          {
          FileName = "cmd.exe",
          Arguments = $"/c dotnet sql-cache create "{options.Value.ConnectionString}" { options.Value.SchemaName } { options.Value.TableName }",
          RedirectStandardOutput = true,
          UseShellExecute = false,
          CreateNoWindow = false,
          WindowStyle = ProcessWindowStyle.Normal,
          RedirectStandardInput = true,
          RedirectStandardError = true
          }
          };
          process.Start();
          string input = process.StandardError.ReadToEnd();
          string result = process.StandardOutput.ReadToEnd();
          process.WaitForExit();
          return services;
          }


          Option2



          For dotnet sql-cache command, it also calls dotnet-sql-cache, and you could implement the code to create the table programmly.



                  private static int CreateTableAndIndexes(SqlServerCacheOptions options)
          {
          using (var connection = new SqlConnection(options.ConnectionString))
          {
          connection.Open();

          var sqlQueries = new SqlQueries(options.SchemaName, options.TableName);
          var command = new SqlCommand(sqlQueries.TableInfo, connection);

          using (var reader = command.ExecuteReader(CommandBehavior.SingleRow))
          {
          if (reader.Read())
          {
          return 1;
          }
          }
          using (var transaction = connection.BeginTransaction())
          {
          try
          {
          command = new SqlCommand(sqlQueries.CreateTable, connection, transaction);

          command.ExecuteNonQuery();

          command = new SqlCommand(
          sqlQueries.CreateNonClusteredIndexOnExpirationTime,
          connection,
          transaction);

          command.ExecuteNonQuery();
          transaction.Commit();
          }
          catch (Exception ex)
          {
          transaction.Rollback();
          return 1;
          }
          }
          }
          return 0;
          }


          For calling CreateTableAndIndexes, you could implement this extension method:



                  public static IServiceCollection ConfigureSqlCache(this IServiceCollection services)
          {
          var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();
          int result = CreateTableAndIndexes(options.Value);
          return services;
          }


          For configuring in Startup.cs



                  services.AddDistributedSqlServerCache(options => {
          options.ConnectionString = @"Server=localhostMSSQLSERVER01;Database=IISWindows;Trusted_Connection=True;";
          options.TableName = "CacheFromCommand";
          options.SchemaName = "dbo";
          });

          //services.ConfigureSqlCache();
          services.ConfigureSqlCacheFromCommand();


          Note




          • SqlQueries is from SqlQueries.


          • install package Microsoft.Extensions.CommandLineUtils.


          • Register ConfigureSqlCache after services.AddDistributedSqlServerCache






          share|improve this answer













          Here are two options:



          Options1



          Since we could run command to create the table, we could run the command from code by Process.



              public static IServiceCollection ConfigureSqlCacheFromCommand(this IServiceCollection services)
          {
          var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();

          var process = new Process()
          {
          StartInfo = new ProcessStartInfo
          {
          FileName = "cmd.exe",
          Arguments = $"/c dotnet sql-cache create "{options.Value.ConnectionString}" { options.Value.SchemaName } { options.Value.TableName }",
          RedirectStandardOutput = true,
          UseShellExecute = false,
          CreateNoWindow = false,
          WindowStyle = ProcessWindowStyle.Normal,
          RedirectStandardInput = true,
          RedirectStandardError = true
          }
          };
          process.Start();
          string input = process.StandardError.ReadToEnd();
          string result = process.StandardOutput.ReadToEnd();
          process.WaitForExit();
          return services;
          }


          Option2



          For dotnet sql-cache command, it also calls dotnet-sql-cache, and you could implement the code to create the table programmly.



                  private static int CreateTableAndIndexes(SqlServerCacheOptions options)
          {
          using (var connection = new SqlConnection(options.ConnectionString))
          {
          connection.Open();

          var sqlQueries = new SqlQueries(options.SchemaName, options.TableName);
          var command = new SqlCommand(sqlQueries.TableInfo, connection);

          using (var reader = command.ExecuteReader(CommandBehavior.SingleRow))
          {
          if (reader.Read())
          {
          return 1;
          }
          }
          using (var transaction = connection.BeginTransaction())
          {
          try
          {
          command = new SqlCommand(sqlQueries.CreateTable, connection, transaction);

          command.ExecuteNonQuery();

          command = new SqlCommand(
          sqlQueries.CreateNonClusteredIndexOnExpirationTime,
          connection,
          transaction);

          command.ExecuteNonQuery();
          transaction.Commit();
          }
          catch (Exception ex)
          {
          transaction.Rollback();
          return 1;
          }
          }
          }
          return 0;
          }


          For calling CreateTableAndIndexes, you could implement this extension method:



                  public static IServiceCollection ConfigureSqlCache(this IServiceCollection services)
          {
          var options = services.BuildServiceProvider().GetRequiredService<IOptions<SqlServerCacheOptions>>();
          int result = CreateTableAndIndexes(options.Value);
          return services;
          }


          For configuring in Startup.cs



                  services.AddDistributedSqlServerCache(options => {
          options.ConnectionString = @"Server=localhostMSSQLSERVER01;Database=IISWindows;Trusted_Connection=True;";
          options.TableName = "CacheFromCommand";
          options.SchemaName = "dbo";
          });

          //services.ConfigureSqlCache();
          services.ConfigureSqlCacheFromCommand();


          Note




          • SqlQueries is from SqlQueries.


          • install package Microsoft.Extensions.CommandLineUtils.


          • Register ConfigureSqlCache after services.AddDistributedSqlServerCache







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 8:34









          Tao ZhouTao Zhou

          7,35931434




          7,35931434

























              0














              How do you want to automate this? I am sure but there are many ways to add a distributed cache.



              You can see the samples the following link:



              https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1






              share|improve this answer




























                0














                How do you want to automate this? I am sure but there are many ways to add a distributed cache.



                You can see the samples the following link:



                https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1






                share|improve this answer


























                  0












                  0








                  0







                  How do you want to automate this? I am sure but there are many ways to add a distributed cache.



                  You can see the samples the following link:



                  https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1






                  share|improve this answer













                  How do you want to automate this? I am sure but there are many ways to add a distributed cache.



                  You can see the samples the following link:



                  https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 19:22









                  mstfcckmstfcck

                  4133719




                  4133719






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53414801%2fsql-distributed-cache-created-on-asp-net-core-startup%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Guess what letter conforming each word

                      Port of Spain

                      Run scheduled task as local user group (not BUILTIN)