private void AddItemToListviewAccounts(CredentialsEntryV3 c)
        {
            ListViewItem item = listViewAccounts.Items.Add(c.MediaService.Name);

            listViewAccounts.Items[item.Index].ForeColor   = Color.Black;
            listViewAccounts.Items[item.Index].ToolTipText = null;
        }
        private async void ButtonLogin_Click(object sender, EventArgs e)
        {
            if (listViewAccounts.SelectedIndices.Count != 1)
            {
                return;
            }
            // code when used from pick-up
            LoginInfo = CredentialList.MediaServicesAccounts[listViewAccounts.SelectedIndices[0]];

            if (LoginInfo == null)
            {
                MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //MessageBox.Show(string.Format("The {0} cannot be empty.", labelE1.Text), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            AmsClient = new AMSClientV3(LoginInfo.Environment, LoginInfo.AzureSubscriptionId, LoginInfo);

            AzureMediaServicesClient response = null;

            try
            {
                response = await AmsClient.ConnectAndGetNewClientV3Async();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            if (response == null)
            {
                return;
            }

            // let's save the credentials (SP) They may be updated by the user when connecting
            CredentialList.MediaServicesAccounts[listViewAccounts.SelectedIndices[0]] = AmsClient.credentialsEntry;
            SaveCredentialsToSettings();

            try
            {   // let's refresh storage accounts
                AmsClient.credentialsEntry.MediaService.StorageAccounts = (await AmsClient.AMSclient.Mediaservices.GetAsync(AmsClient.credentialsEntry.ResourceGroup, AmsClient.credentialsEntry.AccountName)).StorageAccounts;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Program.GetErrorMessage(ex), "Login error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
                return;
            }

            DialogResult = DialogResult.OK;  // form will close with OK result
                                             // else --> form won't close...
        }
        private void ListViewAccounts_SelectedIndexChanged(object sender, EventArgs e)
        {
            buttonLogin.Enabled = (listViewAccounts.SelectedIndices.Count == 1);             // no selected item, so login button not active
            buttonDeleteAccountEntry.Enabled = (listViewAccounts.SelectedIndices.Count > 0); // no selected item, so login button not active
            buttonExport.Enabled             = (listViewAccounts.Items.Count > 0);

            if (listViewAccounts.SelectedIndices.Count > 0) // one selected
            {
                LoginInfo = CredentialList.MediaServicesAccounts[listViewAccounts.SelectedIndices[0]];

                textBoxDescription.Text   = LoginInfo.Description;
                textBoxAMSResourceId.Text = LoginInfo.MediaService.Id;
                textBoxLocation.Text      = LoginInfo.MediaService.Location;
                textBoxAADtenantId.Text   = LoginInfo.AadTenantId;

                DoEnableManualFields(false);
                groupBoxAADAutMode.Visible = true;

                radioButtonAADInteractive.Checked      = !LoginInfo.UseSPAuth;
                radioButtonAADServicePrincipal.Checked = LoginInfo.UseSPAuth;
            }
        }
        private async void buttonPickupAccount_Click(object sender, EventArgs e)
        {
            AddAMSAccount1 addaccount1 = new AddAMSAccount1();

            if (addaccount1.ShowDialog() == DialogResult.OK)
            {
                if (addaccount1.SelectedMode == AddAccountMode.BrowseSubscriptions)
                {
                    environment = addaccount1.GetEnvironment();

                    AuthenticationContext authContext = new AuthenticationContext(
                        // authority:  environment.Authority,
                        authority: environment.AADSettings.AuthenticationEndpoint.ToString() + "common",
                        validateAuthority: true
                        );

                    AuthenticationResult accessToken;
                    try
                    {
                        accessToken = await authContext.AcquireTokenAsync(
                            resource : environment.AADSettings.TokenAudience.ToString(),
                            clientId : environment.ClientApplicationId,
                            redirectUri : new Uri("urn:ietf:wg:oauth:2.0:oob"),
                            parameters : new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto)
                            );
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    TokenCredentials credentials = new TokenCredentials(accessToken.AccessToken, "Bearer");

                    SubscriptionClient subscriptionClient = new SubscriptionClient(environment.ArmEndpoint, credentials);
                    Microsoft.Rest.Azure.IPage <Microsoft.Azure.Management.ResourceManager.Models.Subscription> subscriptions = subscriptionClient.Subscriptions.List();



                    // tenants browsing
                    myTenants tenants = new myTenants();
                    string    URL     = environment.ArmEndpoint + "tenants?api-version=2017-08-01";

                    HttpClient client = new HttpClient();
                    client.DefaultRequestHeaders.Remove("Authorization");
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken.AccessToken);
                    HttpResponseMessage response = await client.GetAsync(URL);

                    if (response.IsSuccessStatusCode)
                    {
                        string str = await response.Content.ReadAsStringAsync();

                        tenants = (myTenants)JsonConvert.DeserializeObject(str, typeof(myTenants));
                    }
                    AddAMSAccount2Browse addaccount2 = new AddAMSAccount2Browse(credentials, subscriptions, environment, tenants.value, new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto));

                    if (addaccount2.ShowDialog() == DialogResult.OK)
                    {
                        // Getting Media Services accounts...
                        AzureMediaServicesClient mediaServicesClient = new AzureMediaServicesClient(environment.ArmEndpoint, credentials);

                        CredentialsEntryV3 entry = new CredentialsEntryV3(addaccount2.selectedAccount,
                                                                          environment,
                                                                          addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto,
                                                                          false,
                                                                          addaccount2.selectedTenantId,
                                                                          false
                                                                          );
                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }


                // Get info from the Azure CLI JSON
                else if (addaccount1.SelectedMode == AddAccountMode.FromAzureCliJson)
                {
                    string        example = @"{
  ""AadClientId"": ""00000000-0000-0000-0000-000000000000"",
  ""AadEndpoint"": ""https://login.microsoftonline.com"",
  ""AadSecret"": ""00000000-0000-0000-0000-000000000000"",
  ""AadTenantId"": ""00000000-0000-0000-0000-000000000000"",
  ""AccountName"": ""amsaccount"",
  ""ArmAadAudience"": ""https://management.core.windows.net/"",
  ""ArmEndpoint"": ""https://management.azure.com/"",
  ""Region"": ""West Europe"",
  ""ResourceGroup"": ""amsResourceGroup"",
  ""SubscriptionId"": ""00000000-0000-0000-0000-000000000000""
}";
                    EditorXMLJSON form    = new EditorXMLJSON("Enter the JSON output of Azure Cli Service Principal creation (az ams account sp create)", example, true, false, true, "The Service Principal secret is stored encrypted in the application settings.");

                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        JsonFromAzureCli json = null;
                        try
                        {
                            json = (JsonFromAzureCli)JsonConvert.DeserializeObject(form.TextData, typeof(JsonFromAzureCli));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Error reading the json", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        string resourceId  = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Media/mediaservices/{2}", json.SubscriptionId, json.ResourceGroup, json.AccountName);
                        string AADtenantId = json.AadTenantId;

                        ActiveDirectoryServiceSettings aadSettings = new ActiveDirectoryServiceSettings()
                        {
                            AuthenticationEndpoint = json.AadEndpoint,
                            TokenAudience          = json.ArmAadAudience,
                            ValidateAuthority      = true
                        };

                        AzureEnvironment env = new AzureEnvironment(AzureEnvType.Custom)
                        {
                            AADSettings = aadSettings, ArmEndpoint = json.ArmEndpoint
                        };

                        CredentialsEntryV3 entry = new CredentialsEntryV3(
                            new SubscriptionMediaService(resourceId, json.AccountName, null, null, json.Region),
                            env,
                            PromptBehavior.Auto,
                            true,
                            AADtenantId,
                            false
                            )
                        {
                            ADSPClientId          = json.AadClientId,
                            ClearADSPClientSecret = json.AadSecret
                        };

                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }
                else if (addaccount1.SelectedMode == AddAccountMode.ManualEntry)
                {
                    AddAMSAccount2Manual form = new AddAMSAccount2Manual();
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        string accountnamecc = form.textBoxAMSResourceId.Text.Split('/').Last();

                        CredentialsEntryV3 entry = new CredentialsEntryV3(
                            new SubscriptionMediaService(form.textBoxAMSResourceId.Text, accountnamecc, null, null, form.textBoxLocation.Text),
                            addaccount1.GetEnvironment(),
                            PromptBehavior.Auto,
                            form.radioButtonAADServicePrincipal.Checked,
                            form.textBoxAADtenantId.Text,
                            true
                            );

                        CredentialList.MediaServicesAccounts.Add(entry);
                        AddItemToListviewAccounts(entry);

                        SaveCredentialsToSettings();
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
        private async void listViewAccounts_SelectedIndexChanged(object sender, EventArgs e)
        {
            ErrorConnectingAMS     = false;
            ErrorConnectingStorage = false;

            listBoxStorage.Items.Clear();

            if (listViewAccounts.SelectedIndices.Count != 1)
            {
                return;
            }
            // code when used from pick-up
            DestinationLoginInfo = CredentialList.MediaServicesAccounts[listViewAccounts.SelectedIndices[0]];

            if (DestinationLoginInfo == null)
            {
                MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //MessageBox.Show(string.Format("The {0} cannot be empty.", labelE1.Text), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            DestinationAmsClient = new AMSClientV3(DestinationLoginInfo.Environment, DestinationLoginInfo.AzureSubscriptionId, DestinationLoginInfo);

            AzureMediaServicesClient response = null;

            try
            {
                response = await DestinationAmsClient.ConnectAndGetNewClientV3Async();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor             = Cursors.Default;
                ErrorConnectingAMS = true;
                return;
            }


            if (response == null)
            {
                Cursor             = Cursors.Default;
                ErrorConnectingAMS = true;
                return;
            }

            // let's save the credentials (SP) They may be updated by the user when connecting
            CredentialList.MediaServicesAccounts[listViewAccounts.SelectedIndices[0]] = DestinationAmsClient.credentialsEntry;
            //SaveCredentialsToSettings();

            try
            {   // let's refresh storage accounts
                DestinationAmsClient.credentialsEntry.MediaService.StorageAccounts = (await DestinationAmsClient.AMSclient.Mediaservices.GetAsync(DestinationAmsClient.credentialsEntry.ResourceGroup, DestinationAmsClient.credentialsEntry.AccountName)).StorageAccounts;

                foreach (var storage in DestinationAmsClient.credentialsEntry.MediaService.StorageAccounts)
                {
                    string storageName = AMSClientV3.GetStorageName(storage.Id);

                    int index = listBoxStorage.Items.Add(new Item(storageName + ((storage.Type == StorageAccountType.Primary) ? AMSExplorer.Properties.Resources.CopyAsset_listBoxAcounts_SelectedIndexChanged_Default : string.Empty), storageName));
                    if (storage.Type == StorageAccountType.Primary)
                    {
                        listBoxStorage.SelectedIndex = index;
                    }
                }

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Program.GetErrorMessage(ex), "Login error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor             = Cursors.Default;
                ErrorConnectingAMS = true;

                return;
            }

            //            DialogResult = DialogResult.OK;  // form will close with OK result
            // else --> form won't close...

            UpdateStatusButtonOk();
        }