Example #1
0
        /// <summary>
        /// Submits asynchronously.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task <IJob> SubmitAsync()
        {
            if (!string.IsNullOrWhiteSpace(this.Id))
            {
                // The job was already submitted.
                throw new InvalidOperationException(StringTable.InvalidOperationSubmitForSubmittedJob);
            }

            IMediaDataServiceContext dataContext = this.GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();


            this.InnerSubmit(dataContext);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(SaveChangesOptions.Batch, this))
                   .ContinueWith(
                       t =>
            {
                t.ThrowIfFaulted();
                JobData data = (JobData)t.Result.AsyncState;
                data.Refresh();
                return (IJob)data;
            }, TaskContinuationOptions.ExecuteSynchronously));
        }
        /// <summary>
        /// Asynchronously saves this <see cref="IJobTemplate"/> when created from a copy of an existing <see cref="IJobTemplate"/>.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task SaveAsync()
        {
            if (!string.IsNullOrWhiteSpace(this.Id))
            {
                // The job template was already saved, and there is no current support to update it.
                throw new InvalidOperationException(StringTable.InvalidOperationSaveForSavedJobTemplate);
            }

            IMediaDataServiceContext dataContext = this.GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            this.InnerSave(dataContext);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(SaveChangesOptions.Batch, this))
                   .ContinueWith(
                       t =>
            {
                t.ThrowIfFaulted();

                JobTemplateData data = (JobTemplateData)t.Result.AsyncState;

                LoadProperty(dataContext, data, TaskTemplatesPropertyName);
            }));
        }
Example #3
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);
        }
Example #4
0
        private Task <IIngestManifestAsset> CreateAsync(IIngestManifest ingestManifest, IAsset asset, CancellationToken token, Action <IngestManifestAssetData> continueWith)
        {
            IngestManifestCollection.VerifyManifest(ingestManifest);

            IMediaDataServiceContext dataContext = MediaContext.MediaServicesClassFactory.CreateDataServiceContext();
            var data = new IngestManifestAssetData
            {
                ParentIngestManifestId = ingestManifest.Id
            };


            dataContext.AddObject(IngestManifestAssetCollection.EntitySet, data);
            dataContext.AttachTo(AssetCollection.AssetSet, asset);
            dataContext.SetLink(data, "Asset", asset);

            MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy();

            Task <IIngestManifestAsset> task = retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(data))
                                               .ContinueWith <IIngestManifestAsset>(t =>
            {
                t.ThrowIfFaulted();
                token.ThrowIfCancellationRequested();
                IngestManifestAssetData ingestManifestAsset = (IngestManifestAssetData)t.Result.AsyncState;
                continueWith(ingestManifestAsset);
                return(ingestManifestAsset);
            }, TaskContinuationOptions.ExecuteSynchronously);

            return(task);
        }
        /// <summary>
        /// Asynchronously creates an <see cref="IContentKeyAuthorizationPolicyOption"/> with the provided name and permissions, valid for the provided duration.
        /// </summary>
        /// <param name="name">Specifies a friendly name for the PolicyOption.</param>
        /// <param name="deliveryType">Delivery method of the content key to the client.</param>
        /// <param name="restrictions">Authorization restrictions.</param>
        /// <param name="keyDeliveryConfiguration">Xml data, specific to the key delivery type that defines how the key is delivered to the client.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;IContentKeyAuthorizationPolicyOption&gt;.</returns>
        public Task <IContentKeyAuthorizationPolicyOption> CreateAsync(
            string name,
            ContentKeyDeliveryType deliveryType,
            List <ContentKeyAuthorizationPolicyRestriction> restrictions,
            string keyDeliveryConfiguration)
        {
            IMediaDataServiceContext dataContext = this.MediaContext.MediaServicesClassFactory.CreateDataServiceContext();
            var policyOption = new ContentKeyAuthorizationPolicyOptionData
            {
                Name                     = name,
                Restrictions             = restrictions,
                KeyDeliveryConfiguration = keyDeliveryConfiguration
            };

            ((IContentKeyAuthorizationPolicyOption)policyOption).KeyDeliveryType = deliveryType;

            policyOption.SetMediaContext(this.MediaContext);
            dataContext.AddObject(ContentKeyAuthorizationPolicyOptionSet, policyOption);

            MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(policyOption))
                   .ContinueWith <IContentKeyAuthorizationPolicyOption>(
                       t =>
            {
                t.ThrowIfFaulted();

                return (ContentKeyAuthorizationPolicyOptionData)t.Result.AsyncState;
            },
                       TaskContinuationOptions.ExecuteSynchronously));
        }
        /// <summary>
        /// Creates a notification endpoint asynchronously
        /// </summary>
        /// <param name="name">Name of notification endpoint</param>
        /// <param name="endPointType">Notification endpoint type</param>
        /// <param name="endPointAddress">Notification endpoint address</param>
        /// <returns>Task of creating notification endpoint.</returns>
        public Task <INotificationEndPoint> CreateAsync(string name, NotificationEndPointType endPointType,
                                                        string endPointAddress)
        {
            NotificationEndPoint notificationEndPoint = new NotificationEndPoint
            {
                Name            = name,
                EndPointType    = (int)endPointType,
                EndPointAddress = endPointAddress
            };

            notificationEndPoint.SetMediaContext(MediaContext);
            IMediaDataServiceContext dataContext = MediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AddObject(NotificationEndPoints, notificationEndPoint);

            MediaRetryPolicy retryPolicy =
                this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(
                       () => dataContext.SaveChangesAsync(notificationEndPoint))
                   .ContinueWith <INotificationEndPoint>(
                       t =>
            {
                t.ThrowIfFaulted();

                return (NotificationEndPoint)t.Result.AsyncState;
            },
                       TaskContinuationOptions.ExecuteSynchronously));
        }
Example #7
0
        /// <summary>
        /// Uploads the destinationPath with given path asynchronously
        /// </summary>
        /// <param name="path">The path of a destinationPath to upload</param>
        /// <param name="blobTransferClient">The <see cref="BlobTransferClient"/> which is used to upload files.</param>
        /// <param name="locator">An asset <see cref="ILocator"/> which defines permissions associated with the Asset.</param>
        /// <param name="token">A <see cref="CancellationToken"/> to use for canceling upload operation.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task UploadAsync(string path, BlobTransferClient blobTransferClient, ILocator locator, CancellationToken token)
        {
            if (blobTransferClient == null)
            {
                throw new ArgumentNullException("blobTransferClient");
            }

            if (locator == null)
            {
                throw new ArgumentNullException("locator");
            }

            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            ValidateFileName(path);

            IContentKey          contentKeyData       = null;
            FileEncryption       fileEncryption       = null;
            AssetCreationOptions assetCreationOptions = this.Asset.Options;

            if (assetCreationOptions.HasFlag(AssetCreationOptions.StorageEncrypted))
            {
                contentKeyData = this.Asset.ContentKeys.Where(c => c.ContentKeyType == ContentKeyType.StorageEncryption).FirstOrDefault();
                if (contentKeyData == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, StringTable.StorageEncryptionContentKeyIsMissing, this.Asset.Id));
                }

                fileEncryption = new FileEncryption(contentKeyData.GetClearKeyValue(), EncryptionUtils.GetKeyIdAsGuid(contentKeyData.Id));
            }

            EventHandler <BlobTransferProgressChangedEventArgs> handler = (s, e) => OnUploadProgressChanged(path, e);

            blobTransferClient.TransferProgressChanged += handler;

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetBlobStorageClientRetryPolicy();

            return(blobTransferClient.UploadBlob(
                       new Uri(locator.BaseUri),
                       path,
                       null,
                       fileEncryption,
                       token,
                       retryPolicy.AsAzureStorageClientRetryPolicy(),
                       () => locator.ContentAccessComponent)
                   .ContinueWith(
                       ts =>
            {
                blobTransferClient.TransferProgressChanged -= handler;
                this.PostUploadAction(ts, path, fileEncryption, assetCreationOptions, token);
            }));
        }
        /// <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);
        }
Example #9
0
        /// <summary>
        /// Gets the encrypted key value.
        /// </summary>
        /// <param name="certToEncryptTo">The cert to use.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;byte[]&gt;.</returns>
        public Task <byte[]> GetEncryptedKeyValueAsync(X509Certificate2 certToEncryptTo)
        {
            if (certToEncryptTo == null)
            {
                throw new ArgumentNullException("certToEncryptTo");
            }

            // Start a new task here because the ExecutAsync on the DataContext returns a Task<string>
            return(Task.Factory.StartNew <byte[]>(() =>
            {
                byte[] returnValue = null;

                if (this.GetMediaContext() != null)
                {
                    string certToSend = Convert.ToBase64String(certToEncryptTo.Export(X509ContentType.Cert));
                    certToSend = HttpUtility.UrlEncode(certToSend);

                    Uri uriRebindContentKey = new Uri(string.Format(CultureInfo.InvariantCulture, "/RebindContentKey?id='{0}'&x509Certificate='{1}'", this.Id, certToSend), UriKind.Relative);
                    IMediaDataServiceContext dataContext = this.GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

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

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

                    string reboundContentKey = results.Single();

                    returnValue = Convert.FromBase64String(reboundContentKey);
                }

                return returnValue;
            }));
        }
Example #10
0
        /// <summary>
        /// Creates the manifest async.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="storageAccountName">The name of storage account </param>
        /// <returns><see cref="Task"/> of type <see cref="IIngestManifest"/></returns>
        public Task <IIngestManifest> CreateAsync(string name, string storageAccountName)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (storageAccountName == null)
            {
                throw new ArgumentNullException("storageAccountName");
            }

            IngestManifestData ingestManifestData = new IngestManifestData
            {
                Name = name,
                StorageAccountName = storageAccountName
            };


            ingestManifestData.SetMediaContext(this.MediaContext);
            IMediaDataServiceContext dataContext = this.MediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AddObject(EntitySet, ingestManifestData);

            MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(ingestManifestData))
                   .ContinueWith <IIngestManifest>(
                       t =>
            {
                t.ThrowIfFaulted();
                IngestManifestData data = (IngestManifestData)t.Result.AsyncState;
                return data;
            }));
        }
Example #11
0
        /// <summary>
        /// Sends delete operation to the service and returns. Use Operations collection to get operation's status.
        /// </summary>
        /// <returns>Operation info that can be used to track the operation.</returns>
        public IOperation SendDeleteOperation()
        {
            if (string.IsNullOrWhiteSpace(Id))
            {
                throw new InvalidOperationException(Resources.ErrorEntityWithoutId);
            }

            IMediaDataServiceContext dataContext = GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AttachTo(EntitySetName, this);
            dataContext.DeleteObject(this);

            MediaRetryPolicy retryPolicy = GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            var response = retryPolicy.ExecuteAction(() => dataContext.SaveChanges());

            string operationId = response.Single().Headers[StreamingConstants.OperationIdHeader];

            var result = new OperationData
            {
                ErrorCode    = null,
                ErrorMessage = null,
                Id           = operationId,
                State        = OperationState.InProgress.ToString(),
            };

            return(result);
        }
Example #12
0
        private Uri GetAccountApiEndpoint(OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter versionAdapter, Uri apiServer, UserAgentAdapter userAgentAdapter, ClientRequestIdAdapter clientRequestIdAdapter)
        {
            MediaRetryPolicy retryPolicy = new MediaRetryPolicy(
                GetWebRequestTransientErrorDetectionStrategy(),
                RetryStrategyFactory.DefaultStrategy());

            Uri apiEndpoint = null;

            retryPolicy.ExecuteAction(
                () =>
            {
                HttpWebRequest request    = (HttpWebRequest)WebRequest.Create(apiServer);
                request.AllowAutoRedirect = false;
                dataServiceAdapter.AddAccessTokenToRequest(request);
                versionAdapter.AddVersionToRequest(request);
                userAgentAdapter.AddUserAgentToRequest(request);
                clientRequestIdAdapter.AddClientRequestId(request);

                using (WebResponse response = request.GetResponse())
                {
                    apiEndpoint = GetAccountApiEndpointFromResponse(response);
                }
            }
                );

            return(apiEndpoint);
        }
        /// <summary>
        /// Asynchronously creates an <see cref="IAssetDeliveryPolicy"/>.
        /// </summary>
        /// <param name="name">Friendly name for the policy.</param>
        /// <param name="policyType">Type of the policy.</param>
        /// <param name="deliveryProtocol">Delivery protocol.</param>
        /// <param name="configuration">Configuration.</param>
        /// <returns>An <see cref="IAssetDeliveryPolicy"/>.</returns>
        public Task <IAssetDeliveryPolicy> CreateAsync(
            string name,
            AssetDeliveryPolicyType policyType,
            AssetDeliveryProtocol deliveryProtocol,
            Dictionary <AssetDeliveryPolicyConfigurationKey, string> configuration)
        {
            IMediaDataServiceContext dataContext = this.MediaContext.MediaServicesClassFactory.CreateDataServiceContext();
            var policy = new AssetDeliveryPolicyData
            {
                Name = name,
            };

            ((IAssetDeliveryPolicy)policy).AssetDeliveryPolicyType    = policyType;
            ((IAssetDeliveryPolicy)policy).AssetDeliveryProtocol      = deliveryProtocol;
            ((IAssetDeliveryPolicy)policy).AssetDeliveryConfiguration = configuration;

            policy.SetMediaContext(this.MediaContext);
            dataContext.AddObject(DeliveryPolicySet, policy);

            MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(policy))
                   .ContinueWith <IAssetDeliveryPolicy>(
                       t =>
            {
                t.ThrowIfFaulted();

                return (AssetDeliveryPolicyData)t.Result.AsyncState;
            },
                       TaskContinuationOptions.ExecuteSynchronously));
        }
        /// <summary>
        /// Asynchronously creates new StreamingFilter.
        /// </summary>
        /// <param name="name">filter name</param>
        /// <param name="timeRange">filter boundaries</param>
        /// <param name="trackConditions">filter track conditions</param>
        /// <returns>The task to create the filter.</returns>
        public Task <IStreamingAssetFilter> CreateAsync(string name, PresentationTimeRange timeRange, IList <FilterTrackSelectStatement> trackConditions)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            AssetFilterData filter = new AssetFilterData(_parentAsset.Id, name, timeRange, trackConditions);

            filter.SetMediaContext(MediaContext);

            IMediaDataServiceContext dataContext = MediaContext.MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AddObject(AssetFilterSet, filter);

            MediaRetryPolicy retryPolicy = MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync(() => dataContext.SaveChangesAsync(filter))
                   .ContinueWith <IStreamingAssetFilter>(
                       t =>
            {
                t.ThrowIfFaulted();
                return (AssetFilterData)t.Result.AsyncState;
            },
                       TaskContinuationOptions.ExecuteSynchronously));
        }
Example #15
0
        /// <summary>
        /// Asynchronously revokes the specified Locator, denying any access it provided.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;ILocator&gt;.</returns>
        public Task DeleteAsync()
        {
            LocatorBaseCollection.VerifyLocator(this);

            IMediaDataServiceContext dataContext = this.GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AttachTo(LocatorBaseCollection.LocatorSet, this);
            dataContext.DeleteObject(this);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(this))
                   .ContinueWith(
                       t =>
            {
                t.ThrowIfFaulted();

                LocatorData data = (LocatorData)t.Result.AsyncState;

                if (GetMediaContext() != null)
                {
                    var cloudContextAsset = (AssetData)GetMediaContext().Assets.Where(c => c.Id == data.AssetId).FirstOrDefault();
                    if (cloudContextAsset != null)
                    {
                        cloudContextAsset.InvalidateLocatorsCollection();
                    }
                }

                if (data.Asset != null)
                {
                    data.Asset.InvalidateLocatorsCollection();
                }
            },
                       TaskContinuationOptions.ExecuteSynchronously));
        }
Example #16
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);
        }
        protected Task ExecuteActionAsync(Uri uri, TimeSpan pollInterval, params OperationParameter[] operationParameters)
        {
            return(Task.Factory.StartNew(() =>
            {
                if (GetMediaContext() != null)
                {
                    IMediaDataServiceContext dataContext = GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

                    MediaRetryPolicy retryPolicy = GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

                    var response = retryPolicy.ExecuteAction(() => dataContext.Execute(uri, "POST", operationParameters));

                    if (response.StatusCode == (int)HttpStatusCode.NotFound)
                    {
                        throw new InvalidOperationException("Entity not found");
                    }

                    if (response.StatusCode >= 400)
                    {
                        var code = (HttpStatusCode)response.StatusCode;
                        throw new InvalidOperationException(code.ToString());
                    }

                    if (response.StatusCode != (int)HttpStatusCode.Accepted) // synchronous complete
                    {
                        Refresh();
                        return;
                    }

                    string operationId = response.Headers[StreamingConstants.OperationIdHeader];

                    var operation = AsyncHelper.WaitOperationCompletion(
                        GetMediaContext(),
                        operationId,
                        pollInterval);

                    Refresh();

                    string messageFormat = Resources.ErrorOperationFailedFormat;

                    switch (operation.State)
                    {
                    case OperationState.Succeeded:
                        return;

                    case OperationState.Failed:
                        throw new InvalidOperationException(
                            string.Format(CultureInfo.CurrentCulture, messageFormat, uri.OriginalString, Resources.Failed, operationId));

                    default:
                        throw new InvalidOperationException(
                            string.Format(CultureInfo.CurrentCulture, messageFormat, uri.OriginalString, operation.State, operationId));
                    }
                }
            }));
        }
Example #18
0
        /// <summary>
        /// Delete this instance of notification endpoint object in asynchronous mode.
        /// </summary>
        /// <returns>Task of deleting the notification endpoint.</returns>
        public Task DeleteAsync()
        {
            IMediaDataServiceContext dataContext = GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();
            dataContext.AttachTo(NotificationEndPointCollection.NotificationEndPoints, this);
            dataContext.DeleteObject(this);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy();

            return retryPolicy.ExecuteAsync<IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(this));
        }
        /// <summary>
        /// Creates retry policy for working with Azure blob storage.
        /// This overrides the GetBlobStorageClientRetryPolicy defined in AzureMediaServicesClassFactory
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetBlobStorageClientRetryPolicy()
        {
            //overriding the retry policy to have 2 retry attempts for working with Azure blob storage.
            //Also using SaveChangesRetry Polciy here.
            var retryPolicy = new MediaRetryPolicy(
                GetSaveChangesErrorDetectionStrategy(),
                ConnectionBlobMaxAttempts);

            return retryPolicy;
        }
Example #20
0
        /// <summary>
        /// Removes the item.
        /// </summary>
        /// <param name="index">The index.</param>
        protected override void RemoveItem(int index)
        {
            this._dataContext.DeleteLink(this._parent, this._propertyName, this[index]);

            MediaRetryPolicy retryPolicy = this._parent.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy();

            retryPolicy.ExecuteAction <IMediaDataServiceResponse>(() => _dataContext.SaveChanges());

            base.RemoveItem(index);
        }
Example #21
0
        /// <summary>
        /// Creates retry policy for working with Azure blob storage.
        /// This overrides the GetBlobStorageClientRetryPolicy defined in AzureMediaServicesClassFactory
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetBlobStorageClientRetryPolicy()
        {
            //overriding the retry policy to have 2 retry attempts for working with Azure blob storage.
            //Also using SaveChangesRetry Polciy here.
            var retryPolicy = new MediaRetryPolicy(
                GetSaveChangesErrorDetectionStrategy(),
                ConnectionBlobMaxAttempts);

            return(retryPolicy);
        }
        /// <summary>
        /// Creates the manifest asset file asynchronously.
        /// </summary>
        /// <param name="ingestManifestAsset">The parent manifest asset.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="token"><see cref="CancellationToken"/></param>
        /// <returns><see cref="Task"/>of type <see cref="IIngestManifestFile"/></returns>
        public Task <IIngestManifestFile> CreateAsync(IIngestManifestAsset ingestManifestAsset, string filePath, CancellationToken token)
        {
            if (ingestManifestAsset == null)
            {
                throw new ArgumentNullException("ingestManifestAsset");
            }

            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, StringTable.ErrorCreatingIngestManifestFileEmptyFilePath));
            }

            AssetCreationOptions options = ingestManifestAsset.Asset.Options;

            Task <IIngestManifestFile> rootTask = new Task <IIngestManifestFile>(() =>
            {
                token.ThrowIfCancellationRequested();

                IngestManifestAssetCollection.VerifyManifestAsset(ingestManifestAsset);

                IMediaDataServiceContext dataContext = this.MediaContext.MediaServicesClassFactory.CreateDataServiceContext();

                // Set a MIME type based on the extension of the file name
                string mimeType = AssetFileData.GetMimeType(filePath);

                IngestManifestFileData data = new IngestManifestFileData
                {
                    Name     = Path.GetFileName(filePath),
                    MimeType = mimeType,
                    ParentIngestManifestId      = ingestManifestAsset.ParentIngestManifestId,
                    ParentIngestManifestAssetId = ingestManifestAsset.Id,
                    Path = filePath,
                };

                SetEncryptionSettings(ingestManifestAsset, options, data);

                dataContext.AddObject(EntitySet, data);

                MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

                Task <IIngestManifestFile> task = retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(data))
                                                  .ContinueWith <IIngestManifestFile>(t =>
                {
                    t.ThrowIfFaulted();
                    token.ThrowIfCancellationRequested();
                    IngestManifestFileData ingestManifestFile = (IngestManifestFileData)t.Result.AsyncState;
                    return(ingestManifestFile);
                });

                return(task.Result);
            });

            rootTask.Start();
            return(rootTask);
        }
        /// <summary>
        /// Retrieves an operation by its Id.
        /// </summary>
        /// <param name="id">Id of the operation.</param>
        /// <returns>Operation.</returns>
        public IOperation GetOperation(string id)
        {
            Uri uri = new Uri(string.Format(CultureInfo.InvariantCulture, "/{0}('{1}')", OperationSet, id), UriKind.Relative);
            IMediaDataServiceContext dataContext = this._cloudMediaContext.MediaServicesClassFactory.CreateDataServiceContext();

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

            IOperation operation = retryPolicy.ExecuteAction <IEnumerable <OperationData> >(() => dataContext.Execute <OperationData>(uri)).SingleOrDefault();

            return(operation);
        }
Example #24
0
        /// <summary>
        /// Asynchronously deletes this instance.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task DeleteAsync()
        {
            IMediaDataServiceContext dataContext = this.GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AttachTo(FileSet, this);
            dataContext.DeleteObject(this);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy();

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(this)));
        }
Example #25
0
        /// <summary>
        /// Asynchronously deletes this instance.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task <IMediaDataServiceResponse> DeleteAsync()
        {
            IMediaDataServiceContext dataContext = this.GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AttachTo(ContentKeyAuthorizationPolicyOptionCollection.ContentKeyAuthorizationPolicyOptionSet, this);
            dataContext.DeleteObject(this);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(this)));
        }
Example #26
0
        /// <summary>
        /// Creates retry policy for saving changes in Media Services REST layer.
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetSaveChangesRetryPolicy()
        {
            var retryPolicy = new MediaRetryPolicy(
                GetSaveChangesErrorDetectionStrategy(),
                retryCount: 5,
                minBackoff: TimeSpan.FromMilliseconds(10),
                maxBackoff: TimeSpan.FromMilliseconds(10000),
                deltaBackoff: TimeSpan.FromMilliseconds(50));

            return(retryPolicy);
        }
        /// <summary>
        /// Asynchronously downloads the represented file to the specified destination path.
        /// </summary>
        /// <param name="destinationPath">The path to download the file to.</param>
        /// <param name="blobTransferClient">The <see cref="BlobTransferClient"/> which is used to download files.</param>
        /// <param name="locator">An asset <see cref="ILocator"/> which defines permissions associated with the Asset.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A function delegate that returns the future result to be available through the Task.
        /// </returns>
        public Task DownloadAsync(string destinationPath, BlobTransferClient blobTransferClient, ILocator locator, CancellationToken cancellationToken)
        {
            if (this.IsFragmented())
            {
                throw new NotSupportedException(StringTable.NotSupportedFragblobDownload);
            }

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetBlobStorageClientRetryPolicy();

            return(this.DownloadToFileAsync(destinationPath, blobTransferClient, locator, retryPolicy.AsAzureStorageClientRetryPolicy(), cancellationToken));
        }
        /// <summary>
        /// Creates retry policy for saving changes in Media Services REST layer.
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetSaveChangesRetryPolicy()
        {
            var retryPolicy = new MediaRetryPolicy(
                GetSaveChangesErrorDetectionStrategy(),
                retryCount: 5,
                minBackoff: TimeSpan.FromMilliseconds(10),
                maxBackoff: TimeSpan.FromMilliseconds(10000),
                deltaBackoff: TimeSpan.FromMilliseconds(50));

            return retryPolicy;
        }
        /// <summary>
        /// Update the notification endpoint object in asynchronous mode.
        /// </summary>
        /// <returns>Task of updating the notification endpoint.</returns>
        public Task UpdateAsync()
        {
            IMediaDataServiceContext dataContext = GetMediaContext().MediaServicesClassFactory.CreateCustomDataServiceContext();

            dataContext.AttachTo(NotificationEndPointCollectionV212.NotificationEndPoints, this);
            dataContext.UpdateObject(this);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(this)));
        }
        /// <summary>
        /// Deletes the manifest asset file asynchronously.
        /// </summary>
        /// <returns><see cref="Task"/></returns>
        public Task DeleteAsync()
        {
            IMediaDataServiceContext dataContext = GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AttachTo(IngestManifestFileCollection.EntitySet, this);
            dataContext.DeleteObject(this);

            MediaRetryPolicy retryPolicy = this.GetMediaContext().MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter);

            return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(this)));
        }
Example #31
0
        /// <summary>
        /// Creates retry policy for working with Azure blob storage.
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetBlobStorageClientRetryPolicy()
        {
            var retryPolicy = new MediaRetryPolicy(
                GetStorageTransientErrorDetectionStrategy(),
                retryCount: ConnectionRetryMaxAttempts,
                minBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum),
                maxBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum * 16),
                deltaBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum));

            return(retryPolicy);
        }
Example #32
0
        /// <summary>
        /// Creates retry policy for querying Media Services REST layer.
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetQueryRetryPolicy(IRetryPolicyAdapter adapter)
        {
            var retryPolicy = new MediaRetryPolicy(
                GetQueryErrorDetectionStrategy(),
                retryCount: ConnectionRetryMaxAttempts,
                minBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum),
                maxBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum * 16),
                deltaBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum));

            retryPolicy.RetryPolicyAdapter = adapter;
            return(retryPolicy);
        }
        /// <summary>
        /// Creates retry policy for saving changes in Media Services REST layer.
        /// This overrides the GetSaveChangesRetryPolicy defined in AzureMediaServicesClassFactory
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetSaveChangesRetryPolicy(IRetryPolicyAdapter adapter)
        {
            //Overriding to create a retrypolicy with a different RetryInitialInterval and retrycount
            //than the default one.Also creating a new custom retrystrategy for adding a new transient
            //type failure in the list of transient exceptions.

            var retryPolicy = new MediaRetryPolicy(
                GetSaveChangesErrorDetectionStrategy(),
                retryCount: ConnectionSaveRetryMaxAttempts,
                initialInterval: TimeSpan.FromMilliseconds(ConnectionRetryInitialInterval),
                increment: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum * 16)
                );
            retryPolicy.RetryPolicyAdapter = adapter;
            return retryPolicy;
        }
        /// <summary>
        /// Creates retry policy for working with Azure blob storage.
        /// </summary>
        /// <returns>Retry policy.</returns>
        public override MediaRetryPolicy GetBlobStorageClientRetryPolicy()
        {
            var retryPolicy = new MediaRetryPolicy(
                GetStorageTransientErrorDetectionStrategy(),
                retryCount: ConnectionRetryMaxAttempts,
                minBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum),
                maxBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum * 16),
                deltaBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum));

            return retryPolicy;
        }
 /// <summary>
 /// Creates retry policy for saving changes in Media Services REST layer.
 /// </summary>
 /// <returns>Retry policy.</returns>
 public override MediaRetryPolicy GetSaveChangesRetryPolicy(IRetryPolicyAdapter adapter)
 {
     var retryPolicy = new MediaRetryPolicy(
         GetSaveChangesErrorDetectionStrategy(),
         retryCount: ConnectionRetryMaxAttempts,
         minBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum),
         maxBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum * 16),
         deltaBackoff: TimeSpan.FromMilliseconds(ConnectionRetrySleepQuantum)
         );
     retryPolicy.RetryPolicyAdapter = adapter;
     return retryPolicy;
 }
        private Uri GetAccountApiEndpoint(OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter versionAdapter, Uri apiServer, UserAgentAdapter userAgentAdapter, IWebRequestAdapter clientRequestIdAdapter)
        {
            MediaRetryPolicy retryPolicy = new MediaRetryPolicy(
                GetWebRequestTransientErrorDetectionStrategy(),
                RetryStrategyFactory.DefaultStrategy());

            Uri apiEndpoint = null;
            retryPolicy.ExecuteAction(
                    () =>
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiServer);
                        request.AllowAutoRedirect = false;
                        dataServiceAdapter.AddAccessTokenToRequest(request);
                        versionAdapter.AddVersionToRequest(request);
                        userAgentAdapter.AddUserAgentToRequest(request);
                        clientRequestIdAdapter.AddClientRequestId(request);

                        using (WebResponse response = request.GetResponse())
                        {
                            apiEndpoint = GetAccountApiEndpointFromResponse(response);
                        }
                    }
                );

            return apiEndpoint;
        }