-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathWebHelper.cs
836 lines (720 loc) · 23.6 KB
/
WebHelper.cs
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
using System;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using SmartStore.Collections;
using SmartStore.Core.Data;
using SmartStore.Core.Domain.Stores;
using SmartStore.Core.Infrastructure;
using SmartStore.Utilities;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Net.Sockets;
namespace SmartStore.Core
{
public partial class WebHelper : IWebHelper
{
private static object s_lock = new object();
private static bool? s_optimizedCompilationsEnabled;
private static AspNetHostingPermissionLevel? s_trustLevel;
private static readonly Regex s_staticExts = new Regex(@"(.*?)\.(css|js|png|jpg|jpeg|gif|bmp|html|htm|xml|pdf|doc|xls|rar|zip|ico|eot|svg|ttf|woff|otf|axd|ashx|less)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex s_htmlPathPattern = new Regex(@"(?<=(?:href|src)=(?:""|'))(?!https?://)(?<url>[^(?:""|')]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
private static readonly Regex s_cssPathPattern = new Regex(@"url\('(?<url>.+)'\)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
private static ConcurrentDictionary<int, string> s_safeLocalHostNames = new ConcurrentDictionary<int, string>();
private readonly HttpContextBase _httpContext;
private bool? _isCurrentConnectionSecured;
private string _storeHost;
private string _storeHostSsl;
private string _ipAddress;
private bool? _appPathPossiblyAppended;
private bool? _appPathPossiblyAppendedSsl;
private Store _currentStore;
public WebHelper(HttpContextBase httpContext)
{
this._httpContext = httpContext;
}
public virtual string GetUrlReferrer()
{
string referrerUrl = string.Empty;
if (_httpContext != null &&
_httpContext.Request != null &&
_httpContext.Request.UrlReferrer != null)
referrerUrl = _httpContext.Request.UrlReferrer.ToString();
return referrerUrl;
}
public virtual string GetClientIdent()
{
var ipAddress = this.GetCurrentIpAddress();
var userAgent = _httpContext.Request != null ? _httpContext.Request.UserAgent : string.Empty;
if (ipAddress.HasValue() && userAgent.HasValue())
{
return (ipAddress + userAgent).GetHashCode().ToString();
}
return null;
}
public virtual string GetCurrentIpAddress()
{
if (_ipAddress != null)
{
return _ipAddress;
}
if (_httpContext == null && _httpContext.Request == null)
{
return string.Empty;
}
var vars = _httpContext.Request.ServerVariables;
var keysToCheck = new string[]
{
"HTTP_CLIENT_IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"REMOTE_ADDR",
"HTTP_CF_CONNECTING_IP"
};
string result = null;
foreach (var key in keysToCheck)
{
var ipString = vars[key];
if (ipString.HasValue())
{
var arrStrings = ipString.Split(',');
// Take the last entry
ipString = arrStrings[arrStrings.Length - 1].Trim();
IPAddress address;
if (IPAddress.TryParse(ipString, out address))
{
result = ipString;
break;
}
}
}
if (result == "::1")
{
result = "127.0.0.1";
}
return (_ipAddress = result.EmptyNull());
}
public virtual string GetThisPageUrl(bool includeQueryString)
{
bool useSsl = IsCurrentConnectionSecured();
return GetThisPageUrl(includeQueryString, useSsl);
}
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null || _httpContext.Request == null)
return url;
if (includeQueryString)
{
bool appPathPossiblyAppended;
string storeHost = GetStoreHost(useSsl, out appPathPossiblyAppended).TrimEnd('/');
string rawUrl;
if (appPathPossiblyAppended)
{
string temp = _httpContext.Request.AppRelativeCurrentExecutionFilePath.TrimStart('~');
rawUrl = temp;
}
else
{
rawUrl = _httpContext.Request.RawUrl;
}
url = storeHost + rawUrl;
}
else
{
if (_httpContext.Request.Url != null)
{
url = _httpContext.Request.Url.GetLeftPart(UriPartial.Path);
}
}
return url;
}
public virtual bool IsCurrentConnectionSecured()
{
if (!_isCurrentConnectionSecured.HasValue)
{
_isCurrentConnectionSecured = false;
if (_httpContext != null && _httpContext.Request != null)
{
_isCurrentConnectionSecured = _httpContext.Request.IsSecureConnection();
}
}
return _isCurrentConnectionSecured.Value;
}
public virtual string ServerVariables(string name)
{
string result = string.Empty;
try
{
if (_httpContext != null && _httpContext.Request != null)
{
if (_httpContext.Request.ServerVariables[name] != null)
{
result = _httpContext.Request.ServerVariables[name];
}
}
}
catch
{
result = string.Empty;
}
return result;
}
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private string GetHostPart(string url)
{
var uri = new Uri(url);
var host = uri.GetComponents(UriComponents.Scheme | UriComponents.Host, UriFormat.Unescaped);
return host;
}
private string GetStoreHost(bool useSsl, out bool appPathPossiblyAppended)
{
string cached = useSsl ? _storeHostSsl : _storeHost;
if (cached != null)
{
appPathPossiblyAppended = useSsl ? _appPathPossiblyAppendedSsl.Value : _appPathPossiblyAppended.Value;
return cached;
}
appPathPossiblyAppended = false;
var result = "";
var httpHost = ServerVariables("HTTP_HOST");
if (httpHost.HasValue())
{
result = "http://" + httpHost.EnsureEndsWith("/");
}
if (!DataSettings.DatabaseIsInstalled())
{
if (useSsl)
{
// Secure URL is not specified.
// So a store owner wants it to be detected automatically.
result = result.Replace("http:/", "https:/");
}
}
else
{
//let's resolve IWorkContext here.
//Do not inject it via contructor because it'll cause circular references
if (_currentStore == null)
{
IStoreContext storeContext;
if (EngineContext.Current.ContainerManager.TryResolve<IStoreContext>(null, out storeContext)) // Unit test safe!
{
_currentStore = storeContext.CurrentStore;
if (_currentStore == null)
throw new Exception("Current store cannot be loaded");
}
}
if (_currentStore != null)
{
var securityMode = _currentStore.GetSecurityMode();
if (httpHost.IsEmpty())
{
// HTTP_HOST variable is not available.
// It's possible only when HttpContext is not available (for example, running in a schedule task)
result = _currentStore.Url.EnsureEndsWith("/");
appPathPossiblyAppended = true;
}
if (useSsl)
{
if (securityMode == HttpSecurityMode.SharedSsl)
{
// Secure URL for shared ssl specified.
// So a store owner doesn't want it to be resolved automatically.
// In this case let's use the specified secure URL
result = _currentStore.SecureUrl.EmptyNull();
if (!result.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
result = "https://" + result;
}
appPathPossiblyAppended = true;
}
else
{
// Secure URL is not specified.
// So a store owner wants it to be resolved automatically.
result = result.Replace("http:/", "https:/");
}
}
else // no ssl
{
if (securityMode == HttpSecurityMode.SharedSsl)
{
// SSL is enabled in this store and shared ssl URL is specified.
// So a store owner doesn't want it to be resolved automatically.
// In this case let's use the specified non-secure URL
result = _currentStore.Url;
appPathPossiblyAppended = true;
}
}
}
}
// cache results for request
result = result.EnsureEndsWith("/");
if (useSsl)
{
_storeHostSsl = result;
_appPathPossiblyAppendedSsl = appPathPossiblyAppended;
}
else
{
_storeHost = result;
_appPathPossiblyAppended = appPathPossiblyAppended;
}
return result;
}
public virtual string GetStoreLocation()
{
bool useSsl = IsCurrentConnectionSecured();
return GetStoreLocation(useSsl);
}
public virtual string GetStoreLocation(bool useSsl)
{
//return HostingEnvironment.ApplicationVirtualPath;
bool appPathPossiblyAppended;
string result = GetStoreHost(useSsl, out appPathPossiblyAppended);
if (result.EndsWith("/"))
{
result = result.Substring(0, result.Length - 1);
}
if (_httpContext != null && _httpContext.Request != null)
{
var appPath = _httpContext.Request.ApplicationPath;
if (!appPathPossiblyAppended && !result.EndsWith(appPath, StringComparison.OrdinalIgnoreCase))
{
// in a shared ssl scenario the user defined https url could contain
// the app path already. In this case we must not append.
result = result + appPath;
}
}
if (!result.EndsWith("/"))
{
result += "/";
}
return result;
}
public virtual bool IsStaticResource(HttpRequest request)
{
return IsStaticResourceRequested(new HttpRequestWrapper(request));
}
public static bool IsStaticResourceRequested(HttpRequest request)
{
Guard.ArgumentNotNull(() => request);
return s_staticExts.IsMatch(request.Path);
}
public static bool IsStaticResourceRequested(HttpRequestBase request)
{
// unit testable
Guard.ArgumentNotNull(() => request);
return s_staticExts.IsMatch(request.Path);
}
public virtual string MapPath(string path)
{
return CommonHelper.MapPath(path, false);
}
public virtual string ModifyQueryString(string url, string queryStringModification, string anchor)
{
url = url.EmptyNull();
queryStringModification = queryStringModification.EmptyNull();
string curAnchor = null;
var hsIndex = url.LastIndexOf('#');
if (hsIndex >= 0)
{
curAnchor = url.Substring(hsIndex);
url = url.Substring(0, hsIndex);
}
var parts = url.Split(new[] { '?' });
var current = new QueryString(parts.Length == 2 ? parts[1] : "");
var modify = new QueryString(queryStringModification);
foreach (var nv in modify.AllKeys)
{
current.Add(nv, modify[nv], true);
}
var result = string.Concat(
parts[0],
current.ToString(),
anchor.NullEmpty() == null ? (curAnchor == null ? "" : "#" + curAnchor) : "#" + anchor
);
return result;
}
public virtual string RemoveQueryString(string url, string queryString)
{
var parts = url.SplitSafe("?");
var current = new QueryString(parts.Length == 2 ? parts[1] : "");
if (current.Count > 0 && queryString.HasValue())
{
current.Remove(queryString);
}
var result = string.Concat(parts[0], current.ToString());
return result;
}
public virtual T QueryString<T>(string name)
{
string queryParam = null;
if (_httpContext != null && _httpContext.Request.QueryString[name] != null)
queryParam = _httpContext.Request.QueryString[name];
if (!String.IsNullOrEmpty(queryParam))
return queryParam.Convert<T>();
return default(T);
}
public virtual void RestartAppDomain(bool makeRedirect = false, string redirectUrl = "", bool aggressive = false)
{
HttpRuntime.UnloadAppDomain();
if (aggressive)
{
TryWriteBinFolder();
}
else
{
// without this, MVC may fail resolving controllers for newly installed plugins after IIS restart
Thread.Sleep(250);
}
// If setting up plugins requires an AppDomain restart, it's very unlikely the
// current request can be processed correctly. So, we redirect to the same URL, so that the
// new request will come to the newly started AppDomain.
if (_httpContext != null && makeRedirect)
{
if (_httpContext.Request.RequestType == "GET")
{
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = GetThisPageUrl(true);
}
_httpContext.Response.Redirect(redirectUrl, true /*endResponse*/);
}
else
{
// Don't redirect posts...
_httpContext.Response.ContentType = "text/html";
_httpContext.Response.WriteFile("~/refresh.html");
_httpContext.Response.End();
}
}
}
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private bool TryWriteWebConfig()
{
try
{
// In medium trust, "UnloadAppDomain" is not supported. Touch web.config
// to force an AppDomain restart.
File.SetLastWriteTimeUtc(MapPath("~/web.config"), DateTime.UtcNow);
return true;
}
catch
{
return false;
}
}
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private bool TryWriteGlobalAsax()
{
try
{
//When a new plugin is dropped in the Plugins folder and is installed into SmartSTore.NET,
//even if the plugin has registered routes for its controllers,
//these routes will not be working as the MVC framework can't
//find the new controller types in order to instantiate the requested controller.
//That's why you get these nasty errors
//i.e "Controller does not implement IController".
//The solution is to touch the 'top-level' global.asax file
File.SetLastWriteTimeUtc(MapPath("~/global.asax"), DateTime.UtcNow);
return true;
}
catch
{
return false;
}
}
private bool TryWriteBinFolder()
{
try
{
var binMarker = MapPath("~/bin/HostRestart");
Directory.CreateDirectory(binMarker);
using (var stream = File.CreateText(Path.Combine(binMarker, "marker.txt")))
{
stream.WriteLine("Restart on '{0}'", DateTime.UtcNow);
stream.Flush();
}
return true;
}
catch
{
return false;
}
}
internal static bool OptimizedCompilationsEnabled
{
get
{
if (!s_optimizedCompilationsEnabled.HasValue)
{
var section = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation");
s_optimizedCompilationsEnabled = section.OptimizeCompilations;
}
return s_optimizedCompilationsEnabled.Value;
}
}
/// <summary>
/// Finds the trust level of the running application (http://blogs.msdn.com/dmitryr/archive/2007/01/23/finding-out-the-current-trust-level-in-asp-net.aspx)
/// </summary>
/// <returns>The current trust level.</returns>
public static AspNetHostingPermissionLevel GetTrustLevel()
{
if (!s_trustLevel.HasValue)
{
//set minimum
s_trustLevel = AspNetHostingPermissionLevel.None;
//determine maximum
foreach (AspNetHostingPermissionLevel trustLevel in
new [] {
AspNetHostingPermissionLevel.Unrestricted,
AspNetHostingPermissionLevel.High,
AspNetHostingPermissionLevel.Medium,
AspNetHostingPermissionLevel.Low,
AspNetHostingPermissionLevel.Minimal
})
{
try
{
new AspNetHostingPermission(trustLevel).Demand();
s_trustLevel = trustLevel;
break; //we've set the highest permission we can
}
catch (System.Security.SecurityException)
{
continue;
}
}
}
return s_trustLevel.Value;
}
/// <summary>
/// Prepends protocol and host to all (relative) urls in a html string
/// </summary>
/// <param name="html">The html string</param>
/// <param name="request">Request object</param>
/// <returns>The transformed result html</returns>
/// <remarks>
/// All html attributed named <c>src</c> and <c>href</c> are affected, also occurences of <c>url('path')</c> within embedded stylesheets.
/// </remarks>
public static string MakeAllUrlsAbsolute(string html, HttpRequestBase request)
{
Guard.ArgumentNotNull(() => request);
if (request.Url == null)
{
return html;
}
return MakeAllUrlsAbsolute(html, request.Url.Scheme, request.Url.Authority);
}
/// <summary>
/// Prepends protocol and host to all (relative) urls in a html string
/// </summary>
/// <param name="html">The html string</param>
/// <param name="protocol">The protocol to prepend, e.g. <c>http</c></param>
/// <param name="host">The host name to prepend, e.g. <c>www.mysite.com</c></param>
/// <returns>The transformed result html</returns>
/// <remarks>
/// All html attributed named <c>src</c> and <c>href</c> are affected, also occurences of <c>url('path')</c> within embedded stylesheets.
/// </remarks>
public static string MakeAllUrlsAbsolute(string html, string protocol, string host)
{
Guard.ArgumentNotEmpty(() => html);
Guard.ArgumentNotEmpty(() => protocol);
Guard.ArgumentNotEmpty(() => host);
string baseUrl = string.Format("{0}://{1}", protocol, host.TrimEnd('/'));
MatchEvaluator evaluator = (match) =>
{
var url = match.Groups["url"].Value;
return "{0}{1}".FormatCurrent(baseUrl, url.EnsureStartsWith("/"));
};
html = s_htmlPathPattern.Replace(html, evaluator);
html = s_cssPathPattern.Replace(html, evaluator);
return html;
}
/// <summary>
/// Prepends protocol and host to the given (relative) url
/// </summary>
[SuppressMessage("ReSharper", "AccessToModifiedClosure")]
public static string GetAbsoluteUrl(string url, HttpRequestBase request)
{
Guard.ArgumentNotEmpty(() => url);
Guard.ArgumentNotNull(() => request);
if (request.Url == null)
{
return url;
}
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return url;
}
if (url.StartsWith("~"))
{
url = VirtualPathUtility.ToAbsolute(url);
}
url = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, url);
return url;
}
public static string GetPublicIPAddress()
{
string result = string.Empty;
try
{
using (var client = new WebClient())
{
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try
{
byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");
string response = Encoding.UTF8.GetString(arr);
result = response.Trim();
}
catch { }
}
}
catch { }
var checkers = new string[]
{
"https://ipinfo.io/ip",
"https://api.ipify.org",
"https://icanhazip.com",
"https://wtfismyip.com/text",
"http://bot.whatismyipaddress.com/"
};
if (string.IsNullOrEmpty(result))
{
using (var client = new WebClient())
{
foreach (var checker in checkers)
{
try
{
result = client.DownloadString(checker).Replace("\n", "");
if (!string.IsNullOrEmpty(result))
{
break;
}
}
catch { }
}
}
}
if (string.IsNullOrEmpty(result))
{
try
{
var url = "http://checkip.dyndns.org";
var req = WebRequest.Create(url);
using (var resp = req.GetResponse())
{
using (var sr = new StreamReader(resp.GetResponseStream()))
{
var response = sr.ReadToEnd().Trim();
var a = response.Split(':');
var a2 = a[1].Substring(1);
var a3 = a2.Split('<');
result = a3[0];
}
}
}
catch { }
}
return result;
}
public static HttpWebRequest CreateHttpRequestForSafeLocalCall(Uri requestUri)
{
Guard.ArgumentNotNull(() => requestUri);
var safeHostName = GetSafeLocalHostName(requestUri);
var uri = requestUri;
if (!requestUri.Host.Equals(safeHostName, StringComparison.OrdinalIgnoreCase))
{
var url = String.Format("{0}://{1}{2}",
requestUri.Scheme,
requestUri.IsDefaultPort ? safeHostName : safeHostName + ":" + requestUri.Port,
requestUri.PathAndQuery);
uri = new Uri(url);
}
var request = WebRequest.CreateHttp(uri);
request.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;
request.ServicePoint.Expect100Continue = false;
request.UserAgent = "SmartStore.NET {0}".FormatInvariant(SmartStoreVersion.CurrentFullVersion);
return request;
}
private static string GetSafeLocalHostName(Uri requestUri)
{
return s_safeLocalHostNames.GetOrAdd(requestUri.Port, (port) =>
{
// first try original host
if (TestHost(requestUri, requestUri.Host, 5000))
{
return requestUri.Host;
}
// try loopback
var hostName = Dns.GetHostName();
var hosts = new List<string> { "localhost", hostName, "127.0.0.1" };
foreach (var host in hosts)
{
if (TestHost(requestUri, host, 500))
{
return host;
}
}
// try local IP addresses
hosts.Clear();
var ipAddresses = Dns.GetHostAddresses(hostName).Where(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.ToString());
hosts.AddRange(ipAddresses);
foreach (var host in hosts)
{
if (TestHost(requestUri, host, 500))
{
return host;
}
}
// None of the hosts are callable. WTF?
return requestUri.Host;
});
}
private static bool TestHost(Uri originalUri, string host, int timeout)
{
var url = String.Format("{0}://{1}/taskscheduler/noop",
originalUri.Scheme,
originalUri.IsDefaultPort ? host : host + ":" + originalUri.Port);
var uri = new Uri(url);
var request = WebRequest.CreateHttp(uri);
request.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;
request.ServicePoint.Expect100Continue = false;
request.UserAgent = "SmartStore.NET";
request.Timeout = timeout;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return true;
}
}
catch
{
// try the next host
}
finally
{
if (response != null)
response.Dispose();
}
return false;
}
}
}