Implementation Strategy
To monitor processing progress in ASP.NET MVC applications, we ipmlement a polling mechanism using JavaScript to periodically query server-side status updates. Below are the implementation details.
Front end Implementation
The JavaScript function timedCount() sends AJAX requests at regular intervals to fetch the latest progress information:
var pollTimer;
function timedCount() {
$.ajax({
type: 'GET',
url: '../../TMS.Service/OrderImport/GetImportProcess?cacheKey=' + sessionKey,
dataType: 'json',
success: function (response) {
if (response.status) {
$('#statusDisplay').html(
"<label>Current Progress:</label>" +
"<span style="color:red;font-size: large;">" + response.message + "</span>"
);
}
}
});
pollTimer = setTimeout(timedCount, 2000);
}
A unique session identifier is generated using a GUID generator function:
var sessionKey = "";
function generateGUID() {
function randomHex() {
return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
}
return (randomHex() + randomHex() + "-" + randomHex() + "-" +
randomHex() + "-" + randomHex() + "-" + randomHex() +
randomHex() + randomHex());
}
Backend Implementation
The controller action handles progress queries via HTTP GET requests:
[HttpGet]
public ActionResult GetImportProcess(string cacheKey = null)
{
try
{
var result = new OrderImportHandler().GetProcessingStatus(cacheKey);
return new ResponseWrapper {
status = !string.IsNullOrEmpty(result),
message = result
};
}
catch (Exception ex)
{
return new ResponseWrapper {
status = false,
message = $"<br></br>Failed to retrieve progress: {ex.Message}!"
};
}
}
Cache Management
Progress information is stored in server-side cache using a helper class:
CacheManager.SetCacheStatus(MSG_CACHE_KEY, "Preparing to submit data to system");
The cache utility class provides methods for status tracking:
public class CacheManager
{
public static object GetCacheValue(string key)
{
return HttpRuntime.Cache.Get(key);
}
public static void SetCacheStatus(string key, object value)
{
var cache = HttpRuntime.Cache;
if (cache != null && value != null)
{
cache.Insert(key, value);
}
}
public static void SetCacheWithExpiration(string key, object value, int seconds = 2)
{
if (value == null) return;
var cache = HttpRuntime.Cache;
cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds), TimeSpan.Zero,
CacheItemPriority.High, null);
}
public static void ClearCache(string key)
{
HttpRuntime.Cache.Remove(key);
}
public static void ClearAllCaches()
{
var cache = HttpRuntime.Cache;
var enumerator = cache.GetEnumerator();
while (enumerator.MoveNext())
{
cache.Remove(enumerator.Key.ToString());
}
}
}