Skip to main content

Manage an In-Memory Data Cache in ASP.NET MVC and ASP.NET Core

  • 8 minutes to read

This article describes the dashboard’s data cache functionality, corresponding API, and how to update the cached data.

The Web Dashboard control can display dashboards supplied with data from different types of data sources, which include SQL databases, Excel files, Entity Framework data sources, and so on. The Web Dashboard manages cache as follows depending on the data processing mode:

Server

The Web Dashboard requests data automatically by sending a query that contains a corresponding SELECT statement.

Web Dashboard - Cache for server mode

Client

The Web Dashboard creates a server-side in-memory cache that stores data from the data source in an optimized way. This capability accelerates specific client-side actions that require data updates (for instance, when you apply master filtering).

Web Dashboard - Cache for in-memory mode

Share Cache

The in-memory cache is created when data is loaded for the first time. The Web Dashboard can create multiple caches to accelerate data loading for different dashboards/data sources. The cache is shared across all users of all Web Dashboard’s instances.

Use Different Caches for Different User Groups

The Web Dashboard can create several caches to accelerate data loading for different dashboards/data sources. Each cache has its own unique key that contains predefined and custom parts:

  • The first part describes the dashboard object model, including information about the data source.
  • The second part includes dashboard parameters (name-value pairs). You can implement custom logic when handling the CustomParameters event to create different caches.

The caches are shared between all users by default:

Web Dashboard - Cache sharing between all users

You can manage access to different caches for different users. For this, set a unique parameter value for each user group:

Web Dashboard - Cache sharing between user groups

To do this in code, handle the DashboardConfigurator.CustomParameters event as follows:

ASP.NET Core

The following example shows how to use a custom parameter for this purpose:

View Example

// Configure user-specific data caching
private void DashboardConfigurator_CustomParameters(object sender, CustomParametersWebEventArgs e) {
    var userId = contextAccessor.HttpContext.Session.GetString("CurrentUser").GetHashCode();
    e.Parameters.Add(new Parameter("UserId", typeof(string), userId));
}
ASP.NET MVC

The following example shows how to use a custom parameter for this purpose:

View Example

// Configure user-specific data caching
private static void DashboardConfigurator_CustomParameters(object sender, CustomParametersWebEventArgs e) {
    var userId = HttpContext.Current.Session["CurrentUser"].GetHashCode();
    e.Parameters.Add(new Parameter("UserId", typeof(string), userId));
}

The parameter’s name-value pair is included in the cache key–users get the cache only for the corresponding user group. Encode the passed parameter value if possible. Do not store any sensitive information in dashboard parameters that isn’t encrypted.

Specify the Cache Timeout on the Server

When the Web Dashboard loads data for the first time, it checks whether any cache exists. If the existing cache is older than 300 seconds, the Web Dashboard recreates it. The Web Dashboard manages this cache in the following independent ways:

Default time interval
The Web Dashboard clears the cache if the time interval between two data requests exceeds 300 seconds. If the time interval between two data requests is less than 300 seconds, the Web Dashboard leaves the old cache unchanged and starts the timer again.
Specified time interval
The Web Dashboard allows you to set a time interval that specifies how frequently the Web Dashboard should refill its cache when a user sends a data request. You can handle the DashboardConfigurator.ConfigureDataReloadingTimeout event to change this time interval. For instance, if you set the e.DataReloadingTimeout event parameter to 100 seconds, the Web Dashboard updates the cache when a new request is received and the current cache version was created more than 100 seconds ago.

Refresh the Control on the Client

When you call the client-side DashboardControl.refresh method, the control requests the latest data from the server and reloads the dashboard items. If a cache exists, the control fetches data from the cache.

Get access to the underlying DashboardControl instance and call the refresh method as follows:

function onClick() {
    clientDashboardControl.refresh();
}

To refresh specific dashboard items, pass their names as a parameter. The code below refreshes Chart and Grid items:

function onClick() {
    clientDashboardControl.refresh(["chartDashboardItem1", "gridDashboardItem1"]);
}

See the following topic for details on how to customize the Web Dashboard control on the client:

Force the Cache Reset

Client Side

To update the data source cache on the client, call the client-side DashboardControl.reloadData method. The method call sends a callback to the server. This forces the cache reset and recreates a new one. Note that multiple users can simultaneously open the dashboard and share the same server-side cache. If one of the users calls the reloadData method, it forces the server cache to be reset and all users get new data on the next request to the server.

function reloadOnClient() {
    dashboardControl1.reloadData();
}

See the following topic for details on how to customize the Web Dashboard control on the client:

Server Side

To refresh the data source cache on the server side, pass a unique parameter value to the DashboardConfigurator.CustomParameters event.

For instance, you can store a unique GUID value within a Session or static variable as a parameter and update its value in your code when you need to refresh the cache.

ASP.NET Core

Create the cache manager that stores a unique GUID value within a Session or static variable as a parameter:

using Microsoft.AspNetCore.Http;
using System;

namespace AspNetCoreDashboardUseDifferentCaches
{
    public class CacheManager {
        const string SessionKey = "UniqueCacheParam";
        protected IHttpContextAccessor HttpContextAccessor { get; }

        public CacheManager(IHttpContextAccessor httpContextAccessor) {
            this.HttpContextAccessor = httpContextAccessor;
        }

        public void ResetCache() {
            HttpContextAccessor?.HttpContext?.Session?.SetString(SessionKey,Guid.NewGuid().ToString());
        }
        public Guid UniqueCacheParam {
            get {
                ISession session = HttpContextAccessor?.HttpContext?.Session;
                if(session == null) {
                    return Guid.Empty;
                } else {
                    if(string.IsNullOrEmpty(session.GetString(SessionKey)))
                        ResetCache();
                    return Guid.Parse(session.GetString(SessionKey));
                }
            }
        }
    }
}

Add the CacheManager singleton to the application:

public void ConfigureServices(IServiceCollection services) {
// ...
    services.AddDistributedMemoryCache().AddSession();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<CacheManager>(serviceProvider => new CacheManager(serviceProvider.GetService<IHttpContextAccessor>()));
}

Create a controller for the Refresh action:

using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreDashboardUseDifferentCaches {
    public class HomeController: Controller {
    // ...
        public IActionResult Refresh([FromServices]CacheManager cacheManager) {
            cacheManager.ResetCache();
            return Ok();
        }
    }
}

Pass the parameter to the DashboardConfigurator.CustomParameters event:

public void ConfigureServices(IServiceCollection services) {
// ...
    services.AddScoped<DashboardConfigurator>((IServiceProvider serviceProvider) => {
        DashboardConfigurator configurator = new DashboardConfigurator();
        // ...
        // Specifies a unique cache parameter.
        configurator.CustomParameters += (sender, e) => {
            e.Parameters.Add(new DashboardParameter("UniqueCacheParam", typeof(Guid), serviceProvider.GetService<CacheManager>().UniqueCacheParam));
        };

        return configurator;
    });
    // ...
}

Reset the cache in your code: use the created Refresh action and call the DashboardControl.refresh method on success:

function reloadOnServer() {
    $.ajax({
        url: '@Url.Action("Refresh")',
        success: function (data) {
            dashboardControl1.refresh();
            // To refresh specific dashboard items, pass their names as parameters:
            // WebDashboard1.GetDashboardControl().refresh( ["chartDashboardItem1", "listBoxDashboardItem1"] );
        }
    })
}

ASP.NET MVC

Create the cache manager that stores a unique GUID value within a Session or static variable as a parameter:

using System;
using System.Web;

namespace MvcDashboardUseDifferentCaches
{
    public class CacheManager {
        public static void ResetCache() {
            if(HttpContext.Current.Session != null)
                HttpContext.Current.Session["UniqueCacheParam"] = Guid.NewGuid();
        }
        public static Guid UniqueCacheParam {
            get {
                if(HttpContext.Current.Session == null)
                    return Guid.Empty;
                else {
                    if(HttpContext.Current.Session["UniqueCacheParam"] == null)
                        ResetCache();
                    return (Guid)HttpContext.Current.Session["UniqueCacheParam"];
                }
            }
        }
    }
}

Create a controller for the Refresh action:

using System.Web.Mvc;

namespace MvcDashboardUseDifferentCaches.Controllers
{
    public class HomeController : Controller {
        public ActionResult Index() {
            return View();
        }
        public ActionResult Refresh() {
            CacheManager.ResetCache();
            return new EmptyResult();
        }
    }
}

Pass the parameter to the DashboardConfigurator.CustomParameters event:

private static void Default_CustomParameters(object sender,CustomParametersWebEventArgs e) {
    e.Parameters.Add(new DashboardParameter("UniqueCacheParam",typeof(Guid),CacheManager.UniqueCacheParam));
}

Reset the cache in your code: use the created Refresh action and call the DashboardControl.refresh method on success:

function reloadOnServer() {
    $.ajax({
        url: '@Url.Action("Refresh")',
        success: function (data) {
            WebDashboard1.GetDashboardControl().refresh();
            // To refresh specific dashboard items, pass their names as parameters:
            // WebDashboard1.GetDashboardControl().refresh( ["chartDashboardItem1", "listBoxDashboardItem1"] );
        }
    })
}

Example: How to Reset the Cache

The following example shows how you can manage the cache in the Web Dashboard control.

  • Click Refresh Cache (Server) to force the cache reset on the server.
  • Click Refresh Cache (Client) to force the cache reset using client API.

View Example: ASP.NET Core View Example: ASP.NET MVC

Web Dashboard - Reset cache example

Example: How to Use Parameters to Update a Specific Dashboard Item Without Refreshing the Entire Dashboard

This example shows how to use dashboard parameters to update a specific dashboard item without refreshing the entire dashboard. This technique is applicable when you need to filter data source data to update a specific dashboard item, but do not want to refresh data in all items in a dashboard because this operation causes performance delays.

View Example: ASP.NET Core

Web Dashboard - How to update specific item