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));
                    }
                }
            }));
        }
        internal virtual void Refresh()
        {
            Uri uri = new Uri(string.Format(CultureInfo.InvariantCulture, "/{0}('{1}')", EntitySetName, Id), UriKind.Relative);
            IMediaDataServiceContext dataContext = GetMediaContext().MediaServicesClassFactory.CreateDataServiceContext();

            dataContext.AttachTo(EntitySetName, this, Guid.NewGuid().ToString());

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

            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            retryPolicy.ExecuteAction(() => dataContext.Execute <T>(uri)).Single();
        }
        protected IOperation SendOperation(Uri uri, params OperationParameter[] operationParameters)
        {
            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(new OperationData
                {
                    ErrorCode = null,
                    ErrorMessage = null,
                    State = OperationState.Succeeded.ToString(),
                    Id = null
                });
            }

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

            return(new OperationData
            {
                ErrorCode = null,
                ErrorMessage = null,
                State = OperationState.InProgress.ToString(),
                Id = operationId
            });
        }
Ejemplo n.º 4
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);
        }
        /// <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>
        /// 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());
        }
Ejemplo n.º 7
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>
        /// 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);
        }
Ejemplo n.º 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;
            }));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the clear key value.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;byte[]&gt;.</returns>
        public Task <byte[]> GetClearKeyValueAsync()
        {
            // 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)
                {
                    Uri uriRebindContentKey = new Uri(string.Format(CultureInfo.InvariantCulture, "/RebindContentKey?id='{0}'&x509Certificate=''", this.Id), 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;
            }));
        }