Skip to content

Instantly share code, notes, and snippets.

@skendrot
Created July 24, 2014 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skendrot/09d4a36a1f913a4339bd to your computer and use it in GitHub Desktop.
Save skendrot/09d4a36a1f913a4339bd to your computer and use it in GitHub Desktop.
Service for determining if a user's trial has expired.
class AzureTrialService : ITrialService
{
private readonly IMobileServiceClient _service;
public AzureTrialService(IMobileServiceClient service)
{
_service = service;
TrialPeriod = TimeSpan.FromDays(7);
}
public TimeSpan TrialPeriod { get; set; }
public async Task<bool> IsExpiredAsync<TUser>(string userId) where TUser : TrialUser, new()
{
bool isExpired = false;
object dateVal;
if (ApplicationData.Current.LocalSettings.Values.TryGetValue("trialExpiration", out dateVal) == false)
{
// get user from server
IMobileServiceTable<TUser> table = _service.GetTable<TUser>();
var users = await table.Where(userInfo => userInfo.Id == userId).ToListAsync();
var user = users.FirstOrDefault();
if (user == null)
{
// new user, add it
var trialExpirationDate = DateTimeOffset.Now + TrialPeriod;
dateVal = trialExpirationDate;
user = new TUser { Id = userId, TrialExpirationDate = trialExpirationDate.ToUniversalTime() };
await table.InsertAsync(user);
}
else
{
// mobile services will deserialize as local DateTime
dateVal = user.TrialExpirationDate;
}
ApplicationData.Current.LocalSettings.Values["trialExpiration"] = dateVal;
}
var expirationDate = (DateTimeOffset)dateVal;
isExpired = expirationDate < DateTimeOffset.Now;
return isExpired;
}
}
/// <summary>
/// Represents information for a trial user.
/// </summary>
abstract class TrialUser
{
/// <summary>
/// Gets or sets the id for the user.
/// </summary>
public abstract string Id { get; set; }
/// <summary>
/// Gets or sets the date the trial will expire for the user.
/// </summary>
public abstract DateTimeOffset TrialExpirationDate { get; set; }
}
interface ITrialService
{
/// <summary>
/// Get or sets the time amount of time the user is allowed to use the trial.
/// </summary>
TimeSpan TrialPeriod { get; set; }
/// <summary>
/// Gets a value indicating if the trial has expired for the given userId.
/// </summary>
/// <param name="userId"></param>
/// <returns>A task that will complete when the data is retrieved.</returns>
Task<bool> IsExpiredAsync<TUser>(string userId) where TUser : TrialUser, new();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment