Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
724 lines (594 loc) · 23.3 KB

File metadata and controls

724 lines (594 loc) · 23.3 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StackifyLib.Models;
using Newtonsoft.Json;
namespace StackifyLib.Utils
{
public class AppIdentityInfo
{
public int? DeviceID { get; set; }
public int? DeviceAppID { get; set; }
public Guid? AppNameID { get; set; }
public short? EnvID { get; set; }
public string AppName { get; set; }
public string Env { get; set; }
public Guid? AppEnvID { get; set; }
public string DeviceAlias { get; set; }
}
public class HttpClient
{
public static IWebProxy CustomWebProxy = null;
public string BaseAPIUrl { get; private set; }
public string APIKey
{
get
{
if (string.IsNullOrEmpty(Config.ApiKey))
{
return _APIKey;
}
else
{
return Config.ApiKey;
}
}
}
private string _APIKey = null;
public AppIdentityInfo AppIdentity { get; internal set; }
//public bool MetricAPIDisabled = false;
private bool IdentityComplete = false;
private DateTime _LastIdentityAttempt;
private DateTime? _UnauthorizedResponse = null;
private DateTime? _LastError = null;
private DateTime? _NextTry = null;
private DateTime? _LastSuccess = DateTime.UtcNow;
public string LastErrorMessage = null;
public class StackifyWebResponse
{
public string ResponseText { get; set; }
public System.Net.HttpStatusCode StatusCode { get; set; }
public Exception Exception { get; set; }
// return true if 4xx status code
public bool IsClientError()
{
return (HttpStatusCode.BadRequest <= StatusCode) && (StatusCode < HttpStatusCode.InternalServerError);
}
}
static HttpClient()
{
#if NETFULL
LoadWebProxyConfig();
#endif
}
public HttpClient(string apiKey, string apiUrl)
{
if (string.IsNullOrEmpty(apiKey))
{
_APIKey = Config.Get("Stackify.ApiKey");
}
else
{
_APIKey = apiKey;
}
if (string.IsNullOrEmpty(apiUrl))
{
string customUrl = Config.Get("Stackify.ApiUrl");
if (!string.IsNullOrWhiteSpace(customUrl))
{
BaseAPIUrl = customUrl;
}
if (BaseAPIUrl == null)
BaseAPIUrl = "https://api.stackify.com/";
}
else
{
BaseAPIUrl = apiUrl;
}
_LastIdentityAttempt = DateTime.UtcNow.AddMinutes(-15);
if (BaseAPIUrl != null && !BaseAPIUrl.EndsWith("/"))
BaseAPIUrl += "/";
}
#if NETFULL
public static void LoadWebProxyConfig()
{
try
{
string val = Config.Get("Stackify.ProxyServer");
if (!string.IsNullOrEmpty(val))
{
StackifyAPILogger.Log("Setting proxy server based on override config", true);
var uri = new Uri(val);
var proxy = new WebProxy(uri, false);
if (!string.IsNullOrEmpty(uri.UserInfo) && uri.UserInfo.Contains(":"))
{
string[] pieces = uri.UserInfo.Split(':');
proxy.Credentials = new NetworkCredential(pieces[0], pieces[1]);
}
else
{
string settingUseDefault = Config.Get("Stackify.ProxyUseDefaultCredentials");
bool useDefault;
if (!string.IsNullOrEmpty(settingUseDefault) && bool.TryParse(settingUseDefault, out useDefault))
{
//will make it use the user of the running windows service
proxy.UseDefaultCredentials = useDefault;
}
}
CustomWebProxy = proxy;
}
}
catch (Exception ex)
{
StackifyAPILogger.Log("Error setting default web proxy " + ex.Message, true);
}
}
#endif
/// <summary>
/// This method does some throttling when errors happen to control when it should try again. Error backoff logic
/// </summary>
private void CalcNextTryOnError()
{
if (_LastError == null)
{
//let the next one go
_NextTry = DateTime.UtcNow;
}
else
{
TimeSpan sinceLastError = DateTime.UtcNow.Subtract(_LastError.Value);
if (sinceLastError < TimeSpan.FromSeconds(1))
{
_NextTry = DateTime.UtcNow.AddSeconds(1);
}
else if (sinceLastError < TimeSpan.FromSeconds(2))
{
_NextTry = DateTime.UtcNow.AddSeconds(2);
}
else if (sinceLastError < TimeSpan.FromSeconds(3))
{
_NextTry = DateTime.UtcNow.AddSeconds(3);
}
else if (sinceLastError < TimeSpan.FromSeconds(4))
{
_NextTry = DateTime.UtcNow.AddSeconds(4);
}
else if (sinceLastError < TimeSpan.FromSeconds(5))
{
_NextTry = DateTime.UtcNow.AddSeconds(5);
}
else if (sinceLastError < TimeSpan.FromSeconds(10))
{
_NextTry = DateTime.UtcNow.AddSeconds(10);
}
else if (sinceLastError < TimeSpan.FromSeconds(20))
{
_NextTry = DateTime.UtcNow.AddSeconds(20);
}
else if (sinceLastError < TimeSpan.FromSeconds(30))
{
_NextTry = DateTime.UtcNow.AddSeconds(30);
}
else
{
_NextTry = DateTime.UtcNow.AddMinutes(1);
}
}
_LastError = DateTime.UtcNow;
}
public bool CanUpload()
{
if (!IsRecentError() && IsAuthorized() && IdentifyApp())
{
return true;
}
return false;
}
public bool IsRecentError()
{
//no error
if (_LastError == null)
{
return false;
}
//last success should really never be greater than last error, but if it is for some reason, go ahead and return false
if (_LastSuccess > _LastError)
{
return false;
}
//If next try is set to a future time, we wait and return true
if (_NextTry != null && DateTime.UtcNow < _NextTry)
{
return true;
}
return false;
}
public bool IsAuthorized()
{
if (_UnauthorizedResponse == null)
{
return true;
}
TimeSpan ts = DateTime.UtcNow.Subtract(_UnauthorizedResponse.Value);
//try again if been more than 5 minutes
return ts.TotalMinutes > 5;
}
public bool MatchedClientDeviceApp()
{
if (IdentifyApp() && this.AppIdentity != null && this.AppIdentity.DeviceAppID != null)
return true;
return false;
}
public bool IdentifyApp()
{
//if identify fails for some reason we can return the previous state incase it was completed before.
bool currentIdentityStatus = IdentityComplete;
try
{
int waitTime = 5; //check every 5
//was successful before and we know the appid
if (this.AppIdentity != null && this.AppIdentity.DeviceAppID.HasValue)
{
waitTime = 15; //refresh every 15
}
if (_LastIdentityAttempt.AddMinutes(waitTime) > DateTime.UtcNow)
{
return currentIdentityStatus;
}
//if we get this far that means it failed more than 5 minutes ago, is the first time, or succeeded more than 15 minutes ago
if (string.IsNullOrEmpty(APIKey))
{
StackifyAPILogger.Log("Skipping IdentifyApp(). No APIKey configured.", true);
return false;
}
StackifyAPILogger.Log("Calling to Identify App");
EnvironmentDetail env = EnvironmentDetail.Get();
env.UpdateEnvironmentName();
env.UpdateAppName();
if (string.IsNullOrEmpty(env.ConfiguredAppName) && !string.IsNullOrEmpty(Config.AppName)) {
env.ConfiguredAppName = Config.AppName;
}
if (string.IsNullOrEmpty(env.ConfiguredEnvironmentName) && !string.IsNullOrEmpty(Config.Environment)) {
env.ConfiguredEnvironmentName = Config.Environment;
}
//Applicable only for Azure AppService
if(AzureConfig.InAzure && AzureConfig.IsWebsite)
{
env.DeviceName = AzureConfig.AzureInstanceName;
}
string jsonData = JsonConvert.SerializeObject(env, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var response =
SendJsonAndGetResponse(
(BaseAPIUrl) + "Metrics/IdentifyApp", jsonData);
if (response.Exception == null && response.StatusCode == HttpStatusCode.OK)
{
_LastIdentityAttempt = DateTime.UtcNow;
AppIdentity = JsonConvert.DeserializeObject<AppIdentityInfo>(response.ResponseText);
if (AppIdentity != null)
{
//always use whatever the configured app name is, don't just use what comes back in case they don't match
if (!string.IsNullOrEmpty(env.ConfiguredAppName) && env.ConfiguredAppName != AppIdentity.AppName)
{
AppIdentity.AppName = env.ConfiguredAppName;
AppIdentity.AppNameID = null;
AppIdentity.AppEnvID = null;
}
IdentityComplete = true;
return true;
}
}
return currentIdentityStatus;
}
catch (Exception ex)
{
_LastIdentityAttempt = DateTime.UtcNow;
StackifyAPILogger.Log("IdentifyApp() HTTP Response Error: " + ex.ToString(), true);
return currentIdentityStatus;
}
}
public Task<StackifyWebResponse> SendJsonAndGetResponseAsync(string url, string jsonData, bool compress = false)
{
return AsyncWrap<StackifyWebResponse>(() => SendJsonAndGetResponse(url, jsonData, compress));
}
private Task<T> AsyncWrap<T>(Func<T> selector)
{
return Task.Factory.StartNew(selector);
}
public StackifyWebResponse SendJsonAndGetResponse(string url, string jsonData, bool compress = false)
{
if (url == null || this.APIKey == null)
{
StackifyAPILogger.Log("unable to send. Missing url or api key");
return new StackifyWebResponse() { Exception = new Exception("Missing url or api key") };
}
if (!IsAuthorized())
{
StackifyAPILogger.Log("Preventing API call due to unauthorized error");
return new StackifyWebResponse() { Exception = new Exception("unauthorized") };
}
StackifyAPILogger.Log("Send to " + url + " key " + this.APIKey + "\r\n" + jsonData);
//default to 500. Should get set below.
StackifyWebResponse result = new StackifyWebResponse() { StatusCode = HttpStatusCode.InternalServerError };
DateTime started = DateTime.UtcNow;
try
{
var request = BuildJsonRequest(url, jsonData, compress);
#if NETFULL
using (var response = (HttpWebResponse)request.GetResponse())
#else
using (var response = (HttpWebResponse)request.GetResponseAsync().GetAwaiter().GetResult())
#endif
{
if (response == null)
return null;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
_UnauthorizedResponse = DateTime.UtcNow;
}
result.ResponseText = GetResponseString(response, started);
result.StatusCode = response.StatusCode;
_LastSuccess = DateTime.UtcNow;
_LastError = null;
LastErrorMessage = null;
#if NET40
response.Close();
#else
response.Dispose();
#endif
}
}
catch (WebException ex)
{
StackifyAPILogger.Log(ex.ToString());
CalcNextTryOnError();
result.Exception = ex;
LastErrorMessage = ex.Message;
if (ex.Response != null)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
_UnauthorizedResponse = DateTime.UtcNow;
}
result.StatusCode = response.StatusCode;
result.ResponseText = GetResponseString(response, started);
#if NET40
response.Close();
#else
response.Dispose();
#endif
}
}
}
catch (Exception ex)
{
StackifyAPILogger.Log(ex.ToString());
CalcNextTryOnError();
LastErrorMessage = ex.Message;
result.Exception = ex;
}
return result;
}
public StackifyWebResponse POSTAndGetResponse(string url, string postData)
{
if (url == null || this.APIKey == null)
{
StackifyAPILogger.Log("unable to send. Missing url or api key");
return new StackifyWebResponse() { Exception = new Exception("Missing url or api key") };
}
if (!IsAuthorized())
{
StackifyAPILogger.Log("Preventing API call due to unauthorized error");
return new StackifyWebResponse() { Exception = new Exception("unauthorized") };
}
StackifyAPILogger.Log("Send to " + url + " key " + this.APIKey + "\r\n" + postData);
//default to 500. Should get set below.
StackifyWebResponse result = new StackifyWebResponse() { StatusCode = HttpStatusCode.InternalServerError };
DateTime started = DateTime.UtcNow;
try
{
var request = BuildPOSTRequest(url, postData);
#if NETFULL
using (var response = (HttpWebResponse)request.GetResponse())
#else
using (var response = (HttpWebResponse)request.GetResponseAsync().GetAwaiter().GetResult())
#endif
{
if (response == null)
return null;
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
_UnauthorizedResponse = DateTime.UtcNow;
}
result.ResponseText = GetResponseString(response, started);
result.StatusCode = response.StatusCode;
_LastSuccess = DateTime.UtcNow;
_LastError = null;
LastErrorMessage = null;
#if NET40
response.Close();
#else
response.Dispose();
#endif
}
}
catch (WebException ex)
{
StackifyAPILogger.Log(ex.ToString());
CalcNextTryOnError();
result.Exception = ex;
LastErrorMessage = ex.Message;
if (ex.Response != null)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
_UnauthorizedResponse = DateTime.UtcNow;
}
result.StatusCode = response.StatusCode;
result.ResponseText = GetResponseString(response, started);
#if NET40
response.Close();
#else
response.Dispose();
#endif
}
}
}
catch (Exception ex)
{
StackifyAPILogger.Log(ex.ToString());
CalcNextTryOnError();
LastErrorMessage = ex.Message;
result.Exception = ex;
}
return result;
}
public string GetResponseString(HttpWebResponse response, DateTime started)
{
if (response == null)
return null;
try
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null || !responseStream.CanRead)
return null;
using (var sr = new StreamReader(responseStream))
{
string responseData = sr.ReadToEnd();
long took = (long)DateTime.UtcNow.Subtract(started).TotalMilliseconds;
bool forceLog = ((int)response.StatusCode) > 400;
StackifyAPILogger.Log("GetResponseString HTTP Response: " + ((int)response.StatusCode).ToString() + ", Took: " + took + "ms - " + responseData + " " + response.ResponseUri.ToString(), forceLog);
return responseData;
}
}
}
catch (Exception ex)
{
StackifyAPILogger.Log("HTTP Response Error: " + ex.ToString() + " " + response.ResponseUri.ToString(), true);
LastErrorMessage = ex.Message;
CalcNextTryOnError();
return null;
}
}
private string _version = null;
private HttpWebRequest BuildJsonRequest(string url, string jsonData, bool compress)
{
if (string.IsNullOrEmpty(_version))
{
#if NETFULL
_version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
#else
_version =
typeof(HttpClient).GetTypeInfo()
.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
#endif
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
#if NETFULL
request.UserAgent = "StackifyLib-" + _version;
#else
request.Headers[HttpRequestHeader.UserAgent] = "StackifyLib-" + _version;
#endif
request.Headers["X-Stackify-Key"] = this.APIKey;
request.ContentType = "application/json";
//if (HttpClient.CustomWebProxy != null)
//{
// request.Proxy = HttpClient.CustomWebProxy;
//}
if (!string.IsNullOrEmpty(jsonData) && compress)
{
request.Method = "POST";
request.Headers[HttpRequestHeader.ContentEncoding] = "gzip";
byte[] payload = Encoding.UTF8.GetBytes(jsonData);
#if NETFULL
using (Stream postStream = request.GetRequestStream())
#else
using (Stream postStream = request.GetRequestStreamAsync().GetAwaiter().GetResult())
#endif
{
using (var zipStream = new GZipStream(postStream, CompressionMode.Compress))
{
zipStream.Write(payload, 0, payload.Length);
}
}
}
else if (!string.IsNullOrEmpty(jsonData))
{
request.Method = "POST";
byte[] payload = Encoding.UTF8.GetBytes(jsonData);
#if NETFULL
request.ContentLength= payload.Length;
using (Stream stream = request.GetRequestStream())
#else
request.Headers[HttpRequestHeader.ContentLength] = payload.Length.ToString();
using (Stream stream = request.GetRequestStreamAsync().GetAwaiter().GetResult())
#endif
{
stream.Write(payload, 0, payload.Length);
}
}
else
{
request.Method = "GET";
}
return request;
}
private HttpWebRequest BuildPOSTRequest(string url, string postdata)
{
if (string.IsNullOrEmpty(_version))
{
#if NETFULL
_version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
#else
_version =
typeof(HttpClient).GetTypeInfo()
.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
#endif
}
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers["X-Stackify-Key"] = this.APIKey;
request.ContentType = "application/x-www-form-urlencoded";
#if NETFULL
request.UserAgent = "StackifyLib-" + _version;
request.ContentLength = 0;
#else
request.Headers[HttpRequestHeader.UserAgent] = "StackifyLib-" + _version;
request.Headers[HttpRequestHeader.ContentLength] = "0";
#endif
//if (HttpClient.CustomWebProxy != null)
//{
// request.Proxy = HttpClient.CustomWebProxy;
//}
request.Method = "POST";
if (!String.IsNullOrEmpty(postdata))
{
byte[] payload = Encoding.UTF8.GetBytes(postdata);
#if NETFULL
using (Stream postStream = request.GetRequestStream())
#else
using (Stream postStream = request.GetRequestStreamAsync().GetAwaiter().GetResult())
#endif
{
postStream.Write(payload, 0, payload.Length);
}
}
return request;
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.