Uploading content to Microsoft Azure Media Services using .NET

The first step when We’re working with Microsoft Azure Media Services is ingesting assets. Like I said in the introduction of this service, from the portal we can upload content up to 200MB or copy files from a Storage account. In this post I would like to show how it is possible to upload through the Azure Media Services SDK.

For this example, I created a console application and I have installed the SDK via Nuget:

PM> Install-Package windowsazure.mediaservices

In the main method, I have listed the process to follow to upload any content that is included in a folder:

        static void Main(string[] args)
        {
            Debug("Upload assets to Azure Media Services");

            #region Constants

            const string folderPath = @"H:wow_trailers";
            const string accountName = "YOUR_ACCOUNT_NAME";
            const string accountKey = "YOUR_ACCOUNT_KEY";
            const string assetName = "WoW_Asset";

            #endregion

            //1. Nuget: Install-Package windowsazure.mediaservices

            //2.Connect to the media account
            CloudMediaContext _context = new CloudMediaContext(accountName, accountKey);

            //3.Create asset
            var asset = _context.Assets.Create(assetName, AssetCreationOptions.None);

            Debug(string.Format("Asset name: {0}", asset.Name));

            //4. Access policy
            var accessPolicy = _context.AccessPolicies.Create(asset.Name, TimeSpan.FromDays(10), AccessPermissions.Write | AccessPermissions.List);

            Debug(string.Format("Access policy - Duration: {0}", accessPolicy.Duration));

            //5. Locator
            var locator = _context.Locators.CreateLocator(LocatorType.Sas, asset, accessPolicy);            

            //6. BlobTransferClient
            var blobTransferClient = new BlobTransferClient
            {
                NumberOfConcurrentTransfers = 20,
                ParallelTransferThreadCount = 20
            };

            //7. TransferProgressChanged
            blobTransferClient.TransferProgressChanged += TransferProgressChanged;

            //8.Get files
            var files = Directory.EnumerateFiles(folderPath);

            //9. Preparing upload tasks
            var uploadTasks = new List<Task>();

            foreach (var file in files)
            {
                var assetFile = asset.AssetFiles.Create(Path.GetFileName(file));

                Debug(string.Format("Created asset for the file {0}", assetFile.Name));

                uploadTasks.Add(assetFile.UploadAsync(file, blobTransferClient, locator, CancellationToken.None));
            }

            //10. Wait
            Task.WaitAll(uploadTasks.ToArray());

            Debug("Done!", MessageType.Result);

            Console.ReadLine();
        }
  1. A region with the necessary data for the demo ( folder path, account name, account key and the name of the asset ).
  2. We install the SDK via Nuget.
  3. We connect the application with our Azure Media Account.
  4. Create the asset , which is the container where the files are stored. I’ll talk about this a little bit later.
  5. We define an access policy. In this case, we decided that this content will be available for only 10 days for writing and listing.
  6. Create a locator, which provides an entry point to the files in the asset.
  7. Create an object of type BlobTransferClient, which will be used for uploading the content.
  8. The previous object, we associate a handler that will give us information on the status of the upload.
  9. Get all the files in the selected folder.
  10. Create a list of tasks and we register a task for each file in order to create a AssetFile and we use the UploadAsyn method in order to prepair the uploading for the file.
  11. Once we have all the tasks you want to run, use Wait.All passing the list.

The code used for the handler TransferProgressChanged is only a trace that tells us the percentage completed:

        static void TransferProgressChanged(object sender, BlobTransferProgressChangedEventArgs e)
        {
            Debug(string.Format("{0}% upload completed for {1}", e.ProgressPercentage, e.LocalFile), MessageType.Progress);
        }

On the other hand, I’ve created a method called Debug where I change the color of the text displayed in the console based on an enumerable, which tells me if It’s Info, Progress or Result:

        static void Debug(string message, MessageType type = MessageType.Info)
        {
            switch (type)
            {
                case MessageType.Info:
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    break;
                case MessageType.Progress:
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    break;
                case MessageType.Result:
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    break;
                default:
                    break;
            }

            Console.WriteLine();
            Console.WriteLine(message);
        }

When the process is completed we can see the result in the CONTENT section:

Upload assets content portal

From here, we can’t check how many files are included in the asset and, moreover, if we publish content through the PUBLISH button It will return only one of the URLs available. However, if we access the Microsoft Azure Storage account associated, we can see that the asset corresponds to one container and we can list the content:

assets Storage containers

The name of the container is asset-locatorID. If we access to any of them, we can see the files for a particular asset:

assetfiles

One thing we should note is that if you have multiple files within an asset will not be possible to use the portal to encode them. Also, as I said, when we use the action publish if we have multiple files the portal just shows us the URL of one of them. However, we can build the rest of URLs by changing the file name, such as seen in the following URL:

https://gismedia.blob.core.windows.net/asset-9eaa68f6-adcf-4c57-800c-10c7e8cb04a3/Mists_of_Pandaria.mp4?sv=2012-02-12&sr=c&si=851c919d-0c13-4228-9e5b-1b8ca95fab72&sig=AOOUXluaeRmRkm%2F1Z9DOwh1Qcry4AJWTFZtkd%2Bf%2F8f8%3D&st=2014-08-13T07%3A38%3A07Z&se=2016-08-12T07%3A38%3A07Z

To play the file named Burning_Crusade.mp4 we would edit the file name in the above URL:

https://gismedia.blob.core.windows.net/asset-9eaa68f6-adcf-4c57-800c-10c7e8cb04a3/Burning_Crusade.mp4?sv=2012-02-12&sr=c&si=851c919d-0c13-4228-9e5b-1b8ca95fab72&sig=AOOUXluaeRmRkm%2F1Z9DOwh1Qcry4AJWTFZtkd%2Bf%2F8f8%3D&st=2014-08-13T07%3A38%3A07Z&se=2016-08-12T07%3A38%3A07Z

Hope this helps.

Happy clouding!