Esempio n. 1
0
        public async Task InitAsync(AMSClientV3 client, SynchronizationContext context)
        {
            _amsClient = client;
            _context   = context;

            Microsoft.Rest.Azure.IPage <Transform> transformsList = await _amsClient.AMSclient.Transforms.ListAsync(_amsClient.credentialsEntry.ResourceGroup, _amsClient.credentialsEntry.AccountName);

            IEnumerable <Task <TransformEntryV3> > transforms = transformsList.Select(async a => new TransformEntryV3(_context)
            {
                Name         = a.Name,
                Description  = a.Description,
                Jobs         = (await _amsClient.AMSclient.Jobs.ListAsync(_amsClient.credentialsEntry.ResourceGroup, _amsClient.credentialsEntry.AccountName, a.Name)).Count(),
                LastModified = a.LastModified.ToLocalTime().ToString("G")
            }
                                                                                      );

            TransformEntryV3[] mappedItems = await Task.WhenAll(transforms);

            BindingList <TransformEntryV3> MyObservTransformthisPageV3 = new BindingList <TransformEntryV3>(mappedItems);

            DataSource = MyObservTransformthisPageV3;

            Task myTask = Task.Factory.StartNew(() =>
            {
                BeginInvoke(new Action(() =>
                {
                    Columns["Name"].AutoSizeMode  = DataGridViewAutoSizeColumnMode.None;
                    Columns["Name"].Width         = 200;
                    Columns["Description"].Width  = 200;
                    Columns["LastModified"].Width = 130;
                }));
            });

            _initialized = true;
        }
        public static async Task <(Uri, bool)> GetValidOnDemandSmoothURIAsync(Asset asset, IAzureMediaServicesClient client, string resourceGroup, string accountName, string useThisLocatorName = null, LiveOutput liveOutput = null)
        {
            bool emptyLiveOutput = false; // used to signal the live output is empty (do not use ListPathsAsync)

            IList <AssetStreamingLocator> locators = (await client.Assets.ListStreamingLocatorsAsync(resourceGroup, accountName, asset.Name)).StreamingLocators;

            Microsoft.Rest.Azure.IPage <StreamingEndpoint> ses = await client.StreamingEndpoints.ListAsync(resourceGroup, accountName);

            StreamingEndpoint runningSes = ses.Where(s => s.ResourceState == StreamingEndpointResourceState.Running).FirstOrDefault();

            if (runningSes == null)
            {
                runningSes = ses.FirstOrDefault();
            }

            if (locators.Count > 0 && runningSes != null)
            {
                string locatorName = useThisLocatorName ?? locators.First().Name;
                AssetStreamingLocator locatorToUse = locators.Where(l => l.Name == locatorName).First();

                IList <StreamingPath>       streamingPaths = (await client.StreamingLocators.ListPathsAsync(resourceGroup, accountName, locatorName)).StreamingPaths;
                IEnumerable <StreamingPath> smoothPath     = streamingPaths.Where(p => p.StreamingProtocol == StreamingPolicyStreamingProtocol.SmoothStreaming);
                if (smoothPath.Any(s => s.Paths.Count != 0))
                {
                    UriBuilder uribuilder = new()
                    {
                        Host = runningSes.HostName,
                        Path = smoothPath.FirstOrDefault().Paths.FirstOrDefault()
                    };
                    return(uribuilder.Uri, emptyLiveOutput);
                }
                else if (smoothPath.Any() && liveOutput != null) // A live output with no data in it as live event not started. But we can determine the output URLs
                {
                    UriBuilder uribuilder = new()
                    {
                        Host = runningSes.HostName,
                        Path = locatorToUse.StreamingLocatorId.ToString() + "/" + liveOutput.ManifestName + ".ism/manifest"
                    };
                    emptyLiveOutput = true;
                    return(uribuilder.Uri, emptyLiveOutput);
                }
                else
                {
                    return(null, emptyLiveOutput);
                }
            }
            else
            {
                return(null, emptyLiveOutput);
            }
        }
        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;
                    }
                }
            }
        }
Esempio n. 4
0
        private async void ChooseStreamingEndpoint_Load(object sender, EventArgs e)
        {
            label.Text = string.Format(label.Text, _asset.Name);

            // SE List
            await _client.RefreshTokenIfNeededAsync();

            // StreamingEndpoint BestSE = Task.Run(async () => await AssetInfo.GetBestStreamingEndpointAsync(_client)).Result;
            StreamingEndpoint BestSE = await AssetInfo.GetBestStreamingEndpointAsync(_client);

            foreach (StreamingEndpoint se in _client.AMSclient.StreamingEndpoints.List(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName))
            {
                listBoxSE.Items.Add(new Item(string.Format(AMSExplorer.Properties.Resources.AssetInformation_AssetInformation_Load_012ScaleUnit, se.Name, se.ResourceState, StreamingEndpointInformation.ReturnTypeSE(se)), se.Name + "|" + se.HostName));
                if (se.Id == BestSE.Id)
                {
                    listBoxSE.SelectedIndex = listBoxSE.Items.Count - 1;
                }

                foreach (string custom in se.CustomHostNames)
                {
                    listBoxSE.Items.Add(new Item(string.Format(AMSExplorer.Properties.Resources.AssetInformation_AssetInformation_Load_012ScaleUnitCustomHostname3, se.Name, se.ResourceState, StreamingEndpointInformation.ReturnTypeSE(se), custom), se.Name + "|" + custom));
                }
            }


            // Filters

            // asset filters
            Microsoft.Rest.Azure.IPage <AssetFilter> assetFilters = await _client.AMSclient.AssetFilters.ListAsync(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName, _asset.Name);

            List <string> afiltersnames = assetFilters.Select(a => a.Name).ToList();

            assetFilters.ToList().ForEach(f =>
            {
                ListViewItem lvitem = new ListViewItem(new string[] { AMSExplorer.Properties.Resources.ChooseStreamingEndpoint_ChooseStreamingEndpoint_Load_AssetFilter + f.Name, f.Name });
                if (_filter != null && f.Name == _filter)
                {
                    lvitem.Checked = true;
                }
                listViewFilters.Items.Add(lvitem);
            }
                                          );


            // account filters
            Microsoft.Rest.Azure.IPage <AccountFilter> acctFilters = await _client.AMSclient.AccountFilters.ListAsync(_client.credentialsEntry.ResourceGroup, _client.credentialsEntry.AccountName);

            acctFilters.ToList().ForEach(f =>
            {
                ListViewItem lvitem = new ListViewItem(new string[] { AMSExplorer.Properties.Resources.ChooseStreamingEndpoint_ChooseStreamingEndpoint_Load_GlobalFilter + f.Name, f.Name });
                if (_filter != null && f.Name == _filter && listViewFilters.CheckedItems.Count == 0) // only if not already selected (asset filter priority > account filter)
                {
                    lvitem.Checked = true;
                }
                if (afiltersnames.Contains(f.Name)) // global filter with same name than asset filter
                {
                    lvitem.ForeColor = Color.Gray;
                }
                listViewFilters.Items.Add(lvitem);
            }
                                         );



            if (_playertype == PlayerType.DASHIFRefPlayer)
            {
                radioButtonDASHCSF.Checked = true;
            }

            comboBoxBrowser.Items.Add(new Item(AMSExplorer.Properties.Resources.ChooseStreamingEndpoint_ChooseStreamingEndpoint_Load_DefaultBrowser, string.Empty));
            if (_displayBrowserSelection)
            { // let's add the browser options to lplayback the content (IE, Edge, Chrome...)
                if (IsWindows10())
                {
                    comboBoxBrowser.Items.Add(new Item(Constants.BrowserEdge[0], Constants.BrowserEdge[1]));
                }

                comboBoxBrowser.Items.Add(new Item(Constants.BrowserIE[0], Constants.BrowserIE[1]));
                comboBoxBrowser.Items.Add(new Item(Constants.BrowserChrome[0], Constants.BrowserChrome[1]));
                comboBoxBrowser.SelectedIndex = 0;
            }
            comboBoxBrowser.Visible = _displayBrowserSelection;

            UpdatePreviewUrl();

            FillLocatorComboInPolicyTab();
        }
        /// <summary>
        /// Gets a list of all the allowed FQDNs in the list of outbound firewall rules for a server
        /// </summary>
        /// <param name="resourceGroupName">The name of the resource group</param>
        /// <param name="serverName">The name of the server</param>
        /// <returns>A list of all the firewall rules</returns>
        public List <AzureSqlServerOutboundFirewallRulesModel> ListOutboundFirewallRules(string resourceGroupName, string serverName)
        {
            Microsoft.Rest.Azure.IPage <Microsoft.Azure.Management.Sql.Models.OutboundFirewallRule> response = Communicator.List(resourceGroupName, serverName);

            return(response.Select((s) =>
            {
                return CreateOutboundFirewallRuleModelFromResponse(resourceGroupName, serverName, s);
            }).ToList());
        }