Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo)
        {
            this.msAccountStatus = MSAccountStatus.Connected;
            return Task.Factory.StartNew(() =>
            {
                using (UsersContext db = new UsersContext())
                {
                    MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
                    if (msAccount != null)
                    {
                        if (tokenInfo.UserId != msAccount.MSUserId)
                        {
                            throw new LiveAuthException("invalid_user", "The account Id from the ticket does not match the current connected user.");
                        }

                        msAccount.RefreshToken = tokenInfo.RefreshToken;
                        db.Entry(msAccount).State = System.Data.EntityState.Modified;
                    }
                    else
                    {
                        // Insert name into the profile table
                        db.MSAccounts.Add(new MSAccount
                        {
                            MSUserId = tokenInfo.UserId,
                            RefreshToken = tokenInfo.RefreshToken,
                            UserName = this.User.Identity.Name
                        });
                    }

                    db.SaveChanges();
                }
            });
        }
        public ActionResult DisconnectMicrosoft()
        {
            if (this.MSAccountStatus != Controllers.MSAccountStatus.NotConnected)
            {
                // Remove the account association
                using (UsersContext db = new UsersContext())
                {
                    MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
                    if (msAccount != null)
                    {
                        db.MSAccounts.Remove(msAccount);
                        db.SaveChanges();
                    }
                }

                this.msAccountStatus = MSAccountStatus.NotConnected;
            }

            this.MSAuthClient.ClearSession(this.HttpContext);

            this.Response.Redirect(this.SiteRootPath + "account/connectmicrosoft");
            return null;
        }