/// <summary>
 /// Get OAuth response access token validating expiration date.
 /// </summary>
 private static string GetAccessToken(OAuthResponse authorization)
 {
     // Validate access token expiration date
     if (DateTime.Now.CompareTo(authorization.ExpirationDate) < 0)
     {
         return(authorization.AccessToken);
     }
     else
     {
         throw new RESTAPIException(400, "", "Session expired", "Access token timed out");
     }
 }
 /// <summary>
 /// Browser navigation event.
 /// </summary>
 private void loginBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
 {
     try
     {
         string accessToken = GetAccessTokenFromUrl("access_token", e.Url.ToString());
         // If navigation url includes an access token, this is our page!
         if (accessToken != "")
         {
             DateTime      expirationDate = DateTime.Now.AddSeconds(Convert.ToInt32(GetAccessTokenFromUrl("expires_in", e.Url.ToString())));
             Int32         userId         = Convert.ToInt32(GetAccessTokenFromUrl("user_id", e.Url.ToString()));
             OAuthResponse response       = new OAuthResponse(accessToken, expirationDate, userId, "");
             FirstForm.MainForm_LoginReady(response);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: " + ex.Message + "___" + ex.StackTrace);
     }
 }
 /// <summary>
 /// Browser navigation event. 
 /// </summary>
 private void loginBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
 {
     try
     {
         string accessToken = GetAccessTokenFromUrl("access_token", e.Url.ToString());
         // If navigation url includes an access token, this is our page!
         if (accessToken != "")
         {
             DateTime expirationDate = DateTime.Now.AddSeconds(Convert.ToInt32(GetAccessTokenFromUrl("expires_in", e.Url.ToString())));
             Int32 userId = Convert.ToInt32(GetAccessTokenFromUrl("user_id", e.Url.ToString()));
             OAuthResponse response = new OAuthResponse(accessToken, expirationDate, userId, "");
             FirstForm.MainForm_LoginReady(response);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: " + ex.Message + "___" + ex.StackTrace);
     }
 }
        /// <summary>
        /// Recursively tries to get a movements page from the MP API.
        /// </summary>
        public static SearchPage <Movement> GetMovementsPage(Int32 offset, Int32 limit, OAuthResponse authorization, DateTime dateFrom, DateTime dateTo, int retryNumber = 0)
        {
            AccountsHelper ah = new AccountsHelper();

            // Set access token
            ah.AccessToken = GetAccessToken(authorization);

            // Prepare API call arguments
            List <KeyValuePair <string, string> > args = new List <KeyValuePair <string, string> >();

            if (authorization.IsAdmin)
            {
                args.Add(new KeyValuePair <string, string>("user_id", authorization.UserId.ToString()));
            }
            // Try optimize the query by site id, taking advantage of the search sharding
            if (authorization.SiteId != null)
            {
                args.Add(new KeyValuePair <string, string>("site_id", authorization.SiteId));
            }
            args.Add(new KeyValuePair <string, string>("sort", "date_created"));
            args.Add(new KeyValuePair <string, string>("criteria", "desc"));
            args.Add(new KeyValuePair <string, string>("offset", offset.ToString()));
            args.Add(new KeyValuePair <string, string>("limit", limit.ToString()));
            args.Add(new KeyValuePair <string, string>("range", "date_created"));
            args.Add(new KeyValuePair <string, string>("begin_date", HttpUtility.UrlEncode(dateFrom.GetDateTimeFormats('s')[0].ToString() + ".000Z")));
            args.Add(new KeyValuePair <string, string>("end_date", HttpUtility.UrlEncode(dateTo.GetDateTimeFormats('s')[0].ToString() + ".000Z")));

            // Call API
            SearchPage <Movement> searchPage = null;

            try
            {
                searchPage = ah.SearchMovements(args);
            }
            catch (RESTAPIException raex)
            {
                // Retries the same call until max is reached
                if (retryNumber <= MAX_RETRIES)
                {
                    LogHelper.WriteLine("SearchMovements breaks. Retry num: " + retryNumber.ToString());
                    BackendHelper.GetMovementsPage(offset, limit, authorization, dateFrom, dateTo, retryNumber + 1);
                }
                else
                {
                    // then breaks
                    throw raex;
                }
            }

            if (searchPage != null)
            {
                return(searchPage);
            }
            else
            {
                LogHelper.WriteLine("null");
                return(null);
            }
        }
        /// <summary>
        /// Receives admin login event and inits authorization vars.
        /// </summary>
        public void MainForm_AdminLoginReady(string adminToken, int userId)
        {
            try
            {
                // Set app authorization
                _authorization = new OAuthResponse(adminToken, DateTime.Now.AddHours(18), userId, null, true);

                // Get user info and set salute label text
                UsersHelper uh = new UsersHelper();
                uh.AccessToken = _authorization.AccessToken;
                User user = uh.GetUser(userId);
                if ((user.FirstName == null) && (user.LastName == null))
                {
                    saluteLabel.Text = "Hi Admin, you're now an alias of " + user.Nickname;
                }
                else
                {
                    saluteLabel.Text = "Hi Admin, you're now an alias of " + user.FirstName + " " + user.LastName + " (" + user.Email + ")";
                }

                // Set authorization site id
                _authorization.SiteId = user.SiteId;

                // Hide admin form and enable main form buttons
                _adminForm.Hide();
                EnableLoginControls();
            }
            catch
            {
                MessageBox.Show("Login failure: Please try again");
            }
        }
        /// <summary>
        /// Receives logout event and resets authorization vars.
        /// </summary>
        public void MainForm_LogoutReady()
        {
            // Reset authorization, form controls and values
            saluteLabel.Text = "";
            DisableLoginControls();
            _authorization = null;

            StopLoading();
        }
        /// <summary>
        /// Receives login event and inits authorization vars.
        /// </summary>
        public void MainForm_LoginReady(OAuthResponse response)
        {
            try
            {
                // Set app authorization
                _authorization = response;

                // Get user info and set salute label text
                UsersHelper uh = new UsersHelper();
                uh.AccessToken = _authorization.AccessToken;
                User user = uh.GetUser(response.UserId);
                saluteLabel.Text = "Hi, " + user.FirstName + " " + user.LastName + " (" + user.Email + ")";

                // Set authorization site id
                _authorization.SiteId = user.SiteId;

                // Hide login form and enable main form buttons
                _loginForm.Hide();
                EnableLoginControls();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Login failure: " + ex.Message);
            }
        }