Eksportuj (0) Drukuj
Rozwiń wszystko
EN
Ta zawartość nie jest dostępna w wymaganym języku. Wersja w języku angielskim znajduje się tutaj.
1 z 4 osób oceniło jako pomocne - Oceń ten temat

Copying an Existing Blob into a Media Services Asset

Updated: February 18, 2014

This topic shows how to copy blobs from a storage account into a new Windows Azure Media Services asset.

Your blobs could exist in a storage account that is associated with Media Services account, or storage account that is not associated with Media Services account. This topic demonstrates how to do the following:

Prerequisites

  • Two Media Services accounts in a new or existing Azure subscription. See the topic How to Create a Media Services Account.

  • Operating Systems: Windows 7, Windows 2008 R2, or Windows 8.

  • .NET Framework 4.5 or .NET Framework 4.

  • Visual Studio 2012 or Visual Studio 2010 SP1 (Professional, Premium, Ultimate, or Express).

Set up your projet

In this section you will create and set up a C# Console Application project.

  1. Use Visual Studio 2012 or Visual Studio 2010 SP1 to create a new solution that contains the C# Console Application project. Enter CopyBlobsIntoAnAsset for the Name and then click OK.

  2. Use Nuget to add references to Media Services related DLLs. In Visual Studio Main Menu, select TOOLS -> Library Package Manager -> Package Manager Console. In the console window type Install-Package windowsazure.mediaservices and press enter.

  3. Add other references that are required for this project: System.Configuration, System.Runtime.Serialization, and System.Web.

  4. Replace using statements that were added to the Programs.cs file by default with the following ones:

    using System;
    using System.Configuration;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Xml;
    using System.Linq;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.MediaServices.Client;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using Microsoft.WindowsAzure.Storage.Auth;
    
    
  5. Add the appSettings section to the .config file and update the values based on your Media Services and Storage key and name values.

    <appSettings>
        <add key="MediaServicesAccountName" value="Media-Services-Account-Name-Source"/>
        <add key="MediaServicesAccountKey" value="Media-Services-Account-Key-Source"/>
        <add key="MediaServicesStorageAccountName" value="Media-Services-Storage-Account-Name-Source"/>
        <add key="MediaServicesStorageAccountKey" value="Media-Services-Storage-Account-Key-Source"/>
        <add key="ExternalStorageAccountName" value="Media-Services-Account-Name-Target" />
        <add key="ExternalStorageAccounKey" value=" Media-Services-Account-Key-Target" />
      </appSettings>
    
  6. Add the following class-level fields to the Program class.

    // Read values from the App.config file.
    private static readonly string MediaServicesAccountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];
    private static readonly string MediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];
    private static readonly string MediaServicesStorageAccountName = ConfigurationManager.AppSettings["MediaServicesStorageAccountName"];
    private static readonly string MediaServicesStorageAccountKey = ConfigurationManager.AppSettings["MediaServicesStorageAccountKey"];
    private static readonly string ExternalStorageAccountName = ConfigurationManager.AppSettings["ExternalStorageAccountName"];
    private static readonly string ExternalStorageAccountKey = ConfigurationManager.AppSettings["ExternalStorageAccounKey"];
    

Copying Blobs from a Storage Account Associated with Media Services Account into a Media Services Asset

The code example below performs the following tasks:

  1. Uploads Smooth Streaming files from a local directory into a blob container (mediaBlobContainer).

  2. Creates a new asset.

  3. Gets the asset container URI and copies blobs from mediaBlobContainer to assetContainer.

  4. Refreshes the asset.

  5. Sets the .ism file to be the primary file.

CloudMediaContext context = new CloudMediaContext(MediaServicesAccountName, MediaServicesAccountKey);

var storageAccount = new CloudStorageAccount(new StorageCredentials(MediaServicesStorageAccountName, MediaServicesStorageAccountKey), true);
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var mediaBlobContainer = cloudBlobClient.GetContainerReference(cloudBlobClient.BaseUri + "mediafiles001");

mediaBlobContainer.CreateIfNotExists();

string StreamingFilesFolder = Path.GetFullPath(@"c:\SupportFiles\streamingfiles\");

// Upload some files to the blob container (for testing purposes). 
DirectoryInfo uploadDirectory = new DirectoryInfo(StreamingFilesFolder);
foreach (var file in uploadDirectory.EnumerateFiles())
{
    CloudBlockBlob blob = mediaBlobContainer.GetBlockBlobReference(file.Name);
    var name = file.Name;
    using (var stream = System.IO.File.OpenRead(StreamingFilesFolder + name))
        blob.UploadFromStream(stream);
}
        

// Create a new asset.
IAsset asset = context.Assets.Create("NewAsset_" + Guid.NewGuid(), AssetCreationOptions.None);
IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy",
    TimeSpan.FromMinutes(120), AccessPermissions.Write);
ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy);

// Get the asset container URI and copy blobs from mediaContainer to assetContainer.
Uri uploadUri = new Uri(destinationLocator.Path);
string assetContainerName = uploadUri.Segments[1];
CloudBlobContainer assetContainer =
    cloudBlobClient.GetContainerReference(assetContainerName);

foreach (var sourceBlob in mediaBlobContainer.ListBlobs())
{
    string fileName = HttpUtility.UrlDecode(Path.GetFileName(sourceBlob.Uri.AbsoluteUri));

    var sourceCloudBlob = mediaBlobContainer.GetBlockBlobReference(fileName);
    sourceCloudBlob.FetchAttributes();

    if (sourceCloudBlob.Properties.Length > 0)
    {
        IAssetFile assetFile = asset.AssetFiles.Create(fileName);
        var destinationBlob = assetContainer.GetBlockBlobReference(fileName);

        destinationBlob.DeleteIfExists();
        destinationBlob.StartCopyFromBlob(sourceCloudBlob);

        destinationBlob.FetchAttributes();
        if (sourceCloudBlob.Properties.Length != destinationBlob.Properties.Length)
            Console.WriteLine("Failed to copy");
    }
}

destinationLocator.Delete();
writePolicy.Delete();

// Refresh the asset.
asset = context.Assets.Where(a => a.Id == asset.Id).FirstOrDefault();

//At this point, you can create a job using your asset.
Console.WriteLine("You are ready to use " + asset.Name);

// Since we copied a set of Smooth Streaming files,
// set the .ism file to be the primary file
var ismAssetFiles = asset.AssetFiles.ToList().
            Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase))
            .ToArray();

if (ismAssetFiles.Count() != 1)
    throw new ArgumentException("The asset should have only one, .ism file");

ismAssetFiles.First().IsPrimary = true;
ismAssetFiles.First().Update();

Copying Blobs from a Storage Account NOT Associated with Media Services Account into a Media Services Asset

Use the following code to copy blobs from a storage account that is not associated with the Media Services account into a Media Services asset.

// Create Media Services context.
CloudMediaContext context = new CloudMediaContext(MediaServicesAccountName, MediaServicesAccountKey);

var externalStorageAccount = new CloudStorageAccount(new StorageCredentials(ExternalStorageAccountName, ExternalStorageAccountKey), true);
var externalCloudBlobClient = externalStorageAccount.CreateCloudBlobClient();
var externalMediaBlobContainer = externalCloudBlobClient.GetContainerReference(externalCloudBlobClient.BaseUri + "mediafiles002");

externalMediaBlobContainer.CreateIfNotExists();

string StreamingFilesFolder = Path.GetFullPath(@"c:\SupportFiles\streamingfiles\");

// Upload some files to the blob container (for testing purposes). 
DirectoryInfo uploadDirectory = new DirectoryInfo(StreamingFilesFolder);
foreach (var file in uploadDirectory.EnumerateFiles())
{
    CloudBlockBlob blob = externalMediaBlobContainer.GetBlockBlobReference(file.Name);
    var name = file.Name;
    using (var stream = System.IO.File.OpenRead(StreamingFilesFolder + name))
        blob.UploadFromStream(stream);
}

// Get the SAS token to use for all blobs if dealing with multiple accounts
string blobToken = externalMediaBlobContainer.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
    // Specify the expiration time for the signature.
    SharedAccessExpiryTime = DateTime.Now.AddMinutes(30),
    // Specify the permissions granted by the signature.
    Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
});


// Create a new asset.
IAsset asset = context.Assets.Create("NewAsset_" + Guid.NewGuid(), AssetCreationOptions.None);
IAccessPolicy writePolicy = context.AccessPolicies.Create("writePolicy",
    TimeSpan.FromMinutes(120), AccessPermissions.Write);
ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.Sas, asset, writePolicy);



var destinationStorageAccount = new CloudStorageAccount(new StorageCredentials(MediaServicesStorageAccountName, MediaServicesStorageAccountKey), true);
var destBlobStorage = destinationStorageAccount.CreateCloudBlobClient();

// Get the asset container URI and Blob copy from mediaContainer to assetContainer.
string destinationContainerName = (new Uri(destinationLocator.Path)).Segments[1];

CloudBlobContainer assetContainer =
    destBlobStorage.GetContainerReference(destinationContainerName);



foreach (var sourceBlob in externalMediaBlobContainer.ListBlobs())
{
    string fileName = HttpUtility.UrlDecode(Path.GetFileName(sourceBlob.Uri.AbsoluteUri));

    var sourceCloudBlob = externalMediaBlobContainer.GetBlockBlobReference(fileName);
    sourceCloudBlob.FetchAttributes();

    if (sourceCloudBlob.Properties.Length > 0)
    {
        assetContainer.CreateIfNotExists();
        var destinationBlob = assetContainer.GetBlockBlobReference(fileName);

        destinationBlob.StartCopyFromBlob(new Uri(sourceBlob.Uri.AbsoluteUri + blobToken));

        var assetFile = asset.AssetFiles.Create(fileName);
    }
}

destinationLocator.Delete();
writePolicy.Delete();

// Refresh the asset.
asset = context.Assets.Where(a => a.Id == asset.Id).FirstOrDefault();

//At this point, you can create a job using your asset.
Console.WriteLine("You are ready to use " + asset.Name);

// Since we copied a set of Smooth Streaming files,
// set the .ism file to be the primary file
var ismAssetFiles = asset.AssetFiles.ToList().
            Where(f => f.Name.EndsWith(".ism", StringComparison.OrdinalIgnoreCase))
            .ToArray();

if (ismAssetFiles.Count() != 1)
    throw new ArgumentException("The asset should have only one, .ism file");

ismAssetFiles.First().IsPrimary = true;
ismAssetFiles.First().Update();

See Also


Build Date:

2014-04-10
Czy oceniasz te materiały jako pomocne?
(Pozostało znaków: 1500)
Dziękujemy za opinię.

Zawartość społeczności

Dodaj
Pokaż:
© 2014 Microsoft. Wszelkie prawa zastrzeżone.