public void TestCreateNewAzureMediaServiceAsync()
        {
            FakeHttpMessageHandler        fakeHttpHandler;
            MediaServicesManagementClient clientWithHandler = CreateMediaManagementClientWithFakeHttpMessageHandler(out fakeHttpHandler);

            const string responseText =
                @"{""AccountId"":""e26ca098-e363-450d-877c-384ce5a97c72"",
            ""AccountName"":""tmp"",
            ""Subscription"":""d4e66bc8-6ccb-4e49-9ee6-dc6925d5bbdb"",
            ""StatusCode"":201}";

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = new FakeHttpContent(responseText)
            };

            fakeHttpHandler.Send = request => response;

            MediaServicesClient target = new MediaServicesClient(null,
                                                                 clientWithHandler,
                                                                 StorageClient);

            MediaServicesAccountCreateParameters creationRequest = new MediaServicesAccountCreateParameters
            {
                AccountName            = AccountName,
                BlobStorageEndpointUri = new Uri("http://tmp"),
                Region             = "West US",
                StorageAccountKey  = Guid.NewGuid().ToString(),
                StorageAccountName = "test"
            };

            MediaServicesAccountCreateResponse result = target.CreateNewAzureMediaServiceAsync(creationRequest).Result;

            Assert.Equal("tmp", result.Account.AccountName);
        }
        public void TestCreateNewAzureMediaServiceAsyncInvalidAccount()
        {
            FakeHttpMessageHandler        fakeHttpHandler;
            MediaServicesManagementClient clientWithHandler = CreateMediaManagementClientWithFakeHttpMessageHandler(out fakeHttpHandler);

            const string responseText = @"<Error xmlns='http://schemas.microsoft.com/windowsazure' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
                                        <Code>BadRequest</Code>
                                        <Message>Account Creation Request contains an invalid account name.</Message>
                                    </Error>";

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new FakeHttpContent(responseText)
            };

            fakeHttpHandler.Send = request => response;

            MediaServicesClient target = new MediaServicesClient(null,
                                                                 clientWithHandler,
                                                                 StorageClient);

            MediaServicesAccountCreateParameters creationRequest = new MediaServicesAccountCreateParameters
            {
                AccountName            = AccountName,
                BlobStorageEndpointUri = new Uri("http://tmp"),
                Region             = "West US",
                StorageAccountKey  = Guid.NewGuid().ToString(),
                StorageAccountName = "test"
            };

            try
            {
                MediaServicesAccountCreateResponse result = target.CreateNewAzureMediaServiceAsync(creationRequest).Result;
            }
            catch (AggregateException ex)
            {
                CloudException cloudException = ex.Flatten().InnerException as CloudException;
                Assert.NotNull(cloudException);
                Assert.Equal(HttpStatusCode.BadRequest, cloudException.Response.StatusCode);
            }
        }
        public override void ExecuteCmdlet()
        {
            MediaServicesClient = MediaServicesClient ?? new MediaServicesClient(Profile, Profile.Context.Subscription, WriteDebug);

            StorageAccountGetKeysResponse storageKeysResponse = null;
            Uri    storageEndPoint   = null;
            string storageAccountKey = null;

            CatchAggregatedExceptionFlattenAndRethrow(() => { storageKeysResponse = MediaServicesClient.GetStorageServiceKeysAsync(StorageAccountName).Result; });
            storageAccountKey = storageKeysResponse.PrimaryKey;

            StorageAccountGetResponse storageGetResponse = null;

            CatchAggregatedExceptionFlattenAndRethrow(() => { storageGetResponse = MediaServicesClient.GetStorageServicePropertiesAsync(StorageAccountName).Result; });

            if (storageGetResponse.StorageAccount.Properties != null && storageGetResponse.StorageAccount.Properties.Endpoints.Count > 0)
            {
                storageEndPoint = storageGetResponse.StorageAccount.Properties.Endpoints[0];
            }
            else
            {
                throw new Exception(string.Format(Resources.EndPointNotFoundForBlobStorage, Name));
            }

            AccountCreationResult result = null;
            var request = new MediaServicesAccountCreateParameters()
            {
                AccountName            = Name,
                BlobStorageEndpointUri = storageEndPoint,
                Region             = Location,
                StorageAccountKey  = storageAccountKey,
                StorageAccountName = StorageAccountName
            };

            CatchAggregatedExceptionFlattenAndRethrow(() => { result = new AccountCreationResult(MediaServicesClient.CreateNewAzureMediaServiceAsync(request).Result); });
            WriteObject(result, false);
        }
        public void TestCreateNewAzureMediaServiceAsync()
        {
            FakeHttpMessageHandler        fakeHttpHandler;
            MediaServicesManagementClient clientWithHandler = CreateMediaManagementClientWithFakeHttpMessageHandler(out fakeHttpHandler);

            const string responseText = @"<AccountCreationResult xmlns='http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
                                    <AccountId>e26ca098-e363-450d-877c-384ce5a97c72</AccountId>
                                    <AccountName>tmp</AccountName>
                                    <StatusCode>Created</StatusCode>
                                    <Subscription>d4e66bc8-6ccb-4e49-9ee6-dc6925d5bbdb</Subscription>
                                </AccountCreationResult>";

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = new FakeHttpContent(responseText)
            };

            fakeHttpHandler.Send = request => response;

            MediaServicesClient target = new MediaServicesClient(null,
                                                                 clientWithHandler,
                                                                 StorageClient);

            MediaServicesAccountCreateParameters creationRequest = new MediaServicesAccountCreateParameters
            {
                AccountName            = AccountName,
                BlobStorageEndpointUri = new Uri("http://tmp"),
                Region             = "West US",
                StorageAccountKey  = Guid.NewGuid().ToString(),
                StorageAccountName = "test"
            };

            MediaServicesAccountCreateResponse result = target.CreateNewAzureMediaServiceAsync(creationRequest).Result;

            Assert.AreEqual("tmp", result.AccountName);
        }
Example #5
0
        public void NewMediaServiceAccountShouldPassWithValidParameters()
        {
            // Setup
            Mock <IMediaServicesClient> clientMock = new Mock <IMediaServicesClient>();

            const string storageAccountName     = "teststorage";
            const string storageAccountKey      = "key";
            const string accountName            = "testaccount";
            const string region                 = "West US";
            const string blobStorageEndpointUri = "http://awesome.blob.core.windows.net/";

            MediaServicesAccountCreateParameters request = new MediaServicesAccountCreateParameters
            {
                AccountName            = accountName,
                BlobStorageEndpointUri = new Uri(blobStorageEndpointUri),
                Region             = region,
                StorageAccountKey  = storageAccountKey,
                StorageAccountName = storageAccountName
            };

            clientMock.Setup(f => f.CreateNewAzureMediaServiceAsync(It.Is <MediaServicesAccountCreateParameters>(creationRequest => request.AccountName == accountName))).Returns(
                Task.Factory.StartNew(() => new MediaServicesAccountCreateResponse
            {
                Account = new MediaServicesCreatedAccount {
                    AccountId      = Guid.NewGuid().ToString(),
                    AccountName    = request.AccountName,
                    SubscriptionId = Guid.NewGuid().ToString()
                }
            }));


            clientMock.Setup(f => f.GetStorageServiceKeysAsync(storageAccountName)).Returns(
                Task.Factory.StartNew(() => new StorageAccountGetKeysResponse
            {
                PrimaryKey   = storageAccountKey,
                SecondaryKey = storageAccountKey
            }));


            clientMock.Setup(f => f.GetStorageServicePropertiesAsync(storageAccountName)).Returns(Task.Factory.StartNew(() =>
            {
                StorageAccountGetResponse response = new StorageAccountGetResponse
                {
                    StorageAccount = new StorageAccount
                    {
                        Properties = new StorageAccountProperties()
                    }
                };
                response.StorageAccount.Properties.Endpoints.Add(new Uri(blobStorageEndpointUri));
                return(response);
            }));

            // Test
            NewAzureMediaServiceCommand command = new NewAzureMediaServiceCommand
            {
                CommandRuntime      = new MockCommandRuntime(),
                Name                = accountName,
                Location            = region,
                StorageAccountName  = storageAccountName,
                MediaServicesClient = clientMock.Object,
            };

            command.ExecuteCmdlet();
            Assert.AreEqual(1, ((MockCommandRuntime)command.CommandRuntime).OutputPipeline.Count);
            AccountCreationResult accountCreationResult = (AccountCreationResult)((MockCommandRuntime)command.CommandRuntime).OutputPipeline.FirstOrDefault();

            Assert.IsNotNull(accountCreationResult);
            Assert.AreEqual(accountName, accountCreationResult.Name);
        }
Example #6
0
 /// <summary>
 ///     Create new azure media service async.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <returns></returns>
 public Task <MediaServicesAccountCreateResponse> CreateNewAzureMediaServiceAsync(MediaServicesAccountCreateParameters request)
 {
     return(_mediaServicesManagementClient.Accounts.CreateAsync(request));
 }
        /// <summary>
        /// The Create Media Services Account operation creates a new media
        /// services account in Windows Azure.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// Parameters supplied to the Create Media Services Account operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Create Media Services Account operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.MediaServices.Models.MediaServicesAccountCreateResponse> CreateAsync(MediaServicesAccountCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.AccountName == null)
            {
                throw new ArgumentNullException("parameters.AccountName");
            }
            if (parameters.AccountName.Length < 3)
            {
                throw new ArgumentOutOfRangeException("parameters.AccountName");
            }
            if (parameters.AccountName.Length > 24)
            {
                throw new ArgumentOutOfRangeException("parameters.AccountName");
            }
            if (parameters.BlobStorageEndpointUri == null)
            {
                throw new ArgumentNullException("parameters.BlobStorageEndpointUri");
            }
            if (parameters.Region == null)
            {
                throw new ArgumentNullException("parameters.Region");
            }
            if (parameters.Region.Length < 3)
            {
                throw new ArgumentOutOfRangeException("parameters.Region");
            }
            if (parameters.Region.Length > 256)
            {
                throw new ArgumentOutOfRangeException("parameters.Region");
            }
            if (parameters.StorageAccountKey == null)
            {
                throw new ArgumentNullException("parameters.StorageAccountKey");
            }
            if (parameters.StorageAccountKey.Length < 14)
            {
                throw new ArgumentOutOfRangeException("parameters.StorageAccountKey");
            }
            if (parameters.StorageAccountKey.Length > 256)
            {
                throw new ArgumentOutOfRangeException("parameters.StorageAccountKey");
            }
            if (parameters.StorageAccountName == null)
            {
                throw new ArgumentNullException("parameters.StorageAccountName");
            }
            if (parameters.StorageAccountName.Length < 3)
            {
                throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
            }
            if (parameters.StorageAccountName.Length > 24)
            {
                throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
            }
            foreach (char storageAccountNameChar in parameters.StorageAccountName)
            {
                if (char.IsLower(storageAccountNameChar) == false && char.IsDigit(storageAccountNameChar) == false)
                {
                    throw new ArgumentOutOfRangeException("parameters.StorageAccountName");
                }
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/mediaservices/Accounts";

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2011-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string    requestContent = null;
                XDocument requestDoc     = new XDocument();

                XElement accountCreationRequestElement = new XElement(XName.Get("AccountCreationRequest", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
                requestDoc.Add(accountCreationRequestElement);

                XElement accountNameElement = new XElement(XName.Get("AccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
                accountNameElement.Value = parameters.AccountName;
                accountCreationRequestElement.Add(accountNameElement);

                XElement blobStorageEndpointUriElement = new XElement(XName.Get("BlobStorageEndpointUri", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
                blobStorageEndpointUriElement.Value = parameters.BlobStorageEndpointUri.ToString();
                accountCreationRequestElement.Add(blobStorageEndpointUriElement);

                XElement regionElement = new XElement(XName.Get("Region", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
                regionElement.Value = parameters.Region;
                accountCreationRequestElement.Add(regionElement);

                XElement storageAccountKeyElement = new XElement(XName.Get("StorageAccountKey", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
                storageAccountKeyElement.Value = parameters.StorageAccountKey;
                accountCreationRequestElement.Add(storageAccountKeyElement);

                XElement storageAccountNameElement = new XElement(XName.Get("StorageAccountName", "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models"));
                storageAccountNameElement.Value = parameters.StorageAccountName;
                accountCreationRequestElement.Add(storageAccountNameElement);

                requestContent      = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    MediaServicesAccountCreateResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new MediaServicesAccountCreateResponse();
                    JToken responseDoc = JToken.Parse(responseContent);

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount();
                        result.Account = accountInstance;

                        JToken accountIdValue = responseDoc["AccountId"];
                        if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
                        {
                            string accountIdInstance = (string)accountIdValue;
                            accountInstance.AccountId = accountIdInstance;
                        }

                        JToken accountNameValue = responseDoc["AccountName"];
                        if (accountNameValue != null && accountNameValue.Type != JTokenType.Null)
                        {
                            string accountNameInstance = (string)accountNameValue;
                            accountInstance.AccountName = accountNameInstance;
                        }

                        JToken subscriptionValue = responseDoc["Subscription"];
                        if (subscriptionValue != null && subscriptionValue.Type != JTokenType.Null)
                        {
                            string subscriptionInstance = (string)subscriptionValue;
                            accountInstance.SubscriptionId = subscriptionInstance;
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 /// <summary>
 /// The Create Media Services Account operation creates a new media
 /// services account in Windows Azure.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.MediaServices.IAccountOperations.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Create Media Services Account
 /// operation.
 /// </param>
 /// <returns>
 /// The Create Media Services Account operation response.
 /// </returns>
 public static Task <MediaServicesAccountCreateResponse> CreateAsync(this IAccountOperations operations, MediaServicesAccountCreateParameters parameters)
 {
     return(operations.CreateAsync(parameters, CancellationToken.None));
 }
 /// <summary>
 /// The Create Media Services Account operation creates a new media
 /// services account in Windows Azure.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.MediaServices.IAccountOperations.
 /// </param>
 /// <param name='parameters'>
 /// Required. Parameters supplied to the Create Media Services Account
 /// operation.
 /// </param>
 /// <returns>
 /// The Create Media Services Account operation response.
 /// </returns>
 public static MediaServicesAccountCreateResponse Create(this IAccountOperations operations, MediaServicesAccountCreateParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IAccountOperations)s).CreateAsync(parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
 /// <summary>
 /// The Create Media Services Account operation creates a new media
 /// services account in Windows Azure.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx
 /// for more information)
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.MediaServices.IAccountOperations.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to the Create Media Services Account operation.
 /// </param>
 /// <returns>
 /// The Create Media Services Account operation response.
 /// </returns>
 public static MediaServicesAccountCreateResponse Create(this IAccountOperations operations, MediaServicesAccountCreateParameters parameters)
 {
     try
     {
         return(operations.CreateAsync(parameters).Result);
     }
     catch (AggregateException ex)
     {
         if (ex.InnerExceptions.Count > 1)
         {
             throw;
         }
         else
         {
             throw ex.InnerException;
         }
     }
 }