Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive.Azure/HeuristicLab.Clients.Hive.CloudManager/3.3/Azure/ServiceWebRequest.cs @ 7326

Last change on this file since 7326 was 7326, checked in by spimming, 13 years ago

#1680:

  • New model classes
  • New service operation methods added
  • License information added
File size: 6.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Diagnostics;
24using System.IO;
25using System.Linq;
26using System.Net;
27using System.Security;
28using System.Security.Cryptography;
29using System.Security.Cryptography.X509Certificates;
30using System.Text;
31using System.Xml.Linq;
32
33namespace HeuristicLab.Clients.Hive.CloudManager.Azure {
34  public class ServiceWebRequest {
35    private string thumbprint;
36    private string versionId;
37
38    #region Constructors
39
40    public ServiceWebRequest(string thumbprint)
41      : this(thumbprint, Constants.APIVersionDefault) {
42
43    }
44
45    public ServiceWebRequest(string thumbprint, string versionId) {
46      this.thumbprint = thumbprint;
47      this.versionId = versionId;
48    }
49
50    #endregion
51
52    #region Public Methods
53
54    public XDocument Invoke(string uri) {
55      XDocument responsePayload = null; ;
56      Uri operationUri = new Uri(uri);
57      HttpWebRequest httpWebRequest = CreateHttpWebRequest(operationUri, Constants.HttpMethodGET);
58      try {
59        using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse()) {
60          Stream responseStream = response.GetResponseStream();
61          responsePayload = XDocument.Load(responseStream);
62        }
63      }
64      catch (WebException ex) {
65        Debug.WriteLine("Response status code: " + ex.Status);
66        string response = ParseResponse(ex.Response);
67        WriteRespone(response);
68        string errorMsg = GetErrorMessageFromWebExceptionResponse(response);
69        throw new SystemException(errorMsg);
70      }
71      return responsePayload;
72    }
73
74    public string Invoke(string uri, XDocument payload) {
75      string requestId = Invoke(uri, Constants.HttpMethodPOST, payload);
76      return requestId;
77    }
78
79    public string Invoke(string uri, string httpWebRequestMethod) {
80      Uri operationUri = new Uri(uri);
81      HttpWebRequest httpWebRequest = CreateHttpWebRequest(operationUri, httpWebRequestMethod);
82      String requestId = String.Empty;
83      try {
84        using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse()) {
85          requestId = response.Headers[Constants.HeaderRequestId];
86        }
87      }
88      catch (WebException ex) {
89        Debug.WriteLine("Response status code: " + ex.Status);
90        string response = ParseResponse(ex.Response);
91        WriteRespone(response);
92        string errorMsg = GetErrorMessageFromWebExceptionResponse(response);
93        throw new SystemException(errorMsg);
94      }
95      return requestId;
96    }
97
98    public string Invoke(string uri, string httpWebRequestMethod, XDocument payload) {
99      Uri operationUri = new Uri(uri);
100      HttpWebRequest httpWebRequest = CreateHttpWebRequest(operationUri, httpWebRequestMethod);
101      using (Stream requestStream = httpWebRequest.GetRequestStream()) {
102        using (StreamWriter streamWriter = new StreamWriter(requestStream, UTF8Encoding.UTF8)) {
103          payload.Save(streamWriter, SaveOptions.DisableFormatting);
104        }
105      }
106      string requestId = String.Empty;
107      try {
108        using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse()) {
109          requestId = response.Headers[Constants.HeaderRequestId];
110        }
111      }
112      catch (WebException ex) {
113        Debug.WriteLine("Response status code: " + ex.Status);
114        string response = ParseResponse(ex.Response);
115        WriteRespone(response);
116        string errorMsg = GetErrorMessageFromWebExceptionResponse(response);
117        throw new SystemException(errorMsg);
118      }
119      return requestId;
120    }
121
122    #endregion
123
124    #region Private Methods
125
126    private string ParseResponse(WebResponse webResponse) {
127      string response = string.Empty;
128      using (Stream responseStream = webResponse.GetResponseStream()) {
129        if (responseStream == null) return response;
130
131        using (StreamReader reader = new StreamReader(responseStream)) {
132          response = reader.ReadToEnd();
133        }
134      }
135      return response;
136    }
137
138    private void WriteRespone(string response) {
139      Debug.WriteLine("Response output:");
140      Debug.WriteLine(response);
141    }
142
143
144    private string GetErrorMessageFromWebExceptionResponse(string response) {
145      XNamespace wa = Constants.NSWindowsAzure;
146      XDocument doc = XDocument.Parse(response);
147      string errorCode = doc.Descendants(wa + "Code").Single().Value;
148      string errorMessage = doc.Descendants(wa + "Message").Single().Value;
149      return errorCode + ": " + errorMessage;
150    }
151
152
153    private X509Certificate2 GetCertificate(string certThumbprint) {
154      X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
155      X509Certificate2 cert = null;
156
157      try {
158        certStore.Open(OpenFlags.ReadOnly);
159        X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false);
160        if (certCollection.Count == 0) {
161          throw new Exception("Error: No certificate found containing thumbprint" + certThumbprint);
162        }
163        cert = certCollection[0];
164      }
165      catch (Exception e) {
166        if (e is CryptographicException)
167          throw new SystemException("Error: The certificate store is unreadable.");
168        else if (e is SecurityException)
169          throw new SystemException("Error: You don't have the required permission.");
170        else if (e is ArgumentException)
171          throw new SystemException("Error: Invalid values in the certificate store.");
172        else
173          throw new SystemException(e.Message, e);
174      }
175      finally {
176        certStore.Close();
177      }
178
179      return cert;
180    }
181
182    private HttpWebRequest CreateHttpWebRequest(Uri uri, string httpWebRequestMethod) {
183      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
184      request.Headers.Add(Constants.HeaderVersionName, versionId);
185      request.Method = httpWebRequestMethod;
186      request.ContentType = Constants.ContentTypeAppXml;
187      X509Certificate2 cert = GetCertificate(thumbprint);
188      request.ClientCertificates.Add(cert);
189
190      return request;
191    }
192
193    #endregion
194  }
195}
Note: See TracBrowser for help on using the repository browser.