Reputation: 8480
I have Azure publishsettings file. Now I have to access storage account with the specified name within the subscription.
How to get it done in C#?
Upvotes: 1
Views: 778
Reputation: 844
I wrote some code below and verified that it works. It's based off Wade's post: Programmatically Installing and Using Your Management Certificate with the New .publishsettings File. Then I call the Get Storage Account Keys method. A couple pointers as mentioned in Wade's post: it's better to create a certificate and install it locally, then use it to call the SM API so that you can delete the .publishsettings file. It has your SM API cert info in it, so you should delete it or keep it safe. This code doesn't do the installing bit for brevity, but Wade's post has it.
var publishSettingsFile =
@"C:\yourPublishSettingsFilePathGoesHere";
XDocument xdoc = XDocument.Load(publishSettingsFile);
var managementCertbase64string =
xdoc.Descendants("PublishProfile").Single().Attribute("ManagementCertificate").Value;
var managementCert = new X509Certificate2(
Convert.FromBase64String(managementCertbase64string));
// If you have more than one subscription, you'll need to change this
string subscriptionId = xdoc.Descendants("Subscription").First().Attribute("Id").Value;
string desiredStorageService = "yourStorageServiceName";
var req = (HttpWebRequest)WebRequest.Create(
string.Format("https://management.core.windows.net/{0}/services/storageservices/{1}/keys",
subscriptionId,
desiredStorageService));
req.Headers["x-ms-version"] = "2012-08-01";
req.ClientCertificates.Add(managementCert);
XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";
XDocument response = XDocument.Load(req.GetResponse().GetResponseStream());
Console.WriteLine("Primary key: " + response.Descendants(xmlns + "Primary").First().Value);
Console.WriteLine("Secondary key: " + response.Descendants(xmlns + "Secondary").First().Value);
Console.Read();
Upvotes: 3