Created
July 24, 2014 03:56
-
-
Save skendrot/09d4a36a1f913a4339bd to your computer and use it in GitHub Desktop.
Service for determining if a user's trial has expired.
This file contains hidden or 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
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