Skip to content

Instantly share code, notes, and snippets.

@steven-r
Last active March 10, 2023 02:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steven-r/90b088b99a753ea51ce9 to your computer and use it in GitHub Desktop.
Save steven-r/90b088b99a753ea51ce9 to your computer and use it in GitHub Desktop.
Example on how to cache values for API calls
#region copyright
// /* Copyright (C) think2infinity LLC - All Rights Reserved
// *
// * TimeJack
// *
// * Written by Stephen Reindl <stephen@think2infinity.com>, 09 2013
// *
// */
#endregion
#region usings
using System;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Microsoft.AspNet.Identity;
using TimeJack.Common.Security;
using TimeJack.Model.Annotations;
using TimeJack.Model.Models;
#endregion
namespace TimeJack.Api
{
/// <summary>
/// Base controller for db and customer id settings
/// </summary>
public abstract class BaseController: ApiController
{
private readonly object _lock = new object();
/// <summary>
/// The customer this controller is referencing to.
/// </summary>
protected Guid CustomerId
{
get
{
if (!_customerId.HasValue)
{
InitApi();
lock (_lock)
{
if (User.Identity.IsAuthenticated)
{
Guid? customerId = HttpContext.Current.Cache["APIID" + User.Identity.Name] as Guid?;
if (customerId.HasValue)
{
CustomerId = customerId.Value;
}
else
{
UserProfile user = UserManager.FindByName(User.Identity.Name);
if (user != null)
{
CustomerId = user.CustomerId;
HttpContext.Current.Cache["APIID" + User.Identity.Name] = user.CustomerId;
}
}
}
else
{
_customerId = Guid.Empty;
}
}
}
return _customerId.GetValueOrDefault();
}
private set { _customerId = value; }
}
/// <summary>
///
/// </summary>
private ITimeJackContext _db;
/// <summary>
///
/// </summary>
protected ITimeJackContext Db
{
get
{
if (_db == null)
{
InitApi();
}
return _db;
}
private set { _db = value; }
}
/// <summary>
///
/// </summary>
protected ApplicationUserManager UserManager
{
get
{
if (_userManager == null)
{
InitApi();
}
return _userManager;
}
private set { _userManager = value; }
}
private Guid? _customerId;
private ApplicationUserManager _userManager;
/// <summary>
///
/// </summary>
/// <param name="controllerContext"></param>
protected override void Initialize([NotNull] HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
}
/// <summary>
///
/// </summary>
private void InitApi()
{
lock (_lock)
{
if (_db == null)
{
Db = new TimeJackContext();
Db.Configuration.ProxyCreationEnabled = false;
}
if (_userManager == null)
{
UserManager = new ApplicationUserManager(_db as TimeJackContext);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment