/// <summary>
 /// Constructor taking the underlying TableEntity object that is read/written in Azure Storage
 /// </summary>
 /// <param name="token">The underlying TableEntity object</param>
 /// <param name="username">The username</param>
 internal OAuth2AzureToken(OAuth2AzureTokenData token, string username)
 {
     this.token = token;
     this.Username = username;
 }
        /// <summary>
        /// Creates or retrieves an OAuth2Token object based on the specified parameters.
        /// The object is not stored in Azure until a call is made to SaveToken. 
        /// If this method returns isNew = true, then caller must make sure SaveToken is called
        /// to persist the token in Azure Storage
        /// </summary>
        /// <param name="username">The username</param>
        /// <param name="consumerKey">The consumer key</param>
        /// <param name="consumerSecret">The consumer secret</param>
        /// <param name="isNew">Out parameter which indicates if the token was retrieved from store (isNew = false).
        /// If the token was not retrieved from the store, the caller must persist the token to the store by calling
        /// SaveToken()
        /// </param>
        /// <returns></returns>
        protected override OAuth2Token CreateTokenInStore(string username, string consumerKey, string consumerSecret, out bool isNew)
        {
            try
            {
                isNew = false;
                TableOperation op = TableOperation.Retrieve<OAuth2TokenReference>(consumerKey, consumerSecret);
                TableResult result = table.Execute(op);

                OAuth2TokenReference token = result.Result as OAuth2TokenReference;

                if (token != null)
                {
                    if (GetToken(token.AccessToken) != null)
                    {
                        OAuth2AzureTokenData data = new OAuth2AzureTokenData(token.AccessToken, DateTime.UtcNow.AddMinutes(OAuth2Config.OAuth2TokenValidityMinutes));
                        data.ConsumerKey = consumerKey;
                        data.ConsumerSecret = consumerSecret;
                        return new OAuth2AzureToken(data, username);
                    }
                }

                isNew = true;
                string rtoken = Guid.NewGuid().ToString();
                string etoken = Convert.ToBase64String(Encoding.UTF8.GetBytes(rtoken));
                OAuth2AzureTokenData data2 = new OAuth2AzureTokenData(etoken, DateTime.UtcNow.AddMinutes(OAuth2Config.OAuth2TokenValidityMinutes));
                data2.ConsumerKey = consumerKey;
                data2.ConsumerSecret = consumerSecret;
                return new OAuth2AzureToken(data2, username);
            }
            catch (Exception ex)
            {
                Logger.Error("CreateToken Failed", ex);
                isNew = false;
                return null;
            }
        }