wasvcmgmntapi /SMLibrary/VMManager.cs

Language C# Lines 652
MD5 Hash 06db2c76a2566b519aebc3cc3ea0cf99
Repository https://github.com/mwasham/wasvcmgmntapi.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace SMLibrary
{
    public class VMManager
    {
        private String _subscriptionid { get; set; }
        private String _certthumbprint { get; set; }
        public XNamespace ns = "http://schemas.microsoft.com/windowsazure";
        XNamespace ns1 = "http://www.w3.org/2001/XMLSchema-instance";
        
        public VMManager(String SubscriptionID, String CertThumbPrint)
        {
            _subscriptionid = SubscriptionID;
            _certthumbprint = CertThumbPrint;
        }

        public HttpClient GetHttpClient()
        {
            WebRequestHandler handler = new WebRequestHandler();
            String CertThumbprint = _certthumbprint;
            X509Certificate2 managementCert = FindX509Certificate(CertThumbprint);
            if (managementCert != null)
            {
                handler.ClientCertificates.Add(managementCert);
                HttpClient httpClient = new HttpClient(handler);
                httpClient.DefaultRequestHeaders.Add("x-ms-version", "2012-03-01");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                return httpClient;
            }
            return null;
        }
        
        async public Task<XDocument> GetAzureSubscription()
        {
            String uri = String.Format("https://management.core.windows.net/{0}", _subscriptionid);
            XDocument subXML = new XDocument();
            HttpClient http = GetHttpClient();
            Stream responseStream = await http.GetStreamAsync(uri);
            if (responseStream != null)
            {
                subXML = XDocument.Load(responseStream);
            }
            return subXML;
        }

        async public Task<List<String>> GetAzureVMImages()
        {
            List<String> imageList = new List<String>();
            String uri = String.Format("https://management.core.windows.net/{0}/services/images", _subscriptionid);

            HttpClient http = GetHttpClient();
            Stream responseStream = await http.GetStreamAsync(uri);

            if (responseStream != null)
            {
                XDocument xml = XDocument.Load(responseStream);
                var images = xml.Root.Descendants(ns + "OSImage").Where(i => i.Element(ns + "OS").Value == "Windows");
                foreach (var image in images)
                {
                    string img = image.Element(ns + "Name").Value;
                    imageList.Add(img);
                }
            }


            return imageList;
        }

        async public Task<String> RebootVM(String ServiceName, String RoleName)
        {
            String requestID = String.Empty;

            String deployment = await GetAzureDeploymentName(ServiceName);
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roleInstances/{3}/Operations", _subscriptionid, ServiceName, deployment, RoleName);

            HttpClient http = GetHttpClient();

            XElement srcTree = new XElement("RestartRoleOperation",
                        new XAttribute(XNamespace.Xmlns + "i", ns1),
                        new XElement("OperationType", "RestartRoleOperation")
                    );
            ApplyNamespace(srcTree, ns);

            XDocument CSXML = new XDocument(srcTree);
            HttpContent content = new StringContent(CSXML.ToString());
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");

            HttpResponseMessage responseMsg = await http.PostAsync(uri, content);
            if (responseMsg != null)
            {
                requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            return requestID;
        }

        async public Task<String> ShutDownVM(String ServiceName, String RoleName)
        {
            String requestID = String.Empty;

            String deployment = await GetAzureDeploymentName(ServiceName);
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roleInstances/{3}/Operations", _subscriptionid, ServiceName, deployment, RoleName);

            HttpClient http = GetHttpClient();

            XElement srcTree = new XElement("ShutdownRoleOperation",
                        new XAttribute(XNamespace.Xmlns + "i", ns1),
                        new XElement("OperationType", "ShutdownRoleOperation")
                    );
            ApplyNamespace(srcTree, ns);

            XDocument CSXML = new XDocument(srcTree);
            HttpContent content = new StringContent(CSXML.ToString());
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");

            HttpResponseMessage responseMsg = await http.PostAsync(uri, content);
            if (responseMsg != null)
            {
                requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }

            return requestID;
        }

        async public Task<XDocument> GetAzureVMs()
        {
            List<XDocument> services = await GetAzureServices();
            XDocument vms = new XDocument();
            vms.Add(new XElement("VirtualMachines"));
            ApplyNamespace(vms.Root, ns);
            foreach (var svc in services)
            {
                string ServiceName = svc.Root.Element(ns + "ServiceName").Value;
                
                String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}", _subscriptionid, ServiceName, "Production");

                try
                {
                    HttpClient http = GetHttpClient();
                    Stream responseStream = await http.GetStreamAsync(uri);

                    if (responseStream != null)
                    {
                        XDocument xml = XDocument.Load(responseStream);
                        var roles = xml.Root.Descendants(ns + "RoleInstance");
                        foreach (XElement r in roles)
                        {
                            XElement svcnameel = new XElement("ServiceName", ServiceName);
                            ApplyNamespace(svcnameel, ns);
                            r.Add(svcnameel); // not part of the roleinstance
                            vms.Root.Add(r);
                        }
                    }
                }
                catch (HttpRequestException http)
                {
                    // no vms with cloud service
                }
            }
            return vms;
        }

        async public Task<List<XDocument>> GetAzureVMs(String ServiceName)
        {
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}", _subscriptionid, ServiceName, "Production");
            List<XDocument> vms = new List<XDocument>();
            
            HttpClient http = GetHttpClient();
            Stream responseStream = await http.GetStreamAsync(uri);

            if (responseStream != null)
            {
                XDocument xml = XDocument.Load(responseStream);
                var roles = xml.Root.Descendants(ns + "RoleInstance");
                foreach (XElement r in roles)
                {
                    XDocument vm = new XDocument(r);
                    vms.Add(vm);
                }
            }

            return vms;
        }

        async public Task<XDocument> GetAzureVM(String ServiceName, String VMName)
        {
            String deployment = await GetAzureDeploymentName(ServiceName);
            XDocument vmXML = new XDocument();

            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roles/{3}", _subscriptionid, ServiceName, deployment, VMName);

            HttpClient http = GetHttpClient();
            Stream responseStream = await http.GetStreamAsync(uri);
            if (responseStream != null)
            {
                vmXML = XDocument.Load(responseStream);
            }

            return vmXML;
        }

        async public Task<String> NewAzureCloudService(String ServiceName, String Location, String AffinityGroup)
        {
            String requestID = String.Empty;

            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices", _subscriptionid);
            HttpClient http = GetHttpClient();

            System.Text.ASCIIEncoding ae = new System.Text.ASCIIEncoding();
            byte[] svcNameBytes = ae.GetBytes(ServiceName);

            String locationEl = String.Empty;
            String locationVal = String.Empty;

            if (String.IsNullOrEmpty(Location) == false)
            {
                locationEl = "Location";
                locationVal = Location;
            }
            else
            {
                locationEl = "AffinityGroup";
                locationVal = AffinityGroup;
            }

            XElement srcTree = new XElement("CreateHostedService",
                        new XAttribute(XNamespace.Xmlns + "i", ns1),
                        new XElement("ServiceName", ServiceName),
                        new XElement("Label", Convert.ToBase64String(svcNameBytes)),
                        new XElement(locationEl, locationVal)
                    );
            ApplyNamespace(srcTree, ns);

            XDocument CSXML = new XDocument(srcTree);
            HttpContent content = new StringContent(CSXML.ToString());
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");

            HttpResponseMessage responseMsg = await http.PostAsync(uri, content);
            if (responseMsg != null)
            {
                requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            return requestID;
        }

        async public Task<String> NewAzureVM(String ServiceName, String VMName, XDocument VMXML)
        {
            String requestID = String.Empty;

            String deployment = await GetAzureDeploymentName(ServiceName);

            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roles", _subscriptionid, ServiceName, deployment);

            HttpClient http = GetHttpClient();
            HttpContent content = new StringContent(VMXML.ToString());
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");
            HttpResponseMessage responseMsg = await http.PostAsync(uri, content);
            if (responseMsg != null)
            {
                requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            return requestID;
        }

        async public Task<String> NewAzureVMDeployment(String ServiceName, String VMName, String VNETName, XDocument VMXML, XDocument DNSXML)
        {
            String requestID = String.Empty;


            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments", _subscriptionid, ServiceName);
            HttpClient http = GetHttpClient();
            XElement srcTree = new XElement("Deployment",
                        new XAttribute(XNamespace.Xmlns + "i", ns1),
                        new XElement("Name", ServiceName),
                        new XElement("DeploymentSlot", "Production"),
                        new XElement("Label", ServiceName),
                        new XElement("RoleList", null)
                    );

            if (String.IsNullOrEmpty(VNETName) == false)
            {
                srcTree.Add(new XElement("VirtualNetworkName", VNETName));
            }
            
            if(DNSXML != null)
            {
                srcTree.Add(new XElement("DNS", new XElement("DNSServers", DNSXML)));
            }

            XDocument deploymentXML = new XDocument(srcTree);
            ApplyNamespace(srcTree, ns);

            deploymentXML.Descendants(ns + "RoleList").FirstOrDefault().Add(VMXML.Root);
                       

            String fixedXML = deploymentXML.ToString().Replace(" xmlns=\"\"", "");
            HttpContent content = new StringContent(fixedXML);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");

            HttpResponseMessage responseMsg = await http.PostAsync(uri, content);
            if (responseMsg != null)
            {
                requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }

            return requestID;
        }

        async public Task<String> UpdateAzureVM(String ServiceName, String VMName, XDocument VMXML)
        {
            String requestID = String.Empty;

            String deployment = await GetAzureDeploymentName(ServiceName);

            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roles/{3}", _subscriptionid, ServiceName, deployment, VMName);

            HttpClient http = GetHttpClient();
            String fixedXML = VMXML.ToString().Replace(" xmlns=\"\"", "");
            HttpContent content = new StringContent(fixedXML);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml");
                
            HttpResponseMessage responseMsg = await http.PutAsync(uri, content);
            if (responseMsg != null)
            {
                requestID = responseMsg.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }

            return requestID;
        }

        async public Task<byte[]> GetRDPFile(String ServiceName, String vmName)
        {
            String deploymentName = await GetAzureDeploymentName(ServiceName);
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deployments/{2}/roleinstances/{3}/ModelFile?FileType=RDP", _subscriptionid, ServiceName, deploymentName, vmName);
            byte[] RDPFile = null;

            HttpClient http = GetHttpClient();
            Stream responseStream = await http.GetStreamAsync(uri);
            if (responseStream != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    responseStream.CopyTo(ms);
                    RDPFile = ms.ToArray();
                }
            }
            return RDPFile;
        }

        async private Task<List<XDocument>> GetAzureServices()
        {
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices ", _subscriptionid);
            List<XDocument> services = new List<XDocument>();

            HttpClient http = GetHttpClient();

            Stream responseStream = await http.GetStreamAsync(uri);

            if (responseStream != null)
            {
                XDocument xml = XDocument.Load(responseStream);
                var svcs = xml.Root.Descendants(ns + "HostedService");
                foreach (XElement r in svcs)
                {
                    XDocument vm = new XDocument(r);
                    services.Add(vm);
                }
           }

            return services;
        }

        async public Task<bool> IsServiceNameAvailable(String ServiceName)
        {
            bool available = false;
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/operations/isavailable/{1}", _subscriptionid, ServiceName);
            HttpClient http = GetHttpClient();
            Stream responseStream = await http.GetStreamAsync(uri);
            if (responseStream != null)
            {
                XDocument xml = XDocument.Load(responseStream);
                var response = xml.Descendants(ns + "AvailabilityResponse").FirstOrDefault();
                var strAvailable = response.Element(ns + "Result").Value;
                if (strAvailable == "true")
                    available = true;
            }
            return available;
        }

        async private Task<String> GetAzureDeploymentName(String ServiceName)
        {
            String uri = String.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}", _subscriptionid, ServiceName, "Production");
            String DeploymentName = String.Empty;

            HttpClient http = GetHttpClient();

            Stream responseStream = await http.GetStreamAsync(uri);

            if (responseStream != null)
            {
                XDocument xml = XDocument.Load(responseStream);
                var name = xml.Root.Element(ns + "Name");
                DeploymentName = name.Value;
            }

            return DeploymentName;
        }

        public XDocument NewAzureVMConfig(String RoleName, String VMSize, String ImageName, String MediaLocation, bool InitialDeployment = false)
        {
            System.Text.ASCIIEncoding ae = new System.Text.ASCIIEncoding();
            byte[] roleNameBytes = ae.GetBytes(RoleName);
            XElement srcTree = null;

            if (InitialDeployment == false)
            {
                srcTree = new XElement("PersistentVMRole",
                                        new XAttribute(XNamespace.Xmlns + "i", ns1),
                                        new XElement("RoleName", RoleName),
                                        new XElement("OsVersion", new XAttribute(ns1 + "nil", true)),
                                        new XElement("RoleType", "PersistentVMRole"),
                                        new XElement("ConfigurationSets", null),
                                        new XElement("DataVirtualHardDisks", null),
                                        new XElement("Label", Convert.ToBase64String(roleNameBytes)),
                                        new XElement("OSVirtualHardDisk",
                                            new XElement("MediaLink", MediaLocation),
                                            new XElement("SourceImageName", ImageName)),
                                        new XElement("RoleSize", VMSize)
                                    );

                ApplyNamespace(srcTree, ns);
            }
            else
            {
                srcTree = new XElement("Role",
                        new XAttribute(ns1 + "type", "PersistentVMRole"),
                        new XElement("RoleName", RoleName),
                        new XElement("OsVersion", new XAttribute(ns1 + "nil", true)),
                        new XElement("RoleType", "PersistentVMRole"),
                        new XElement("ConfigurationSets", null),
                        new XElement("DataVirtualHardDisks", null),
                        new XElement("Label", Convert.ToBase64String(roleNameBytes)),
                        new XElement("OSVirtualHardDisk",
                            new XElement("MediaLink", MediaLocation),
                            new XElement("SourceImageName", ImageName)),
                        new XElement("RoleSize", VMSize)
                    );

                ApplyNamespace(srcTree, ns);
            }

            XDocument VMXML = new XDocument();
            VMXML.Add(srcTree);
            return VMXML;
        }

        public XDocument NewWindowsProvisioningConfig(XDocument VMXML, String ComputerName, String Password, bool EnableAutomaticUpdate = false, bool ResetPasswordOnFirstLogon = false)
        {

            XElement srcTree = new XElement("ConfigurationSet",
                        new XAttribute(ns1 + "type", "WindowsProvisioningConfigurationSet"),
                        new XElement("ConfigurationSetType", "WindowsProvisioningConfiguration"),
                        new XElement("ComputerName", ComputerName),
                        new XElement("AdminPassword", Password),
                        new XElement("EnableAutomaticUpdates", EnableAutomaticUpdate),
                        new XElement("ResetPasswordOnFirstLogon", ResetPasswordOnFirstLogon)
                    );


            VMXML.Root.Element(ns + "ConfigurationSets").Add(srcTree);
            return VMXML;
        }

        public XDocument NewNetworkConfigurationSet(XDocument VMXML)
        {
            XElement srcTree = new XElement("ConfigurationSet",
                new XAttribute(ns1 + "type", "NetworkConfigurationSet"),
                new XElement("ConfigurationSetType", "NetworkConfiguration"),
                new XElement("InputEndpoints", null),
                new XElement("SubnetNames", null)
            );


            VMXML.Root.Element(ns + "ConfigurationSets").Add(srcTree);
            return VMXML;
        }

        public XDocument AddNewDataDisk(XDocument VMXML, int DiskSizeInGB, int Lun, String DiskLabel, String MediaLocation)
        {
            XElement srcTree = new XElement("DataVirtualHardDisk",
                                    new XElement("DiskLabel", DiskLabel),
                                    new XElement("Lun", Lun),
                                    new XElement("LogicalDiskSizeInGB", DiskSizeInGB),
                                    new XElement("MediaLink", MediaLocation)
                                );
            VMXML.Root.Element(ns + "DataVirtualHardDisks").Add(srcTree);
            return VMXML;
        }

        public XDocument AddNewInputEndpoint(XDocument VMXML, String Name, String Protocol, int LocalPort, int PublicPort)
        {
            
            XElement srcTree = new XElement("InputEndpoint",
                                    new XElement("LocalPort", LocalPort),
                                    new XElement("Name", Name),
                                    new XElement("Port", PublicPort),
                                    new XElement("Protocol", Protocol)
                                );

           VMXML.Descendants("InputEndpoints").FirstOrDefault().Add(srcTree);
           return VMXML;
        }

        public XDocument AddNewSubnet(XDocument VMXML, String Name)
        {
            XElement srcTree = new XElement("SubnetName", Name);
            VMXML.Descendants("SubnetNames").FirstOrDefault().Add(srcTree);
            return VMXML;
        }



        async public Task<XElement> GetOperationStatus(string requestId)
        {
            string uriFormat = "https://management.core.windows.net/{0}/operations/{1}";

            Uri uri = new Uri(String.Format(uriFormat, _subscriptionid, requestId));
            
            HttpClient http = GetHttpClient();
            
            Stream responseStream = await http.GetStreamAsync(uri);
            if (responseStream != null)
            {
                StreamReader response = new StreamReader(responseStream);

                if (responseStream != null)
                {
                    XDocument xml = XDocument.Load(responseStream);
                    return xml.Element(ns + "Operation");
                }
            }
            return null;
        }

        async public Task<OperationResult> PollGetOperationStatus(string requestId, int pollIntervalSeconds, int timeoutSeconds)
        {
            OperationResult result = new OperationResult();
            DateTime beginPollTime = DateTime.UtcNow;
            TimeSpan pollInterval = new TimeSpan(0, 0, pollIntervalSeconds);
            DateTime endPollTime = beginPollTime + new TimeSpan(0, 0, timeoutSeconds);
            bool done = false;
            while (!done)
            {
                XElement operation = await GetOperationStatus(requestId);
                result.RunningTime = DateTime.UtcNow - beginPollTime;
                try
                {
                    // Turn the Status string into an OperationStatus value
                    result.Status = (OperationStatus)Enum.Parse(
                        typeof(OperationStatus),
                        operation.Element(ns + "Status").Value);
                }
                catch (Exception)
                {
                    throw new ApplicationException(string.Format(
                        "Get Operation Status {0} returned unexpected status: {1}{2}",
                        requestId,
                        Environment.NewLine,
                        operation.ToString(SaveOptions.OmitDuplicateNamespaces)));
                }

                switch (result.Status)
                {
                    case OperationStatus.InProgress:
                        Thread.Sleep((int)pollInterval.TotalMilliseconds);
                        break;

                    case OperationStatus.Failed:
                        result.StatusCode = (HttpStatusCode)Convert.ToInt32(
                            operation.Element(ns + "HttpStatusCode").Value);
                        XElement error = operation.Element(ns + "Error");
                        result.Code = error.Element(ns + "Code").Value;
                        result.Message = error.Element(ns + "Message").Value;
                        done = true;
                        break;

                    case OperationStatus.Succeeded:
                        result.StatusCode = (HttpStatusCode)Convert.ToInt32(
                            operation.Element(ns + "HttpStatusCode").Value);
                        done = true;
                        break;
                }

                if (!done && DateTime.UtcNow > endPollTime)
                {
                    result.Status = OperationStatus.TimedOut;
                    done = true;
                }
            }

            return result;
        }

        private static X509Certificate2 FindX509Certificate(string thumbprint)
        {
            X509Store certificateStore = null;
            X509Certificate2 certificate = null;

            try
            {
                certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

                certificateStore.Open(OpenFlags.ReadOnly);

                var certificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (certificates.Count > 0)
                {
                    certificate = certificates[0];
                }
            }
            finally
            {
                if (certificateStore != null) certificateStore.Close();
            }

            return certificate;
        }
        

        private static void ApplyNamespace(XElement parent, XNamespace nameSpace)
        {
            parent.Name = nameSpace + parent.Name.LocalName;
            foreach (XElement child in parent.Elements())
            {
                ApplyNamespace(child, nameSpace);
            }
        }

    }
}
Back to Top