Working With Azure Media Service Account

In this article we are going to work with Media Service Account in Azure. Once we create a media service account, we will create a console application in which we will add the operations like creating the media assets dynamically. You can also upload some files to the assets created. We will discuss that here too. I hope you will like this.

You can always download the source code here: Azure Media Service

Background

A few days back I  got a requirement to store some files in the cloud. As you all know, Azure will be the right choice if you talk about cloud services. And I had account with Azure already, so things were pretty easy for me. Thus I decided to create a media service account for this requirement. Here we are going to see how we can create an Azure media service account and how to use the same. Following are the prerequisites.

What is media service account?

  • A media service account is a Azure based account which gives you access to cloud based media services in Azure.

  • Stores metadata of the media files you create, instead saving the actual media content.

  • To work with media service account, you must have an associated storage account.

  • While creating a media service account, you can either select the storage account you already have or you can create a new one.

  • Since the media service account and storage account is treated separately, the content will be available in your storage account even if you delete your media service account

Please note that your storage account region must be the same as your media service account region.

Prerequisites

  • Visual Studio
  • Azure account with active subscription

If you are a start up company or you are in thinking to start a one, you can always go for BizSpark(Software and services made for the start ups), to join please check here: How to join bizspark. Or you can always create a free account here.

Things we are going to do

The following are the tasks we are going to do.

Creating an Azure media service account

If you don’t have an Azure account with active subscription, you must create it first before going to do this task.

  • Creating a Console application to use Media service account
  • Create an Asset dynamically via console application
  • Uploading image to the assets
  • Retrieving the items from the Asset

Now we will go and create our media service account.

Steps to create an Azure media service account

To create an Azure media service account, please follow the preceding steps.

Step 1: Login to your Azure Portal (https://portal.azure.com)

Azure Home

Figure: Azure Home

Step 2: Click New and select Media + CDN

Media And CDN

Figure: Media And CDN

Step 3: Click on the media service

This will redirect you to old azure portal, If you are not redirected, no worries. It is fine.

Media Service

Figure: Media Service

Step 4: Give the details.

New Storage Account

Figure: New Storage Account

Here you can select if you have a storage account or a new one will be created for you automatically.

Step 5: Finish

Once you give the needed details, you can click on the tick symbol.

Media Service Created

Figure: Media Service Created

Now we have our storage account and media service account with us. You can always download the sample applications given there. What you need to do all is just select the language you wish and click on the download link. We will create a console application to use this media service account. Sounds cool?

Creating a Console application to use Media service account

To create a console application in Visual Studio click File->New project-> Select language->Select Console Application.

Now go back to your Azure portal and click on Manage Keys at the bottom, copy the MEDIA SERVICE ACCOUNT NAME and MEDIA SERVICE ACCESS KEY (Either primary or secondary). Then you need to add the settings as appSettings in your App.config file as follows.

  1. <appSettings>  
  2.    <add key="MediaServicesAccountName" value="****" />  
  3.    <add key="MediaServicesAccountKey" value="***************************" />  
  4. </appSettings>   

The next thing you need to do is installing windowsazure.mediaservices from package manager console. For that please go to your package manger console from NuGet Package Manager. And run the below query.

  1. install-package windowsazure.mediaservices   

Now you need to include the preceding namespace to get started with.      

  1. using Microsoft.WindowsAzure.MediaServices.Client;   

Now change your Program.cs codes as follows

  1. using Microsoft.WindowsAzure.MediaServices.Client;  
  2. using System;  
  3. using System.Configuration;  
  4. namespace AzureMediaServiceApp  
  5. {  
  6.     class Program  
  7.     {#region Constants  
  8.         private static string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];  
  9.         private static string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];#  
  10.         endregion  
  11.         static void Main(string[] args)  
  12.         {  
  13.             string input = string.Empty;  
  14.             Console.WriteLine("Enter the asset name to be created...");  
  15.             input = Console.ReadLine();  
  16.             CreateBLOBContainer(input);  
  17.         }  
  18.         public static string CreateBLOBContainer(string containerName)  
  19.         {  
  20.             try  
  21.             {  
  22.                 string result = string.Empty;  
  23.                 CloudMediaContext mediaContext;  
  24.                 mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);  
  25.                 IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);  
  26.                 return asset.Uri.ToString();  
  27.             }  
  28.             catch (Exception ex)  
  29.             {  
  30.                 return ex.Message;  
  31.             }  
  32.         }  
  33.     }  
  34. }   

What we are doing in the above code is, we are fetching the account details from the App.config and calling a function CreateBLOBContainer with the name of the asset as a parameter. We will ask for this name in the console window. Sounds good?

Media Service Created Output

Figure: Media Service Created Output

Now go back to your azure portal and click on content tab, you can see the asset you are just created.

Media Service Created Azure Portal Output

Figure: Media Service Created Azure Portal Output

Now we will create a function which will upload some files to asset. So that we will change our Program.cs file as follows.

  1. using Microsoft.WindowsAzure.MediaServices.Client;  
  2. using System;  
  3. using System.Configuration;  
  4. using System.IO;  
  5. namespace AzureMediaServiceApp  
  6. {  
  7.     class Program  
  8.     {#region Constants  
  9.         private static readonly string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];  
  10.         private static readonly string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];  
  11.         private static readonly string myAzureCon = ConfigurationManager.ConnectionStrings["myAzureStorageCon"].ConnectionString;  
  12.         private static MediaServicesCredentials _mediaServiceCredentials = null;#  
  13.         endregion  
  14.         static void Main(string[] args)  
  15.         {  
  16.             string input = string.Empty;  
  17.             Console.WriteLine("Enter the asset name to be created...");  
  18.             input = Console.ReadLine();  
  19.             _mediaServiceCredentials = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey);  
  20.             IAsset asset = CreateBLOBContainer(input, _mediaServiceCredentials);  
  21.             UploadImages(asset, _mediaServiceCredentials);  
  22.         }  
  23.         public static IAsset CreateBLOBContainer(string containerName, MediaServicesCredentials _medServCredentials)  
  24.         {  
  25.             try  
  26.             {  
  27.                 string result = string.Empty;  
  28.                 CloudMediaContext mediaContext;  
  29.                 mediaContext = new CloudMediaContext(_medServCredentials);  
  30.                 IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);  
  31.                 return asset;  
  32.             }  
  33.             catch (Exception)  
  34.             {  
  35.                 throw;  
  36.             }  
  37.         }  
  38.         public static string UploadImages(IAsset asset, MediaServicesCredentials _medServCredentials)  
  39.         {  
  40.             try  
  41.             {  
  42.                 string _singleInputFilePath = Path.GetFullPath(@ "E:\X7Md4VB.JPG");  
  43.                 CloudMediaContext mediaContext;  
  44.                 mediaContext = new CloudMediaContext(_medServCredentials);  
  45.                 var fileName = Path.GetFileName(_singleInputFilePath);  
  46.                 var assetFile = asset.AssetFiles.Create(fileName);  
  47.                 var policy = mediaContext.AccessPolicies.Create("policy for upload", TimeSpan.FromMinutes(30), AccessPermissions.Read | AccessPermissions.Write | AccessPermissions.List);  
  48.                 var locator = mediaContext.Locators.CreateSasLocator(asset, policy, DateTime.UtcNow.AddDays(1));  
  49.                 assetFile.Upload(_singleInputFilePath);  
  50.                 return "Success!";  
  51.             }  
  52.             catch (Exception)  
  53.             {  
  54.                 throw;  
  55.             }  
  56.         }  
  57.     }  
  58. }   

Here we calls a function UploadImages which accepts IAsset and MediaServicesCredentials as a parameter to upload the images to the asset we created. Once you run this, you can see that image has been uploaded in your asset. To check that, please go to your Azure portal and see your asset size in content tab. I am sure that the size must be changed.

Image uploaded to Media Service

Figure: Image uploaded to Media Service

Now we will list down all the items we saved to the asset. Shall we?

Retrieving the items from the Asset

To retrieve the items we will add an another function as follows.

  1. private static void GetAllTheAssetsAndFiles(MediaServicesCredentials _medServCredentials)  
  2. {  
  3.     try  
  4.     {  
  5.         string result = string.Empty;  
  6.         CloudMediaContext mediaContext;  
  7.         mediaContext = new CloudMediaContext(_medServCredentials);  
  8.         StringBuilder myBuilder = new StringBuilder();  
  9.         foreach(var item in mediaContext.Assets)  
  10.         {  
  11.             myBuilder.AppendLine(Environment.NewLine);  
  12.             myBuilder.AppendLine("--My Assets--");  
  13.             myBuilder.AppendLine("Name: " + item.Name);  
  14.             myBuilder.AppendLine("++++++++++++++++++++");  
  15.             foreach(var subItem in item.AssetFiles)  
  16.             {  
  17.                 myBuilder.AppendLine("File Name: " + subItem.Name);  
  18.                 myBuilder.AppendLine("Size: " + subItem.ContentFileSize);  
  19.                 myBuilder.AppendLine("++++++++++++++++++++++");  
  20.             }  
  21.         }  
  22.         Console.WriteLine(myBuilder);  
  23.     }  
  24.     catch (Exception)  
  25.     {  
  26.         throw;  
  27.     }  
  28. }   

And it will give you an output as follows.

My Assets and contents

Figure: My Assets and contents

Conclusion

Did I miss anything that you may think is needed? Have you ever tried Azure media service account? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Please see this article in my blog here