public void GetClient_InitializeDefaults()
        {
            var appId = "appId";

            var client = BusinessClientExtensions.GetClientInternal(
                new BusinessAppConfig
            {
                ActiveDirectoryAppId = appId,
            },
                serviceInfoProvider: null,
                credentialCache: null,
                httpProvider: null) as OneDriveClient;

            var adalAppConfig = client.appConfig as BusinessAppConfig;

            Assert.IsNotNull(adalAppConfig, "Unexpected app configuration initialized.");

            Assert.IsNotNull(client.credentialCache, "Credential cache not initialized.");
            Assert.IsInstanceOfType(client.credentialCache, typeof(AdalCredentialCache), "Unexpected credential cache initialized.");

            Assert.IsNotNull(client.HttpProvider, "HTTP provider not initialized.");
            Assert.IsInstanceOfType(client.HttpProvider, typeof(HttpProvider), "Unexpected HTTP provider initialized.");

            Assert.IsNotNull(client.serviceInfoProvider, "Service info provider not initialized.");
            Assert.IsInstanceOfType(client.serviceInfoProvider, typeof(AdalServiceInfoProvider), "Unexpected service info provider initialized.");

            Assert.AreEqual(ClientType.Business, client.ClientType, "Unexpected client type set.");
        }
        private async void InitializeClient(ClientType clientType, RoutedEventArgs e)
        {
            if (((App)Application.Current).OneDriveClient == null)
            {
                var client = clientType == ClientType.Consumer
                    ? OneDriveClientExtensions.GetUniversalClient(this.scopes) as OneDriveClient
                    : BusinessClientExtensions.GetActiveDirectoryClient(
                    oneDriveForBusinessAppId,
                    oneDriveForBusinessReturnUrl) as OneDriveClient;

                try
                {
                    await client.AuthenticateAsync();

                    ((App)Application.Current).OneDriveClient = client;
                    ((App)Application.Current).NavigationStack.Add(new ItemModel(new Item()));
                    Frame.Navigate(typeof(MainPage), e);
                }
                catch (OneDriveException exception)
                {
                    // Swallow the auth exception but write message for debugging.
                    Debug.WriteLine(exception.Error.Message);
                    client.Dispose();
                }
            }
            else
            {
                Frame.Navigate(typeof(MainPage), e);
            }
        }
        public void GetWebClientUsingAppOnlyAuthentication()
        {
            var appId  = "appId";
            var tenant = "tenant";

            var clientCertificate = new X509Certificate2(@"Certs\testwebapplication.pfx", "password");

            var client = BusinessClientExtensions.GetWebClientUsingAppOnlyAuthentication(
                new BusinessAppConfig
            {
                ActiveDirectoryAppId             = appId,
                ActiveDirectoryClientCertificate = clientCertificate,
                ActiveDirectoryServiceResource   = serviceResourceId,
            },
                serviceResourceId,
                tenant,
                this.credentialCache.Object,
                this.httpProvider.Object) as OneDriveClient;

            Assert.AreEqual(
                string.Format(
                    Constants.Authentication.OneDriveBusinessBaseUrlFormatString,
                    serviceResourceId.TrimEnd('/'),
                    "v2.0"),
                client.appConfig.ActiveDirectoryServiceEndpointUrl,
                "Unexpected service endpoint URL initialized for app config.");

            Assert.AreEqual(
                string.Format(Constants.Authentication.ActiveDirectoryAuthenticationServiceUrlFormatString, tenant),
                client.appConfig.ActiveDirectoryAuthenticationServiceUrl,
                "Unexpected authentication service URL.");

            Assert.IsInstanceOfType(client.serviceInfoProvider, typeof(AdalAppOnlyServiceInfoProvider), "Unexpected authentication provider.");
        }
        public async Task GetAuthenticatedClientUsingCustomAuthenticationAsync()
        {
            var baseEndpointUrl = "https://resource/";

            var client = await BusinessClientExtensions.GetAuthenticatedClientUsingCustomAuthenticationAsync(
                baseEndpointUrl,
                this.authenticationProvider.Object,
                this.httpProvider.Object) as OneDriveClient;

            var clientServiceInfoProvider = client.serviceInfoProvider as ServiceInfoProvider;

            Assert.IsNotNull(clientServiceInfoProvider, "Unexpected service info provider initialized for client.");
            Assert.AreEqual(this.authenticationProvider.Object, clientServiceInfoProvider.AuthenticationProvider, "Unexpected authentication provider set.");
            Assert.AreEqual(this.httpProvider.Object, client.HttpProvider, "Unexpected HTTP provider set.");
            Assert.IsNull(client.credentialCache, "Unexpected credential cache set.");

            Assert.AreEqual(
                string.Format(
                    Constants.Authentication.OneDriveBusinessBaseUrlFormatString,
                    baseEndpointUrl.TrimEnd('/'),
                    "v2.0"),
                client.BaseUrl,
                "Unexpected base service URL initialized.");

            this.authenticationProvider.Verify(provider => provider.AuthenticateAsync(), Times.Once);
        }
        public async Task GetAuthenticatedWebClientUsingAppOnlyAuthenticationAsync_TenantIdRequired()
        {
            var appId = "appId";

            var clientCertificate = new X509Certificate2(@"Certs\testwebapplication.pfx", "password");

            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedWebClientUsingAppOnlyAuthenticationAsync(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId             = appId,
                    ActiveDirectoryClientCertificate = clientCertificate,
                    ActiveDirectoryServiceResource   = serviceResourceId,
                },
                    serviceResourceId,
                    /* tenantId */ null,
                    this.credentialCache.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("Tenant ID is required for app-only authentication.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetAuthenticatedWebClientUsingAppOnlyAuthenticationAsync_ClientCertificateRequired()
        {
            var appId  = "appId";
            var siteId = "site_id";
            var tenant = "tenant";

            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedWebClientUsingAppOnlyAuthenticationAsync(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId           = appId,
                    ActiveDirectoryServiceResource = serviceResourceId,
                },
                    siteId,
                    tenant,
                    this.credentialCache.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("ActiveDirectoryClientCertificate is required for app-only authentication.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetAuthenticatedClientAsync_AppIdRequired()
        {
            bool exceptionThrown = false;

            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedClientAsync(
                    new AppConfig
                {
                    ActiveDirectoryReturnUrl = "https://return"
                },
                    /* userId */ null,
                    this.credentialCache,
                    this.httpProvider);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("ActiveDirectoryAppId is required for authentication.", exception.Error.Message, "Unexpected error thrown.");

                exceptionThrown = true;
            }

            Assert.IsTrue(exceptionThrown, "Expected exception not thrown.");
        }
        public async Task GetSilentlyAuthenticatedClientAsync_ServiceResourceRequired()
        {
            bool exceptionThrown = false;

            try
            {
                var client = await BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync(
                    new AppConfig
                {
                    ActiveDirectoryAppId = "appId",
                },
                    "refreshToken",
                    this.credentialCache,
                    this.httpProvider);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("ActiveDirectoryServiceResource is required for silently authenticating a business client.", exception.Error.Message, "Unexpected error thrown.");

                exceptionThrown = true;
            }

            Assert.IsTrue(exceptionThrown, "Expected exception not thrown.");
        }
        private async Task SignIn(ClientType clientType)
        {
            if (this.oneDriveClient == null)
            {
                this.oneDriveClient = clientType == ClientType.Consumer
                    ? OneDriveClient.GetMicrosoftAccountClient(
                    FormBrowser.MsaClientId,
                    FormBrowser.MsaReturnUrl,
                    FormBrowser.Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi())
                    : BusinessClientExtensions.GetClient(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId     = FormBrowser.AadClientId,
                    ActiveDirectoryReturnUrl = FormBrowser.AadReturnUrl,
                });
            }

            try
            {
                if (!this.oneDriveClient.IsAuthenticated)
                {
                    await this.oneDriveClient.AuthenticateAsync();
                }

                await LoadFolderFromPath();

                UpdateConnectedStateUx(true);
            }
            catch (OneDriveException exception)
            {
                // Swallow authentication cancelled exceptions, but reset the client
                if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
                {
                    if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                    {
                        MessageBox.Show(
                            "Authentication failed",
                            "Authentication failed",
                            MessageBoxButtons.OK);

                        ((OneDriveClient)this.oneDriveClient).Dispose();
                        this.oneDriveClient = null;
                    }
                    else
                    {
                        PresentOneDriveException(exception);
                    }
                }
                else
                {
                    ((OneDriveClient)this.oneDriveClient).Dispose();
                    this.oneDriveClient = null;
                }
            }
        }
        public void GetClientUsingCustomAuthentication_InitializeDefaults()
        {
            var baseEndpointUrl = "https://resource/";

            var client = BusinessClientExtensions.GetClientUsingCustomAuthentication(
                baseEndpointUrl,
                this.authenticationProvider.Object) as OneDriveClient;

            var clientServiceInfoProvider = client.serviceInfoProvider as ServiceInfoProvider;

            Assert.IsNotNull(clientServiceInfoProvider, "Unexpected service info provider initialized for client.");
            Assert.AreEqual(this.authenticationProvider.Object, clientServiceInfoProvider.AuthenticationProvider, "Unexpected authentication provider set.");
            Assert.IsInstanceOfType(client.HttpProvider, typeof(HttpProvider), "Unexpected HTTP provider set.");
            Assert.IsNull(client.credentialCache, "Unexpected credential cache set.");
            Assert.AreEqual(ClientType.Business, client.ClientType, "Unexpected client type set.");
        }
        public async Task GetAuthenticatedClientUsingCustomAuthenticationAsync_ServiceEndpointBaseUrlRequired()
        {
            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedClientUsingCustomAuthenticationAsync(
                    /* serviceEndpointBaseUrl */ null,
                    this.authenticationProvider.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("Service endpoint base URL is required when using custom authentication.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetAuthenticatedClientAsync_ReturnUrlRequired()
        {
            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedClientAsync(
                    new BusinessAppConfig(),
                    /* userId */ null,
                    this.credentialCache.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("ActiveDirectoryReturnUrl is required for authenticating a business client.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetAuthenticatedClientUsingCustomAuthenticationAsync_AuthenticationProviderRequired()
        {
            var baseEndpointUrl = "https://resource/";

            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedClientUsingCustomAuthenticationAsync(
                    baseEndpointUrl,
                    /* authenticationProvider */ null,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("An authentication provider is required for a client using custom authentication.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetSilentlyAuthenticatedWebClientAsync_ClientCertificateOrSecretRequired()
        {
            try
            {
                var client = await BusinessClientExtensions.GetSilentlyAuthenticatedWebClientAsync(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId = "appId",
                },
                    "refresh",
                    this.credentialCache.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("Client certificate or client secret is required for authenticating a business web client.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetSilentlyAuthenticatedClientAsync_RefreshTokenRequired()
        {
            try
            {
                var client = await BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId           = "appId",
                    ActiveDirectoryServiceResource = "https://localhost/resource/"
                },
                    /* refreshToken */ null,
                    this.credentialCache.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("Refresh token is required for silently authenticating a business client.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public async Task GetAuthenticatedWebClientUsingAuthenticationByCodeAsync_ServiceResourceRequired()
        {
            try
            {
                var client = await BusinessClientExtensions.GetAuthenticatedWebClientUsingAuthenticationByCodeAsync(
                    new BusinessAppConfig
                {
                    ActiveDirectoryAppId     = "appId",
                    ActiveDirectoryReturnUrl = "https://return",
                },
                    "code",
                    this.credentialCache.Object,
                    this.httpProvider.Object);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("Service resource ID is required for authentication by code.", exception.Error.Message, "Unexpected error thrown.");

                throw;
            }
        }
        public void GetClient()
        {
            var appId     = "appId";
            var returnUrl = "returnUrl";
            var userId    = "userId";

            var client = BusinessClientExtensions.GetClient(
                new BusinessAppConfig
            {
                ActiveDirectoryAppId           = appId,
                ActiveDirectoryReturnUrl       = returnUrl,
                ActiveDirectoryServiceResource = serviceResourceId,
            },
                userId,
                this.credentialCache.Object,
                this.httpProvider.Object) as OneDriveClient;

            var clientServiceInfoProvider = client.serviceInfoProvider as ServiceInfoProvider;

            Assert.IsNotNull(clientServiceInfoProvider, "Unexpected service info provider initialized for client.");
            Assert.AreEqual(userId, clientServiceInfoProvider.UserSignInName, "Unexpected user sign-in name set.");
            Assert.AreEqual(this.httpProvider.Object, client.HttpProvider, "Unexpected HTTP provider set.");
            Assert.AreEqual(this.credentialCache.Object, client.credentialCache, "Unexpected credential cache set.");
        }