Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 75.39 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Net;
  5. using System.Text;
  6. using System.IO;
  7. using System.IO.Compression;
  8. using System.Reflection;
  9. using System.Windows.Forms;
  10. using System.ComponentModel;
  11. using System.Security.Cryptography;
  12. using System.Runtime.InteropServices;
  13. using System.Net.Security;
  14. using System.Security;
  15. using System.Security.Cryptography.X509Certificates;
  16. using System.Security.Principal;
  17. using System.Net.Cache;
  18. using System.Threading;
  19. using System.Net.Sockets;
  20. using System.Drawing;
  21. using System.Globalization;
  22.  
  23. // Version: 2.1.1.1, Changed: 11/1/2016
  24.  
  25. namespace NetSeal
  26. {
  27.  
  28.     internal sealed class Broker
  29.     {
  30.  
  31.         #region " Events "
  32.  
  33.         /// <summary>
  34.         /// Occurs when the user's license is suspended.
  35.         /// </summary>
  36.         public event LicenseSuspendedEventHandler LicenseSuspended;
  37.         public delegate void LicenseSuspendedEventHandler(object sender, EventArgs e);
  38.  
  39.         /// <summary>
  40.         /// Occurs when the user's license is authorized by the server.
  41.         /// </summary>
  42.         public event LicenseAuthorizedEventHandler LicenseAuthorized;
  43.         public delegate void LicenseAuthorizedEventHandler(object sender, EventArgs e);
  44.  
  45.         /// <summary>
  46.         /// Occurs when the user's license is reauthorized by the server.
  47.         /// </summary>
  48.         public event LicenseRefreshedEventHandler LicenseRefreshed;
  49.         public delegate void LicenseRefreshedEventHandler(object sender, EventArgs e);
  50.  
  51.         #endregion
  52.  
  53.         #region " Properties "
  54.  
  55.         /// <summary>
  56.         /// Gets the user's wide area network IPv4 address.
  57.         /// </summary>
  58.         public IPAddress IPAddress
  59.         {
  60.             get
  61.             {
  62.                 EnsureInitialization();
  63.  
  64.                 return (IPAddress)_AuthenticatorType.GetMethod("GetIPAddress").Invoke(_Authenticator, null);
  65.             }
  66.         }
  67.  
  68.         /// <summary>
  69.         /// Gets the user's sign-in name.
  70.         /// </summary>
  71.         public string UserName
  72.         {
  73.             get
  74.             {
  75.                 EnsureInitialization();
  76.  
  77.                 return (string)_AuthenticatorType.GetMethod("GetUserName").Invoke(_Authenticator, null);
  78.             }
  79.         }
  80.  
  81.         /// <summary>
  82.         /// Gets the expiration date of the user's license, when <see cref="LicenseExpires"/> is True.
  83.         /// </summary>
  84.         public System.DateTime ExpirationDate
  85.         {
  86.             get
  87.             {
  88.                 EnsureInitialization();
  89.  
  90.                 return (System.DateTime)_AuthenticatorType.GetMethod("GetExpirationDate").Invoke(_Authenticator, null);
  91.             }
  92.         }
  93.  
  94.         /// <summary>
  95.         /// Gets the time remaining on the user's license, when <see cref="LicenseExpires"/> is True.
  96.         /// </summary>
  97.         public TimeSpan TimeRemaining
  98.         {
  99.             get
  100.             {
  101.                 EnsureInitialization();
  102.  
  103.                 return (TimeSpan)_AuthenticatorType.GetMethod("GetTimeRemaining").Invoke(_Authenticator, null);
  104.             }
  105.         }
  106.  
  107.         /// <summary>
  108.         /// Gets the license type associated with the user's license.
  109.         /// </summary>
  110.         public LicenseType LicenseType
  111.         {
  112.             get
  113.             {
  114.                 EnsureInitialization();
  115.  
  116.                 return (LicenseType)_AuthenticatorType.GetMethod("GetLicenseType").Invoke(_Authenticator, null);
  117.             }
  118.         }
  119.  
  120.         /// <summary>
  121.         /// Gets a value indicating whether the user's license will expire.
  122.         /// </summary>
  123.         public bool LicenseExpires
  124.         {
  125.             get
  126.             {
  127.                 EnsureInitialization();
  128.  
  129.                 return (bool)_AuthenticatorType.GetMethod("GetLicenseExpires").Invoke(_Authenticator, null);
  130.             }
  131.         }
  132.  
  133.         /// <summary>
  134.         /// Gets a unique identifier for the machine. This value is not static.
  135.         /// </summary>
  136.         public string MachineId
  137.         {
  138.             get
  139.             {
  140.                 EnsureInitialization();
  141.  
  142.                 return (string)_AuthenticatorType.GetMethod("GetMachineId").Invoke(_Authenticator, null);
  143.             }
  144.         }
  145.  
  146.         #endregion
  147.  
  148.         #region " Commands "
  149.  
  150.         /// <summary>
  151.         /// Gets a token representing the key returned by <see cref="GetPrivateKey"/> which can be decoded with the PrivateKey web API.
  152.         /// </summary>
  153.         public string GetPublicToken()
  154.         {
  155.             EnsureInitialization();
  156.  
  157.             return (string)_AuthenticatorType.GetMethod("GetPublicToken").Invoke(_Authenticator, null);
  158.         }
  159.  
  160.         /// <summary>
  161.         /// Gets a secret key that can be used for encryption.
  162.         /// </summary>
  163.         public byte[] GetPrivateKey()
  164.         {
  165.             EnsureInitialization();
  166.  
  167.             return (byte[])_AuthenticatorType.GetMethod("GetPrivateKey").Invoke(_Authenticator, null);
  168.         }
  169.  
  170.         /// <summary>
  171.         /// Gets the number of users currently signed in and using the program.
  172.         /// </summary>
  173.         public int GetUsersOnline()
  174.         {
  175.             EnsureInitialization();
  176.  
  177.             return (int)_AuthenticatorType.GetMethod("GetUsersOnline").Invoke(_Authenticator, null);
  178.         }
  179.  
  180.         /// <summary>
  181.         /// Gets a value indicating whether updates are available.
  182.         /// </summary>
  183.         public bool GetUpdatesAvailable()
  184.         {
  185.             EnsureInitialization();
  186.  
  187.             return (bool)_AuthenticatorType.GetMethod("GetUpdatesAvailable").Invoke(_Authenticator, null);
  188.         }
  189.  
  190.         /// <summary>
  191.         /// Gets blog posts submitted by the application developer.
  192.         /// </summary>
  193.         public BlogPost[] GetBlogPosts()
  194.         {
  195.             EnsureInitialization();
  196.  
  197.             List<BlogPost> Posts = new List<BlogPost>();
  198.             object[] Values = (object[])_AuthenticatorType.GetMethod("GetBlogPosts").Invoke(_Authenticator, null);
  199.  
  200.             for (int I = 0; I <= Values.Length - 1; I += 4)
  201.             {
  202.                 int Id = (int)Values[I];
  203.                 string Title = (string)Values[I + 1];
  204.                 int TimesRead = (int)Values[I + 2];
  205.                 System.DateTime DatePosted = (System.DateTime)Values[I + 3];
  206.  
  207.                 BlogPost Post = new BlogPost(Id, Title, TimesRead, DatePosted, new GetPostBodyDelegate(GetPostBody));
  208.                 Posts.Add(Post);
  209.             }
  210.  
  211.             return Posts.ToArray();
  212.         }
  213.  
  214.         /// <summary>
  215.         /// Gets settings defined by the application developer.
  216.         /// </summary>
  217.         public string GetSetting(string name)
  218.         {
  219.             EnsureInitialization();
  220.  
  221.             return (string)_AuthenticatorType.GetMethod("GetSetting").Invoke(_Authenticator, new object[] { name });
  222.         }
  223.  
  224.         /// <summary>
  225.         /// Downloads and installs updates if they are available.
  226.         /// </summary>
  227.         public void InstallUpdates()
  228.         {
  229.             EnsureInitialization();
  230.  
  231.             _AuthenticatorType.GetMethod("InstallUpdates").Invoke(_Authenticator, null);
  232.         }
  233.  
  234.         /// <summary>
  235.         /// Suspends the currently signed in user's license.
  236.         /// </summary>
  237.         public void SuspendUser(string reason)
  238.         {
  239.             EnsureInitialization();
  240.  
  241.             _AuthenticatorType.GetMethod("SuspendUser").Invoke(_Authenticator, new object[] { reason });
  242.         }
  243.  
  244.         #endregion
  245.  
  246.         #region " Members "
  247.  
  248.  
  249.         private Version _Version;
  250.  
  251.         private Type _LzmaLibType;
  252.         private object _Authenticator;
  253.  
  254.         private Type _AuthenticatorType;
  255.         private HttpClient _HttpClient;
  256.         private DnsClient _DnsClient;
  257.  
  258.         private StrongNameVerifierLite _StrongNameVerifier;
  259.         private string _PreferredMetadataEndPoint;
  260.  
  261.         private string _AlternateMetadataEndPoint;
  262.         private ICryptoTransform _ComponentAesEncryptor;
  263.  
  264.         private ICryptoTransform _ComponentAesDecryptor;
  265.         private byte[] _ComponentKey;
  266.  
  267.         private byte[] _AuthenticatorKey;
  268.         private string _ServerEndPoint;
  269.  
  270.         private string _ComponentEndPoint;
  271.         private string _LzmaLibHash;
  272.  
  273.         private string _AuthenticatorHash;
  274.         private byte[] _LzmaLibData;
  275.  
  276.         private byte[] _AuthenticatorData;
  277.  
  278.         private string _ProductDirectory;
  279.         #endregion
  280.  
  281.         #region " Delegates "
  282.  
  283.         private delegate void CallbackDelegate();
  284.         private delegate string GetPostBodyDelegate(int postId);
  285.  
  286.         #endregion
  287.  
  288.         #region " Event Handling "
  289.  
  290.         private void HttpClient_WebRequestResolveHost(object sender, HttpClient.WebRequestResolveHostEventArgs e)
  291.         {
  292.             try
  293.             {
  294.                 IPAddress[] AddressList = null;
  295.  
  296.                 lock (_DnsClient)
  297.                 {
  298.                     AddressList = _DnsClient.Resolve(e.HostName);
  299.                 }
  300.  
  301.                 if (AddressList.Length == 0)
  302.                 {
  303.                     return;
  304.                 }
  305.  
  306.                 e.Address = AddressList[0];
  307.             }
  308.             catch (Exception ex)
  309.             {
  310.                 HandleException(ex);
  311.             }
  312.         }
  313.  
  314.         #endregion
  315.  
  316.         #region " Constructor "
  317.  
  318.         public Broker()
  319.         {
  320.             _Version = new Version(2, 1, 1, 1);
  321.  
  322.             _PreferredMetadataEndPoint = "http://seal.nimoru.com/Base/checksumSE.php";
  323.             _AlternateMetadataEndPoint = "https://s3-us-west-2.amazonaws.com/netseal/checksumSE.txt";
  324.  
  325.             _ComponentKey = new byte[] { 65, 118, 65, 114, 101, 79, 118, 101, 114, 122, 101, 97, 108, 111, 117, 115 };
  326.             _AuthenticatorKey = new byte[] { 6, 2, 0, 0, 0, 34, 0, 0, 68, 83, 83, 49, 0, 4, 0, 0, 165, 101, 186, 183, 89, 49, 161, 242, 152, 217, 52, 227, 36, 114, 221, 81, 163, 208, 24, 95, 234, 1, 136, 6, 193, 171, 215, 57, 56, 216, 186, 221, 159, 6, 11, 126, 249, 251, 48, 16, 34, 98, 128, 135, 217, 192, 244, 236, 207, 199, 184, 206, 141, 91, 85, 170, 37, 5, 69, 218, 137, 176, 31, 148, 182, 215, 92, 31, 188, 16, 174, 181, 79, 118, 71, 21, 229, 118, 103, 239, 119, 78, 165, 241, 228, 42, 154, 154, 115, 181, 130, 43, 93, 220, 102, 91, 64, 81, 150, 139, 1, 40, 243, 57, 154, 206, 152, 93, 153, 232, 48, 171, 30, 2, 138, 153, 232, 8, 243, 107, 197, 61, 64, 34, 76, 145, 33, 210, 71, 227, 182, 220, 74, 6, 143, 213, 126, 239, 28, 36, 10, 134, 7, 146, 81, 109, 44, 156, 196, 68, 30, 178, 252, 53, 181, 4, 32, 135, 132, 182, 229, 206, 145, 115, 250, 104, 109, 212, 32, 250, 196, 8, 182, 64, 19, 88, 238, 246, 92, 89, 214, 234, 163, 230, 75, 79, 140, 187, 179, 15, 35, 83, 173, 101, 137, 128, 110, 100, 176, 63, 183, 238, 138, 30, 26, 8, 193, 159, 141, 32, 74, 236, 8, 117, 185, 68, 63, 101, 159, 149, 105, 48, 46, 186, 192, 16, 156, 99, 159, 120, 101, 50, 12, 106, 114, 46, 190, 106, 112, 225, 228, 26, 81, 118, 79, 160, 202, 32, 127, 111, 96, 38, 2, 82, 162, 86, 131, 131, 152, 143, 213, 112, 234, 204, 228, 207, 187, 212, 93, 176, 119, 183, 71, 86, 90, 54, 9, 107, 47, 78, 115, 161, 51, 61, 225, 153, 37, 228, 164, 254, 108, 240, 20, 11, 223, 100, 26, 177, 3, 152, 216, 169, 123, 171, 99, 240, 92, 40, 57, 51, 77, 105, 54, 142, 189, 102, 101, 93, 59, 64, 125, 172, 106, 25, 94, 59, 159, 18, 159, 105, 184, 49, 18, 93, 60, 159, 71, 55, 60, 18, 68, 141, 70, 115, 39, 135, 33, 193, 13, 132, 199, 96, 57, 185, 128, 96, 70, 233, 28, 152, 169, 145, 153, 220, 8, 166, 17, 234, 208, 140, 29, 163, 20, 181, 251, 161, 210, 193, 124, 96, 213, 221, 196, 16, 10, 49, 39, 190, 81, 213, 228, 151, 23, 231, 23, 57, 224, 187, 119, 245, 54, 81, 141, 45, 171, 0, 0, 0, 203, 211, 139, 62, 110, 51, 58, 65, 64, 134, 29, 53, 198, 216, 158, 178, 112, 28, 230, 228 };
  327.         }
  328.  
  329.         #endregion
  330.  
  331.         #region " Initialization "
  332.  
  333.         /// <summary>
  334.         /// Initializes the authenticator and shows the authentication dialog.
  335.         /// </summary>
  336.         public void Initialize(string productId)
  337.         {
  338.             Initialize(productId, new BrokerSettings());
  339.         }
  340.        
  341.         /// <summary>
  342.         /// Initializes the authenticator and shows the authentication dialog.
  343.         /// </summary>
  344.         public void Initialize(string productId, BrokerSettings settings)
  345.         {
  346.             try
  347.             {
  348.                 if (_Authenticator != null)
  349.                 {
  350.                     throw new Exception("Loader has already been initialized.");
  351.                 }
  352.  
  353.                 if (settings == null)
  354.                 {
  355.                     throw new ArgumentNullException("settings");
  356.                 }
  357.                
  358.                 ThreadCulture Culture = NormalizeCulture();
  359.  
  360.                 if (settings.VerifyRuntimeIntegrity)
  361.                 {
  362.                     _StrongNameVerifier = new StrongNameVerifierLite();
  363.                     CheckFrameworkStrongNames();
  364.                 }
  365.  
  366.                 InitializeWebHandling();
  367.                 InitializeComponentTransform();
  368.  
  369.                 _ProductDirectory = GetProductDirectory();
  370.  
  371.                 string[] Metadata = GetMetadata();
  372.                 ParseMetadata(Metadata);
  373.  
  374.                 if (!Directory.Exists(_ProductDirectory))
  375.                 {
  376.                     Directory.CreateDirectory(_ProductDirectory);
  377.                 }
  378.  
  379.                 InitializeLzmaLib();
  380.                 InitializeAuthenticator();
  381.  
  382.                 VerifyAuthenticator();
  383.  
  384.                 _AuthenticatorType = Assembly.Load(_AuthenticatorData).GetType("Controller");
  385.                 _Authenticator = Activator.CreateInstance(_AuthenticatorType);
  386.  
  387.                 MethodInfo UpdateMethod = _AuthenticatorType.GetMethod("UpdateValue");
  388.  
  389.                 UpdateMethod.Invoke(_Authenticator, new object[] { "ProductId", productId });
  390.                 UpdateMethod.Invoke(_Authenticator, new object[] { "CatchUnhandledExceptions", settings.CatchUnhandledExceptions });
  391.                 UpdateMethod.Invoke(_Authenticator, new object[] { "DeferAutomaticUpdates", settings.DeferAutomaticUpdates });
  392.                 UpdateMethod.Invoke(_Authenticator, new object[] { "SilentAuthentication", settings.SilentAuthentication });
  393.                 UpdateMethod.Invoke(_Authenticator, new object[] { "DialogTheme", Convert.ToInt32(settings.DialogTheme) });
  394.                 UpdateMethod.Invoke(_Authenticator, new object[] { "LoaderVersion", _Version });
  395.                 UpdateMethod.Invoke(_Authenticator, new object[] { "ProductVersion", new Version(Application.ProductVersion) });
  396.                 UpdateMethod.Invoke(_Authenticator, new object[] { "Metadata", Metadata });
  397.                 UpdateMethod.Invoke(_Authenticator, new object[] { "AuthorizedCallback", new CallbackDelegate(AuthorizedCallback) });
  398.                 UpdateMethod.Invoke(_Authenticator, new object[] { "RefreshedCallback", new CallbackDelegate(RefreshedCallback) });
  399.                 UpdateMethod.Invoke(_Authenticator, new object[] { "SuspendedCallback", new CallbackDelegate(SuspendedCallback) });
  400.  
  401.                 MethodInfo InitializeMethod = _AuthenticatorType.GetMethod("Initialize");
  402.                 InitializeMethod.Invoke(_Authenticator, null);
  403.  
  404.                 DisposeMembers();
  405.  
  406.                 RestoreCulture(Culture);
  407.             }
  408.             catch (Exception ex)
  409.             {
  410.                 HandleException(ex);
  411.             }
  412.         }
  413.  
  414.         private void InitializeWebHandling()
  415.         {
  416.             _DnsClient = new DnsClient();
  417.             _HttpClient = new HttpClient();
  418.  
  419.             _HttpClient.RequestThrottleTime = 100;
  420.             _HttpClient.MaxConcurrentRequests = 1;
  421.  
  422.             _HttpClient.WebRequestResolveHost += HttpClient_WebRequestResolveHost;
  423.         }
  424.  
  425.         private void InitializeComponentTransform()
  426.         {
  427.             RijndaelManaged Aes = new RijndaelManaged();
  428.             Aes.BlockSize = 128;
  429.             Aes.KeySize = 128;
  430.             Aes.Padding = PaddingMode.PKCS7;
  431.             Aes.Mode = CipherMode.CBC;
  432.  
  433.             Aes.Key = _ComponentKey;
  434.             Aes.IV = Aes.Key;
  435.  
  436.             _ComponentAesEncryptor = Aes.CreateEncryptor();
  437.             _ComponentAesDecryptor = Aes.CreateDecryptor();
  438.         }
  439.  
  440.         #endregion
  441.  
  442.         #region " Delegate Handling "
  443.  
  444.         private void AuthorizedCallback()
  445.         {
  446.             if (LicenseAuthorized != null)
  447.             {
  448.                 LicenseAuthorized(this, EventArgs.Empty);
  449.             }
  450.         }
  451.  
  452.         private void RefreshedCallback()
  453.         {
  454.             if (LicenseRefreshed != null)
  455.             {
  456.                 LicenseRefreshed(this, EventArgs.Empty);
  457.             }
  458.         }
  459.  
  460.         private void SuspendedCallback()
  461.         {
  462.             if (LicenseSuspended != null)
  463.             {
  464.                 LicenseSuspended(this, EventArgs.Empty);
  465.             }
  466.         }
  467.  
  468.         private string GetPostBody(int postId)
  469.         {
  470.             return (string)_AuthenticatorType.GetMethod("GetPostBody").Invoke(_Authenticator, new object[] { postId });
  471.         }
  472.  
  473.         #endregion
  474.  
  475.         #region " Exception Handling "
  476.  
  477.         private void HandleException(Exception ex)
  478.         {
  479.             string StackTrace = ExceptionToString(ex);
  480.  
  481.             StringBuilder Builder = new StringBuilder();
  482.             Builder.AppendFormat("[Loader: {0}]", _Version);
  483.             Builder.AppendLine();
  484.             Builder.AppendLine();
  485.             Builder.Append(StackTrace);
  486.  
  487.             ExceptionForm ExceptionForm = new ExceptionForm(Builder.ToString());
  488.             ExceptionForm.ShowDialog();
  489.  
  490.             Environment.Exit(0);
  491.         }
  492.  
  493.         private string ExceptionToString(Exception ex)
  494.         {
  495.             StringBuilder Builder = new StringBuilder();
  496.  
  497.             Builder.AppendLine(ex.Message);
  498.             Builder.AppendLine();
  499.             Builder.AppendLine(ex.GetType().FullName);
  500.             Builder.AppendLine(ex.StackTrace);
  501.  
  502.             if (ex.InnerException != null)
  503.             {
  504.                 Builder.AppendLine();
  505.                 Builder.AppendLine(ExceptionToString(ex.InnerException));
  506.             }
  507.  
  508.             return Builder.ToString();
  509.         }
  510.  
  511.         private void EnsureInitialization()
  512.         {
  513.             if (_Authenticator == null)
  514.             {
  515.                 throw new Exception("Loader has not been initialized.");
  516.             }
  517.         }
  518.  
  519.         #endregion
  520.  
  521.         #region " Verification "
  522.  
  523.         private void CheckFrameworkStrongNames()
  524.         {
  525.             string Base = RuntimeEnvironment.GetRuntimeDirectory();
  526.             byte[] EcmaToken = new byte[] { 183, 122, 92, 86, 25, 52, 224, 137 }; //b77a5c561934e089
  527.             byte[] FinalToken = new byte[] { 176, 63, 95, 127, 17, 213, 10, 58 }; //b03f5f7f11d50a3a
  528.  
  529.             CheckStrongName(Path.Combine(Base, "mscorlib.dll"), EcmaToken);
  530.             CheckStrongName(Path.Combine(Base, "System.dll"), EcmaToken);
  531.             CheckStrongName(Path.Combine(Base, "System.Security.dll"), FinalToken);
  532.         }
  533.  
  534.         private void CheckStrongName(string fileName, byte[] token)
  535.         {
  536.             string AssemblyName = Path.GetFileName(fileName);
  537.  
  538.             if (!_StrongNameVerifier.VerifyStrongName(fileName, token))
  539.             {
  540.                 throw new Exception(string.Format("Could not verify strong name of file or assembly '{0}'.", AssemblyName));
  541.             }
  542.         }
  543.  
  544.         private void VerifyAuthenticator()
  545.         {
  546.             byte[] Signature = new byte[40];
  547.             byte[] ImageData = new byte[_AuthenticatorData.Length - 42];
  548.  
  549.             Buffer.BlockCopy(_AuthenticatorData, 2, Signature, 0, Signature.Length);
  550.             Buffer.BlockCopy(_AuthenticatorData, 42, ImageData, 0, ImageData.Length);
  551.  
  552.             DSACryptoServiceProvider DsaProvider = new DSACryptoServiceProvider();
  553.             DsaProvider.ImportCspBlob(_AuthenticatorKey);
  554.  
  555.             if (!DsaProvider.VerifyData(ImageData, Signature))
  556.             {
  557.                 throw new Exception("Could not verify signature of authenticator.");
  558.             }
  559.         }
  560.  
  561.         #endregion
  562.  
  563.         #region " Metadata "
  564.  
  565.         private string[] GetMetadata()
  566.         {
  567.             try
  568.             {
  569.                 byte[] Data = DownloadData(_PreferredMetadataEndPoint);
  570.                 return Encoding.UTF8.GetString(Data).Split(char.MinValue);
  571.             }
  572.             catch
  573.             {
  574.                 return GetMetadataFallback();
  575.             }
  576.         }
  577.  
  578.         private string[] GetMetadataFallback()
  579.         {
  580.             try
  581.             {
  582.                 byte[] Data = DownloadData(_AlternateMetadataEndPoint);
  583.                 return Encoding.UTF8.GetString(Data).Split('|');
  584.             }
  585.             catch (Exception ex)
  586.             {
  587.                 HandleException(ex);
  588.             }
  589.  
  590.             return null;
  591.         }
  592.  
  593.         private void ParseMetadata(string[] metadata)
  594.         {
  595.             _ComponentEndPoint = metadata[0];
  596.             _LzmaLibHash = metadata[1];
  597.             _AuthenticatorHash = metadata[3];
  598.             _ServerEndPoint = metadata[5];
  599.         }
  600.  
  601.         #endregion
  602.  
  603.         #region " Hashing "
  604.  
  605.         private string Md5HashData(byte[] data)
  606.         {
  607.             MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
  608.             return ByteArrayToString(MD5.ComputeHash(data));
  609.         }
  610.  
  611.         private string ByteArrayToString(byte[] data)
  612.         {
  613.             return BitConverter.ToString(data).ToLower().Replace("-", string.Empty);
  614.         }
  615.  
  616.         #endregion
  617.  
  618.         #region " LzmaLib "
  619.  
  620.         private void InitializeLzmaLib()
  621.         {
  622.             string LzmaLibFileName = GetLzmaLibFileName();
  623.  
  624.             if (File.Exists(LzmaLibFileName))
  625.             {
  626.                 _LzmaLibData = LoadComponentData(LzmaLibFileName);
  627.  
  628.                 if (!_LzmaLibHash.Equals(Md5HashData(_LzmaLibData)))
  629.                 {
  630.                     _LzmaLibData = InstallLzmaLib(LzmaLibFileName);
  631.                 }
  632.             }
  633.             else
  634.             {
  635.                 _LzmaLibData = InstallLzmaLib(LzmaLibFileName);
  636.             }
  637.         }
  638.  
  639.         private byte[] InstallLzmaLib(string fileName)
  640.         {
  641.             string Url = GetComponentEndPoint(_LzmaLibHash);
  642.             byte[] Data = DeflateDecompress(DownloadData(Url));
  643.  
  644.             SaveComponentData(fileName, Data);
  645.  
  646.             return Data;
  647.         }
  648.  
  649.         private string GetLzmaLibFileName()
  650.         {
  651.             return Path.Combine(_ProductDirectory, "LzmaLib.bin");
  652.         }
  653.  
  654.         #endregion
  655.  
  656.         #region " Authenticator "
  657.  
  658.         private void InitializeAuthenticator()
  659.         {
  660.             string AuthenticatorFileName = GetAuthenticatorFileName();
  661.  
  662.             if (File.Exists(AuthenticatorFileName))
  663.             {
  664.                 _AuthenticatorData = LoadComponentData(AuthenticatorFileName);
  665.  
  666.                 if (!_AuthenticatorHash.Equals(Md5HashData(_AuthenticatorData)))
  667.                 {
  668.                     _AuthenticatorData = InstallAuthenticator(AuthenticatorFileName);
  669.                 }
  670.             }
  671.             else
  672.             {
  673.                 _AuthenticatorData = InstallAuthenticator(AuthenticatorFileName);
  674.             }
  675.         }
  676.  
  677.         private byte[] InstallAuthenticator(string fileName)
  678.         {
  679.             string Url = GetComponentEndPoint(_AuthenticatorHash);
  680.             byte[] Data = LzmaDecompress(DownloadData(Url));
  681.  
  682.             SaveComponentData(fileName, Data);
  683.  
  684.             return Data;
  685.         }
  686.  
  687.         private string GetAuthenticatorFileName()
  688.         {
  689.             return Path.Combine(_ProductDirectory, "License.bin");
  690.         }
  691.  
  692.         #endregion
  693.  
  694.         #region " Component Helpers "
  695.  
  696.         private string GetComponentEndPoint(string hash)
  697.         {
  698.             return Path.Combine(_ComponentEndPoint, hash) + ".co";
  699.         }
  700.  
  701.         private byte[] LoadComponentData(string fileName)
  702.         {
  703.             byte[] Data = File.ReadAllBytes(fileName);
  704.  
  705.             return _ComponentAesDecryptor.TransformFinalBlock(Data, 0, Data.Length);
  706.         }
  707.  
  708.         private void SaveComponentData(string fileName, byte[] data)
  709.         {
  710.             byte[] ComponentData = _ComponentAesEncryptor.TransformFinalBlock(data, 0, data.Length);
  711.  
  712.             File.WriteAllBytes(fileName, ComponentData);
  713.         }
  714.  
  715.         #endregion
  716.  
  717.         #region " Decompression "
  718.  
  719.         private byte[] DeflateDecompress(byte[] data)
  720.         {
  721.             int Length = BitConverter.ToInt32(data, 0);
  722.  
  723.             byte[] Buffer = new byte[Length];
  724.             MemoryStream Stream = new MemoryStream(data, 4, data.Length - 4);
  725.  
  726.             DeflateStream Deflate = new DeflateStream(Stream, CompressionMode.Decompress, false);
  727.             Deflate.Read(Buffer, 0, Buffer.Length);
  728.  
  729.             Deflate.Close();
  730.             Stream.Close();
  731.  
  732.             return Buffer;
  733.         }
  734.  
  735.         private byte[] LzmaDecompress(byte[] data)
  736.         {
  737.             if (_LzmaLibType == null)
  738.             {
  739.                 _LzmaLibType = Assembly.Load(_LzmaLibData).GetType("H");
  740.             }
  741.  
  742.             return (byte[])_LzmaLibType.GetMethod("Decompress").Invoke(null, new object[] { data });
  743.         }
  744.  
  745.         #endregion
  746.  
  747.         #region " Helpers "
  748.  
  749.         private byte[] DownloadData(string url)
  750.         {
  751.             HttpClient.RequestOptions Options = new HttpClient.RequestOptions();
  752.             Options.Timeout = 60000;
  753.             Options.RetryCount = 3;
  754.             Options.Proxy = null;
  755.             Options.Method = "GET";
  756.  
  757.             return _HttpClient.UploadValues(url, null, Options);
  758.         }
  759.  
  760.         private string GetProductDirectory()
  761.         {
  762.             return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Net Seal");
  763.         }
  764.  
  765.         private ThreadCulture NormalizeCulture()
  766.         {
  767.             Thread Thread = System.Threading.Thread.CurrentThread;
  768.             ThreadCulture Culture = new ThreadCulture(Thread.CurrentCulture, Thread.CurrentUICulture);
  769.  
  770.             Thread.CurrentCulture = CultureInfo.InvariantCulture;
  771.             Thread.CurrentUICulture = CultureInfo.InvariantCulture;
  772.  
  773.             return Culture;
  774.         }
  775.  
  776.         private void RestoreCulture(ThreadCulture threadCulture)
  777.         {
  778.             Thread Thread = System.Threading.Thread.CurrentThread;
  779.  
  780.             Thread.CurrentCulture = threadCulture.Culture;
  781.             Thread.CurrentUICulture = threadCulture.UICulture;
  782.         }
  783.  
  784.         #endregion
  785.  
  786.         #region " Disposal "
  787.  
  788.         private void DisposeMembers()
  789.         {
  790.             _LzmaLibData = null;
  791.             _AuthenticatorData = null;
  792.             _ComponentKey = null;
  793.             _AuthenticatorKey = null;
  794.  
  795.             _ComponentEndPoint = null;
  796.             _ServerEndPoint = null;
  797.             _AuthenticatorHash = null;
  798.             _LzmaLibHash = null;
  799.             _PreferredMetadataEndPoint = null;
  800.             _AlternateMetadataEndPoint = null;
  801.  
  802.             _LzmaLibType = null;
  803.  
  804.             _HttpClient = null;
  805.             _DnsClient = null;
  806.             _StrongNameVerifier = null;
  807.  
  808.             _ComponentAesDecryptor = null;
  809.             _ComponentAesEncryptor = null;
  810.         }
  811.  
  812.         #endregion
  813.  
  814.         #region " Private Types "
  815.  
  816.         private sealed class ThreadCulture
  817.         {
  818.  
  819.             public CultureInfo Culture
  820.             {
  821.                 get { return _Culture; }
  822.             }
  823.  
  824.             public CultureInfo UICulture
  825.             {
  826.                 get { return _UICulture; }
  827.             }
  828.  
  829.             private CultureInfo _Culture;
  830.  
  831.             private CultureInfo _UICulture;
  832.             public ThreadCulture(CultureInfo culture, CultureInfo uiCulture)
  833.             {
  834.                 _Culture = culture;
  835.                 _UICulture = uiCulture;
  836.             }
  837.  
  838.         }
  839.  
  840.         private sealed class StrongNameVerifierLite
  841.         {
  842.  
  843.             private string _RuntimeVersion;
  844.             private IStrongName _StrongName;
  845.  
  846.             private bool _UsingComInterfaces;
  847.             public StrongNameVerifierLite()
  848.             {
  849.                 _RuntimeVersion = RuntimeEnvironment.GetSystemVersion();
  850.  
  851.                 if (Int32.Parse(_RuntimeVersion[1].ToString()) >= 4)
  852.                 {
  853.                     _UsingComInterfaces = true;
  854.                     InitializeComInterfaces();
  855.                 }
  856.             }
  857.  
  858.             private void InitializeComInterfaces()
  859.             {
  860.                 Guid CID_META_HOST = new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE");
  861.                 Guid CID_STRONG_NAME = new Guid("B79B0ACD-F5CD-409B-B5A5-A16244610B92");
  862.  
  863.                 IMeta Meta = (IMeta)CLRCreateInstance(CID_META_HOST, typeof(IMeta).GUID);
  864.                 IRuntime Runtime = (IRuntime)Meta.GetRuntime(_RuntimeVersion, typeof(IRuntime).GUID);
  865.  
  866.                 _StrongName = (IStrongName)Runtime.GetInterface(CID_STRONG_NAME, typeof(IStrongName).GUID);
  867.             }
  868.  
  869.             public bool VerifyStrongName(string assemblyPath, byte[] publicToken)
  870.             {
  871.                 return VerifyStrongName(assemblyPath, publicToken, false);
  872.             }
  873.  
  874.             public bool VerifyStrongName(string assemblyPath, byte[] publicToken, bool ignoreToken)
  875.             {
  876.                 IntPtr Token = default(IntPtr);
  877.                 int TokenLength = 0;
  878.                 bool Genuine = false;
  879.  
  880.                 if (_UsingComInterfaces)
  881.                 {
  882.                     if (!(_StrongName.StrongNameSignatureVerificationEx(assemblyPath, true, ref Genuine) == 0 && Genuine))
  883.                     {
  884.                         return false;
  885.                     }
  886.  
  887.                     if (!ignoreToken && !(_StrongName.StrongNameTokenFromAssembly(assemblyPath, ref Token, ref TokenLength) == 0))
  888.                     {
  889.                         return false;
  890.                     }
  891.                 }
  892.                 else
  893.                 {
  894.                     if (!(StrongNameSignatureVerificationEx(assemblyPath, true, ref Genuine) && Genuine))
  895.                     {
  896.                         return false;
  897.                     }
  898.  
  899.                     if (!ignoreToken && !StrongNameTokenFromAssembly(assemblyPath, ref Token, ref TokenLength))
  900.                     {
  901.                         return false;
  902.                     }
  903.                 }
  904.  
  905.                 if (!ignoreToken)
  906.                 {
  907.                     byte[] TokenData = new byte[TokenLength];
  908.                     Marshal.Copy(Token, TokenData, 0, TokenLength);
  909.  
  910.                     if (_UsingComInterfaces)
  911.                     {
  912.                         _StrongName.StrongNameFreeBuffer(Token);
  913.                     }
  914.                     else
  915.                     {
  916.                         StrongNameFreeBuffer(Token);
  917.                     }
  918.  
  919.                     if (!(TokenData.Length == publicToken.Length))
  920.                     {
  921.                         return false;
  922.                     }
  923.  
  924.                     for (int I = 0; I <= TokenData.Length - 1; I++)
  925.                     {
  926.                         if (!(TokenData[I] == publicToken[I]))
  927.                             return false;
  928.                     }
  929.                 }
  930.  
  931.                 return true;
  932.             }
  933.  
  934.             [DllImport("mscoree.dll", EntryPoint = "StrongNameFreeBuffer")]
  935.             private static extern void StrongNameFreeBuffer(IntPtr token);
  936.  
  937.             [DllImport("mscoree.dll", EntryPoint = "StrongNameSignatureVerificationEx", CharSet = CharSet.Unicode)]
  938.             private static extern bool StrongNameSignatureVerificationEx(string fileName, bool force, ref bool genuine);
  939.  
  940.             [DllImport("mscoree.dll", EntryPoint = "StrongNameTokenFromAssembly", CharSet = CharSet.Unicode)]
  941.             private static extern bool StrongNameTokenFromAssembly(string fileName, ref IntPtr token, ref int tokenLength);
  942.  
  943.             [DllImport("mscoree.dll", PreserveSig = false, EntryPoint = "CLRCreateInstance")]
  944.             [return: MarshalAs(UnmanagedType.Interface)]
  945.             private static extern object CLRCreateInstance([MarshalAs(UnmanagedType.LPStruct)] Guid cid, [MarshalAs(UnmanagedType.LPStruct)] Guid iid);
  946.  
  947.             [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("D332DB9E-B9B3-4125-8207-A14884F53216")]
  948.             private interface IMeta
  949.             {
  950.                 [return: MarshalAs(UnmanagedType.Interface)]
  951.                 object GetRuntime(string version, [MarshalAs(UnmanagedType.LPStruct)] Guid iid);
  952.             }
  953.  
  954.             [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
  955.             private interface IRuntime
  956.             {
  957.                 void Reserved1();
  958.                 void Reserved2();
  959.                 void Reserved3();
  960.                 void Reserved4();
  961.                 void Reserved5();
  962.                 void Reserved6();
  963.                 [return: MarshalAs(UnmanagedType.Interface)]
  964.                 object GetInterface([MarshalAs(UnmanagedType.LPStruct)] Guid cid, [MarshalAs(UnmanagedType.LPStruct)] Guid iid);
  965.             }
  966.  
  967.             [InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("9FD93CCF-3280-4391-B3A9-96E1CDE77C8D")]
  968.             private interface IStrongName
  969.             {
  970.                 void Reserved1();
  971.                 void Reserved2();
  972.                 void Reserved3();
  973.                 void Reserved4();
  974.                 void Reserved5();
  975.                 void Reserved6();
  976.                 void Reserved7();
  977.                 int StrongNameFreeBuffer(IntPtr token);
  978.                 void Reserved8();
  979.                 void Reserved9();
  980.                 void Reserved10();
  981.                 void Reserved11();
  982.                 void Reserved12();
  983.                 void Reserved13();
  984.                 void Reserved14();
  985.                 void Reserved15();
  986.                 void Reserved16();
  987.                 void Reserved17();
  988.                 void Reserved18();
  989.                 void Reserved19();
  990.                 int StrongNameSignatureVerificationEx(string filePath, bool force, ref bool genuine);
  991.                 void Reserved20();
  992.                 int StrongNameTokenFromAssembly(string filePath, ref IntPtr token, ref int tokenLength);
  993.             }
  994.  
  995.         }
  996.  
  997.         private sealed class ExceptionForm : Form
  998.         {
  999.  
  1000.             public ExceptionForm(string stackTrace)
  1001.             {
  1002.                 SuspendLayout();
  1003.  
  1004.                 PictureBox PictureBox = new PictureBox();
  1005.                 PictureBox.Location = new Point(12, 9);
  1006.                 PictureBox.Size = new Size(32, 32);
  1007.                 PictureBox.TabStop = false;
  1008.                 PictureBox.Image = SystemIcons.Error.ToBitmap();
  1009.  
  1010.                 Label Label = new Label();
  1011.                 Label.Anchor = (AnchorStyles)13;
  1012.                 Label.AutoEllipsis = true;
  1013.                 Label.Font = new Font("Verdana", 8.25f);
  1014.                 Label.Location = new Point(50, 9);
  1015.                 Label.Size = new Size(367, 32);
  1016.                 Label.Text = "The application has encountered an unexpected exception and must terminate.";
  1017.                 Label.TextAlign = ContentAlignment.MiddleLeft;
  1018.  
  1019.                 TextBox TextBox = new TextBox();
  1020.                 TextBox.Anchor = (AnchorStyles)15;
  1021.                 TextBox.BackColor = SystemColors.Window;
  1022.                 TextBox.Font = new Font("Verdana", 8.25f);
  1023.                 TextBox.Location = new Point(12, 47);
  1024.                 TextBox.Multiline = true;
  1025.                 TextBox.ReadOnly = true;
  1026.                 TextBox.ScrollBars = ScrollBars.Vertical;
  1027.                 TextBox.Size = new Size(405, 183);
  1028.                 TextBox.Text = stackTrace;
  1029.  
  1030.                 Button Button = new Button();
  1031.                 Button.Anchor = (AnchorStyles)10;
  1032.                 Button.DialogResult = (DialogResult)2;
  1033.                 Button.Font = new Font("Verdana", 8.25f);
  1034.                 Button.Location = new Point(312, 236);
  1035.                 Button.Size = new Size(105, 26);
  1036.                 Button.TabIndex = 0;
  1037.                 Button.Text = "Close";
  1038.                 Button.UseVisualStyleBackColor = true;
  1039.  
  1040.                 Text = "Application Error";
  1041.                 ClientSize = new Size(430, 270);
  1042.                 MinimumSize = new Size(360, 245);
  1043.                 MaximizeBox = false;
  1044.                 MinimizeBox = false;
  1045.                 ShowIcon = false;
  1046.  
  1047.                 Controls.Add(PictureBox);
  1048.                 Controls.Add(Label);
  1049.                 Controls.Add(TextBox);
  1050.                 Controls.Add(Button);
  1051.  
  1052.                 ResumeLayout(false);
  1053.                 PerformLayout();
  1054.             }
  1055.  
  1056.         }
  1057.  
  1058.         #endregion
  1059.  
  1060.     }
  1061.  
  1062.     #region " Public Types "
  1063.  
  1064.     internal sealed class DnsClient
  1065.     {
  1066.  
  1067.         #region " Properties "
  1068.  
  1069.         public IPAddress PreferredDnsServer
  1070.         {
  1071.             get { return _PreferredDnsServer; }
  1072.             set
  1073.             {
  1074.                 _PreferredDnsServer = value;
  1075.                 ClearCache();
  1076.             }
  1077.         }
  1078.  
  1079.         public IPAddress AlternateDnsServer
  1080.         {
  1081.             get { return _AlternateDnsServer; }
  1082.             set
  1083.             {
  1084.                 _AlternateDnsServer = value;
  1085.                 ClearCache();
  1086.             }
  1087.         }
  1088.  
  1089.         public bool IgnoreHostsFile
  1090.         {
  1091.             get { return _IgnoreHostsFile; }
  1092.             set
  1093.             {
  1094.                 _IgnoreHostsFile = value;
  1095.                 ClearCache();
  1096.             }
  1097.         }
  1098.  
  1099.         public bool IgnoreResolverCache
  1100.         {
  1101.             get { return _IgnoreResolverCache; }
  1102.             set
  1103.             {
  1104.                 _IgnoreResolverCache = value;
  1105.                 ClearCache();
  1106.             }
  1107.         }
  1108.  
  1109.         public bool SystemDnsFallback
  1110.         {
  1111.             get { return _SystemDnsFallback; }
  1112.             set
  1113.             {
  1114.                 _SystemDnsFallback = value;
  1115.                 ClearCache();
  1116.             }
  1117.         }
  1118.  
  1119.         public bool CacheDnsResults
  1120.         {
  1121.             get { return _CacheDnsResults; }
  1122.             set
  1123.             {
  1124.                 _CacheDnsResults = value;
  1125.                 ClearCache();
  1126.             }
  1127.         }
  1128.  
  1129.         public int CacheTTL
  1130.         {
  1131.             get { return _CacheTTL; }
  1132.             set { _CacheTTL = value; }
  1133.         }
  1134.  
  1135.         #endregion
  1136.  
  1137.         #region " Members "
  1138.  
  1139.         private IPAddress _PreferredDnsServer;
  1140.  
  1141.         private IPAddress _AlternateDnsServer;
  1142.         private bool _IgnoreHostsFile;
  1143.         private bool _IgnoreResolverCache;
  1144.  
  1145.         private bool _SystemDnsFallback;
  1146.         private bool _CacheDnsResults;
  1147.  
  1148.         private int _CacheTTL;
  1149.  
  1150.         private Dictionary<string, DnsResult> Cache;
  1151.         #endregion
  1152.  
  1153.         #region " Constructor "
  1154.  
  1155.         public DnsClient()
  1156.         {
  1157.             _PreferredDnsServer = new IPAddress(new byte[] { 8, 8, 8, 8 }); //NOTE: Google preferred DNS server
  1158.             _AlternateDnsServer = new IPAddress(new byte[] { 8, 8, 4, 4 }); //NOTE: Google alternate DNS server
  1159.  
  1160.             _CacheTTL = 900; //NOTE: 15 minutes.
  1161.  
  1162.             _IgnoreHostsFile = true;
  1163.             _IgnoreResolverCache = true;
  1164.             _SystemDnsFallback = true;
  1165.             _CacheDnsResults = true;
  1166.  
  1167.             Cache = new Dictionary<string, DnsResult>();
  1168.         }
  1169.  
  1170.         #endregion
  1171.  
  1172.         #region " DNS Handling "
  1173.  
  1174.         public IPAddress[] Resolve(string hostName)
  1175.         {
  1176.             IPAddress IP = IPAddress.None;
  1177.  
  1178.             //NOTE: If we get an IP address just return it.
  1179.             if (IPAddress.TryParse(hostName, out IP))
  1180.             {
  1181.                 if (IP.AddressFamily == AddressFamily.InterNetwork)
  1182.                 {
  1183.                     return new IPAddress[] { IP };
  1184.                 }
  1185.                 else
  1186.                 {
  1187.                     //NOTE: For the sake of consistency we should reject IPv6 addresses.
  1188.                     throw new NotImplementedException("IPv6 addresses are not supported.");
  1189.                 }
  1190.             }
  1191.  
  1192.             if (IsHostNameValid(hostName))
  1193.             {
  1194.                 IPAddress[] AddressList = null;
  1195.  
  1196.                 //NOTE: Host names should be normalized for caching.
  1197.                 string Host = hostName.Trim().ToLower();
  1198.  
  1199.                 if (CacheDnsResults)
  1200.                 {
  1201.                     AddressList = QueryCache(Host);
  1202.  
  1203.                     if (!(AddressList.Length == 0))
  1204.                     {
  1205.                         return AddressList;
  1206.                     }
  1207.                 }
  1208.  
  1209.                 if (PreferredDnsServer != null)
  1210.                 {
  1211.                     AddressList = GetDnsRecords(Host, PreferredDnsServer);
  1212.  
  1213.                     if (!(AddressList.Length == 0))
  1214.                     {
  1215.                         return CacheResults(Host, AddressList);
  1216.                     }
  1217.                 }
  1218.  
  1219.                 if (AlternateDnsServer != null)
  1220.                 {
  1221.                     AddressList = GetDnsRecords(Host, AlternateDnsServer);
  1222.  
  1223.                     if (!(AddressList.Length == 0))
  1224.                     {
  1225.                         return CacheResults(Host, AddressList);
  1226.                     }
  1227.                 }
  1228.  
  1229.                 //NOTE: This is required when resolving LAN host names.
  1230.                 if (SystemDnsFallback)
  1231.                 {
  1232.                     AddressList = GetDnsRecords(Host, null);
  1233.  
  1234.                     if (!(AddressList.Length == 0))
  1235.                     {
  1236.                         return CacheResults(Host, AddressList);
  1237.                     }
  1238.                 }
  1239.             }
  1240.  
  1241.             return new IPAddress[] { };
  1242.         }
  1243.  
  1244.         private IPAddress[] GetDnsRecords(string hostName, IPAddress dnsServer)
  1245.         {
  1246.             IntPtr QueryList = default(IntPtr);
  1247.             List<IPAddress> Addresses = new List<IPAddress>();
  1248.  
  1249.             IntPtr reserved = IntPtr.Zero;
  1250.             IPv4Array IPv4Array = GetIPv4ArrayFromIPAddress(dnsServer);
  1251.  
  1252.             if (DnsQueryA(hostName, 1, 8 | 64, ref IPv4Array, ref QueryList, ref reserved) == 0)
  1253.             {
  1254.                 DnsRecordA Record = (DnsRecordA)Marshal.PtrToStructure(QueryList, typeof(DnsRecordA));
  1255.                 IPAddress Address = GetAddressFromRecord(Record);
  1256.  
  1257.                 if (!object.ReferenceEquals(Address, IPAddress.None))
  1258.                 {
  1259.                     Addresses.Add(Address);
  1260.                 }
  1261.  
  1262.                 while (!(Record.NextRecord == IntPtr.Zero))
  1263.                 {
  1264.                     Record = (DnsRecordA)Marshal.PtrToStructure(Record.NextRecord, typeof(DnsRecordA));
  1265.                     Address = GetAddressFromRecord(Record);
  1266.  
  1267.                     if (!object.ReferenceEquals(Address, IPAddress.None))
  1268.                     {
  1269.                         Addresses.Add(Address);
  1270.                     }
  1271.                 }
  1272.             }
  1273.  
  1274.             return Addresses.ToArray();
  1275.         }
  1276.  
  1277.         private IPv4Array GetIPv4ArrayFromIPAddress(IPAddress address)
  1278.         {
  1279.             IPv4Array IP4rray = new IPv4Array();
  1280.  
  1281.             if (address != null)
  1282.             {
  1283.                 IP4rray.Count = 1;
  1284.                 IP4rray.Addresses = new uint[] { BitConverter.ToUInt32(address.GetAddressBytes(), 0) };
  1285.             }
  1286.  
  1287.             return IP4rray;
  1288.         }
  1289.  
  1290.         private IPAddress GetAddressFromRecord(DnsRecordA record)
  1291.         {
  1292.             if (!(record.Type == 1))
  1293.             {
  1294.                 return IPAddress.None;
  1295.             }
  1296.  
  1297.             if (!((record.Flags & 3) < 2))
  1298.             {
  1299.                 return IPAddress.None;
  1300.             }
  1301.  
  1302.             return new IPAddress(record.Data);
  1303.         }
  1304.  
  1305.         #endregion
  1306.  
  1307.         #region " Cache Handling "
  1308.  
  1309.         private void ClearCache()
  1310.         {
  1311.             Cache.Clear();
  1312.         }
  1313.  
  1314.         private IPAddress[] QueryCache(string hostName)
  1315.         {
  1316.             if (Cache.ContainsKey(hostName))
  1317.             {
  1318.                 DnsResult Result = Cache[hostName];
  1319.  
  1320.                 if ((System.DateTime.Now - Result.ResolutionTime).TotalSeconds > CacheTTL)
  1321.                 {
  1322.                     Cache.Remove(hostName);
  1323.                 }
  1324.                 else
  1325.                 {
  1326.                     return Result.AddressList;
  1327.                 }
  1328.             }
  1329.  
  1330.             return new IPAddress[] { };
  1331.         }
  1332.  
  1333.         private IPAddress[] CacheResults(string hostName, IPAddress[] addressList)
  1334.         {
  1335.             if (CacheDnsResults)
  1336.             {
  1337.                 Cache.Add(hostName, new DnsResult(addressList));
  1338.             }
  1339.  
  1340.             return addressList;
  1341.         }
  1342.  
  1343.         #endregion
  1344.  
  1345.         #region " Validation "
  1346.  
  1347.         private bool IsHostNameValid(string hostName)
  1348.         {
  1349.             //NOTE: RFC 2181 [Sec. 11] states a maximum length of 255 characters.
  1350.             if (hostName.Length > byte.MaxValue)
  1351.             {
  1352.                 throw new ArgumentOutOfRangeException("hostName", "Host name must not exceed 255 characters.");
  1353.             }
  1354.  
  1355.             string[] Labels = null;
  1356.  
  1357.             if (hostName.Contains("."))
  1358.             {
  1359.                 Labels = hostName.Split('.');
  1360.             }
  1361.             else
  1362.             {
  1363.                 Labels = new string[] { hostName };
  1364.             }
  1365.  
  1366.             //NOTE: RFC 952 [Sec. 1] & RFC 1123 [Sec. 2.1] states host names should follow these naming conventions.
  1367.             //-Labels (delimited by periods) must be between 1 and 63 characters long.
  1368.             //-Labels must start and end with alphanumeric characters.
  1369.             //-Host names may only contains letters a-z, digits 0-9, hyphen (-), and periods (.).
  1370.  
  1371.             foreach (string Label in Labels)
  1372.             {
  1373.                 if (Label.Length == 0 || Label.Length > 63)
  1374.                 {
  1375.                     throw new FormatException("Labels in host names must be between 1 and 63 characters in length.");
  1376.                 }
  1377.  
  1378.                 int FirstChar = Convert.ToInt32(Label[0]);
  1379.                 int LastChar = Convert.ToInt32(Label[Label.Length - 1]);
  1380.  
  1381.                 if (!(IsLetterOrDigit(FirstChar) || IsLetterOrDigit(LastChar)))
  1382.                 {
  1383.                     throw new FormatException("Labels in host names must begin and end with alphanumeric ASCII characters.");
  1384.                 }
  1385.  
  1386.                 for (int I = 1; I <= Label.Length - 2; I++)
  1387.                 {
  1388.                     int Value = Convert.ToInt32(Label[I]);
  1389.  
  1390.                     if (!(IsLetterOrDigit(Value) || IsHyphen(Value)))
  1391.                     {
  1392.                         throw new FormatException("Host names may only contain alphanumeric ASCII characters, hyphens (-), and periods (.).");
  1393.                     }
  1394.                 }
  1395.             }
  1396.  
  1397.             return true;
  1398.         }
  1399.  
  1400.         private bool IsLetterOrDigit(int value)
  1401.         {
  1402.             return (value >= 48 && value <= 57) || (value >= 65 && value <= 90) || (value >= 97 && value <= 122);
  1403.         }
  1404.  
  1405.         private bool IsHyphen(int value)
  1406.         {
  1407.             return value == 45;
  1408.         }
  1409.  
  1410.         #endregion
  1411.  
  1412.         #region " Win32 "
  1413.  
  1414.         [DllImport("dnsapi.dll", EntryPoint = "DnsQuery_A")]
  1415.         private static extern int DnsQueryA(string hostName, short type, int options, ref IPv4Array dnsServers, ref IntPtr recordList, ref IntPtr reserved);
  1416.  
  1417.         #endregion
  1418.  
  1419.         #region " Type Definitions "
  1420.  
  1421.         private class DnsResult
  1422.         {
  1423.  
  1424.             public readonly System.DateTime ResolutionTime;
  1425.  
  1426.             public readonly IPAddress[] AddressList;
  1427.             public DnsResult(IPAddress[] addressesList)
  1428.             {
  1429.                 this.ResolutionTime = System.DateTime.Now;
  1430.                 this.AddressList = addressesList;
  1431.             }
  1432.  
  1433.         }
  1434.  
  1435.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  1436.         private struct DnsRecordA
  1437.         {
  1438.             public IntPtr NextRecord;
  1439.             public string Name;
  1440.             public short Type;
  1441.             public short DataLength;
  1442.             public int Flags;
  1443.             public int Ttl;
  1444.             public int Reserved;
  1445.             public uint Data;
  1446.         }
  1447.  
  1448.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  1449.         private struct IPv4Array
  1450.         {
  1451.             public int Count;
  1452.             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1, ArraySubType = UnmanagedType.U4)]
  1453.             public uint[] Addresses;
  1454.         }
  1455.  
  1456.         #endregion
  1457.  
  1458.     }
  1459.  
  1460.     internal sealed class HttpClient
  1461.     {
  1462.  
  1463.         #region " Properties "
  1464.  
  1465.         public bool BypassPageCaching
  1466.         {
  1467.             get { return _BypassPageCaching; }
  1468.             set { _BypassPageCaching = value; }
  1469.         }
  1470.  
  1471.         public int RequestThrottleTime
  1472.         {
  1473.             get { return _RequestThrottleTime; }
  1474.             set { _RequestThrottleTime = Math.Max(value, 0); }
  1475.         }
  1476.  
  1477.         public int MaxConcurrentRequests
  1478.         {
  1479.             get { return _MaxConcurrentRequests; }
  1480.             set { _MaxConcurrentRequests = Math.Max(value, 0); }
  1481.         }
  1482.  
  1483.         public int RetryDelayTime
  1484.         {
  1485.             get { return _RetryDelayTime; }
  1486.             set { _RetryDelayTime = Math.Max(value, 0); }
  1487.         }
  1488.  
  1489.         #endregion
  1490.  
  1491.         #region " Events "
  1492.  
  1493.         public event WebRequestDownloadProgressEventHandler WebRequestDownloadProgress;
  1494.         public delegate void WebRequestDownloadProgressEventHandler(object sender, WebRequestProgressEventArgs e);
  1495.  
  1496.         public event WebRequestUploadProgressEventHandler WebRequestUploadProgress;
  1497.         public delegate void WebRequestUploadProgressEventHandler(object sender, WebRequestProgressEventArgs e);
  1498.  
  1499.         public event WebRequestCompletedEventHandler WebRequestCompleted;
  1500.         public delegate void WebRequestCompletedEventHandler(object sender, WebRequestCompletedEventArgs e);
  1501.  
  1502.         public event WebRequestResolveHostEventHandler WebRequestResolveHost;
  1503.         public delegate void WebRequestResolveHostEventHandler(object sender, WebRequestResolveHostEventArgs e);
  1504.  
  1505.         #endregion
  1506.  
  1507.         #region " Members "
  1508.  
  1509.         private int _RetryDelayTime;
  1510.         private int _ConcurrentRequests;
  1511.         private int _RequestThrottleTime;
  1512.         private int _MaxConcurrentRequests;
  1513.         private bool _BypassPageCaching;
  1514.         private System.DateTime _RequestTime;
  1515.  
  1516.         private object _ThrottleLock;
  1517.         #endregion
  1518.  
  1519.         #region " Constructor "
  1520.  
  1521.         public HttpClient()
  1522.         {
  1523.             _BypassPageCaching = true;
  1524.             _RetryDelayTime = 1000;
  1525.             _ThrottleLock = new object();
  1526.  
  1527.             ServicePointManager.CheckCertificateRevocationList = false;
  1528.             ServicePointManager.DnsRefreshTimeout = Timeout.Infinite;
  1529.             ServicePointManager.EnableDnsRoundRobin = false;
  1530.         }
  1531.  
  1532.         #endregion
  1533.  
  1534.         #region " Request Handling "
  1535.  
  1536.         public byte[] DownloadData(string host)
  1537.         {
  1538.             RequestOptions Options = new RequestOptions();
  1539.             Options.Method = "GET";
  1540.  
  1541.             return UploadValues(host, null, Options);
  1542.         }
  1543.  
  1544.         public byte[] UploadValues(string host, Dictionary<string, object> values)
  1545.         {
  1546.             return UploadValues(host, values, null);
  1547.         }
  1548.  
  1549.         public byte[] UploadValues(string host, Dictionary<string, object> values, RequestOptions options)
  1550.         {
  1551.             if(options == null){
  1552.                 options = new RequestOptions();
  1553.             }
  1554.            
  1555.             return ExecuteRequest(host, values, new RequestState(options, null, false));
  1556.         }
  1557.  
  1558.         public void DownloadDataAsync(string host)
  1559.         {
  1560.             RequestOptions Options = new RequestOptions();
  1561.             Options.Method = "GET";
  1562.  
  1563.             UploadValuesAsync(host, null, Options, null);
  1564.         }
  1565.  
  1566.         public void DownloadDataAsync(string host, object userState)
  1567.         {
  1568.             RequestOptions Options = new RequestOptions();
  1569.             Options.Method = "GET";
  1570.  
  1571.             UploadValuesAsync(host, null, Options, userState);
  1572.         }
  1573.  
  1574.         public void UploadValuesAsync(string host, Dictionary<string, object> values)
  1575.         {
  1576.             UploadValuesAsync(host, values, null, null);
  1577.         }
  1578.  
  1579.         public void UploadValuesAsync(string host, Dictionary<string, object> values, object userState)
  1580.         {
  1581.             UploadValuesAsync(host, values, null, userState);
  1582.         }
  1583.  
  1584.         public void UploadValuesAsync(string host, Dictionary<string, object> values, RequestOptions options)
  1585.         {
  1586.             UploadValuesAsync(host, values, options, null);
  1587.         }
  1588.  
  1589.         public void UploadValuesAsync(string host, Dictionary<string, object> values, RequestOptions options, object userState)
  1590.         {
  1591.             if(options == null){
  1592.                 options = new RequestOptions();
  1593.             }          
  1594.            
  1595.             ThreadPool.QueueUserWorkItem((object obj) => ExecuteRequest(host, values, new RequestState(options, userState, true)));
  1596.         }
  1597.  
  1598.         private void ThrottleRequest()
  1599.         {
  1600.             while (true)
  1601.             {
  1602.                 TimeSpan ElapsedTime = default(TimeSpan);
  1603.                 int CurrentRequests = _ConcurrentRequests;
  1604.  
  1605.                 if (_RequestThrottleTime == 0)
  1606.                 {
  1607.                     ElapsedTime = TimeSpan.MaxValue;
  1608.                 }
  1609.                 else
  1610.                 {
  1611.                     lock (_ThrottleLock)
  1612.                     {
  1613.                         ElapsedTime = (System.DateTime.Now - _RequestTime);
  1614.                     }
  1615.                 }
  1616.  
  1617.                 if (_MaxConcurrentRequests == 0)
  1618.                 {
  1619.                     CurrentRequests = -1;
  1620.                 }
  1621.  
  1622.                 if ((ElapsedTime.TotalMilliseconds > _RequestThrottleTime) && (CurrentRequests < _MaxConcurrentRequests))
  1623.                 {
  1624.                     break;
  1625.                 }
  1626.  
  1627.                 Thread.Sleep(15);
  1628.             }
  1629.         }
  1630.  
  1631.         private byte[] ExecuteRequest(string host, Dictionary<string, object> values, RequestState state)
  1632.         {
  1633.             Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  1634.             Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
  1635.  
  1636.             int Count = 0;
  1637.             WebRequest Request = null;
  1638.             Exception Error = null;
  1639.             byte[] Result = null;
  1640.             WebHeaderCollection Headers = null;
  1641.  
  1642.             while (state.Options.RetryCount >= Count)
  1643.             {
  1644.                 if ((_RequestThrottleTime > 0) || (_MaxConcurrentRequests > 0))
  1645.                 {
  1646.                     ThrottleRequest();
  1647.                 }
  1648.  
  1649.                 lock (_ThrottleLock)
  1650.                 {
  1651.                     if (System.DateTime.Now > _RequestTime)
  1652.                     {
  1653.                         _RequestTime = System.DateTime.Now;
  1654.                     }
  1655.                 }
  1656.  
  1657.                 Interlocked.Increment(ref _ConcurrentRequests);
  1658.  
  1659.                 try
  1660.                 {
  1661.                     Request = null;
  1662.                     Error = null;
  1663.                     Result = null;
  1664.  
  1665.                     Uri Address = PrepareUri(host, values, state.Options);
  1666.                     Request = PrepareWebRequest(Address, state.Options);
  1667.  
  1668.                     if ((values != null) && (state.Options.Method == "POST"))
  1669.                     {
  1670.                         WriteRequest(Request, values, state);
  1671.                     }
  1672.  
  1673.                     WebResponse Response = Request.GetResponse();
  1674.  
  1675.                     Result = ReadResponse(Response, state);
  1676.                     Headers = Response.Headers;
  1677.  
  1678.                     Interlocked.Decrement(ref _ConcurrentRequests);
  1679.  
  1680.                     break;
  1681.                 }
  1682.                 catch (Exception ex)
  1683.                 {
  1684.                     Error = ex;
  1685.                 }
  1686.  
  1687.                 Count += 1;
  1688.                 Interlocked.Decrement(ref _ConcurrentRequests);
  1689.  
  1690.                 Thread.Sleep(RetryDelayTime);
  1691.             }
  1692.  
  1693.             if (state.RaiseEvents)
  1694.             {
  1695.                 WebRequestCompletedEventArgs EventArgs = new WebRequestCompletedEventArgs(Error, Result, Headers, state.UserState);
  1696.  
  1697.                 if (WebRequestCompleted != null)
  1698.                 {
  1699.                     WebRequestCompleted(this, EventArgs);
  1700.                 }
  1701.             }
  1702.             else if (Error != null)
  1703.             {
  1704.                 throw Error;
  1705.             }
  1706.  
  1707.             return Result;
  1708.         }
  1709.  
  1710.         private Uri PrepareUri(string host, Dictionary<string, object> values, RequestOptions options)
  1711.         {
  1712.             UriBuilder UriBuilder = new UriBuilder(host);
  1713.             StringBuilder StringBuilder = new StringBuilder();
  1714.  
  1715.             if (UriBuilder.Query.Length > 0)
  1716.             {
  1717.                 StringBuilder.AppendFormat("{0}&", UriBuilder.Query.Substring(1));
  1718.             }
  1719.  
  1720.             if ((values != null) && (options.Method == "GET"))
  1721.             {
  1722.                 foreach (KeyValuePair<string, object> K in values)
  1723.                 {
  1724.                     StringBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(K.Key), Uri.EscapeDataString(K.Value.ToString()));
  1725.                 }
  1726.  
  1727.                 StringBuilder.Length -= 1;
  1728.             }
  1729.  
  1730.             if (_BypassPageCaching)
  1731.             {
  1732.                 StringBuilder.Append(Guid.NewGuid().ToString().Remove(8));
  1733.             }
  1734.  
  1735.             UriBuilder.Query = StringBuilder.ToString();
  1736.  
  1737.             return UriBuilder.Uri;
  1738.         }
  1739.  
  1740.         private HttpWebRequest PrepareWebRequest(Uri address, RequestOptions options)
  1741.         {
  1742.             HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(address);
  1743.  
  1744.             HttpRequest.Accept = null;
  1745.             HttpRequest.AllowAutoRedirect = true;
  1746.             HttpRequest.AllowWriteStreamBuffering = false;
  1747.             HttpRequest.AuthenticationLevel = AuthenticationLevel.None;
  1748.             HttpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  1749.             HttpRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
  1750.             HttpRequest.ClientCertificates = new X509CertificateCollection();
  1751.             HttpRequest.ConnectionGroupName = null;
  1752.             HttpRequest.ContentLength = 0;
  1753.             HttpRequest.ContinueDelegate = null;
  1754.             HttpRequest.Credentials = null;
  1755.             HttpRequest.CookieContainer = options.Cookies;
  1756.             HttpRequest.Expect = null;
  1757.             HttpRequest.ImpersonationLevel = TokenImpersonationLevel.None;
  1758.             HttpRequest.KeepAlive = true;
  1759.             HttpRequest.MaximumAutomaticRedirections = 10;
  1760.             HttpRequest.MaximumResponseHeadersLength = -1;
  1761.             HttpRequest.MediaType = null;
  1762.             HttpRequest.Method = options.Method;
  1763.             HttpRequest.Pipelined = true;
  1764.             HttpRequest.PreAuthenticate = false;
  1765.             HttpRequest.ProtocolVersion = HttpVersion.Version11;
  1766.             HttpRequest.Proxy = options.Proxy;
  1767.             HttpRequest.ReadWriteTimeout = options.Timeout;
  1768.             HttpRequest.Referer = options.Referer;
  1769.             HttpRequest.SendChunked = false;
  1770.             HttpRequest.Timeout = options.Timeout;
  1771.             HttpRequest.TransferEncoding = null;
  1772.             HttpRequest.UnsafeAuthenticatedConnectionSharing = true;
  1773.             HttpRequest.UseDefaultCredentials = false;
  1774.             HttpRequest.UserAgent = options.UserAgent;
  1775.  
  1776.             HttpRequest.ServicePoint.BindIPEndPointDelegate = BindIPEndPoint;
  1777.             HttpRequest.ServicePoint.ConnectionLeaseTimeout = 60000;
  1778.             HttpRequest.ServicePoint.ConnectionLimit = 100;
  1779.             HttpRequest.ServicePoint.Expect100Continue = false;
  1780.             HttpRequest.ServicePoint.MaxIdleTime = 10000;
  1781.             HttpRequest.ServicePoint.ReceiveBufferSize = ushort.MaxValue;
  1782.             HttpRequest.ServicePoint.UseNagleAlgorithm = true;
  1783.  
  1784.             if (_BypassPageCaching)
  1785.             {
  1786.                 HttpRequest.Headers["Cache-Control"] = "no-cache, no-store, no-transform";
  1787.                 HttpRequest.Headers["Pragma"] = "no-cache";
  1788.             }
  1789.  
  1790.             if (options.Headers != null)
  1791.             {
  1792.                 HttpRequest.Headers.Add(options.Headers);
  1793.             }
  1794.  
  1795.             return HttpRequest;
  1796.         }
  1797.  
  1798.         private byte[] PrepareRequestStream(Dictionary<string, object> values, string boundary)
  1799.         {
  1800.             MemoryStream MemoryStream = new MemoryStream();
  1801.             StreamWriter StreamWriter = new StreamWriter(MemoryStream);
  1802.  
  1803.             //NOTE: RFC 2388 describes the format of multipart/form-data POST requests.
  1804.  
  1805.             bool IsBinary = false;
  1806.  
  1807.             foreach (KeyValuePair<string, object> K in values)
  1808.             {
  1809.                 IsBinary = (K.Value is byte[]);
  1810.  
  1811.                 StreamWriter.WriteLine(string.Format("--{0}", boundary));
  1812.                 StreamWriter.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", K.Key));
  1813.  
  1814.                 if (IsBinary)
  1815.                 {
  1816.                     StreamWriter.WriteLine("Content-Type: application/octet-stream");
  1817.                 }
  1818.  
  1819.                 StreamWriter.WriteLine();
  1820.  
  1821.                 if (IsBinary)
  1822.                 {
  1823.                     byte[] ValueData = (byte[])K.Value;
  1824.  
  1825.                     StreamWriter.Flush();
  1826.                     MemoryStream.Write(ValueData, 0, ValueData.Length);
  1827.  
  1828.                     StreamWriter.WriteLine();
  1829.                 }
  1830.                 else
  1831.                 {
  1832.                     StreamWriter.WriteLine(K.Value);
  1833.                 }
  1834.             }
  1835.  
  1836.             StreamWriter.WriteLine(string.Format("--{0}--", boundary));
  1837.             StreamWriter.Close();
  1838.  
  1839.             return MemoryStream.ToArray();
  1840.         }
  1841.  
  1842.         private void WriteRequest(WebRequest request, Dictionary<string, object> values, RequestState state)
  1843.         {
  1844.             if (values.Count == 0)
  1845.             {
  1846.                 return;
  1847.             }
  1848.  
  1849.             string Boundary = System.DateTime.UtcNow.Ticks.ToString();
  1850.             byte[] Data = PrepareRequestStream(values, Boundary);
  1851.  
  1852.             request.ContentType = string.Format("multipart/form-data; boundary={0}", Boundary);
  1853.             request.ContentLength = Data.Length;
  1854.  
  1855.             int BytesToWrite = 0;
  1856.             int BytesTransferred = 0;
  1857.  
  1858.             Stream RequestStream = request.GetRequestStream();
  1859.  
  1860.             while (true)
  1861.             {
  1862.                 if (state.RaiseEvents)
  1863.                 {
  1864.                     if (WebRequestUploadProgress != null)
  1865.                     {
  1866.                         WebRequestUploadProgress(this, new WebRequestProgressEventArgs(BytesTransferred, Data.Length, state.UserState));
  1867.                     }
  1868.                 }
  1869.  
  1870.                 BytesToWrite = Math.Min(ushort.MaxValue, Data.Length - BytesTransferred);
  1871.  
  1872.                 if (BytesToWrite == 0)
  1873.                 {
  1874.                     break;
  1875.                 }
  1876.  
  1877.                 RequestStream.Write(Data, BytesTransferred, BytesToWrite);
  1878.                 BytesTransferred += BytesToWrite;
  1879.             }
  1880.         }
  1881.  
  1882.         private byte[] ReadResponse(WebResponse response, RequestState state)
  1883.         {
  1884.             MemoryStream MemoryStream = new MemoryStream();
  1885.  
  1886.             int Length = Convert.ToInt32(response.ContentLength);
  1887.  
  1888.             int BytesRead = 0;
  1889.             int BytesTransferred = 0;
  1890.  
  1891.             byte[] Buffer = new byte[ushort.MaxValue];
  1892.             Stream ResponseStream = response.GetResponseStream();
  1893.  
  1894.             while (true)
  1895.             {
  1896.                 if (state.RaiseEvents)
  1897.                 {
  1898.                     if (Length == -1)
  1899.                     {
  1900.                         if (WebRequestDownloadProgress != null)
  1901.                         {
  1902.                             WebRequestDownloadProgress(this, new WebRequestProgressEventArgs(BytesTransferred, BytesTransferred, state.UserState));
  1903.                         }
  1904.                     }
  1905.                     else
  1906.                     {
  1907.                         if (WebRequestDownloadProgress != null)
  1908.                         {
  1909.                             WebRequestDownloadProgress(this, new WebRequestProgressEventArgs(BytesTransferred, Length, state.UserState));
  1910.                         }
  1911.                     }
  1912.                 }
  1913.  
  1914.                 BytesRead = ResponseStream.Read(Buffer, 0, Buffer.Length);
  1915.  
  1916.                 if (BytesRead == 0)
  1917.                 {
  1918.                     break;
  1919.                 }
  1920.  
  1921.                 MemoryStream.Write(Buffer, 0, BytesRead);
  1922.                 BytesTransferred += BytesRead;
  1923.             }
  1924.  
  1925.             response.Close();
  1926.             MemoryStream.Close();
  1927.  
  1928.             return MemoryStream.ToArray();
  1929.         }
  1930.  
  1931.         #endregion
  1932.  
  1933.         #region " Resolve Host "
  1934.  
  1935.         private IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
  1936.         {
  1937.             string HostName = servicePoint.Address.DnsSafeHost.ToLower();
  1938.             WebRequestResolveHostEventArgs EventArgs = new WebRequestResolveHostEventArgs(HostName, remoteEndPoint.Address);
  1939.  
  1940.             if (WebRequestResolveHost != null)
  1941.             {
  1942.                 WebRequestResolveHost(this, EventArgs);
  1943.             }
  1944.  
  1945.             remoteEndPoint.Address = EventArgs.Address;
  1946.  
  1947.             return null;
  1948.         }
  1949.  
  1950.         #endregion
  1951.  
  1952.         #region " Type Definitions "
  1953.  
  1954.         [EditorBrowsable(EditorBrowsableState.Advanced)]
  1955.         public sealed class WebRequestResolveHostEventArgs
  1956.         {
  1957.  
  1958.             #region " Properties "
  1959.  
  1960.             public string HostName
  1961.             {
  1962.                 get { return _HostName; }
  1963.             }
  1964.  
  1965.             public IPAddress Address
  1966.             {
  1967.                 get { return _Address; }
  1968.                 set { _Address = value; }
  1969.             }
  1970.  
  1971.             #endregion
  1972.  
  1973.             #region " Members "
  1974.  
  1975.             private string _HostName;
  1976.  
  1977.             private IPAddress _Address;
  1978.             #endregion
  1979.  
  1980.             #region " Constructor "
  1981.  
  1982.             public WebRequestResolveHostEventArgs(string hostName, IPAddress address)
  1983.             {
  1984.                 _HostName = hostName;
  1985.                 _Address = address;
  1986.             }
  1987.  
  1988.             #endregion
  1989.  
  1990.         }
  1991.  
  1992.         [EditorBrowsable(EditorBrowsableState.Advanced)]
  1993.         public sealed class WebRequestCompletedEventArgs
  1994.         {
  1995.  
  1996.             #region " Properties "
  1997.  
  1998.             public Exception Error
  1999.             {
  2000.                 get { return _Error; }
  2001.             }
  2002.  
  2003.             public byte[] Result
  2004.             {
  2005.                 get { return _Result; }
  2006.             }
  2007.  
  2008.             public WebHeaderCollection Headers
  2009.             {
  2010.                 get { return _Headers; }
  2011.             }
  2012.  
  2013.             public object UserState
  2014.             {
  2015.                 get { return _UserState; }
  2016.             }
  2017.  
  2018.             #endregion
  2019.  
  2020.             #region " Members "
  2021.  
  2022.             private Exception _Error;
  2023.             private byte[] _Result;
  2024.             private WebHeaderCollection _Headers;
  2025.  
  2026.             private object _UserState;
  2027.             #endregion
  2028.  
  2029.             #region " Constructor "
  2030.  
  2031.             public WebRequestCompletedEventArgs(Exception error, byte[] result, WebHeaderCollection headers, object userState)
  2032.             {
  2033.                 _Error = error;
  2034.                 _Result = result;
  2035.                 _Headers = headers;
  2036.                 _UserState = userState;
  2037.             }
  2038.  
  2039.             #endregion
  2040.  
  2041.         }
  2042.  
  2043.         [EditorBrowsable(EditorBrowsableState.Advanced)]
  2044.         public sealed class WebRequestProgressEventArgs
  2045.         {
  2046.  
  2047.             #region " Properties "
  2048.  
  2049.             public double ProgressPercentage
  2050.             {
  2051.                 get { return _ProgressPercentage; }
  2052.             }
  2053.  
  2054.             public int BytesTransferred
  2055.             {
  2056.                 get { return _BytesTransferred; }
  2057.             }
  2058.  
  2059.             public int TotalBytesToTransfer
  2060.             {
  2061.                 get { return _TotalBytesToTransfer; }
  2062.             }
  2063.  
  2064.             public object UserState
  2065.             {
  2066.                 get { return _UserState; }
  2067.             }
  2068.  
  2069.             #endregion
  2070.  
  2071.             #region " Members "
  2072.  
  2073.             private double _ProgressPercentage;
  2074.             private int _BytesTransferred;
  2075.             private int _TotalBytesToTransfer;
  2076.  
  2077.             private object _UserState;
  2078.             #endregion
  2079.  
  2080.             #region " Constructor "
  2081.  
  2082.             public WebRequestProgressEventArgs(int bytesTransferred, int totalBytesToTransfer, object userState)
  2083.             {
  2084.                 _BytesTransferred = bytesTransferred;
  2085.                 _TotalBytesToTransfer = totalBytesToTransfer;
  2086.  
  2087.                 if (!(totalBytesToTransfer == 0))
  2088.                 {
  2089.                     _ProgressPercentage = (_BytesTransferred / _TotalBytesToTransfer) * 100;
  2090.                 }
  2091.  
  2092.                 _UserState = userState;
  2093.             }
  2094.  
  2095.             #endregion
  2096.  
  2097.         }
  2098.  
  2099.         public sealed class RequestOptions
  2100.         {
  2101.  
  2102.             #region " Properties "
  2103.  
  2104.             public IWebProxy Proxy
  2105.             {
  2106.                 get { return _Proxy; }
  2107.                 set { _Proxy = value; }
  2108.             }
  2109.  
  2110.             public string UserAgent
  2111.             {
  2112.                 get { return _UserAgent; }
  2113.                 set { _UserAgent = value; }
  2114.             }
  2115.  
  2116.             public string Referer
  2117.             {
  2118.                 get { return _Referer; }
  2119.                 set { _Referer = value; }
  2120.             }
  2121.  
  2122.             public CookieContainer Cookies
  2123.             {
  2124.                 get { return _Cookies; }
  2125.                 set { _Cookies = value; }
  2126.             }
  2127.  
  2128.             public WebHeaderCollection Headers
  2129.             {
  2130.                 get { return _Headers; }
  2131.                 set { _Headers = value; }
  2132.             }
  2133.  
  2134.             public int Timeout
  2135.             {
  2136.                 get { return _Timeout; }
  2137.                 set { _Timeout = value; }
  2138.             }
  2139.  
  2140.             public int RetryCount
  2141.             {
  2142.                 get { return _RetryCount; }
  2143.                 set { _RetryCount = Math.Max(value, 0); }
  2144.             }
  2145.  
  2146.             public string Method
  2147.             {
  2148.                 get { return _Method; }
  2149.                 set
  2150.                 {
  2151.                     if (string.IsNullOrEmpty(value))
  2152.                     {
  2153.                         _Method = "POST";
  2154.                     }
  2155.                     else
  2156.                     {
  2157.                         _Method = value.Trim().ToUpper();
  2158.                     }
  2159.                 }
  2160.             }
  2161.  
  2162.             #endregion
  2163.  
  2164.             #region " Members "
  2165.  
  2166.             private IWebProxy _Proxy;
  2167.             private string _UserAgent;
  2168.             private string _Referer;
  2169.             private CookieContainer _Cookies;
  2170.             private WebHeaderCollection _Headers;
  2171.             private int _Timeout;
  2172.             private int _RetryCount;
  2173.  
  2174.             private string _Method;
  2175.             #endregion
  2176.  
  2177.             #region " Constructor "
  2178.  
  2179.             public RequestOptions()
  2180.             {
  2181.                 _Method = "POST";
  2182.                 _Timeout = 60000;
  2183.                 _Proxy = WebRequest.DefaultWebProxy;
  2184.                 _Cookies = new CookieContainer();
  2185.                 _Headers = new WebHeaderCollection();
  2186.             }
  2187.  
  2188.             #endregion
  2189.  
  2190.         }
  2191.  
  2192.         private sealed class RequestState
  2193.         {
  2194.  
  2195.             #region " Properties "
  2196.  
  2197.             public RequestOptions Options
  2198.             {
  2199.                 get { return _Options; }
  2200.             }
  2201.  
  2202.             public object UserState
  2203.             {
  2204.                 get { return _UserState; }
  2205.             }
  2206.  
  2207.             public bool RaiseEvents
  2208.             {
  2209.                 get { return _RaiseEvents; }
  2210.             }
  2211.  
  2212.             #endregion
  2213.  
  2214.             #region " Members "
  2215.  
  2216.             private RequestOptions _Options;
  2217.             private object _UserState;
  2218.  
  2219.             private bool _RaiseEvents;
  2220.             #endregion
  2221.  
  2222.             #region " Constructor "
  2223.  
  2224.             public RequestState(RequestOptions options, object userState, bool raiseEvents)
  2225.             {
  2226.                 _Options = options;
  2227.                 _UserState = userState;
  2228.                 _RaiseEvents = raiseEvents;
  2229.             }
  2230.  
  2231.             #endregion
  2232.  
  2233.         }
  2234.  
  2235.         #endregion
  2236.  
  2237.         public static int EstimateMaxTimeout(int numberOfBytes)
  2238.         {
  2239.             int GracePeriod = 5000;
  2240.             //5 seconds to establish a connection.
  2241.             int TimePerChunk = 1000;
  2242.             //We'll assume each chunk takes 1 second.
  2243.             int TransferSpeed = 32000;
  2244.             //256 Kbps download / upload speed.
  2245.             int NumberOfChunks = Convert.ToInt32(Math.Ceiling((double)(numberOfBytes / TransferSpeed)));
  2246.  
  2247.             return GracePeriod + (NumberOfChunks * TimePerChunk);
  2248.         }
  2249.  
  2250.     }
  2251.  
  2252.     internal sealed class BlogPost
  2253.     {
  2254.  
  2255.         /// <summary>
  2256.         /// Gets the unique id for the post.
  2257.         /// </summary>
  2258.         public int Id
  2259.         {
  2260.             get { return _Id; }
  2261.         }
  2262.  
  2263.         /// <summary>
  2264.         /// Gets the title for the post.
  2265.         /// </summary>
  2266.         public string Title
  2267.         {
  2268.             get { return _Title; }
  2269.         }
  2270.  
  2271.         /// <summary>
  2272.         /// Gets the number of times the post has been read by users.
  2273.         /// </summary>
  2274.         public int TimesRead
  2275.         {
  2276.             get { return _TimesRead; }
  2277.         }
  2278.  
  2279.         /// <summary>
  2280.         /// Gets the date that the post was originally posted.
  2281.         /// </summary>
  2282.         public System.DateTime DatePosted
  2283.         {
  2284.             get { return _DatePosted; }
  2285.         }
  2286.  
  2287.         private int _Id;
  2288.         private string _Title;
  2289.         private int _TimesRead;
  2290.         private System.DateTime _DatePosted;
  2291.  
  2292.         private Delegate _GetPostBodyDelegate;
  2293.         public BlogPost(int id, string title, int timesRead, System.DateTime datePosted, Delegate getPostBodyDelegate)
  2294.         {
  2295.             _Id = id;
  2296.             _Title = title;
  2297.             _TimesRead = timesRead;
  2298.             _DatePosted = datePosted;
  2299.             _GetPostBodyDelegate = getPostBodyDelegate;
  2300.         }
  2301.  
  2302.         /// <summary>
  2303.         /// Gets the body for the post.
  2304.         /// </summary>
  2305.         public string GetPostBody()
  2306.         {
  2307.             return (string)_GetPostBodyDelegate.DynamicInvoke(_Id);
  2308.         }
  2309.  
  2310.     }
  2311.  
  2312.     internal sealed class BrokerSettings
  2313.     {
  2314.  
  2315.  
  2316.         /// <summary>
  2317.         /// Gets or sets the theme that will be used by the authentication dialog.
  2318.         /// </summary>
  2319.         public DialogTheme DialogTheme { get; set; }
  2320.  
  2321.         /// <summary>
  2322.         /// Gets or sets a value indicating whether to catch unhandled exceptions and report them to the server.
  2323.         /// </summary>
  2324.         public bool CatchUnhandledExceptions { get; set; }
  2325.  
  2326.         /// <summary>
  2327.         /// Gets or sets a value indicating whether to ignore automatic updates.
  2328.         /// </summary>
  2329.         public bool DeferAutomaticUpdates { get; set; }
  2330.        
  2331.         /// <summary>
  2332.         /// Gets or sets a value indicating whether the authentication window will be shown. This option should only be used in
  2333.         /// products that provide lifetime licenses.
  2334.         /// </summary>
  2335.         public bool SilentAuthentication { get; set; }
  2336.  
  2337.         /// <summary>
  2338.         /// Gets or sets a value indicating whether to verify the integrity of core runtime files (mscorlib, System, and System.Security).
  2339.         /// </summary>
  2340.         public bool VerifyRuntimeIntegrity { get; set; }
  2341.  
  2342.  
  2343.         public BrokerSettings()
  2344.         {
  2345.             CatchUnhandledExceptions = true;
  2346.             VerifyRuntimeIntegrity = true;
  2347.             DialogTheme = NetSeal.DialogTheme.Light;
  2348.         }
  2349.  
  2350.     }
  2351.  
  2352.     internal enum DialogTheme : int
  2353.     {
  2354.         None = 0,
  2355.         Light = 1,
  2356.         Dark = 2
  2357.     }
  2358.  
  2359.     internal enum LicenseType : byte
  2360.     {
  2361.         Special = 0,
  2362.         Bronze = 1,
  2363.         Silver = 2,
  2364.         Gold = 3,
  2365.         Platinum = 4,
  2366.         Diamond = 5
  2367.     }
  2368.  
  2369.     #endregion
  2370.  
  2371. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement