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 here that too. I hope you will like this.
Download the source code
You can always download the source code here: Azure Media Service
Background
Few days back I have got a requirement of storing some files in the cloud. As you all know, Azure will be the right choice if you talk about the cloud services. And I had account with Azure already, so the things were pretty much 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 be noted that your storage account region must be same as your media service account region.
Prerequisites
Visual StudioAzure account with active subscriptionIf 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 creates it first before going to do this task.
Creating a Console application to use Media service accountCreate an Asset dynamically via console applicationUploading image to the assetsRetrieving the items from the AssetNow 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 follows the preceding steps.
Step 1: Login to your Azure Portal (https://portal.azure.com)
Azure Home
Step 2: Click New and select Media + CDN
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
Step 4: Give the details.
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
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.
<appSettings>
<add key="MediaServicesAccountName" value="****" />
<add key="MediaServicesAccountKey" value="***************************" />
</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.
install-package windowsazure.mediaservices
Now you need to include the preceding namespace to get started with.
using Microsoft.WindowsAzure.MediaServices.Client;
Now change your Program.cs codes as follows
using Microsoft.WindowsAzure.MediaServices.Client;
using System;
using System.Configuration;
namespace AzureMediaServiceApp
{
class Program
{
#region Constants
private static string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];
private static string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];
#endregion
static void Main(string[] args)
{
string input = string.Empty;
Console.WriteLine("Enter the asset name to be created...");
input = Console.ReadLine();
CreateBLOBContainer(input);
}
public static string CreateBLOBContainer(string containerName)
{
try
{
string result = string.Empty;
CloudMediaContext mediaContext;
mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);
IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);
return asset.Uri.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
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
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
Now we will create a function which will upload some files to asset. So that we will change our Program.cs file as follows.
using Microsoft.WindowsAzure.MediaServices.Client;
using System;
using System.Configuration;
using System.IO;
namespace AzureMediaServiceApp
{
class Program
{
#region Constants
private static readonly string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];
private static readonly string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];
private static readonly string myAzureCon = ConfigurationManager.ConnectionStrings["myAzureStorageCon"].ConnectionString;
private static MediaServicesCredentials _mediaServiceCredentials = null;
#endregion
static void Main(string[] args)
{
string input = string.Empty;
Console.WriteLine("Enter the asset name to be created...");
input = Console.ReadLine();
_mediaServiceCredentials = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey);
IAsset asset = CreateBLOBContainer(input, _mediaServiceCredentials);
UploadImages(asset, _mediaServiceCredentials);
}
public static IAsset CreateBLOBContainer(string containerName, MediaServicesCredentials _medServCredentials)
{
try
{
string result = string.Empty;
CloudMediaContext mediaContext;
mediaContext = new CloudMediaContext(_medServCredentials);
IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);
return asset;
}
catch (Exception)
{
throw;
}
}
public static string UploadImages(IAsset asset, MediaServicesCredentials _medServCredentials)
{
try
{
string _singleInputFilePath = Path.GetFullPath(@"E:\X7Md4VB.JPG");
CloudMediaContext mediaContext;
mediaContext = new CloudMediaContext(_medServCredentials);
var fileName = Path.GetFileName(_singleInputFilePath);
var assetFile = asset.AssetFiles.Create(fileName);
var policy = mediaContext.AccessPolicies.Create("policy for upload", TimeSpan.FromMinutes(30), AccessPermissions.Read | AccessPermissions.Write | AccessPermissions.List);
var locator = mediaContext.Locators.CreateSasLocator(asset, policy, DateTime.UtcNow.AddDays(1));
assetFile.Upload(_singleInputFilePath);
return "Success!";
}
catch (Exception)
{
throw;
}
}
}
}
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
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.
private static void GetAllTheAssetsAndFiles(MediaServicesCredentials _medServCredentials)
{
try
{
string result = string.Empty;
CloudMediaContext mediaContext;
mediaContext = new CloudMediaContext(_medServCredentials);
StringBuilder myBuilder = new StringBuilder();
foreach (var item in mediaContext.Assets)
{
myBuilder.AppendLine(Environment.NewLine);
myBuilder.AppendLine("--My Assets--");
myBuilder.AppendLine("Name: " + item.Name);
myBuilder.AppendLine("++++++++++++++++++++");
foreach (var subItem in item.AssetFiles)
{
myBuilder.AppendLine("File Name: "+subItem.Name);
myBuilder.AppendLine("Size: " + subItem.ContentFileSize);
myBuilder.AppendLine("++++++++++++++++++++++");
}
}
Console.WriteLine(myBuilder);
}
catch (Exception)
{
throw;
}
}
And it will give you an output as follows.
My Assets and contents
Conclusion
Did I miss anything that you may think which is needed? Have you ever tried Azure media service account? Could you find this post as useful? I hope you liked this article. Please share 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.
Kindest Regards
Sibeesh Venu