Created
June 14, 2015 15:00
-
-
Save shawnweisfeld/fdf5e8584a99da196e2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DistributedMutex; | |
using Microsoft.WindowsAzure.Storage; | |
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Web; | |
using System.Web.Mvc; | |
namespace LbsTest.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
public async Task<ActionResult> ProbeEndpoint() | |
{ | |
string leaseId = string.Empty; | |
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["CsaMutex"].ConnectionString); | |
string container = ConfigurationManager.AppSettings["CsaMutexContainer"]; | |
string blobName = ConfigurationManager.AppSettings["CsaMutexBlob"]; | |
BlobSettings blobSettings = new BlobSettings(storageAccount, container, blobName); | |
CancellationToken token = new CancellationToken(false); | |
BlobLeaseManager leaseManager = new BlobLeaseManager(blobSettings); | |
// Get the lease from the application state | |
leaseId = GetCachedLeaseId(); | |
// If we could not get the lease from application state try to acquire the blob lease | |
if (string.IsNullOrEmpty(leaseId)) | |
{ | |
leaseId = await leaseManager.AcquireLeaseAsync(token); | |
// Cache the lease id | |
SetCachedLeaseId(leaseId); | |
} | |
// Try to Renew the lease | |
// If you cannot clear the cache | |
if (!string.IsNullOrEmpty(leaseId)) | |
{ | |
if (await leaseManager.RenewLeaseAsync(leaseId, token)) | |
{ | |
return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK); | |
} | |
else | |
{ | |
SetCachedLeaseId(string.Empty); | |
} | |
} | |
return new HttpStatusCodeResult(System.Net.HttpStatusCode.ServiceUnavailable); | |
} | |
private void SetCachedLeaseId(string leaseId) | |
{ | |
System.Web.HttpContext.Current.Application.Lock(); | |
System.Web.HttpContext.Current.Application["leaseId"] = leaseId; | |
System.Web.HttpContext.Current.Application.UnLock(); | |
} | |
private string GetCachedLeaseId() | |
{ | |
string leaseId = string.Empty; | |
System.Web.HttpContext.Current.Application.Lock(); | |
if (System.Web.HttpContext.Current.Application["leaseId"] != null) | |
{ | |
leaseId = System.Web.HttpContext.Current.Application["leaseId"].ToString(); | |
}; | |
System.Web.HttpContext.Current.Application.UnLock(); | |
return leaseId; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment