public void ConnectUsingUserIdentity_UIDPW_CtorV1_Discovery()
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            string Conn_UserName = System.Environment.GetEnvironmentVariable("XUNITCONNTESTUSERID");
            string Conn_PW       = System.Environment.GetEnvironmentVariable("XUNITCONNTESTPW");
            string Conn_Url      = System.Environment.GetEnvironmentVariable("XUNITCONNTESTURI");

            //Connection params.
            string onlineRegion = string.Empty;
            string orgName      = string.Empty;
            bool   isOnPrem     = false;

            Utilities.GetOrgnameAndOnlineRegionFromServiceUri(new Uri(Conn_Url), out onlineRegion, out orgName, out isOnPrem);

            Assert.NotNull(onlineRegion);
            Assert.NotNull(orgName);
            Assert.False(isOnPrem);

            Uri    orgUri   = new Uri(Conn_Url);
            string hostName = orgUri.Host.Split('.')[0];

            CdsServiceClient client = new CdsServiceClient(Conn_UserName, CdsServiceClient.MakeSecureString(Conn_PW), onlineRegion, hostName, true, null, CdsConnectionStringProcessor.sampleClientId, new Uri(CdsConnectionStringProcessor.sampleRedirectUrl), PromptBehavior.Never);

            Assert.True(client.IsReady, "Failed to Create Connection via Constructor - Discovery");

            // Validate connection
            ValidateConnection(client);
        }
        public void ConnectUsingUserIdentity_UIDPW_CtorV2()
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            string Conn_UserName = System.Environment.GetEnvironmentVariable("XUNITCONNTESTUSERID");
            string Conn_PW       = System.Environment.GetEnvironmentVariable("XUNITCONNTESTPW");
            string Conn_Url      = System.Environment.GetEnvironmentVariable("XUNITCONNTESTURI");

            // Connection params.
            CdsServiceClient client = new CdsServiceClient(Conn_UserName, CdsServiceClient.MakeSecureString(Conn_PW), new Uri(Conn_Url), true, CdsConnectionStringProcessor.sampleClientId, new Uri(CdsConnectionStringProcessor.sampleRedirectUrl), PromptBehavior.Never);

            Assert.True(client.IsReady, "Failed to Create Connection via Constructor - Direct Connect");

            // Validate connection
            ValidateConnection(client);
        }
        /// <summary>
        ///  Token refresh flow for MSAL User Flows.
        /// </summary>
        /// <param name="publicAppClient">MSAL Client to use.</param>
        /// <param name="scopes">Scopes to send in.</param>
        /// <param name="account"></param>
        /// <param name="promptBehavior">prompting behavior</param>
        /// <param name="clientCredentials">user credential package</param>
        /// <param name="useDefaultCreds">should system default creds be used</param>
        /// <param name="logSink">logger to write logs too.</param>
        /// <returns></returns>
        internal async static Task <AuthenticationResult> ObtainAccessTokenAsync(
            IPublicClientApplication publicAppClient,
            List <string> scopes,
            IAccount account,
            PromptBehavior promptBehavior,
            ClientCredentials clientCredentials,
            bool useDefaultCreds   = false,
            CdsTraceLogger logSink = null)
        {
            // This works for user Auth flows.
            AuthenticationResult _authenticationResult = null;
            bool clientCredentialsCheck = clientCredentials != null && clientCredentials.UserName != null && !string.IsNullOrEmpty(clientCredentials.UserName.UserName) && !string.IsNullOrEmpty(clientCredentials.UserName.Password);
            // Login user hint
            string loginUserHint = (clientCredentials != null && clientCredentials.UserName != null) ? clientCredentials.UserName.UserName : string.Empty;

            if (publicAppClient != null)
            {
                if (clientCredentialsCheck && !useDefaultCreds && !(promptBehavior == PromptBehavior.Always || promptBehavior == PromptBehavior.SelectAccount))
                {
                    _authenticationResult = publicAppClient.AcquireTokenByUsernamePassword(scopes, clientCredentials.UserName.UserName, CdsServiceClient.MakeSecureString(clientCredentials.UserName.Password)).ExecuteAsync().Result;
                }
                else
                {
                    if (useDefaultCreds)
                    {
                        if (!string.IsNullOrEmpty(loginUserHint))
                        {
                            _authenticationResult = await publicAppClient.AcquireTokenByIntegratedWindowsAuth(scopes).WithUsername(loginUserHint).ExecuteAsync();
                        }
                        else
                        {
                            _authenticationResult = await publicAppClient.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync();
                        }
                    }
                    else
                    {
                        logSink.Log(string.Format("ObtainAccessToken - PROMPT - Behavior: {0}", promptBehavior), TraceEventType.Verbose);
                        Microsoft.Identity.Client.Prompt?userPrompt = null;
                        switch (promptBehavior)
                        {
                        case PromptBehavior.Auto:
                            break;

                        case PromptBehavior.Always:
                            userPrompt = Microsoft.Identity.Client.Prompt.ForceLogin;
                            break;

                        case PromptBehavior.Never:
                        case PromptBehavior.RefreshSession:
                            userPrompt = Microsoft.Identity.Client.Prompt.NoPrompt;
                            break;

                        case PromptBehavior.SelectAccount:
                            userPrompt = Microsoft.Identity.Client.Prompt.SelectAccount;
                            break;

                        default:
                            break;
                        }

                        if (userPrompt != null)
                        {
                            _authenticationResult = await publicAppClient.AcquireTokenInteractive(scopes).WithLoginHint(loginUserHint).WithPrompt(userPrompt.Value).ExecuteAsync();
                        }
                        else
                        {
                            if (account != null)
                            {
                                _authenticationResult = await publicAppClient.AcquireTokenSilent(scopes, account).ExecuteAsync();
                            }
                            else
                            {
                                _authenticationResult = await publicAppClient.AcquireTokenInteractive(scopes).WithLoginHint(loginUserHint).ExecuteAsync();
                            }
                        }
                    }
                }
            }
            else
            {
                // throw here.
            }
            return(_authenticationResult);
        }
        public void ConnectUsingServiceIdentity_ClientSecret_CtorV2()
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            string Conn_AppID  = System.Environment.GetEnvironmentVariable("XUNITCONNTESTAPPID");
            string Conn_Secret = System.Environment.GetEnvironmentVariable("XUNITCONNTESTSECRET");
            string Conn_Url    = System.Environment.GetEnvironmentVariable("XUNITCONNTESTURI");

            // connection params + secure string.
            CdsServiceClient client = new CdsServiceClient(new Uri(Conn_Url), Conn_AppID, CdsServiceClient.MakeSecureString(Conn_Secret), true);

            Assert.True(client.IsReady, "Failed to Create Connection via Constructor");

            // Validate connection
            ValidateConnection(client);
        }