public virtual Credentials GetCredentials(AuthScope authscope)
        {
            Args.NotNull(authscope, "Auth scope");
            Credentials localcreds = @internal.GetCredentials(authscope);

            if (localcreds != null)
            {
                return(localcreds);
            }
            if (authscope.GetHost() != null)
            {
                PasswordAuthentication systemcreds = GetSystemCreds(authscope, Authenticator.RequestorType
                                                                    .Server);
                if (systemcreds == null)
                {
                    systemcreds = GetSystemCreds(authscope, Authenticator.RequestorType.Proxy);
                }
                if (systemcreds != null)
                {
                    return(new UsernamePasswordCredentials(systemcreds.GetUserName(), new string(systemcreds
                                                                                                 .GetPassword())));
                }
            }
            return(null);
        }
Пример #2
0
        private XmlDocument GetLoginResponse()
        {
            PasswordAuthentication authData = ServerLogin.AuthData;
            string rql = string.Format(RQL_IODATA,
                                       string.Format(RQL_LOGIN, HttpUtility.HtmlEncode(authData.Username),
                                                     HttpUtility.HtmlEncode(authData.Password)));

            //hide password in log messages
            string debugOutputRQL = string.Format(RQL_IODATA,
                                                  string.Format(RQL_LOGIN, HttpUtility.HtmlEncode(authData.Username),
                                                                "*****"));
            var xmlDoc = new XmlDocument();

            try
            {
                string result = SendRQLToServer(rql, debugOutputRQL);
                xmlDoc.LoadXml(result);
            } catch (RQLException e)
            {
                if (e.ErrorCode != ErrorCode.RDError101)
                {
                    throw e;
                }
                xmlDoc.LoadXml(e.Response);
            }
            return(xmlDoc);
        }
Пример #3
0
        static void Main(string[] args)
        {
            // RedDot Login with (user/password)
            var authData = new PasswordAuthentication("user", "password");

            var login = new ServerLogin()
            {
                Address = new Uri("http://localhost/cms"), AuthData = authData
            };

            // Session is the entry point to interact with the RedDot server.
            // Creating the session object automatically creates a connection.
            // Dispose() closes the connection in a a clean way (this is done
            // automatically at the end of the using block).
            using (var session = SessionBuilder.CreateOrReplaceOldestSession(login))
            {
                // Select a project based on the name
                var project = session.ServerManager.Projects.GetByName("MyProjekt");

                // Find all pages based on the Content Class "MyContentClass"
                var pageSearch = project.Pages.CreateSearch();
                pageSearch.ContentClass = project.ContentClasses.GetByName("MyContentClass");

                var pages = pageSearch.Execute();

                // Attach suffix ".php" to all filenames of the pages found
                foreach (var curPage in pages)
                {
                    curPage.Filename = curPage.Filename + ".php";

                    // Commit changes to the server
                    curPage.Commit();
                }
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            var url      = args[0];
            var user     = args[1];
            var password = args[2];

            var authData = new PasswordAuthentication(user, password);
            var login    = new ServerLogin()
            {
                Address = new Uri(url), AuthData = authData
            };

            using (var session = SessionBuilder.CreateOrReplaceOldestSession(login))
            {
                var project = session.ServerManager.Projects["nav_demo"];
                var search  = project.Pages.CreateSearch();
                search.PageType = PageType.Unlinked;
                var unlinkedPages = search.Execute();

                IEnumerable <IPage> processedPages = new List <IPage>();

                while (unlinkedPages.Any())
                {
                    foreach (var curPage in unlinkedPages)
                    {
                        Console.WriteLine("Deleting " + curPage);
                        //curPage.Delete();
                    }
                    processedPages = processedPages.Union(unlinkedPages);
                    unlinkedPages  = search.Execute().Where(page => !processedPages.Contains(page));
                }

                Console.WriteLine("Done");
            }
        }
        public PasswordTestWindow()
        {
            PAuth = new PasswordAuthentication(((App)Application.Current).ServerConnection);

            InitializeComponent();

            ShowSessionInfo();
        }
Пример #6
0
        private void ParseLoginResponse(XmlNodeList xmlNodes, PasswordAuthentication authData, XmlDocument xmlDoc,
                                        Func <IEnumerable <RunningSessionInfo>, RunningSessionInfo>
                                        sessionReplacementSelector)
        {
            // check if already logged in
            var    xmlNode      = (XmlElement)xmlNodes[0];
            string oldLoginGuid = CheckAlreadyLoggedIn(xmlNode);

            if (oldLoginGuid != "")
            {
                RunningSessionInfo sessionToReplace;
                if (sessionReplacementSelector == null ||
                    !TryGetSessionInfo(xmlDoc, sessionReplacementSelector, out sessionToReplace))
                {
                    throw new RedDotConnectionException(RedDotConnectionException.FailureTypes.AlreadyLoggedIn,
                                                        "User is already logged in and no open session was selected to get replaced");
                }
                xmlNode = GetForceLoginXmlNode(authData, sessionToReplace.LoginGuid);
                if (xmlNode == null)
                {
                    throw new RedDotConnectionException(RedDotConnectionException.FailureTypes.CouldNotLogin,
                                                        "Could not force login.");
                }
            }

            // here xmlNode has a valid login guid
            string loginGuid = xmlNode.GetAttributeValue("guid");

            if (string.IsNullOrEmpty(loginGuid))
            {
                throw new RedDotConnectionException(RedDotConnectionException.FailureTypes.CouldNotLogin,
                                                    "Could not login");
            }
            LogonGuid  = Guid.Parse(loginGuid);
            SessionKey = LogonGuid.ToRQLString();
            LoadSelectedProject(xmlNode.OwnerDocument);
            var    loginNode   = (XmlElement)xmlNodes[0];
            string userGuidStr = loginNode.GetAttributeValue("userguid");

            if (string.IsNullOrEmpty(userGuidStr))
            {
                XmlNodeList userNodes = xmlDoc.GetElementsByTagName("USER");
                if (userNodes.Count != 1)
                {
                    throw new RedDotConnectionException(RedDotConnectionException.FailureTypes.CouldNotLogin,
                                                        "Could not login; Invalid user data");
                }
                var xmlElement = ((XmlElement)userNodes[0]);
                ((Users)ServerManager.Users).Current = new User(this, xmlElement.GetGuid())
                {
                    Name = xmlElement.GetAttributeValue("name")
                };
            }
            else
            {
                ((Users)ServerManager.Users).Current = new User(this, Guid.Parse(loginNode.GetAttributeValue("userguid")));
            }
        }
 public async void TestAuthenticateFailure_EmptyPassword()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
     {
         Username = "******",
     };
     await AssertEx.ThrowsAsync<InvalidOperationException>(async () => await pAuth.Authenticate());
 }
 public async void TestAuthenticateFailure_EmptyPassword()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
     {
         Username = "******",
     };
     await AssertEx.ThrowsAsync <InvalidOperationException>(async() => await pAuth.Authenticate());
 }
 public async void TestLogOnSuccess_Username()
 {
     var authentication = new PasswordAuthentication(Generator.ServerConnection)
     {
         Username = Generator.Username,
         Password = Generator.Password
     };
     var userInfo = await authentication.Authenticate();
     ValidateUserInfo(userInfo);
 }
        public async void TestLogOnSuccess_Username()
        {
            var authentication = new PasswordAuthentication(Generator.ServerConnection)
            {
                Username = Generator.Username,
                Password = Generator.Password
            };
            var userInfo = await authentication.Authenticate();

            ValidateUserInfo(userInfo);
        }
Пример #11
0
    static void Main(string[] args)
    {
        var authData = new PasswordAuthentication("admin", "123456");
        var url      = "http://localhost/cms";

        var login = new ServerLogin(url, authData);

        using (var session = SessionBuilder.CreateOrReplaceOldestSession(login))
        {
            //this is the currently active project in the session
            var selectedProject = session.SelectedProject;

            var serverManager = session.ServerManager;

            //these are all projects, the active user is assigned to
            var currentUsersProjects = serverManager.Projects.ForCurrentUser;

            //these are all projects for the user xy, you need to be server manager to do this
            var user             = serverManager.Users["some username"];
            var projectsOfUserXy = serverManager.Projects.ForUser(user.Guid);

            //these are all projects on the server, you need to be server manager to access projects you are not assigned to
            var allProjects = serverManager.Projects;

            //you can access a single project by name
            //var myProject = serverManager.Projects.ForCurrentUser["myproject"];
            //this is the short for
            //var myProjectToo = serverManager.Projects.ForCurrentUser.GetByName("myproject");

            //if you do not know whether a specific project exists, you can use
            IProject unknownProject;
            if (serverManager.Projects.ForCurrentUser.TryGetByName("nav_demo", out unknownProject))
            {
                Console.WriteLine($"Found project with guid: {unknownProject.Guid}");
            }
            else
            {
                Console.WriteLine("No project with name myproject assigned to user");
            }

            //you can also get a project by guid
            var projectGuid   = new Guid("...");
            var projectByGuid = serverManager.Projects.ForCurrentUser.GetByGuid(projectGuid);
            // a TryGetByGuid method is available, too

            //print all project names and guids
            Console.WriteLine("Projects:");
            foreach (var curProject in serverManager.Projects)
            {
                Console.WriteLine(curProject);
            }
        }
    }
 public async void TestAuthenticateFailure_InvalidJson()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var expectedPostUri = new Uri("https://www.douban.com/service/auth2/token");
     serverConnectionMock.Setup(s => s.Post(It.Is<Uri>(u => u == expectedPostUri), It.Is<byte[]>(d => d.Length > 0))).ReturnsAsync("###").Verifiable();
     var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
     {
         Username = "******",
         Password = "******",
     };
     await AssertEx.ThrowsAsync<JsonReaderException>(async () => await pAuth.Authenticate());
     serverConnectionMock.Verify();
 }
 public async void TestAuthenticateFailure_Exception()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var expectedPostUri = new Uri("https://www.douban.com/service/auth2/token");
     serverConnectionMock.Setup(s => s.Post(It.Is<Uri>(u => u == expectedPostUri), It.Is<byte[]>(d => d.Length > 0))).ThrowsAsync(new Exception("Test message.")).Verifiable();
     var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
     {
         Username = "******",
         Password = "******",
     };
     var ex = await AssertEx.ThrowsAsync<Exception>(async () => await pAuth.Authenticate());
     Assert.AreEqual("Test message.", ex.Message);
     serverConnectionMock.Verify();
 }
Пример #14
0
        private XmlElement GetForceLoginXmlNode(PasswordAuthentication pa, Guid oldLoginGuid)
        {
            LOG.InfoFormat("User login will be forced. Old login guid was: {0}", oldLoginGuid.ToRQLString());
            //hide user password in log message
            string rql            = string.Format(RQL_IODATA, RQL_LOGIN_FORCE.RQLFormat(pa.Username, pa.Password, oldLoginGuid));
            string debugRQLOutput = string.Format(RQL_IODATA,
                                                  RQL_LOGIN_FORCE.RQLFormat(pa.Username, "*****", oldLoginGuid));
            string result = SendRQLToServer(rql, debugRQLOutput);
            var    xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(result);
            XmlNodeList xmlNodes = xmlDoc.GetElementsByTagName("LOGIN");

            return((XmlElement)(xmlNodes.Count > 0 ? xmlNodes[0] : null));
        }
        public async void TestAuthenticateFailure_InvalidJson()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var expectedPostUri      = new Uri("https://www.douban.com/service/auth2/token");

            serverConnectionMock.Setup(s => s.Post(It.Is <Uri>(u => u == expectedPostUri), It.Is <byte[]>(d => d.Length > 0))).ReturnsAsync("###").Verifiable();
            var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
            {
                Username = "******",
                Password = "******",
            };
            await AssertEx.ThrowsAsync <JsonReaderException>(async() => await pAuth.Authenticate());

            serverConnectionMock.Verify();
        }
Пример #16
0
 public UserDTO AuthenticateUser(string username, string password)
 {
     if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
     {
         User User = DataContext.Users.FirstOrDefault(x => x.UserName == username);
         if (User != null)
         {
             if (PasswordAuthentication.VerifyPasswordHash(password, User.PasswordHash, User.PasswordSalt))      // check if password is correct
             {
                 return(UserMapper.MapToDTO(User));
             }
         }
     }
     return(null);
 }
Пример #17
0
        public void Insert(UserDTO UserDTO)
        {
            if (UserDTO != null)
            {
                User User = UserMapper.MapToDbEntity(UserDTO);
                #region Add Password Hash
                byte[] passwordHash, passwordSalt;
                PasswordAuthentication.CreatePasswordHash(UserDTO.Password, out passwordHash, out passwordSalt);
                User.PasswordHash = passwordHash;
                User.PasswordSalt = passwordSalt;
                #endregion

                DataContext.Add(User);
                DataContext.SaveChanges();
            }
        }//Regist
        public async void TestAuthenticateFailure_Exception()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var expectedPostUri      = new Uri("https://www.douban.com/service/auth2/token");

            serverConnectionMock.Setup(s => s.Post(It.Is <Uri>(u => u == expectedPostUri), It.Is <byte[]>(d => d.Length > 0))).ThrowsAsync(new Exception("Test message.")).Verifiable();
            var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
            {
                Username = "******",
                Password = "******",
            };
            var ex = await AssertEx.ThrowsAsync <Exception>(async() => await pAuth.Authenticate());

            Assert.AreEqual("Test message.", ex.Message);
            serverConnectionMock.Verify();
        }
Пример #19
0
        async Task <bool> PasswordMatches(string password, PasswordAuthentication auth)
        {
            var data = StoredPassword.Deserialize(auth.EncodedStoredPassword);

            var passwordBytes = password.ToBytes();

            var hash = await hasher.Hash(passwordBytes, data.Salt, data.Options);

            if (!data.Hash.ArrayEquals(hash))
            {
                return(false);
            }

            // TODO automatically upgrade algorithm here if it's outdated

            return(true);
        }
 public async void TestAuthenticateSuccess()
 {
     var serverConnectionMock = CreateServerConnectionMockWithContext();
     var expectedPostUri = new Uri("https://www.douban.com/service/auth2/token");
     serverConnectionMock.Setup(s => s.Post(It.Is<Uri>(u => u == expectedPostUri), It.Is<byte[]>(d => d.Length > 0))).ReturnsAsync(Resource.TestOAuthResponse).Verifiable();
     var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
     {
         Username = "******",
         Password = "******",
     };
     var result = await pAuth.Authenticate();
     Assert.IsNotNull(result);
     Assert.IsNotNull(result.AccessToken);
     Assert.IsNotNull(result.RefreshToken);
     Assert.IsNotNull(result.Username);
     Assert.AreNotEqual(0, result.UserId);
     Assert.AreNotEqual(0, result.ExpiresIn);
     serverConnectionMock.Verify();
 }
Пример #21
0
        }//Regist

        public void Update(UserDTO UserDTO)
        {
            User User = DataContext.Users.Find(UserDTO.Id);

            if (User != null)
            {
                User.LastName  = UserDTO.LastName;
                User.FirstName = UserDTO.FirstName;
                User.UserName  = UserDTO.UserName;
                #region Add Password Hash
                byte[] passwordHash, passwordSalt;
                PasswordAuthentication.CreatePasswordHash(UserDTO.Password, out passwordHash, out passwordSalt);
                User.PasswordHash = passwordHash;
                User.PasswordSalt = passwordSalt;
                #endregion

                DataContext.Users.Update(User);
                DataContext.SaveChanges();
            }
        }
Пример #22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var authData = new PasswordAuthentication("", "");
        var url = "";
        var login = new ServerLogin(url, authData);
        using (var session = SessionBuilder.CreateOrReplaceOldestSession(login))
        {

            var selectedProject = session.SelectedProject;
            var serverManager = session.ServerManager;

            var languageVariant = selectedProject.LanguageVariants.Current;
            var pageGuid = new Guid("");
            var elementGuid = new Guid("");

            var getElement = (ITextHtml)erminas.SmartAPI.CMS.Project.Pages.Elements.PageElementFactory.Instance.CreateElement(selectedProject, elementGuid, languageVariant);
            getElement.Value = "<p>my new text</p>";
            getElement.Commit();

    }
}
Пример #23
0
        //获取一个可用的SFTPClient
        private SFTPClient GetAvailableSFTP()
        {
            //关闭之前的
            Close();

            SSHConnector con = SSHConnector.Create();

            ssh = con.Connect(new TcpClientTransport(ipAddress, 22), loginUser, true);

            PasswordAuthentication pwd = new PasswordAuthentication();

            pwd.Password = loginPass;

            // Authenticate the user
            if (ssh.Authenticate(pwd) == AuthenticationResult.COMPLETE)
            {
                // Open up a session and do something..
                sftp = new SFTPClient(ssh);
            }
            return(sftp);
        }
        public async void TestAuthenticateSuccess()
        {
            var serverConnectionMock = CreateServerConnectionMockWithContext();
            var expectedPostUri      = new Uri("https://www.douban.com/service/auth2/token");

            serverConnectionMock.Setup(s => s.Post(It.Is <Uri>(u => u == expectedPostUri), It.Is <byte[]>(d => d.Length > 0))).ReturnsAsync(Resource.TestOAuthResponse).Verifiable();
            var pAuth = new PasswordAuthentication(serverConnectionMock.Object)
            {
                Username = "******",
                Password = "******",
            };
            var result = await pAuth.Authenticate();

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.AccessToken);
            Assert.IsNotNull(result.RefreshToken);
            Assert.IsNotNull(result.Username);
            Assert.AreNotEqual(0, result.UserId);
            Assert.AreNotEqual(0, result.ExpiresIn);
            serverConnectionMock.Verify();
        }
Пример #25
0
        public async Task <IActionResult> Register(Guid identityId, [FromBody] PasswordRegisterRequest req)
        {
            var hash = await HashPassword(req.Password);

            var auth = new PasswordAuthentication
            {
                Id                    = Guid.NewGuid(),
                CreatedAt             = DateTime.UtcNow,
                EncodedStoredPassword = hash.Serialize(),
                IdentityId            = identityId,
            };

            await DisableRegistration(identityId);

            await ctx.PasswordAuthentications.AddAsync(auth);

            await ctx.SaveChangesAsync();

            return(Ok(new AuthenticationResponse {
                IdentityId = identityId
            }));
        }
Пример #26
0
        private static void EncryptDecryptPassword()
        {
            Console.WriteLine("---- Encrypt password ----");
            Console.WriteLine();

            Console.WriteLine("Please enter a password to use:");
            string password = Console.ReadLine();

            string salt = PasswordAuthentication.GenerateSalt();

            string hash = PasswordAuthentication.GenerateHash(salt, password);

            Console.WriteLine("Your encrypted password : {0}", hash);

            Console.WriteLine();
            Console.WriteLine("---- Decrypt password ----");
            Console.WriteLine();

            Console.WriteLine("Please enter your password:"******"New password hash: {0}", newHash));

            bool passwordsMatch = PasswordAuthentication.CompareHashes(hash, newHash);

            if (passwordsMatch)
            {
                Console.WriteLine("Given password matches the original.");
            }
            else
            {
                Console.WriteLine("Given password does not match the original.");
            }

            Console.ReadKey();
        }
Пример #27
0
        protected sealed override PasswordAuthentication GetPasswordAuthentication()
        {
            string host = GetRequestingHost();
            int    port = GetRequestingPort();

            foreach (CachedAuthenticator.CachedAuthentication ca in cached)
            {
                if (ca.host.Equals(host) && ca.port == port)
                {
                    return(ca.ToPasswordAuthentication());
                }
            }
            PasswordAuthentication pa = PromptPasswordAuthentication();

            if (pa != null)
            {
                CachedAuthenticator.CachedAuthentication ca_1 = new CachedAuthenticator.CachedAuthentication
                                                                    (host, port, pa.GetUserName(), new string(pa.GetPassword()));
                Add(ca_1);
                return(ca_1.ToPasswordAuthentication());
            }
            return(null);
        }
        ///
        /// Handle server authentication challenge request,
        /// Popup a login window for username/password
        ///
        public PasswordAuthentication AuthenticationHandler()
        {
            PasswordAuthentication credentials = null;
            LoginDemoForm loginForm = new LoginDemoForm();
            AutoResetEvent userInputCompleted = new AutoResetEvent(false);

            //
            //Popup login window on new Task. Note: please use Task to do parallel jobs
            //
            Task t = Task.Factory.StartNew(() =>
            {
                if (loginForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    credentials = new PasswordAuthentication(loginForm.Username, loginForm.Password.ToCharArray());
                }
                userInputCompleted.Set();
            });

            // wait user click 'OK' or 'Cancel' on login window
            userInputCompleted.WaitOne();
            return credentials;
        }
Пример #29
0
 public KBIRequestHandlerWhenUserUsingPasswordAuthentication(PasswordAuthentication pwdAuth)
 {
     password = pwdAuth.Password;
 }
Пример #30
0
        /// <summary>
        /// Prompt for user credentials and then call the Bing Ads Customer Management service
        /// with the current authenticated Microsoft account user.
        /// </summary>
        private async void AuthenticateUser()
        {
            try
            {
                Authentication authentication;

                if (OAuthCheckBox.IsChecked == true)
                {
                    authentication = await OAuthHelper.AuthorizeDesktopMobileAuthCodeGrant();

                    var authenticationToken =
                        ((OAuthDesktopMobileAuthCodeGrant)(authentication)).OAuthTokens.AccessToken;
                }
                else
                {
                    authentication = new PasswordAuthentication(UserNameTextBox.Text,
                                                                UserNamePasswordBox.Password);
                }

                ClearUserData();

                // Get user's CustomerId and AccountId

                _authorizationData = new AuthorizationData
                {
                    Authentication = authentication,
                    DeveloperToken =
                        (SandboxCheckBox.IsChecked == false)
                            ? Settings.Default["DeveloperToken"].ToString()
                            : Settings.Default["DeveloperTokenSandbox"].ToString()
                };

                _customerService = new ServiceClient <ICustomerManagementService>(_authorizationData);

                var user = await GetUserAsync(null);

                UserNameTextBox.Text = user.UserName;

                // Search for the accounts that matches the specified criteria.

                var accounts = await SearchAccountsByUserIdAsync(user.Id);

                // Store the parent customer identifier in the second dimension of the array.

                _accountCustomerIds = new long?[accounts.Length, 2];

                for (var i = 0; i < accounts.Length; i++)
                {
                    AccountIdsComboBox.Items.Add(accounts[i].Id);
                    _accountCustomerIds[i, 0] = accounts[i].Id;
                    _accountCustomerIds[i, 1] = accounts[i].ParentCustomerId;
                }

                AccountIdsComboBox.SelectedIndex = 0;
                SetUserDataByAccountIndex(AccountIdsComboBox.SelectedIndex);

                if (accounts.Length > 0)
                {
                    RunButton.IsEnabled = true;
                }
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}",
                                                  ex.Details.Error, ex.Details.Description));
            }
            // Catch Customer Management service exceptions
            catch (FaultException <Microsoft.BingAds.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error =>
                {
                    if ((error.Code == 105) || (error.Code == 106))
                    {
                        return("Authorization data is missing or incomplete for the specified environment.\n" +
                               "To run the examples switch users or contact support for help with the following error.\n");
                    }
                    return(string.Format("{0}: {1}", error.Code, error.Message));
                })));
                OutputStatusMessage(string.Join("; ",
                                                ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ",
                                                ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (HttpRequestException ex)
            {
                OutputStatusMessage(ex.Message);
            }
            finally
            {
                SwitchUserButton.IsEnabled = true;
            }
        }
 public  PasswordAuthentication AuthenticationHandler()
 {
     PasswordAuthentication credentials = null;
     try {
         _userInputCompleted.Reset();
         Device.BeginInvokeOnMainThread(() => {
             _demoPage.Navigation.PushModalAsync(new KaazingDemoLoginPage(this));
         });
         _userInputCompleted.WaitOne();
         credentials = new PasswordAuthentication(_username, _password.ToCharArray());
     } catch(Exception ex) {
         _demoPage.Log(ex.Message);
     }
     return credentials;
 }