Represents a base media context containing collections to operate on.
Ejemplo n.º 1
0
        /// <summary>
        /// Gets the certificate for protection key id.
        /// </summary>
        /// <param name="mediaContext">The media context.</param>
        /// <param name="protectionKeyId">The protection key id.</param>
        /// <returns>The content key.</returns>
        internal static X509Certificate2 GetCertificateForProtectionKeyId(MediaContextBase mediaContext, string protectionKeyId)
        {
            // First check to see if we have the cert in our store already.
            X509Certificate2 certToUse = EncryptionUtils.GetCertificateFromStore(protectionKeyId);

            IMediaDataServiceContext dataContext = mediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            if ((certToUse == null) && (dataContext != null))
            {
                // If not, download it from Nimbus to use.
                Uri uriGetProtectionKey = new Uri(String.Format(CultureInfo.InvariantCulture, "/GetProtectionKey?protectionKeyId='{0}'", protectionKeyId), UriKind.Relative);

                MediaRetryPolicy retryPolicy = mediaContext.MediaServicesClassFactory.GetQueryRetryPolicy();

                IEnumerable <string> results2 = retryPolicy.ExecuteAction <IEnumerable <string> >(() => dataContext.Execute <string>(uriGetProtectionKey));

                string certString = results2.Single();

                byte[] certBytes = Convert.FromBase64String(certString);
                certToUse = new X509Certificate2(certBytes);

                // Finally save it for next time.
                EncryptionUtils.SaveCertificateToStore(certToUse);
            }

            return(certToUse);
        }
        /// <summary>
        /// Gets the certificate for protection key id.
        /// </summary>
        /// <param name="mediaContext">The media context.</param>
        /// <param name="protectionKeyId">The protection key id.</param>
        /// <returns>The content key.</returns>
        internal static X509Certificate2 GetCertificateForProtectionKeyId(MediaContextBase mediaContext, string protectionKeyId)
        {
            // First check to see if we have the cert in our store already.
            X509Certificate2 certToUse = EncryptionUtils.GetCertificateFromStore(protectionKeyId);

            IMediaDataServiceContext dataContext = mediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            if ((certToUse == null) && (dataContext != null))
            {
                // If not, download it from Nimbus to use.
                Uri uriGetProtectionKey = new Uri(String.Format(CultureInfo.InvariantCulture, "/GetProtectionKey?protectionKeyId='{0}'", protectionKeyId), UriKind.Relative);

                MediaRetryPolicy retryPolicy = mediaContext.MediaServicesClassFactory.GetQueryRetryPolicy(dataContext as IRetryPolicyAdapter);

                IEnumerable <string> results2 = retryPolicy.ExecuteAction <IEnumerable <string> >(() => dataContext.Execute <string>(uriGetProtectionKey));

                string certString = results2.Single();

                byte[] certBytes = Convert.FromBase64String(certString);
                certToUse = new X509Certificate2(certBytes);

                try
                {
                    // Finally save it for next time.
                    EncryptionUtils.SaveCertificateToStore(certToUse);
                }
                catch
                {
                    // Azure Web Sites does not allow writing access to the local certificate store (it is blocked by the security model used to isolate each web site).
                    // Swallow the exception and continue executing.
                }
            }

            return(certToUse);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProgramBaseCollection"/> class.
        /// </summary>
        /// <param name="cloudMediaContext">The <seealso cref="MediaContextBase"/> instance.</param>
        internal ProgramBaseCollection(MediaContextBase cloudMediaContext)
            : base(cloudMediaContext)
        {
            var dataContext = cloudMediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            _programQuery = new Lazy <IQueryable <IProgram> >(() => dataContext.CreateQuery <IProgram, ProgramData>(ProgramSet));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetFileCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The cloud media context.</param>
 /// <param name="parentAsset">The parent <see cref="IAsset"/>.</param>
 internal AssetFileCollection(MediaContextBase cloudMediaContext, IAsset parentAsset)
     : this(cloudMediaContext)
 {
     _parentAsset = parentAsset;
     MediaServicesClassFactory factory = this.MediaContext.MediaServicesClassFactory;
     this._assetFileQuery = new Lazy<IQueryable<IAssetFile>>(() => factory.CreateDataServiceContext().CreateQuery<IAssetFile, AssetFileData>(FileSet));
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Waits for REST Nimbus Streaming operation completion
        /// </summary>
        /// <param name="context">The <seealso cref="CloudMediaContext"/> instance.</param>
        /// <param name="operationId">Id of the operation.</param>
        /// <param name="pollInterval">Poll interval.</param>
        /// <returns>Operation.</returns>
        public static IOperation WaitOperationCompletion(MediaContextBase context, string operationId, TimeSpan pollInterval)
        {
            IOperation operation;

            do
            {
                Thread.Sleep(pollInterval);

                IMediaDataServiceContext dataContext = context.MediaServicesClassFactory.CreateDataServiceContext();
                Uri uri = new Uri(string.Format(CultureInfo.InvariantCulture, "/Operations('{0}')", operationId), UriKind.Relative);

                MediaRetryPolicy retryPolicy = context.MediaServicesClassFactory.GetQueryRetryPolicy(dataContext as IRetryPolicyAdapter);

                try
                {
                    operation = retryPolicy.ExecuteAction <IEnumerable <OperationData> >(() => dataContext.Execute <OperationData>(uri)).SingleOrDefault();
                }
                catch (Exception e)
                {
                    e.Data.Add("OperationId", operationId);
                    throw;
                }

                if (operation == null)
                {
                    throw new InvalidOperationException(
                              string.Format(CultureInfo.CurrentCulture, Resources.ErrorOperationNotFoundFormat, operationId));
                }
            }while (operation.State == OperationState.InProgress);

            return(operation);
        }
        internal StreamingFilterBaseCollection(MediaContextBase cloudMediaContext)
            : base(cloudMediaContext)
        {
            var dataContext = cloudMediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            _filterQuery = new Lazy <IQueryable <IStreamingFilter> >(() => dataContext.CreateQuery <IStreamingFilter, StreamingFilterData>(FilterSet));
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetFileCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The cloud media context.</param>
 /// <param name="parentAsset">The parent <see cref="IAsset"/>.</param>
 internal AssetFileCollection(MediaContextBase cloudMediaContext, IAsset parentAsset)
     : this(cloudMediaContext)
 {
     _parentAsset = parentAsset;
     MediaServicesClassFactory factory = this.MediaContext.MediaServicesClassFactory;
     this._assetFileQuery = new Lazy <IQueryable <IAssetFile> >(() => factory.CreateDataServiceContext().CreateQuery <IAssetFile, AssetFileData>(FileSet));
 }
 internal NotificationEndPointCollection(MediaContextBase cloudMediaContext)
     : base(cloudMediaContext)
 {
     Queryable =
         MediaContext.MediaServicesClassFactory.CreateDataServiceContext()
         .CreateQuery <INotificationEndPoint, NotificationEndPoint>(NotificationEndPoints);
 }
Ejemplo n.º 9
0
        internal static async Task <IAssetFile> CreateAssetFileFromLocalFileAsync(this IAsset asset, string filePath, ILocator sasLocator, EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedEventArgs, CancellationToken cancellationToken)
        {
            string     assetFileName = Path.GetFileName(filePath);
            IAssetFile assetFile     = await asset.AssetFiles.CreateAsync(assetFileName, cancellationToken).ConfigureAwait(false);

            MediaContextBase context = asset.GetMediaContext();

            assetFile.UploadProgressChanged += uploadProgressChangedEventArgs;

            BlobTransferClient blobTransferClient = new BlobTransferClient
            {
                NumberOfConcurrentTransfers = context.NumberOfConcurrentTransfers,
                ParallelTransferThreadCount = context.ParallelTransferThreadCount
            };

            await assetFile.UploadAsync(filePath, blobTransferClient, sasLocator, cancellationToken).ConfigureAwait(false);

            assetFile.UploadProgressChanged -= uploadProgressChangedEventArgs;

            if (assetFileName.EndsWith(ILocatorExtensions.ManifestFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                assetFile.IsPrimary = true;
                await assetFile.UpdateAsync().ConfigureAwait(false);
            }

            return(assetFile);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaServicesClassFactory" /> class.
 /// </summary>
 /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
 /// <param name="mediaContext">The <seealso cref="CloudMediaContext" /> instance.</param>
 public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, CloudMediaContext mediaContext)
 {
     _dataServiceAdapter         = new OAuthDataServiceAdapter(mediaContext.Credentials, NimbusRestApiCertificateThumbprint, NimbusRestApiCertificateSubject);
     _serviceVersionAdapter      = new ServiceVersionAdapter(KnownApiVersions.Current);
     _userAgentAdapter           = new UserAgentAdapter(KnownClientVersions.Current);
     _mediaContext               = mediaContext;
     _azureMediaServicesEndpoint = CreateAzureMediaServicesEndPoint(azureMediaServicesEndpoint, mediaContext);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MediaServicesClassFactory"/> class.
        /// </summary>
        /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
        /// <param name="dataServiceAdapter">The data service adapter.</param>
        /// <param name="serviceVersionAdapter">The service version adapter.</param>
        /// <param name="mediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
        public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter serviceVersionAdapter, MediaContextBase mediaContext)
        {
            this._dataServiceAdapter = dataServiceAdapter;
            this._serviceVersionAdapter = serviceVersionAdapter;
            this._mediaContext = mediaContext;

            this._azureMediaServicesEndpoint = GetAccountApiEndpoint(this._dataServiceAdapter, this._serviceVersionAdapter, azureMediaServicesEndpoint);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaServicesClassFactory" /> class.
 /// </summary>
 /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
 /// <param name="dataServiceAdapter">The data service adapter.</param>
 /// <param name="serviceVersionAdapter">The service version adapter.</param>
 /// <param name="mediaContext">The <seealso cref="CloudMediaContext" /> instance.</param>
 /// <param name="userAgentAdapter">The user agent request adapter</param>
 public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter serviceVersionAdapter, MediaContextBase mediaContext, UserAgentAdapter userAgentAdapter)
 {
     _dataServiceAdapter = dataServiceAdapter;
     _serviceVersionAdapter = serviceVersionAdapter;
     _mediaContext = mediaContext;
     _userAgentAdapter = userAgentAdapter;
     _azureMediaServicesEndpoint = CreateAzureMediaServicesEndPoint(azureMediaServicesEndpoint, mediaContext);
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaServicesClassFactory" /> class.
 /// </summary>
 /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
 /// <param name="dataServiceAdapter">The data service adapter.</param>
 /// <param name="serviceVersionAdapter">The service version adapter.</param>
 /// <param name="mediaContext">The <seealso cref="CloudMediaContext" /> instance.</param>
 /// <param name="userAgentAdapter">The user agent request adapter</param>
 public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter serviceVersionAdapter, MediaContextBase mediaContext, UserAgentAdapter userAgentAdapter)
 {
     _dataServiceAdapter         = dataServiceAdapter;
     _serviceVersionAdapter      = serviceVersionAdapter;
     _mediaContext               = mediaContext;
     _userAgentAdapter           = userAgentAdapter;
     _azureMediaServicesEndpoint = CreateAzureMediaServicesEndPoint(azureMediaServicesEndpoint, mediaContext);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaServicesClassFactory" /> class.
 /// </summary>
 /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
 /// <param name="mediaContext">The <seealso cref="CloudMediaContext" /> instance.</param>
 public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, CloudMediaContext mediaContext)
 {
     _dataServiceAdapter = new OAuthDataServiceAdapter(mediaContext.TokenProvider);
     _serviceVersionAdapter = new ServiceVersionAdapter(KnownApiVersions.Current);
     _userAgentAdapter = new UserAgentAdapter(KnownClientVersions.Current);
     _mediaContext = mediaContext;
     _azureMediaServicesEndpoint = CreateAzureMediaServicesEndPoint(azureMediaServicesEndpoint, mediaContext);
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaServicesClassFactory" /> class.
 /// </summary>
 /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
 /// <param name="mediaContext">The <seealso cref="CloudMediaContext" /> instance.</param>
 public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, CloudMediaContext mediaContext)
 {
     _dataServiceAdapter         = new OAuthDataServiceAdapter(mediaContext.TokenProvider);
     _serviceVersionAdapter      = new ServiceVersionAdapter(KnownApiVersions.Current);
     _userAgentAdapter           = new UserAgentAdapter(KnownClientVersions.Current);
     _mediaContext               = mediaContext;
     _azureMediaServicesEndpoint = CreateAzureMediaServicesEndPoint(azureMediaServicesEndpoint, mediaContext);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaServicesClassFactory" /> class.
 /// </summary>
 /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
 /// <param name="mediaContext">The <seealso cref="CloudMediaContext" /> instance.</param>
 public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, CloudMediaContext mediaContext)
 {
     _dataServiceAdapter = new OAuthDataServiceAdapter(mediaContext.Credentials, NimbusRestApiCertificateThumbprint,NimbusRestApiCertificateSubject);
     _serviceVersionAdapter = new ServiceVersionAdapter(KnownApiVersions.Current);
     _userAgentAdapter = new UserAgentAdapter(KnownClientVersions.Current);
     _mediaContext = mediaContext;
     _azureMediaServicesEndpoint = CreateAzureMediaServicesEndPoint(azureMediaServicesEndpoint, mediaContext);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
 internal AssetCollection(MediaContextBase cloudMediaContext)
     : base(cloudMediaContext)
 {
     this._assetQuery = new Lazy<IQueryable<IAsset>>(
         () => this.MediaContext
             .MediaServicesClassFactory
             .CreateDataServiceContext()
             .CreateQuery<IAsset, AssetData>(AssetSet));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
 internal AssetCollection(MediaContextBase cloudMediaContext)
     : base(cloudMediaContext)
 {
     this._assetQuery = new Lazy <IQueryable <IAsset> >(
         () => this.MediaContext
         .MediaServicesClassFactory
         .CreateDataServiceContext()
         .CreateQuery <IAsset, AssetData>(AssetSet));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Copies the files in the <paramref name="sourceAsset"/> into into the <paramref name="destinationAsset"/> instance.
        /// </summary>
        /// <param name="sourceAsset">The <see cref="IAsset"/> instance that contains the asset files to copy.</param>
        /// <param name="destinationAsset">The <see cref="IAsset"/> instance that receives asset files.</param>
        /// <param name="destinationStorageCredentials">The <see cref="Microsoft.WindowsAzure.Storage.Auth.StorageCredentials"/> instance for the <paramref name="destinationAsset"/> Storage Account.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> instance to copy the files in the <paramref name="sourceAsset"/> into into the <paramref name="destinationAsset"/> instance.</returns>
        public static async Task CopyAsync(this IAsset sourceAsset, IAsset destinationAsset, StorageCredentials destinationStorageCredentials, CancellationToken cancellationToken)
        {
            if (sourceAsset == null)
            {
                throw new ArgumentNullException("sourceAsset", "The source asset cannot be null.");
            }

            if (destinationAsset == null)
            {
                throw new ArgumentNullException("destinationAsset", "The destination asset cannot be null.");
            }

            if (destinationStorageCredentials == null)
            {
                throw new ArgumentNullException("destinationStorageCredentials", "The destination storage credentials cannot be null.");
            }

            if (destinationStorageCredentials.IsAnonymous || destinationStorageCredentials.IsSAS)
            {
                throw new ArgumentException("The destination storage credentials must contain the account key credentials.", "destinationStorageCredentials");
            }

            if (!string.IsNullOrWhiteSpace(destinationStorageCredentials.AccountName) && !destinationStorageCredentials.AccountName.Equals(destinationAsset.StorageAccountName, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("The destination storage credentials does not belong to the destination asset storage account.", "destinationStorageCredentials");
            }

            MediaContextBase sourceContext = sourceAsset.GetMediaContext();
            ILocator         sourceLocator = null;

            try
            {
                sourceLocator = await sourceContext.Locators.CreateAsync(LocatorType.Sas, sourceAsset, AccessPermissions.Read | AccessPermissions.List, AssetBaseCollectionExtensions.DefaultAccessPolicyDuration).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();

                IRetryPolicy       retryPolicy = sourceContext.MediaServicesClassFactory.GetBlobStorageClientRetryPolicy().AsAzureStorageClientRetryPolicy();
                BlobRequestOptions options     = new BlobRequestOptions {
                    RetryPolicy = retryPolicy
                };
                CloudBlobContainer sourceContainer      = new CloudBlobContainer(sourceAsset.Uri, new StorageCredentials(sourceLocator.ContentAccessComponent));
                CloudBlobContainer destinationContainer = new CloudBlobContainer(destinationAsset.Uri, destinationStorageCredentials);

                await CopyBlobHelpers.CopyBlobsAsync(sourceContainer, destinationContainer, options, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();

                await CopyAssetFilesAsync(sourceAsset, destinationAsset, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                if (sourceLocator != null)
                {
                    sourceLocator.Delete();
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Constructor for the CapacityBasedAccountSelectionStrategy class
        /// </summary>
        /// <param name="mediaContextBase">MediaContextBase instance to query IStorageAccount entities</param>
        public CapacityBasedAccountSelectionStrategy(MediaContextBase mediaContextBase)
        {
            if (mediaContextBase == null)
            {
                throw new ArgumentNullException("mediaContextBase");
            }

            SetMediaContext(mediaContextBase);
            _weightedList = new List <CapacityBasedAccountSelectionStrategyListEntry>();
        }
Ejemplo n.º 21
0
 public static IMonitoringSettings CreateOrUpdateMonitoringSettings(this MediaContextBase context, string level)
 {
     try
     {
         return(context.CreateOrUpdateMonitoringSettingsAsync(level).Result);
     }
     catch (AggregateException exception)
     {
         throw exception.InnerException;
     }
 }
 /// <summary>
 /// Inits the cloud media context.
 /// </summary>
 /// <param name="context">The context.</param>
 private void InitCloudMediaContext(MediaContextBase context)
 {
     this._mediaContextBase = context;
     InvalidateLocatorsCollection();
     InvalidateContentKeysCollection();
     InvalidateFilesCollection();
     if (context != null)
     {
         this._fileCollection = new AssetFileCollection(context, this);
     }
 }
Ejemplo n.º 23
0
 public static ServiceMetadata GetServiceMetadata(this MediaContextBase context)
 {
     try
     {
         return(context.GetServiceMetadataAsync().Result);
     }
     catch (AggregateException exception)
     {
         throw exception.InnerException;
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task"/> instance to download all the asset files in the <paramref name="asset"/> to the <paramref name="folderPath"/>.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance from where to download the asset files.</param>
        /// <param name="folderPath">The path to the folder where to download the asset files in the <paramref name="asset"/>.</param>
        /// <param name="downloadProgressChangedCallback">A callback to report download progress for each asset file in the <paramref name="asset"/>.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> instance to download all the asset files in the <paramref name="asset"/>.</returns>
        public static async Task DownloadToFolderAsync(this IAsset asset, string folderPath, Action <IAssetFile, DownloadProgressChangedEventArgs> downloadProgressChangedCallback, CancellationToken cancellationToken)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            if (!Directory.Exists(folderPath))
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture, "The folder '{0}' does not exist.", folderPath),
                          "folderPath");
            }

            MediaContextBase context = asset.GetMediaContext();

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Read, AssetBaseCollectionExtensions.DefaultAccessPolicyDuration).ConfigureAwait(false);

            EventHandler <DownloadProgressChangedEventArgs> downloadProgressChangedHandler =
                (s, e) =>
            {
                IAssetFile assetFile = (IAssetFile)s;
                DownloadProgressChangedEventArgs eventArgs = e;

                if (downloadProgressChangedCallback != null)
                {
                    downloadProgressChangedCallback(assetFile, eventArgs);
                }
            };

            List <Task>       downloadTasks = new List <Task>();
            List <IAssetFile> assetFiles    = asset.AssetFiles.ToList();

            foreach (IAssetFile assetFile in assetFiles)
            {
                string             localDownloadPath  = Path.Combine(folderPath, assetFile.Name);
                BlobTransferClient blobTransferClient = new BlobTransferClient
                {
                    NumberOfConcurrentTransfers = context.NumberOfConcurrentTransfers,
                    ParallelTransferThreadCount = context.ParallelTransferThreadCount
                };

                assetFile.DownloadProgressChanged += downloadProgressChangedHandler;

                downloadTasks.Add(
                    assetFile.DownloadAsync(Path.GetFullPath(localDownloadPath), blobTransferClient, sasLocator, cancellationToken));
            }

            await Task.Factory.ContinueWhenAll(downloadTasks.ToArray(), t => t, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);

            await sasLocator.DeleteAsync().ConfigureAwait(false);

            assetFiles.ForEach(af => af.DownloadProgressChanged -= downloadProgressChangedHandler);
        }
Ejemplo n.º 25
0
        private Uri CreateAzureMediaServicesEndPoint(Uri azureMediaServicesEndpoint, MediaContextBase mediaContext)
        {
            string cacheKey = string.Format(
                "{0},{1}",
                mediaContext.TokenProvider.MediaServicesAccountName,
                azureMediaServicesEndpoint.ToString());

            return(_endpointCache.GetOrAdd(
                       cacheKey,
                       () => GetAccountApiEndpoint(_dataServiceAdapter, _serviceVersionAdapter, azureMediaServicesEndpoint, _userAgentAdapter, CreateClientRequestIdAdapter()),
                       () => mediaContext.TokenProvider.GetAccessToken().Item2.DateTime));
        }
Ejemplo n.º 26
0
        private Uri CreateAzureMediaServicesEndPoint(Uri azureMediaServicesEndpoint, MediaContextBase mediaContext)
        {
            string cacheKey = string.Format(
                "{0},{1}",
                mediaContext.Credentials.ClientId,
                azureMediaServicesEndpoint.ToString());

            return(_endpointCache.GetOrAdd(
                       cacheKey,
                       () => GetAccountApiEndpoint(_dataServiceAdapter, _serviceVersionAdapter, azureMediaServicesEndpoint, _userAgentAdapter, CreateClientRequestIdAdapter()),
                       () => mediaContext.Credentials.TokenExpiration));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="IngestManifestFileCollection"/> class.
        /// </summary>
        /// <param name="mediaContext"></param>
        /// <param name="parentIngestManifestAsset">The parent manifest asset.</param>
        internal IngestManifestFileCollection(MediaContextBase mediaContext, IIngestManifestAsset parentIngestManifestAsset)
            : base(mediaContext)
        {
            MediaServicesClassFactory factory = this.MediaContext.MediaServicesClassFactory;

            this._query = new Lazy <IQueryable <IIngestManifestFile> >(() => factory.CreateDataServiceContext().CreateQuery <IIngestManifestFile, IngestManifestFileData>(EntitySet));

            if (parentIngestManifestAsset != null)
            {
                this._parentIngestManifestAsset = (IngestManifestAssetData)parentIngestManifestAsset;
            }
        }
Ejemplo n.º 28
0
        public static string GetAzureTableEndPointAddress(this MediaContextBase context)
        {
            var azureTableEndPointAddress = string.Empty;
            var storageAccount            = context.StorageAccounts.Where(s => s.IsDefault).FirstOrDefault();

            if (storageAccount != null)
            {
                azureTableEndPointAddress = string.Format(CultureInfo.InvariantCulture, AzureTableBaseEndPointAddress, storageAccount.Name);
            }

            return(azureTableEndPointAddress);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the file in <paramref name="sourceBlob"/>.
        /// </summary>
        /// <param name="assets">The <see cref="AssetBaseCollection"/> instance.</param>
        /// <param name="sourceBlob">The <see cref="Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob"/> instance that contains the file to copy.</param>
        /// <param name="storageCredentials">The <see cref="Microsoft.WindowsAzure.Storage.Auth.StorageCredentials"/> instance for the new asset to create.</param>
        /// <param name="options">The <see cref="AssetCreationOptions"/>.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the file in <paramref name="sourceBlob"/>.</returns>
        public static async Task <IAsset> CreateFromBlobAsync(this AssetBaseCollection assets, CloudBlockBlob sourceBlob, StorageCredentials storageCredentials, AssetCreationOptions options, CancellationToken cancellationToken)
        {
            if (assets == null)
            {
                throw new ArgumentNullException("assets", "The assets collection cannot be null.");
            }

            if (sourceBlob == null)
            {
                throw new ArgumentNullException("sourceBlob", "The source blob cannot be null.");
            }

            if (storageCredentials == null)
            {
                throw new ArgumentNullException("storageCredentials", "The destination storage credentials cannot be null.");
            }

            if (storageCredentials.IsAnonymous || storageCredentials.IsSAS)
            {
                throw new ArgumentException("The destination storage credentials must contain the account key credentials.", "destinationStorageCredentials");
            }

            MediaContextBase context = assets.MediaContext;

            IAsset asset = await assets.CreateAsync(sourceBlob.Name, storageCredentials.AccountName, options, cancellationToken).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            IRetryPolicy       retryPolicy = context.MediaServicesClassFactory.GetBlobStorageClientRetryPolicy().AsAzureStorageClientRetryPolicy();
            BlobRequestOptions blobOptions = new BlobRequestOptions {
                RetryPolicy = retryPolicy
            };
            CloudBlobContainer container = new CloudBlobContainer(asset.Uri, storageCredentials);
            CloudBlockBlob     blob      = container.GetBlockBlobReference(sourceBlob.Name);

            await CopyBlobHelpers.CopyBlobAsync(sourceBlob, blob, blobOptions, cancellationToken).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            IAssetFile assetFile = await asset.AssetFiles.CreateAsync(sourceBlob.Name, cancellationToken).ConfigureAwait(false);

            assetFile.IsPrimary = true;
            if (sourceBlob.Properties != null)
            {
                assetFile.ContentFileSize = sourceBlob.Properties.Length;
                assetFile.MimeType        = sourceBlob.Properties.ContentType;
            }

            await assetFile.UpdateAsync().ConfigureAwait(false);

            return(asset);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.
        /// </summary>
        /// <param name="assets">The <see cref="AssetBaseCollection"/> instance.</param>
        /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param>
        /// <param name="storageAccountName">The name of the storage account where to store the new <see cref="IAsset"/>.</param>
        /// <param name="options">The <see cref="AssetCreationOptions"/>.</param>
        /// <param name="uploadProgressChangedCallback">A callback to report upload progress of the files.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.</returns>
        public static async Task <IAsset> CreateFromFolderAsync(this AssetBaseCollection assets, string folderPath, string storageAccountName, AssetCreationOptions options, Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback, CancellationToken cancellationToken)
        {
            if (assets == null)
            {
                throw new ArgumentNullException("assets", "The assets collection cannot be null.");
            }

            IEnumerable <string> filePaths = Directory.EnumerateFiles(folderPath);

            if (!filePaths.Any())
            {
                throw new FileNotFoundException(
                          string.Format(CultureInfo.InvariantCulture, "No files in directory, check the folder path: '{0}'", folderPath));
            }

            MediaContextBase context = assets.MediaContext;

            if (string.IsNullOrWhiteSpace(storageAccountName))
            {
                storageAccountName = context.DefaultStorageAccount.Name;
            }

            string assetName = Path.GetFileName(Path.GetFullPath(folderPath.TrimEnd('\\')));
            IAsset asset     = await context.Assets.CreateAsync(assetName, storageAccountName, options, cancellationToken).ConfigureAwait(false);

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Write | AccessPermissions.List, DefaultAccessPolicyDuration).ConfigureAwait(false);

            EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedHandler =
                (s, e) =>
            {
                IAssetFile assetFile = (IAssetFile)s;
                UploadProgressChangedEventArgs eventArgs = e;

                if (uploadProgressChangedCallback != null)
                {
                    uploadProgressChangedCallback(assetFile, eventArgs);
                }
            };

            IList <Task> uploadTasks = new List <Task>();

            foreach (string filePath in filePaths)
            {
                uploadTasks.Add(asset.CreateAssetFileFromLocalFileAsync(filePath, sasLocator, uploadProgressChangedHandler, cancellationToken));
            }

            await Task.Factory.ContinueWhenAll(uploadTasks.ToArray(), t => t, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);

            await sasLocator.DeleteAsync().ConfigureAwait(false);

            return(asset);
        }
Ejemplo n.º 31
0
        internal MonitoringSettingsCollection(MediaContextBase context)
            : base(context)
        {
            this.filterQuery = new Lazy <IQueryable <IMonitoringSettings> >(
                () =>
            {
                var dataContext = this.MediaContext
                                  .MediaServicesClassFactory
                                  .CreateCustomDataServiceContext();

                return(dataContext.CreateQuery <IMonitoringSettings, MonitoringSettingsData>(MonitoringConfigurationsSet));
            });
        }
        /// <summary>
        /// Gets the protection key id for content key.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="contentKeyType">Type of the content key.</param>
        /// <returns>The content key.</returns>
        internal static string GetProtectionKeyIdForContentKey(MediaContextBase mediaContext, ContentKeyType contentKeyType)
        {
            // First query Nimbus to find out what certificate to encrypt the content key with.
            string uriString             = String.Format(CultureInfo.InvariantCulture, "/GetProtectionKeyId?contentKeyType={0}", Convert.ToInt32(contentKeyType, CultureInfo.InvariantCulture));
            Uri    uriGetProtectionKeyId = new Uri(uriString, UriKind.Relative);

            IMediaDataServiceContext dataContext = mediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            MediaRetryPolicy retryPolicy = mediaContext.MediaServicesClassFactory.GetQueryRetryPolicy(dataContext as IRetryPolicyAdapter);

            IEnumerable <string> results = retryPolicy.ExecuteAction <IEnumerable <string> >(() => dataContext.Execute <string>(uriGetProtectionKeyId));

            return(results.Single());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MediaServicesClassFactory"/> class.
        /// </summary>
        /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
        /// <param name="dataServiceAdapter">The data service adapter.</param>
        /// <param name="serviceVersionAdapter">The service version adapter.</param>
        /// <param name="mediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
        public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter serviceVersionAdapter, MediaContextBase mediaContext)
        {
            this._dataServiceAdapter    = dataServiceAdapter;
            this._serviceVersionAdapter = serviceVersionAdapter;
            this._mediaContext          = mediaContext;

            string cacheKey = string.Format(
                "{0},{1}",
                mediaContext.Credentials.ClientId,
                azureMediaServicesEndpoint.ToString());

            this._azureMediaServicesEndpoint = _endpointCache.GetOrAdd(
                cacheKey,
                () => GetAccountApiEndpoint(this._dataServiceAdapter, this._serviceVersionAdapter, azureMediaServicesEndpoint),
                () => mediaContext.Credentials.TokenExpiration);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MediaServicesClassFactory"/> class.
        /// </summary>
        /// <param name="azureMediaServicesEndpoint">The Windows Azure Media Services endpoint to use.</param>
        /// <param name="dataServiceAdapter">The data service adapter.</param>
        /// <param name="serviceVersionAdapter">The service version adapter.</param>
        /// <param name="mediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
        public AzureMediaServicesClassFactory(Uri azureMediaServicesEndpoint, OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter serviceVersionAdapter, MediaContextBase mediaContext)
        {
            this._dataServiceAdapter = dataServiceAdapter;
            this._serviceVersionAdapter = serviceVersionAdapter;
            this._mediaContext = mediaContext;

            string cacheKey = string.Format(
                "{0},{1}",
                mediaContext.Credentials.ClientId,
                azureMediaServicesEndpoint.ToString());

            this._azureMediaServicesEndpoint = _endpointCache.GetOrAdd(
                cacheKey,
                () => GetAccountApiEndpoint(this._dataServiceAdapter, this._serviceVersionAdapter, azureMediaServicesEndpoint),
                () => mediaContext.Credentials.TokenExpiration);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Returns the parent <see cref="MediaContextBase"/> instance.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance.</param>
        /// <returns>The parent <see cref="MediaContextBase"/> instance.</returns>
        public static MediaContextBase GetMediaContext(this IAsset asset)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            IMediaContextContainer mediaContextContainer = asset as IMediaContextContainer;
            MediaContextBase       context = null;

            if (mediaContextContainer != null)
            {
                context = mediaContextContainer.GetMediaContext();
            }

            return(context);
        }
        /// <summary>
        /// Returns the parent <see cref="MediaContextBase"/> instance.
        /// </summary>
        /// <param name="job">The <see cref="IJob"/> instance.</param>
        /// <returns>The parent <see cref="MediaContextBase"/> instance.</returns>
        public static MediaContextBase GetMediaContext(this IJob job)
        {
            if (job == null)
            {
                throw new ArgumentNullException("job", "The job cannot be null.");
            }

            IMediaContextContainer mediaContextContainer = job as IMediaContextContainer;
            MediaContextBase       context = null;

            if (mediaContextContainer != null)
            {
                context = mediaContextContainer.GetMediaContext();
            }

            return(context);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;System.Collections.Generic.IEnumerable&lt;AssetFileMetadata&gt;&gt;"/> instance to retrieve the <paramref name="asset"/> metadata.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance from where to get the metadata.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;System.Collections.Generic.IEnumerable&lt;AssetFileMetadata&gt;&gt;"/> instance to retrieve the <paramref name="asset"/> metadata.</returns>
        public static async Task <IEnumerable <AssetFileMetadata> > GetMetadataAsync(this IAsset asset, CancellationToken cancellationToken)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            MediaContextBase context = asset.GetMediaContext();

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Read, AssetBaseCollectionExtensions.DefaultAccessPolicyDuration).ConfigureAwait(false);

            IEnumerable <AssetFileMetadata> assetMetadata = await asset.GetMetadataAsync(sasLocator, cancellationToken).ConfigureAwait(false);

            await sasLocator.DeleteAsync().ConfigureAwait(false);

            return(assetMetadata);
        }
        /// <summary>
        /// Decrypts the configuration string.
        /// </summary>
        /// <param name="cloudMediaContext">The cloud media context.</param>
        /// <param name="encryptionKeyId">The encryption key id.</param>
        /// <param name="initializationVector">The initialization vector.</param>
        /// <param name="encryptedConfiguration">The encrypted configuration.</param>
        /// <returns>The decrypted configuration.</returns>
        internal static string DecryptConfigurationString(MediaContextBase cloudMediaContext, string encryptionKeyId, string initializationVector, string encryptedConfiguration)
        {
            if (cloudMediaContext == null)
            {
                throw new ArgumentNullException("cloudMediaContext");
            }

            if (string.IsNullOrEmpty(encryptionKeyId))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, StringTable.ErrorArgCannotBeNullOrEmpty, "encryption key identifier"), "encryptionKeyId");
            }

            if (string.IsNullOrEmpty(initializationVector))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, StringTable.ErrorArgCannotBeNullOrEmpty, "initialization vector"), "initializationVector");
            }

            if (string.IsNullOrEmpty(encryptedConfiguration))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, StringTable.ErrorArgCannotBeNullOrEmpty, "encrypted configuration"), "encryptedConfiguration");
            }

            string returnValue;
            Guid keyId = EncryptionUtils.GetKeyIdAsGuid(encryptionKeyId);

            byte[] iv = Convert.FromBase64String(initializationVector);

            IContentKey configKey = cloudMediaContext.ContentKeys.Where(c => c.Id == encryptionKeyId).Single();
            byte[] contentKey = configKey.GetClearKeyValue();

            using (ConfigurationEncryption configEnc = new ConfigurationEncryption(keyId, contentKey, iv))
            {
                returnValue = configEnc.Decrypt(encryptedConfiguration);
            }

            return returnValue;
        }
 internal ChannelMetricsCollection(MediaContextBase cloudMediaContext)
 {
     MediaContext = cloudMediaContext;
 }
Ejemplo n.º 40
0
        private static void AddOpenRestrictedAuthorizationPolicy(MediaContextBase context, IContentKey contentKey)
        {
            // Create ContentKeyAuthorizationPolicy with Open restrictions and create authorization policy
            IContentKeyAuthorizationPolicy policy = context.ContentKeyAuthorizationPolicies.CreateAsync("Open Authorization Policy").Result;
            List<ContentKeyAuthorizationPolicyRestriction> restrictions = new List<ContentKeyAuthorizationPolicyRestriction>
                {
                    new ContentKeyAuthorizationPolicyRestriction
                    {
                        Name = "Open Authorization Policy",
                        KeyRestrictionType = (int)ContentKeyRestrictionType.Open,
                        Requirements = null // no requirements needed
                    }
                };
            IContentKeyAuthorizationPolicyOption policyOption = context.ContentKeyAuthorizationPolicyOptions.Create("Option", ContentKeyDeliveryType.BaselineHttp, restrictions, string.Empty);

            policy.Options.Add(policyOption);

            // Add ContentKeyAutorizationPolicy to ContentKey
            contentKey.AuthorizationPolicyId = policy.Id;
            IContentKey updatedKey = contentKey.UpdateAsync().Result;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentKeyCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
 internal ContentKeyCollection(MediaContextBase cloudMediaContext)
     : base(cloudMediaContext)
 {
 }
Ejemplo n.º 42
0
        private static void CreateAssetDeliveryPolicy(MediaContextBase context, IAsset asset, IContentKey key)
        {
            Uri keyAcquisitionUri = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp);

            string envelopeEncryptionIV = Convert.ToBase64String(GetRandomBuffer(16));

            // The following policy configuration specifies:
            //   key url that will have KID=<Guid> appended to the envelope and
            //   the Initialization Vector (IV) to use for the envelope encryption.
            Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration = new Dictionary<AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, keyAcquisitionUri.ToString() },
                { AssetDeliveryPolicyConfigurationKey.EnvelopeEncryptionIVAsBase64, envelopeEncryptionIV }
            };

            IAssetDeliveryPolicy assetDeliveryPolicy = context.AssetDeliveryPolicies.Create(
                "AssetDeliveryPolicy",
                AssetDeliveryPolicyType.DynamicEnvelopeEncryption,
                AssetDeliveryProtocol.SmoothStreaming | AssetDeliveryProtocol.HLS | AssetDeliveryProtocol.Dash,
                assetDeliveryPolicyConfiguration);

            // Add AssetDelivery Policy to the asset
            asset.DeliveryPolicies.Add(assetDeliveryPolicy);
        }
 public AccessPolicyFactoryBase(TimeSpan duration, AccessPermissions permissions)
 {
     mediaContext = new CloudMediaContext("videolibraryprototype", "9Dg80l+1mdAgou+O9/bzahxBzaYnIlod85dMdJm7908=");
     this.duration = duration;
     this.permissions = permissions;
 }
Ejemplo n.º 44
0
        private static IContentKey CreateEnvelopeTypeContentKey(MediaContextBase context, IAsset asset)
        {
            // Create envelope encryption content key
            Guid keyId = Guid.NewGuid();
            byte[] contentKey = GetRandomBuffer(16);

            IContentKey key = context.ContentKeys.Create(keyId, contentKey, "AES Content Key", ContentKeyType.EnvelopeEncryption);

            // Associate the key with the asset.
            asset.ContentKeys.Add(key);

            return key;
        }
        private Uri CreateAzureMediaServicesEndPoint(Uri azureMediaServicesEndpoint, MediaContextBase mediaContext)
        {
            string cacheKey = string.Format(
                "{0},{1}",
                mediaContext.Credentials.ClientId,
                azureMediaServicesEndpoint.ToString());

            return (_endpointCache.GetOrAdd(
                cacheKey,
                () => GetAccountApiEndpoint(_dataServiceAdapter,_serviceVersionAdapter, azureMediaServicesEndpoint, _userAgentAdapter,CreateClientRequestIdAdapter()),
                () => mediaContext.Credentials.TokenExpiration));
        }
 public virtual void SetMediaContext(MediaContextBase value)
 {
     _mediaContextBase = value;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentKeyCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
 internal ContentKeyCollection(MediaContextBase cloudMediaContext)
     : base(cloudMediaContext)
 {
     this.ContentKeyQueryable = this.MediaContext.MediaServicesClassFactory.CreateDataServiceContext().CreateQuery<ContentKeyData>(ContentKeySet);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetFileCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The cloud media context.</param>
 internal AssetFileCollection(MediaContextBase cloudMediaContext)
     : base(cloudMediaContext)
 {
     this._assetFileQuery = new Lazy<IQueryable<IAssetFile>>(() => cloudMediaContext.MediaServicesClassFactory.CreateDataServiceContext().CreateQuery<AssetFileData>(FileSet));
 }
 internal StreamingEndPointRequestLogCollection(MediaContextBase cloudMediaContext)
 {
     MediaContext = cloudMediaContext;
 }
        /// <summary>
        /// Creates a RandomAccountSelectionStrategy instance using all of storage account names found in the MediaContextBase.StorageAccounts collection.
        /// </summary>
        /// <param name="mediaContextBase">MediaContextBase to use to query the storage account names from.</param>
        /// <returns>A new RandomAccountSelectionStrategy instance.</returns>
        public static RandomAccountSelectionStrategy FromAccounts(MediaContextBase mediaContextBase)
        {
            string[] storageAccountNames = mediaContextBase.StorageAccounts.ToList().Select(c => c.Name).ToArray();

            return new RandomAccountSelectionStrategy(storageAccountNames);
        }
        private Uri CreateAzureMediaServicesEndPoint(Uri azureMediaServicesEndpoint, MediaContextBase mediaContext)
        {
            string cacheKey = string.Format(
                "{0},{1}",
                mediaContext.TokenProvider.MediaServicesAccountName,
                azureMediaServicesEndpoint.ToString());

            return (_endpointCache.GetOrAdd(
                cacheKey,
                () => GetAccountApiEndpoint(_dataServiceAdapter, _serviceVersionAdapter, azureMediaServicesEndpoint, _userAgentAdapter, CreateClientRequestIdAdapter()),
                () => mediaContext.TokenProvider.GetAccessToken().Item2.DateTime));
        }
 private static Task<IAsset> CreateEmptyAsset(MediaContextBase context, string assetName, AssetCreationOptions assetCreationOptions)
 {
     return context.Assets.CreateAsync(assetName, assetCreationOptions, CancellationToken.None);
 }