/// <summary>
        /// Renew the OAuth tokens
        /// </summary>
        /// <param name="request"></param>
        /// <param name="oAuthResponse">The current OAuth response object</param>
        /// <param name="onComplete">The action to call when the new tokens have been retrieved</param>
        /// <param name="onError">The action to call on an error</param>
        public void RenewOAuthTokens(WebRequest request, OAuthTokens oAuthResponse, Action<HttpStatusCode, OAuthTokens> onComplete, Action<Uri, Exception> onError)
        {
            var data = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token",
                                        _configuration.ClientId, _configuration.ClientSecret, oAuthResponse.RefreshToken);

            BeginRequest(request, (statusCode, s, response) => onComplete(statusCode, response), onError, data);
        }
Example #2
0
        public OAuthTokens RenewTokens(OAuthTokens oauthTokens)
        {
            var wait = new ManualResetEvent(false);
            OAuthTokens newTokens = null;
            Exception ex = null;
            var requestUri = default(Uri);

            RenewTokens(
                oauthTokens,
                (statusCode, tokens) =>
                    {
                        newTokens = tokens;
                        wait.Set();
                    },
                (uri, exception) =>
                    {
                        requestUri = uri;
                        ex = exception;
                        wait.Set();
                    });

            if (wait.WaitOne(new TimeSpan(0, 0, 0, 60)))
            {
                ex.ProcessException(requestUri);
            }

            return newTokens;
        }
 public ApiStreamRequestHandler(IApiConfiguration configuration, ICompanyFileCredentials credentials, OAuthTokens oauth = null)
 {
     _oauth = oauth;
     _configuration = configuration;
     _credentials = credentials;
     _helper = new ApiRequestHelper();
 }
 public void SetStandardHeaders(WebRequest request, IApiConfiguration configuration, ICompanyFileCredentials credentials, OAuthTokens oauth = null)
 {
     request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", oauth.Maybe(_ => _.AccessToken, string.Empty));
     request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
     request.Headers["x-myobapi-key"] = configuration.ClientId;
     request.Headers["x-myobapi-version"] = "v2";
     request.Headers["x-myobapi-cftoken"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", 
         credentials.Maybe(_ => _.Username).Maybe(_ => _, string.Empty), credentials.Maybe(_ => _.Password).Maybe(_ => _, string.Empty))));
 }
 /// <summary>
 /// Renew the OAuth tokens required to access the cloud based API (Synchronous)
 /// </summary>
 /// <param name="oauthTokens">The tokens that are required to access the user's company files</param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 async public Task<OAuthTokens> RenewTokensAsync(OAuthTokens oauthTokens, CancellationToken cancellationToken)
 {
     var handler = new OAuthRequestHandler(_configuration);
     var request = this.Factory.Create(OAuthRequestHandler.OAuthRequestUri);
     var tokens = await handler.RenewOAuthTokensAsync(request, oauthTokens, cancellationToken);
     return tokens.Item2;
 } 
 /// <summary>
 /// Renew the OAuth tokens required to access the cloud based API (Synchronous)
 /// </summary>
 /// <param name="oauthTokens">The tokens that are required to access the user's company files</param>
 /// <returns></returns>
 public Task<OAuthTokens> RenewTokensAsync(OAuthTokens oauthTokens)
 {
     return this.RenewTokensAsync(oauthTokens, CancellationToken.None);
 } 
 /// <summary>
 /// Renew the OAuth tokens required to access the cloud based API (Delegate)
 /// </summary>
 /// <param name="oauthTokens">The tokens that are required to access the user's company files</param>
 /// <param name="onComplete">The action to call when the operation is complete</param>
 /// <param name="onError">The action to call when the operation has an error</param>
 public void RenewTokens(OAuthTokens oauthTokens, Action<HttpStatusCode, OAuthTokens> onComplete, Action<Uri, Exception> onError)
 {
     var handler = new OAuthRequestHandler(_configuration);
     var request = this.Factory.Create(OAuthRequestHandler.OAuthRequestUri);
     handler.RenewOAuthTokens(request, oauthTokens, onComplete, onError);
 }
        /// <summary>
        /// Method to read Tokens from Isolated storage
        /// </summary>
        /// <remarks></remarks>
        private void ReadFromFile()
        {
            try
            {
                // Get an isolated store for user and application
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(
                    IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);

                var isoStream = new IsolatedStorageFileStream(CsTokensFile, FileMode.Open,
                                                              FileAccess.Read, FileShare.Read);

                var reader = new StreamReader(isoStream);
                // Read the data.

                _tokens = JsonConvert.DeserializeObject<OAuthTokens>(reader.ReadToEnd());
                reader.Close();

                isoStore.Dispose();
                isoStore.Close();
            }
            catch (FileNotFoundException)
            {
                // Expected exception if a file cannot be found. This indicates that we have a new user.
                _tokens = null;
            }
        }
        /// <summary>
        /// Set common headers on the request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="configuration"></param>
        /// <param name="credentials"></param>
        /// <param name="oauth"></param>
        public void SetStandardHeaders(WebRequest request, IApiConfiguration configuration, 
            ICompanyFileCredentials credentials, OAuthTokens oauth = null)
        {
            if (oauth != null)
            {
                request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}",
                    oauth.AccessToken.Maybe(_ => _, string.Empty));
            }
#if !PORTABLE
            if ((request as HttpWebRequest).Maybe(_ => _.ClientCertificates.Maybe(c => c.Count != 0)))
            {
                request.Headers.Remove(HttpRequestHeader.Authorization);
            }
#endif
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
            
            IgnoreError(() =>
                {
#if PORTABLE
                    request.Headers[HttpRequestHeader.UserAgent] = UserAgent;
#else
                    try
                    {
                        var webRequest = request as HttpWebRequest;
                        if (webRequest != null)
                            webRequest.UserAgent = UserAgent;
                    }
                    catch (Exception)
                    {
                        request.Headers[HttpRequestHeader.UserAgent] = UserAgent;
                    }
#endif
                });

            request.Headers["x-myobapi-key"] = configuration.ClientId;
            request.Headers["x-myobapi-version"] = "v2";

            if (credentials != null)
            {
                request.Headers["x-myobapi-cftoken"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}",
                    credentials.Username.Maybe(_ => _, string.Empty), credentials.Password.Maybe(_ => _, string.Empty))));
            }
        }