CPE_learningsite
This repository has no backups
This repository's network speed is throttled to 100KB/sec
Upgrade your account to fix these warnings, or use backups.vc for automated backups
4cd176a439ea516368a5d8827cdf8726027259a6
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; using System.Net.Http.Formatting; using CPE.App.Web.Models; using System.Net; using System.Security.Cryptography; using System.Text; using System.Reflection; using CPE.App.Web.Code; namespace CPE.App.Web.Elucidat { public class EludicatClient { private readonly string _publicKey; private readonly string _secretKey; private readonly bool _simulationMode; private readonly Uri _baseUrl; private readonly JsonMediaTypeFormatter[] _jsonFormatters = { new JsonMediaTypeFormatter { SerializerSettings = new JsonSerializerSettings { ContractResolver = new UnderscoreContractResolver(), } } }; /// <summary> /// Create and configure API client service /// </summary> /// <param name="publicKey"></param> /// <param name="secretKey"></param> /// <param name="simulationMode"></param> /// <param name="baseUrl"></param> public EludicatClient(string publicKey, string secretKey, bool simulationMode, string baseUrl) { this._publicKey = publicKey; this._secretKey = secretKey; this._simulationMode = simulationMode; this._baseUrl = new Uri(baseUrl); } /// <summary> /// Call a GET API method returning a structure of type T without URL parameters /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <returns></returns> private T Get<T>(string url) { return Get<T>(url, new Dictionary<string, string>()); } /// <summary> /// Call a GET API method returning a structure of type T with URL parameters /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="fields"></param> /// <returns></returns> public T Get<T>(string url, IDictionary<string, string> fields) { //string fieldsFirstKeyValue = String.Empty; //if (fields.Count > 0) //{ // fieldsFirstKeyValue = fields.First().Key + " " + fields.First().Value; //} //Extensions.LogServiceCall("[EludicatClient][Get]", String.Format("url = {0} fieldsFirstKeyValue = {1} _simulationMode = {2}", url, fieldsFirstKeyValue, _simulationMode)); if (_simulationMode) fields = fields.Concat(new Dictionary<string, string> { { "simulation_mode", "simulation" } }) .ToDictionary(x => x.Key, x => x.Value); return CallGet<T>(AuthHeaders(GetNonce(url)), fields, url); } /// <summary> /// Internal get-based API call. Used for both actual API call and obtaining nonces. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="headers"></param> /// <param name="fields"></param> /// <param name="url"></param> /// <returns></returns> private T CallGet<T>(IDictionary<string, string> headers, IDictionary<string, string> fields, string url) { T result = default(T); string fieldsFirstKeyValue = String.Empty; //if (fields.Count > 0) //{ // fieldsFirstKeyValue = fields.First().Key + " " + fields.First().Value; //} //Extensions.LogServiceCall("[EludicatClient][CallGet]", String.Format("fields.Count = {0} fieldsFirstKeyValue = {1}", fields.Count, fieldsFirstKeyValue)); var signedHeaders = headers.Concat(new Dictionary<string, string> { {"oauth_signature", Sign(headers.Concat(fields), url, "GET")} }); // Remove insecure protocols (SSL3, TLS 1.0, TLS 1.1) ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11; // Add TLS 1.2 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; var client = new WebClient { BaseAddress = _baseUrl.ToString() }; client.Headers.Clear(); client.Headers["Accept"] = "application/json"; client.Headers.Add("Authorization", BuildBaseString(signedHeaders, ",")); var urlFull = url + "?" + BuildBaseString(fields, "&"); var response = client.DownloadString(urlFull); try { result = (T)JsonConvert.DeserializeObject(response, typeof(T), _jsonFormatters[0].SerializerSettings); } catch (Exception exception) { if (fields.Count > 0) { fieldsFirstKeyValue = fields.First().Key + " " + fields.First().Value; } Extensions.LogServiceCall("[EludicatClient][CallGet]", String.Format("urlFull = {0} typeof(T) = {1} fields.Count = {2} fieldsFirstKeyValue = {3} _baseUrl = {4} response = {5}", urlFull, typeof(T).ToString(), fields.Count, fieldsFirstKeyValue, _baseUrl, response)); Extensions.LogServiceError("[EludicatClient][CallGet]", exception); throw; } return result; } /// <summary> /// Call a POST-based API method with parameters /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="fields"></param> /// <returns></returns> public T Post<T>(string url, IDictionary<string, string> fields) { if (_simulationMode) fields = fields.Concat(new Dictionary<string, string> { { "simulation_mode", "simulation" } }) .ToDictionary(x => x.Key, x => x.Value); return CallPost<T>(AuthHeaders(GetNonce(url)), fields, url); } /// <summary> /// Internal POST call. Used only for actual API method invocations. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="headers"></param> /// <param name="fields"></param> /// <param name="url"></param> /// <returns></returns> private T CallPost<T>(IDictionary<string, string> headers, IDictionary<string, string> fields, string url) { var signedHeaders = headers.Concat(new Dictionary<string, string> { {"oauth_signature", Sign(headers.Concat(fields), url, "POST")} }); // Remove insecure protocols (SSL3, TLS 1.0, TLS 1.1) ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11; // Add TLS 1.2 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; var client = new WebClient(); client.BaseAddress = _baseUrl.ToString(); client.Headers.Clear(); client.Headers["Accept"] = "application/json"; client.Headers["Content-Type"] = "application/x-www-form-urlencoded"; client.Headers.Add("Authorization", BuildBaseString(signedHeaders, ",")); client.Headers.Add("Expect", ""); var content = BuildBaseString(fields, "&"); try { var response = client.UploadString(url, content); var result = (T)JsonConvert.DeserializeObject(response, typeof(T), _jsonFormatters[0].SerializerSettings); return result; } catch (WebException e) { throw; } } /// <summary> /// Generate an HMAC signature for an API request /// </summary> /// <param name="parameters"></param> /// <param name="url"></param> /// <param name="httpMethod"></param> /// <returns></returns> private string Sign(IEnumerable<KeyValuePair<string, string>> parameters, string url, string httpMethod) { var baseString = httpMethod + "&" + new Uri(_baseUrl, url) + "&" + BuildBaseString(parameters.OrderBy(x => x.Key), "&"); var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(_secretKey.RawUrlEncode())); hmac.Initialize(); return Convert.ToBase64String(hmac.ComputeHash(Encoding.ASCII.GetBytes(baseString))); } /// <summary> /// Create a query-string like single string from a parameter dictionary. /// </summary> /// <param name="parameters"></param> /// <param name="delimiter"></param> /// <returns></returns> private string BuildBaseString(IEnumerable<KeyValuePair<string, string>> parameters, string delimiter) { return string.Join(delimiter, parameters.Select(x => x.Key.RawUrlEncode() + "=" + x.Value.RawUrlEncode())); } /// <summary> /// Create a parameter dictionary from an object /// </summary> /// <param name="o"></param> ///// <returns></returns> //private IDictionary<string, string> BuildParameterDictionary(object o) //{ // IDictionary<string, string> dict = o.GetType() // .FindMembers(MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public, null, null) // .Where(p => (((PropertyInfo)p).GetValue(o)) != null) // .ToDictionary(propertyInfo => propertyInfo.Name.TransformPropertyName(), propertyInfo => Convert.ToString(((PropertyInfo)propertyInfo).GetValue(o))); // return dict; //} /// <summary> /// Base authentication headers required for every API request. /// </summary> /// <param name="nonce"></param> /// <returns></returns> private IDictionary<string, string> AuthHeaders(string nonce) { var headers = new Dictionary<string, string> { {"oauth_consumer_key", _publicKey}, {"oauth_signature_method", "HMAC-SHA1"}, { "oauth_timestamp", Math.Floor( DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds) .ToString() }, {"oauth_version", "1.0"} }; if (nonce != null) headers.Add("oauth_nonce", nonce); return headers; } /// <summary> /// Retrieve a security nonce from the API to authenticate the next method call. /// </summary> /// <param name="url"></param> /// <returns></returns> private string GetNonce(string url) { string returnValue = null; var response = CallGet<NonceModel>(AuthHeaders(null), new Dictionary<string, string>(), url); if (response != null) { returnValue = response.Nonce; } return returnValue; } /// <summary> /// Retrieve the details of a single release /// </summary> /// <param name="releaseCode"></param> /// <returns></returns> public ReleaseModel GetRelease(string releaseCode) { return Get<ReleaseModel>("releases/details", new Dictionary<string, string> { { "release_code", releaseCode } }); } /// <summary> /// Retrieve a link which can be used to launch the given release. /// </summary> /// <param name="releaseCode"></param> /// <returns></returns> public LinkModel GetLaunchLink(string releaseCode) { return Get<LinkModel>("releases/launch", new Dictionary<string, string> { {"release_code", releaseCode} }); } /// <summary> /// Retrieve a link which can be used to launch the given release. /// </summary> /// <param name="releaseCode"></param> /// <param name="firstname"></param> /// <param name="lastname"></param> /// <param name="email"></param> /// <param name="passcode"></param> /// <returns></returns> public LinkModel GetLaunchLink(string releaseCode, string firstname, string lastname, string email) { return Get<LinkModel>("releases/launch", new Dictionary<string, string> { { "release_code", releaseCode}, { "name", firstname + " " + lastname}, { "email_address", email} }); } public MessageModel ConfigureProject(ProjectSettingModel settings) { Extensions.LogServiceCall("[EludicatClient][ConfigureProject]", String.Format("ProjectCode = {0}", settings.ProjectCode)); return Post<MessageModel>("projects/configure", BuildParameterDictionary(settings)); } public MessageModel CreateRelease(ReleaseSettingModel settings) { Extensions.LogServiceCall("[EludicatClient][CreateRelease]", String.Format("ReleaseCode = {0} ProjectCode = {1} Description = {2}", settings.ReleaseCode, settings.ProjectCode, settings.Description)); return Post<MessageModel>("releases/create", BuildParameterDictionary(settings)); } /// <summary> /// Create a parameter dictionary from an object /// </summary> /// <param name="o"></param> /// <returns></returns> private IDictionary<string, string> BuildParameterDictionary(object o) { IDictionary<string, string> dict = o.GetType() .FindMembers(MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public, null, null) .Where(p => (((PropertyInfo)p).GetValue(o)) != null) .ToDictionary(propertyInfo => propertyInfo.Name.TransformPropertyName(), propertyInfo => Convert.ToString(((PropertyInfo)propertyInfo).GetValue(o))); return dict; } } } |
Commits for CPE_learningsiteCPE/CPE.App/CPE.App.Web/Elucidat/EludicatClient.cs
Revision | Author | Commited | Message |
---|---|---|---|
4cd176 ... | v.shishlov | Fri 27 Aug, 2021 14:33:17 +0000 | initial commit |