Jaa


Connect to Media Services v3 API - .NET

Media Services logo v3


Warning

Azure Media Services will be retired June 30th, 2024. For more information, see the AMS Retirement Guide.

This article shows you how to connect to the Azure Media Services v3 .NET SDK using the service principal login method.

Prerequisites

Important

Review naming conventions.

Create a console application

  1. Start Visual Studio.
  2. From the File menu, click New > Project.
  3. Create a .NET Core console application.

The sample app in this topic, targets netcoreapp2.0. The code uses 'async main', which is available starting with C# 7.1. See this blog for more details.

Add required NuGet packages/assemblies

  1. In Visual Studio, select Tools > NuGet Package Manager > NuGet Manager Console.
  2. In the Package Manager Console window, use Install-Package command to add the following NuGet packages. For example, Install-Package Microsoft.Azure.Management.Media.
Package Description
Microsoft.Azure.Management.Media Azure Media Services SDK.
To make sure you are using the latest Azure Media Services package, check Microsoft.Azure.Management.Media.

Other required assemblies

  • Azure.Storage.Blobs
  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Rest.ClientRuntime.Azure.Authentication

Create and configure the app settings file

Create appsettings.json

  1. Go go General > Text file.
  2. Name it "appsettings.json".
  3. Set the "Copy to Output Directory" property of the .json file to "Copy if newer" (so that the application is able to access it when published).

Set values in appsettings.json

Run the az ams account sp create command as described in access APIs. The command returns json that you should copy into your "appsettings.json".

Add configuration file

For convenience, add a configuration file that is responsible for reading values from "appsettings.json".

  1. Add a new .cs class to your project. Name it ConfigWrapper.
  2. Paste the following code in this file (this example assumes you have the namespace is ConsoleApp1).
using System;

using Microsoft.Extensions.Configuration;

namespace ConsoleApp1
{
    public class ConfigWrapper
    {
        private readonly IConfiguration _config;

        public ConfigWrapper(IConfiguration config)
        {
            _config = config;
        }

        public string SubscriptionId
        {
            get { return _config["SubscriptionId"]; }
        }

        public string ResourceGroup
        {
            get { return _config["ResourceGroup"]; }
        }

        public string AccountName
        {
            get { return _config["AccountName"]; }
        }

        public string AadTenantId
        {
            get { return _config["AadTenantId"]; }
        }

        public string AadClientId
        {
            get { return _config["AadClientId"]; }
        }

        public string AadSecret
        {
            get { return _config["AadSecret"]; }
        }

        public Uri ArmAadAudience
        {
            get { return new Uri(_config["ArmAadAudience"]); }
        }

        public Uri AadEndpoint
        {
            get { return new Uri(_config["AadEndpoint"]); }
        }

        public Uri ArmEndpoint
        {
            get { return new Uri(_config["ArmEndpoint"]); }
        }

        public string Location
        {
            get { return _config["Location"]; }
        }
    }
}

Connect to the .NET client

To start using Media Services APIs with .NET, you need to create an AzureMediaServicesClient object. To create the object, you need to supply credentials needed for the client to connect to Azure using Azure AD. In the code below, the GetCredentialsAsync function creates the ServiceClientCredentials object based on the credentials supplied in local configuration file.

  1. Open Program.cs.
  2. Paste the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.Azure.Management.Media;
using Microsoft.Azure.Management.Media.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.Rest.Azure.Authentication;

namespace ConsoleApp1
{
    class Program
    {
        public static async Task Main(string[] args)
        {

            ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build());

            try
            {
                IAzureMediaServicesClient client = await CreateMediaServicesClientAsync(config);
                Console.WriteLine("connected");
            }
            catch (Exception exception)
            {
                if (exception.Source.Contains("ActiveDirectory"))
                {
                    Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                }

                Console.Error.WriteLine($"{exception.Message}");


                if (exception.GetBaseException() is ErrorResponseException apiException)
                {
                    Console.Error.WriteLine(
                        $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'.");
                }
            }

            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }

        private static async Task<ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config)
        {
            // Use ApplicationTokenProvider.LoginSilentWithCertificateAsync or UserTokenProvider.LoginSilentAsync to get a token using service principal with certificate
            //// ClientAssertionCertificate
            //// ApplicationTokenProvider.LoginSilentWithCertificateAsync

            // Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symmetric key
            ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);
            return await ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure);
        }

        private static async Task<IAzureMediaServicesClient> CreateMediaServicesClientAsync(ConfigWrapper config)
        {
            var credentials = await GetCredentialsAsync(config);

            return new AzureMediaServicesClient(config.ArmEndpoint, credentials)
            {
                SubscriptionId = config.SubscriptionId,
            };
        }

    }
}

Get help and support

You can contact Media Services with questions or follow our updates by one of the following methods: