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 =
            @"{""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);
        }
 /// <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;
         }
     }
 }
        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.IsNotNull(cloudException);
                Assert.AreEqual(HttpStatusCode.BadRequest, cloudException.Response.StatusCode);
            }

        }
 /// <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 Task<MediaServicesAccountCreateResponse> CreateAsync(this IAccountOperations operations, MediaServicesAccountCreateParameters parameters)
 {
     return operations.CreateAsync(parameters, CancellationToken.None);
 }
        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);
        }
        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.Equal(1, ((MockCommandRuntime)command.CommandRuntime).OutputPipeline.Count);
            AccountCreationResult accountCreationResult = (AccountCreationResult)((MockCommandRuntime)command.CommandRuntime).OutputPipeline.FirstOrDefault();
            Assert.NotNull(accountCreationResult);
            Assert.Equal(accountName, accountCreationResult.Name);
        }