public void Logout(bool unlockOnLogout, bool async)
 {
   Process(new Command("<logoff skip_unlock=\"" + (unlockOnLogout ? 0 : 1) + "\"/>").WithAction(CommandAction.LogOff), async)
     .Done(r =>
     {
       _database = null;
       _factory = null;
       _renewalToken = null;
       _sessionToken = null;
       _userId = null;
       _timer.Enabled = false;
       _writeVault = null;
     });
 }
    public IPromise<string> Login(ICredentials credentials, bool async)
    {
      var result = new Promise<string>();

      _lastCredentials = credentials;
      var database = string.Empty;
      var tokenCred = credentials as TokenCredentials;
      IPromise<IHttpResponse> loginPromise;

      if (tokenCred != null)
      {
        database = tokenCred.Database;
        loginPromise = PolicyToken(PolicyTokenType.connection, null, null, true)
          .Continue(p =>
          {
            return RenewSession(tokenCred.Content, p, true);
          });
      }
      else
      {
        var tokenPromise = (_lastLoginToken == null
                        || _lastLoginToken.Expiration > DateTime.UtcNow.AddSeconds(-5)) ?
        Query(null, null, null, this.SessionPolicy, null, async)
          .Convert<IHttpResponse, InitializeSessionToken>((r, p) =>
          {
            p.Reject(new Exception("Unauthorized error expected"));
          }, (ex, p) =>
          {
            var httpEx = ex as HttpException;
            if (httpEx != null
              && httpEx.Response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
              var header = AuthenticationScheme.Parse(httpEx.Response.Headers["WWW-Authenticate"]);
              var auth = header.FirstOrDefault(a => a.Name == "bearer");
              if (auth == null) throw new InvalidOperationException();
              var ssoAuth = header.FirstOrDefault(a => a.Name == "winsso");

              _lastLoginToken = new InitializeSessionToken(auth.Parameters["token"]
                                      , auth.Parameters["nonce"], auth.Parameters["public_key"]);
              _lastLoginToken.SsoUrl = ssoAuth.Parameters["uri"];
              p.Resolve(_lastLoginToken);
            }
            else
            {
              p.Reject(ex);
            }
          }) :
        Promises.Resolved(_lastLoginToken);

      loginPromise = Promises.All(tokenPromise
                              , PolicyToken(PolicyTokenType.connection, null, null, async))
        .Continue(r =>
        {
          var winCred = credentials as WindowsCredentials;
          if (winCred == null)
          {
            SecureToken password = null;
            var username = string.Empty;

            var explicitCred = credentials as ExplicitCredentials;
            if (explicitCred != null)
            {
              database = explicitCred.Database;
              password = explicitCred.Password;
              username = explicitCred.Username;
            }
            else
            {
              var anon = credentials as AnonymousCredentials;
              if (anon != null)
              {
                database = anon.Database;
              }
              else
              {
                throw new ArgumentException(string.Format("Login credentials must be one of the built-in types, {0} is not supported"
                  , credentials == null, "NULL", credentials.GetType()), "credentials");
              }
            }

            string encodedData;
            var usernameLength = (username == null ? 0 : username.Length);
            var passwordLength = (password == null ? 0 : password.Length);
            var buffer = new byte[3 + 2 * (r.Result1.Nonce.Length + database.Length
                                            + usernameLength + passwordLength)];
            try
            {
              var i = Encoding.UTF8.GetBytes(r.Result1.Nonce, 0, r.Result1.Nonce.Length, buffer, 0);
              buffer[i++] = (byte)'|';
              i += Encoding.UTF8.GetBytes(database, 0, database.Length, buffer, i);
              buffer[i++] = (byte)'|';
              if (usernameLength > 0)
                i += Encoding.UTF8.GetBytes(username, 0, username.Length, buffer, i);
              buffer[i++] = (byte)'|';
              if (passwordLength > 0) password.UseBytes<bool>((ref byte[] b) =>
              {
                for (var j = 0; j < b.Length; j++)
                {
                  buffer[j + i] = b[j];
                }
                i += b.Length;
                return false;
              });

              encodedData = Convert.ToBase64String(r.Result1.Encryptor.Encrypt(buffer, 0, i));
            }
            finally
            {
              for (var j = 0; j < buffer.Length; j++)
              {
                buffer[j] = 0;
              }
            }
            return Query(r.Result1.Content + " " + encodedData, "ValidateUser", "<Item/>"
              , this.SessionPolicy , r.Result2, async);
          }
          else
          {
            // Windows authentication
            return Query(r.Result1.SsoUrl, r.Result1.Content, "ValidateUser", "<Item/>"
              , this.SessionPolicy, r.Result2, winCred.Credentials, async
              , req => req.SetHeader("DATABASE", winCred.Database));
          }
        });
      }

      loginPromise.Progress((p, m) => result.Notify(p, m))
        .Done(r => {
          _database = database;

          var data = r.AsXml().DescendantsAndSelf("Result").FirstOrDefault();
          _userId = data.Element("id").Value;

          var auth = data.Element("Authorization");
          _renewalToken = new TokenCredentials(auth.Element("refresh_token").Value);
          _renewalToken.Database = database;
          SetSessionToken(auth.Element("access_token").Value
            , int.Parse(auth.Element("expires_in").Value));

          var i18n = data.Element("i18nsessioncontext");
          var context = new ServerContext();
          context.DefaultLanguageCode = i18n.Element("default_language_code").Value;
          context.DefaultLanguageSuffix = i18n.Element("default_language_suffix").Value;
          context.LanguageCode = i18n.Element("language_code").Value;
          context.LanguageSuffix = i18n.Element("language_suffix").Value;
          context.Locale = i18n.Element("locale").Value;
          context.TimeZone = i18n.Element("time_zone").Value;
          _factory = new ElementFactory(context);

          var upload = data.Element("WriteVault") == null
            ? null : data.Element("WriteVault").Element("Item");
          if (upload == null)
          {
            var strategy = new DefaultVaultStrategy();
            strategy.Initialize(this);
            _writeVault = strategy.WritePriority(true).Convert(v => v.First());
          }
          else
          {
            _writeVault = Promises.Resolved(Vault.GetVault(
              (IReadOnlyItem)_factory.FromXml(upload.ToString())));
          }

          result.Resolve(_userId);
        }).Fail(ex => {
          var httpEx = ex as HttpException;
          if (httpEx != null
            && httpEx.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
          {
            var auth = AuthenticationScheme.Parse(httpEx.Response.Headers["WWW-Authenticate"])
              .FirstOrDefault(a => a.Name == "bearer");
            string msg;
            if (auth != null && auth.Parameters.TryGetValue("error_description", out msg))
            {
              result.Reject(new Exception("Error logging in: " + msg));
            }
            else
            {
              result.Reject(new Exception("Unanticipated error logging in."));
            }
          }
          else
          {
            result.Reject(ex);
          }
        });
      result.CancelTarget(loginPromise);

      return result;
    }