Ping 域名或者IP地址,判读是否能正常连接到目标服务器。建议执行循环3~5次,取平均值判断网络延时更准确。

实例:

public static void SimplePing ()
{
    Ping pingSender = new Ping ();
    PingReply reply = pingSender.Send ("www.24kplus.com");

    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine ("Address: {0}", reply.Address.ToString ());
        Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
        Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
        Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
        Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
    }
    else
    {
        Console.WriteLine (reply.Status);
    }
}

该组件允许用户通过IP地址查询是否VPN代理、开放代理、Web代理、Tor出口、数据中心、Web主机(DCH)范围和搜索引擎机器人(SES),组件从 ip2proxy bin 数据文件中查询代理IP信息。

文件下载:

IP2Proxy 组件: https://down.24kplus.com/dev/ip2proxy-1.0.0.0.zip

免费 IP2Proxy BIN 数据: https://lite.ip2location.com

商业 IP2Proxy BIN 数据: https://www.ip2location.com/database/ip2proxy

要求

Microsoft .NET 4.0 framework 或更高 / Microsoft .NET Core 2.0 或更高.

方法

方法名
描述
Close
关闭并清理文件缓存
GetPackageVersion
获取软件包版本(PX1到PX8的1到8)
GetDatabaseVersion
获取数据库版本
ProxyQuery
代理信息查询

属性

属性名
描述
UseMemoryMappedFile
设置或获取是否使用内存映射文件(MMF)
MapFileName
内存映射文件名(仅Win32平台有效)
ProxyDatabasePath
代理数据库文件位置
IsProxy
检查IP地址是否是代理
  • -1:错误
  • 0:非代理
  • 1:代理
  • 2:数据中心IP地址或搜索引擎机器人
ProxyType
代理类型
  • VPN
  • TOR
  • DCH
  • PUB*
  • WEB
  • SES

示例

static void Main(string[] args)
{
	using (var component = new IP2Proxy.Component())
	{
		component.ProxyDatabasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IP2PROXY-PX8.BIN");
		component.UseMemoryMappedFile = true;
		var proxy = component.ProxyQuery("58.220.95.56");

		Console.WriteLine("IsProxy: " + proxy.IsProxy.ToString());
		Console.WriteLine("ProxyType: " + proxy.ProxyType);
		Console.WriteLine("CountryCode: " + proxy.CountryCode);
		Console.WriteLine("Country: " + proxy.Country);
		Console.WriteLine("Region: " + proxy.Region);
		Console.WriteLine("City: " + proxy.City);
		Console.WriteLine("ISP: " + proxy.ISP);
		Console.WriteLine("Domain: " + proxy.Domain);
		Console.WriteLine("UsageType: " + proxy.UsageType);
		Console.WriteLine("ASN: " + proxy.ASN);
		Console.WriteLine("AS: " + proxy.AS);
		Console.WriteLine("LastSeen: " + proxy.LastSeen);
	}
	Console.ReadKey();
}

Whois 简单来说,就是一个用来查询域名是否已经被注册,以及注册域名的详细信息的数据库(如域名所有人、域名注册商、域名注册日期和过期日期等)。通过域名Whois服务器查询,可以查询域名归属者联系方式,以及注册和到期时间。

以下为 C# 域名 Whois 查询代码

public static string Whois(string domain)
{
	if (domain == null)
		throw new ArgumentNullException();
	int ccStart = domain.LastIndexOf(".");
	if (ccStart < 0 || ccStart == domain.Length)
		throw new ArgumentException();
	string ret = "";
	Socket s = null;
	try
	{
		string cc = domain.Substring(ccStart + 1);
		s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		s.Connect(new IPEndPoint(Dns.GetHostEntry(cc + ".whois-servers.net").AddressList[0], 43));
		s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
		byte[] buffer = new byte[1024];
		int recv = s.Receive(buffer);
		while (recv > 0)
		{
			ret += Encoding.ASCII.GetString(buffer, 0, recv);
			recv = s.Receive(buffer);
		}
		s.Shutdown(SocketShutdown.Both);
	}
	catch
	{
		throw new SocketException();
	}
	finally
	{
		if (s != null)
			s.Close();
	}
	return ret;
}

调用事例:

[TestMethod]
public void TestWhoisMethod()
{
	string whois = Whois("24kplus.com");
	Debug.WriteLine(whois);
	Console.ReadKey();
}

结果:

   Server Name: 24KPLUS.COM
   IP Address: 34.92.152.179
   Registrar: DNSPod, Inc.
   Registrar WHOIS Server: whois.dnspod.com
   Registrar URL: http://www.dnspod.cn

   Domain Name: 24KPLUS.COM
   Registry Domain ID: 2377863045_DOMAIN_COM-VRSN
   Registrar WHOIS Server: whois.dnspod.com
   Registrar URL: http://www.dnspod.cn
   Updated Date: 2019-07-05T12:32:38Z
   Creation Date: 2019-04-08T03:16:41Z
   Registry Expiry Date: 2023-04-08T03:16:41Z
   Registrar: DNSPod, Inc.
   Registrar IANA ID: 1697
   Registrar Abuse Contact Email: abuse@dnspod.com
   Registrar Abuse Contact Phone: +86.95716
   Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
   Name Server: F1G1NS1.DNSPOD.NET
   Name Server: F1G1NS2.DNSPOD.NET
   DNSSEC: unsigned
   URL of the ICANN Whois Inaccuracy Complaint Form: https://www.icann.org/wicf/
>>> Last update of whois database: 2019-08-25T11:21:50Z <<<

For more information on Whois status codes, please visit https://icann.org/epp

NOTICE: The expiration date displayed in this record is the date the
registrar's sponsorship of the domain name registration in the registry is
currently set to expire. This date does not necessarily reflect the expiration
date of the domain name registrant's agreement with the sponsoring
registrar.  Users may consult the sponsoring registrar's Whois database to
view the registrar's reported date of expiration for this registration.

TERMS OF USE: You are not authorized to access or query our Whois
database through the use of electronic processes that are high-volume and
automated except as reasonably necessary to register domain names or
modify existing registrations; the Data in VeriSign Global Registry
Services' ("VeriSign") Whois database is provided by VeriSign for
information purposes only, and to assist persons in obtaining information
about or related to a domain name registration record. VeriSign does not
guarantee its accuracy. By submitting a Whois query, you agree to abide
by the following terms of use: You agree that you may use this Data only
for lawful purposes and that under no circumstances will you use this Data
to: (1) allow, enable, or otherwise support the transmission of mass
unsolicited, commercial advertising or solicitations via e-mail, telephone,
or facsimile; or (2) enable high volume, automated, electronic processes
that apply to VeriSign (or its computer systems). The compilation,
repackaging, dissemination or other use of this Data is expressly
prohibited without the prior written consent of VeriSign. You agree not to
use electronic processes that are automated and high-volume to access or
query the Whois database except as reasonably necessary to register
domain names or modify existing registrations. VeriSign reserves the right
to restrict your access to the Whois database in its sole discretion to ensure
operational stability.  VeriSign may restrict or terminate your access to the
Whois database for failure to abide by these terms of use. VeriSign
reserves the right to modify these terms at any time.

The Registry database contains ONLY .COM, .NET, .EDU domains and
Registrars.

Microsoft SQL Server

非官方MS SQL Server 2019,2017,2016,2014,2012,2008 R2,2008,2005,2000版本对照表。

发布版本
RTM
累积更新
SQL Server 2019
SQL Server 15
SQL Server 2017
SQL Server 14
14.0.1000.169
(CU17 Latest)14.0.3238.1
SP1
SP2
SP3
SP4
SQL Server 2016
SQL Server 13
13.0.1601.5
13.0.4001.0
13.1.4001.0
13.0.5026.0
13.2.5026.0
SQL Server 2014
SQL Server 12
12.0.2000.8
12.0.4100.1
12.1.4100.1
12.0.5000.0
12.2.5000.0
12.0.6024.0
12.3.6024.0
SQL Server 2012
SQL Server 11
11.0.2100.60
11.0.3000.0
11.1.3000.0
11.0.5058.0
11.2.5058.0
11.0.6020.0
11.3.6020.0
11.0.7001.0
11.4.7001.0
SQL Server 2008 R2
SQL Server 10.5
10.50.1600.1
10.50.2500.0
10.51.2500.0
10.50.4000.0
10.52.4000.0
10.50.6000.34
10.53.6000.34
SQL Server 2008
SQL Server 10
10.0.1600.22
10.0.2531.0
10.1.2531.0
10.0.4000.0
10.2.4000.0
10.0.5500.0
10.3.5500.0
10.0.6000.29
10.4.6000.29
SQL Server 2005
SQL Server 9
9.0.1399.06
9.0.2047
9.0.3042
9.0.4035
9.0.5000
SQL Server 2000
SQL Server 8
8.0.194
8.0.384
8.0.532
8.0.760
8.0.2039

MongoDB 索引

索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。这种扫描全集合的查询效率是非常低的,特别在处理大量的数据时,查询可以要花费几十秒甚至几分钟,这对网站的性能是非常致命的。索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中,索引是对数据库表中一列或多列的值进行排序的一种结构

createIndex() 方法

语法

createIndex()方法基本语法格式如下所示:

>db.collection.createIndex(keys, options)

语法中 Key 值为你要创建的索引字段,1 为指定按升序创建索引,如果你想按降序来创建索引指定为 -1 即可。

实例

>db.testdb1.createIndex({"title":1})

createIndex() 方法中你也可以设置使用多个字段创建索引(关系型数据库中称作复合索引)。

>db.testdb1.createIndex({"title":1,"description":-1})

createIndex() 接收可选参数,可选参数列表如下:

参数
类型
描述
background
Boolean
建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引,即增加 “background” 可选参数。 “background” 默认值为false。
unique
Boolean
建立的索引是否唯一。指定为true创建唯一索引。默认值为false.
name
string
索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。
sparse
Boolean
对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.
expireAfterSeconds
integer
指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。
v
index version
索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
weights
document
索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。
default_language
string
对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
language_override
string
对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.

实例

在后台创建索引:

db.testdb1.createIndex({"title":1,"description":-1}, {background: true})

通过在创建索引时加 background:true 的选项,让创建工作在后台执行

Spire.XLS for .NET

Spire.XLS for .NET 是一个独立的 Excel 组件,不依赖于 Microsoft Office Excel。它同时支持旧版的 Excel 97-2003(.xls) 格式文档和新版的 Excel 2007、Excel 2010、Excel 2013、Excel 2016(.xlsx, .xlsb, .xlsm) 以及 Open Office(.ods) 格式文档。

Spire.XLS for .NET 提供免费版和商业版,根据需要自行定夺,本站不给予任何授权和破解支持。官网:http://www.e-iceblue.cn/

以下是简单的 Execl 文件打印例子:

/// <summary>
/// 打印 Execl
/// </summary>
/// <param name="fileName">要打印的 Execl 文件</param>
/// <param name="documentName">打印机上显示的文件名称</param>
/// <param name="printerName">打印机全名</param>
/// <param name="paperName">纸张名称(默认:A4)</param>
/// <param name="landscape">是否横向打印(默认:false)</param>
/// <param name="copies">打印份数(默认:1)</param>
public static void PrintExecl(string fileName, string documentName, string printerName, string paperName = "A4", bool landscape = false, short copies = 1)
{
	using (Spire.Xls.Workbook workbook = new Spire.Xls.Workbook())
	{
		//加载要打印的execl
		workbook.LoadFromFile(fileName);
		//打印机全名
		workbook.PrintDocument.PrinterSettings.PrinterName = printerName;
		//打印机上显示的文件名称
		workbook.PrintDocument.DocumentName = documentName;
		//打印份数
		workbook.PrintDocument.PrinterSettings.Copies = copies;
		//设定纸张大小
		foreach (PaperSize pageSize in workbook.PrintDocument.PrinterSettings.PaperSizes)
		{
			if (pageSize.PaperName == paperName)
			{
				workbook.PrintDocument.PrinterSettings.DefaultPageSettings.PaperSize = pageSize;
			}
		}
		//是否横向打印
		workbook.PrintDocument.PrinterSettings.DefaultPageSettings.Landscape = landscape;
		//打印
		workbook.PrintDocument.Print();
	}
}

C# .NET 利用 HttpWebRequest 模拟浏览器 http、https 请求。

/// <summary>
/// Http 请求
/// </summary>
/// <param name="url">url地址</param>
/// <param name="data">请求参数(可选参数)</param>
/// <param name="method">请求方法(可选参数,默认:GET)</param>
/// <param name="timeout">连接超时(可选参数,默认: 100,000 毫秒(100 秒))</param>
/// <param name="encoding">编码(可选参数,默认:utf-8)</param>
/// <param name="contentType">Content-type HTTP 标头(可选参数)</param>
/// <param name="userAgent">模拟浏览器UA(可选参数)</param>
/// <param name="headers">HTTP 标头(可选参数)</param>
/// <returns>远程服务器返回的数据</returns>
public static string HttpRequest(string url, string data = null, string method = "GET", int? timeout = null, Encoding encoding = null, string contentType = "application/x-www-form-urlencoded", string userAgent = null, Dictionary<string, string> headers = null)
{
	encoding = encoding ?? Encoding.UTF8;
	var myWebRequest = (HttpWebRequest)WebRequest.Create(url);
	myWebRequest.ContentType = contentType;
	myWebRequest.Method = method;
	if (!string.IsNullOrWhiteSpace(userAgent))
	{
		myWebRequest.UserAgent = userAgent;
	}
	if (timeout.HasValue)
	{
		myWebRequest.Timeout = timeout.Value;
	}
	if (myWebRequest.RequestUri.Scheme == "https")
	{
		myWebRequest.ProtocolVersion = HttpVersion.Version11;
		myWebRequest.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidationCallback);
		// 这里设置了协议类型。
		ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
		myWebRequest.KeepAlive = false;
		ServicePointManager.CheckCertificateRevocationList = true;
		ServicePointManager.DefaultConnectionLimit = 100;
		ServicePointManager.Expect100Continue = false;
	}
	if (headers != null && headers.Count > 0)
	{
		foreach (KeyValuePair<string, string> item in headers)
		{
			myWebRequest.Headers[item.Key] = item.Value;
		}
	}
	try
	{
		if (!string.IsNullOrWhiteSpace(data))
		{
			using (Stream stream = myWebRequest.GetRequestStream())
			{
				var bytes = encoding.GetBytes(data);
				stream.Write(bytes, 0, bytes.Length);
				stream.Flush();
			}
		}
		using (HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse())
		{
			if (myWebResponse.StatusCode == HttpStatusCode.OK)
			{
				using (Stream receiveStream = myWebResponse.GetResponseStream())
				{
					using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
					{
						return readStream.ReadToEnd();
					}
				}
			}
			else
			{
				throw new WebException(myWebResponse.StatusDescription);
			}
		}
	}
	catch (Exception ex)
	{
		throw ex;
	}
	finally
	{
		myWebRequest.Abort();
	}
}
/// <summary>
/// (SSL) 证书验证回调
/// </summary>
/// <param name="sender">一个对象,它包含此验证的状态信息。</param>
/// <param name="certificate">用于对远程方进行身份验证的证书。</param>
/// <param name="chain">与远程证书关联的证书颁发机构链。</param>
/// <param name="sslPolicyErrors">与远程证书关联的一个或多个错误。</param>
/// <returns>是否接受指定证书进行身份验证</returns>
private static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
	if (sslPolicyErrors == SslPolicyErrors.None)
		return true;

	Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
	return false;
}

IP地址转数字

public long IPToNumber(string ip)
{
	string[] arrayIP = ip.Split('.');
	long sip1 = long.Parse(arrayIP[0]);
	long sip2 = long.Parse(arrayIP[1]);
	long sip3 = long.Parse(arrayIP[2]);
	long sip4 = long.Parse(arrayIP[3]);
	long ipNum = sip1 * 256 * 256 * 256 + sip2 * 256 * 256 + sip3 * 256 + sip4;
	return ipNum;
}

数字转IP地址

public string NumberToIP(long ipNum)
{
	StringBuilder builder = new StringBuilder();
	builder.Append((ipNum >> 24) & 0xFF).Append(".");
	builder.Append((ipNum >> 16) & 0xFF).Append(".");
	builder.Append((ipNum >> 8) & 0xFF).Append(".");
	builder.Append(ipNum & 0xFF);
	return builder.ToString();
}

.NET 版 Chromium WebBrowser 动态设置 http, https, socks5 代理方法。

private void InitWebBrowser(string url)
{
	ChromiumWebBrowser browser = new ChromiumWebBrowser(url);
	browser.Dock = DockStyle.Fill;
	//绑定 WebBrowser 初始化完成事件
	browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
	//添加到WinForm中
	this.Controls.Add(browser);
	browser.BringToFront();
}

private void Browser_IsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs e)
{
	if(e.IsBrowserInitialized)
	{
		//只能在WebBrowser UI呈现后获取 Request 上下文
		Cef.UIThreadTaskFactory.StartNew(delegate
		{
			//获取 Request 上下文
			var rc = browser.GetBrowser().GetHost().RequestContext;
			var dict = new Dictionary<string, object>();
			dict.Add("mode", "fixed_servers");
			dict.Add("server", "127.0.0.1:1080");
			string error;
			//设置代理
			rc.SetPreference("proxy", dict, out error);
			//如果 error 不为空则表示设置失败。
			if(!string.IsNullOrWhiteSpace(error))
			{
				MessageBox.Show(error, "Tip", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		});
	}
}

不要在 Cef.Initialize 时设置 CefCommandLineArgs.Add("proxy-server", "127.0.0.1:1080");,否则修改代理设置会失败。