public void SynchronizeStorageAccountKey(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts/{2}/StorageAccounts/{3}/Key",
                Endpoint, SubscriptionId, accountInfo.AccountName, accountInfo.StorageAccountName));
            request.Method = "PUT";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.Headers.Add("Accept-Encoding: gzip, deflate");
            request.ClientCertificates.Add(clientCert);

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write("\"");
                streamWriter.Write(accountInfo.StorageAccountKey);
                streamWriter.Write("\"");
                streamWriter.Flush();
            }

            AccountDetails details = GetAccountDetails(accountInfo);

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                string jsonResponse;
                Stream receiveStream = response.GetResponseStream();
                Encoding encode = Encoding.GetEncoding("utf-8");
                if (receiveStream != null)
                {
                    var readStream = new StreamReader(receiveStream, encode);
                    jsonResponse = readStream.ReadToEnd();
                }
            }
        }
        private void DoAttachAnotherStorageAccount()
        {
            AttachStorage form = new AttachStorage(_credentials);

            if (form.ShowDialog() == DialogResult.OK)
            {
                ManagementRESTAPIHelper helper = new ManagementRESTAPIHelper(form.GetAzureServiceManagementURL, form.GetCertBody, form.GetAzureSubscriptionID);

                // Initialize the AccountInfo class.
                MediaServicesAccount accountInfo = new MediaServicesAccount()
                {
                    AccountName = _context.Credentials.ClientId,
                    StorageAccountName = _context.DefaultStorageAccount.Name
                };

                AttachStorageAccountRequest storageAccountToAttach = new AttachStorageAccountRequest()
                {
                    StorageAccountName = form.GetStorageName,
                    StorageAccountKey = form.GetStorageKey,
                    BlobStorageEndpointUri = form.GetStorageEndpointURL
                };

                // Call AttachStorageAccountToMediaServiceAccount to 
                // attach an existing storage account to the Media Services account.
                try
                {
                    helper.AttachStorageAccountToMediaServiceAccount(accountInfo, storageAccountToAttach);
                    TextBoxLogWriteLine("Storage account '{0}' attached to '{1}' account.", form.GetStorageName, _context.Credentials.ClientId);
                }
                catch (Exception ex)
                {
                    // Add useful information to the exception
                    TextBoxLogWriteLine("There is a problem when attaching the storage account.", true);
                    TextBoxLogWriteLine(ex);
                    TextBoxLogWriteLine(helper.stringBuilderLog.ToString());
                }
            }
        }
        public List<AzureMediaServicesResource> ListSubscriptionAccounts(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts",
                Endpoint, SubscriptionId));
            request.Method = "GET";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.Accept = "application/json";
            request.ContentType = "application/json";
            request.ClientCertificates.Add(clientCert);

            List<AzureMediaServicesResource> accounts;

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var stream1 = response.GetResponseStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<AzureMediaServicesResource>));
                accounts = (List<AzureMediaServicesResource>)ser.ReadObject(stream1);

                foreach (var r in accounts)
                {
                    Console.WriteLine("Name: {0}", r.Name);
                }
            }

            return accounts;
        }
        public void RegenerateSecondaryAccountKey(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts/{2}/AccountKeys/Secondary/Regenerate",
                Endpoint, SubscriptionId, accountInfo.AccountName));
            request.Method = "Post";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.Headers.Add("Accept-Encoding: gzip, deflate");
            request.Accept = "application/json";
            request.ClientCertificates.Add(clientCert);

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write("\"");
                streamWriter.Write(accountInfo.AccountName);
                streamWriter.Write("\"");
                streamWriter.Flush();
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.NoContent)
                    Console.WriteLine("The secondary key was regenerated.");
            }
        }
        public List<StorageAccountDetails> ListStorageAccountDetails(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts/{2}/StorageAccounts",
                Endpoint, SubscriptionId, accountInfo.AccountName));
            request.Method = "GET";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.Accept = "application/json";
            request.ContentType = "application/json";
            request.ClientCertificates.Add(clientCert);

            List<StorageAccountDetails> storageAccounts;

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var stream1 = response.GetResponseStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<StorageAccountDetails>));
                storageAccounts = (List<StorageAccountDetails>)ser.ReadObject(stream1);

                foreach (var r in storageAccounts)
                {
                    Console.WriteLine("Account name: {0}", r.StorageAccountName);
                    Console.WriteLine("IsDefault: {0}", r.IsDefault);
                }
            }

            return storageAccounts;
        }
        public AccountDetails GetAccountDetails(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts/{2}",
                Endpoint, SubscriptionId, accountInfo.AccountName));
            request.Method = "GET";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.Accept = "application/json";
            request.ContentType = "application/json";
            request.ClientCertificates.Add(clientCert);

            AccountDetails accountDetails = null;

            Console.WriteLine(string.Format("Try to get the details of accountName[{0}].", accountInfo.AccountName));
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var stream1 = response.GetResponseStream();
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AccountDetails));
                accountDetails = (AccountDetails)ser.ReadObject(stream1);
                Console.WriteLine("Deserialized back:");
                Console.WriteLine(accountDetails.AccountName);
                Console.WriteLine(accountDetails.StorageAccountName);
            }

            Console.WriteLine("Got account detail successfully");
            return accountDetails;
        }
        public void DeleteAccount(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts/{2}",
                Endpoint, SubscriptionId, accountInfo.AccountName));
            request.Method = "DELETE";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.Accept = "application/json";
            request.ContentType = "application/json";
            request.ClientCertificates.Add(clientCert);

            Console.WriteLine(string.Format("Try to delete account \"{0}\".", accountInfo.AccountName));
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                // "using" used just to dispose the response received.
            }

            try
            {
                AccountDetails detail = GetAccountDetails(accountInfo);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("(404) Not Found"))
                {
                    Console.WriteLine("Account[{0}] has been deleted successfully", accountInfo.AccountName);
                }
                else
                {
                    Console.WriteLine("Deleted Account[{0}] Failed", accountInfo.AccountName);
                }
            }
        }
        public string CreateMediaServiceAccountUsingXmlContentType(MediaServicesAccount accountInfo)
        {
            var clientCert = GetClientCertificate();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts",
                Endpoint, SubscriptionId));

            // Create the request XML document
            XNamespace ns = "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models";
            XDocument requestBody = new XDocument(
                new XElement(
                    ns + "AccountCreationRequest",
                    new XElement(ns + "AccountName", accountInfo.AccountName),
                    new XElement(ns + "BlobStorageEndpointUri", accountInfo.BlobStorageEndpointUri),
                    new XElement(ns + "Region", accountInfo.Region),
                    new XElement(ns + "StorageAccountKey", accountInfo.StorageAccountKey),
                    new XElement(ns + "StorageAccountName", accountInfo.StorageAccountName)
                    ));

            XDocument responseBody;
            responseBody = null;
            string requestId = String.Empty;

            request.Method = "POST";
            request.Headers.Add("x-ms-version", "2011-10-01");
            request.ClientCertificates.Add(clientCert);
            request.ContentType = "application/xml";
            request.Accept = "application/atom+xml";

            if (requestBody != null)
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    using (StreamWriter streamWriter = new StreamWriter(
                        requestStream, System.Text.UTF8Encoding.UTF8))
                    {
                        requestBody.Save(streamWriter, SaveOptions.DisableFormatting);
                    }
                }
            }

            HttpWebResponse response;
            HttpStatusCode statusCode = HttpStatusCode.Unused;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                // GetResponse throws a WebException for 4XX and 5XX status codes
                response = (HttpWebResponse)ex.Response;
            }

            try
            {
                statusCode = response.StatusCode;
                if (response.ContentLength > 0)
                {
                    if (response.ContentType.Contains("application/xml") || response.ContentType.Contains("application/atom+xml"))
                    {
                        using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
                        {
                            responseBody = XDocument.Load(reader);
                            Console.WriteLine(responseBody.ToString());

                        }
                    }
                    else
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            Console.WriteLine(reader.ReadToEnd());
                        }
                    }

                }

                if (response.Headers != null)
                {
                    requestId = response.Headers["x-ms-request-id"];
                }
            }
            finally
            {
                response.Close();
            }

            if (!statusCode.Equals(HttpStatusCode.Created))
            {
                throw new ApplicationException(string.Format(
                    "Call to CreateAccount returned an error. Status Code: {0}",
                    statusCode
                    ));
            }

            return requestId;
        }
        public void AttachStorageAccountToMediaServiceAccount(MediaServicesAccount accountInfo, AttachStorageAccountRequest storageaccount)
        {
            try
            {
                var clientCert = GetClientCertificate();
                stringBuilderLog.AppendLine("..Called GetClientCertificate");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/{1}/services/mediaservices/Accounts/{2}/StorageAccounts", Endpoint, SubscriptionId, accountInfo.AccountName));
                request.Method = "POST";
                request.ContentType = "application/json; charset=utf-8";
                request.Headers.Add("x-ms-version", "2011-10-01");
                request.Headers.Add("Accept-Encoding: gzip, deflate");
                request.ClientCertificates.Add(clientCert);
                stringBuilderLog.AppendLine("..HttpWebRequest built");
                stringBuilderLog.AppendLine("..HttpWebRequest Request Uri: " + request.RequestUri.ToString());

                string jsonString;

                using (MemoryStream ms = new MemoryStream())
                {
                    DataContractJsonSerializer serializer
                            = new DataContractJsonSerializer(typeof(AttachStorageAccountRequest));

                    serializer.WriteObject(ms, storageaccount);
                    stringBuilderLog.AppendLine("..memorystream serialized");

                    jsonString = Encoding.Default.GetString(ms.ToArray());

                    stringBuilderLog.AppendLine("..jsonString created");
                }

                using (Stream requestStream = request.GetRequestStream())
                {
                    var requestBytes = System.Text.Encoding.ASCII.GetBytes(jsonString);
                    stringBuilderLog.AppendLine("..jsonString to bytes");

                    requestStream.Write(requestBytes, 0, requestBytes.Length);
                    stringBuilderLog.AppendLine("..requestStream.Write");

                    requestStream.Close();
                    stringBuilderLog.AppendLine("..requestStream.Close");

                }

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.NoContent)
                        stringBuilderLog.AppendLine("..Response NoContent Status code - The primary key was regenerated.");

                    stringBuilderLog.AppendLine("..Response Status Code: " + response.StatusCode.ToString());
                    stringBuilderLog.AppendLine("..Response Status Description: " + response.StatusDescription);
                    stringBuilderLog.AppendLine("..Response Uri: " + response.ResponseUri);
                    stringBuilderLog.AppendLine("..Response Server: " + response.Server);
                    stringBuilderLog.AppendLine("..Response ContentType: " + response.ContentType);
                    stringBuilderLog.AppendLine("..Response ContentLength: " + response.ContentLength);
                    stringBuilderLog.AppendLine("..Response ContentEncoding: " + response.ContentEncoding);
                }
            }
            catch (Exception ex)
            { throw ex; }
        }