/// <summary> /// Match a String against the given pattern, supporting the following simple /// pattern styles: "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality. /// </summary> /// <param name="pattern"> /// the pattern to match against /// </param> /// <param name="text"> /// the String to match /// </param> /// <returns> /// whether the String matches the given pattern /// </returns> public static bool IsMatch(string pattern, string text) { AssertUtil.ArgumentNotEmpty(pattern, nameof(pattern)); AssertUtil.ArgumentNotEmpty(text, nameof(text)); if (string.Equals("*", pattern, StringComparison.InvariantCultureIgnoreCase)) { return(true); } if (pattern.StartsWith("*", StringComparison.InvariantCultureIgnoreCase) && pattern.EndsWith("*", StringComparison.InvariantCultureIgnoreCase)) { pattern = pattern.Trim('*'); return(text.IndexOf(pattern, StringComparison.InvariantCultureIgnoreCase) >= 0); } else if (pattern.StartsWith("*", StringComparison.InvariantCultureIgnoreCase)) { pattern = pattern.TrimStart('*'); return(text.EndsWith(pattern, StringComparison.InvariantCultureIgnoreCase)); } else if (pattern.EndsWith("*", StringComparison.InvariantCultureIgnoreCase)) { pattern = pattern.TrimEnd('*'); return(text.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase)); } return(false); }
/// <summary> /// Gets if specified string is valid "token" value. /// </summary> /// <param name="text">String value to check.</param> /// <returns>Returns true if specified string value is valid "token" value.</returns> /// <exception cref="ArgumentNullException">Is raised if <b>value</b> is null.</exception> public static bool IsToken(string text) { AssertUtil.ArgumentNotEmpty(text, nameof(text)); /* This syntax is taken from rfc 3261, but token must be universal so ... . * token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" ) * alphanum = ALPHA / DIGIT * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z * DIGIT = %x30-39 ; 0-9 */ var tokenChars = new char[] { '-', '.', '!', '%', '*', '_', '+', '`', '\'', '~' }; foreach (char c in text) { // We don't have letter or digit, so we only may have token char. if (!((c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A) || (c >= 0x30 && c <= 0x39))) { if (!tokenChars.Contains(c)) { return(false); } } } return(true); }
/// <summary> /// Match a String against the given pattern, supporting the following simple /// pattern styles: "*xxx*xxx" and "xxx*xxx..." matches, as well as direct equality. /// </summary> /// <param name="pattern"> /// the pattern to match against /// </param> /// <param name="text"> /// the String to match /// </param> /// <returns> /// whether the String matches the given pattern /// </returns> public static bool IsAstericMatch(string pattern, string text) { AssertUtil.ArgumentNotEmpty(pattern, nameof(pattern)); AssertUtil.ArgumentNotEmpty(text, nameof(text)); while (pattern.Length > 0) { // *xxx[*xxx...] if (pattern.StartsWith("*", StringComparison.InvariantCultureIgnoreCase)) { // *xxx*xxx var patternParts = pattern.TrimStart('*').Split('*', 2); if (patternParts.Length == 2) { int indexPos = text.IndexOf(patternParts[0], StringComparison.InvariantCultureIgnoreCase); if (indexPos == -1) { return(false); } pattern = patternParts[1]; text = text.Substring(indexPos + patternParts[0].Length); } // *xxx This is last pattern else { return(text.EndsWith(patternParts[0], StringComparison.InvariantCultureIgnoreCase)); } } // xxx*[xxx...] else if (pattern.IndexOf('*') > -1) { var patternParts = pattern.Split('*', 2); if (patternParts.Length == 2) { // Text must startwith if (!text.StartsWith(patternParts[0], StringComparison.InvariantCultureIgnoreCase)) { return(false); } pattern = patternParts[1]; text = text.Substring(patternParts[0].Length); } // xxx* This is last pattern else { return(text.StartsWith(patternParts[0], StringComparison.InvariantCultureIgnoreCase)); } } // xxx else { return(text == pattern); } } return(true); }
/// <summary> /// Gets if specified IP address is private LAN IP address. For example 192.168.x.x is private ip. /// </summary> /// <param name="ip">IP address to check.</param> /// <returns>Returns true if IP is private IP.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static bool IsPrivateIPAddress(string ip) { AssertUtil.ArgumentNotEmpty(ip, nameof(ip)); if (!IsIPAddress(ip)) { throw new ArgumentException($"Argument '{ip}' is not valid ip address."); } return(IsPrivateIPAddress(IPAddress.Parse(ip))); }
/// <summary> /// Gets mailbox's domain. /// </summary> public static string GetMxDomain(string mailbox) { AssertUtil.ArgumentNotEmpty(mailbox, nameof(mailbox)); if (!ValidateUtil.IsMailAddress(mailbox)) { throw new ArgumentException($"Argument '{mailbox}' is not valid mail address."); } return(mailbox.Split('@', 2)[1]); }
/// <summary> /// Instantiates the type using the assembly specified to load the type. /// </summary> /// <remarks>This is a convenience in the case of needing to instantiate a type but not /// wanting to specify in the string the version, culture and public key token.</remarks> /// <param name="assembly">The assembly.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// If the <paramref name="assembly"/> or <paramref name="typeName"/> is <see langword="null"/> /// </exception> /// <exception cref="ECode.Core.ReflectionException"> /// If cannot load the type from the assembly or the call to <code>InstantiateType(Type)</code> fails. /// </exception> public static object InstantiateType(Assembly assembly, string typeName) { AssertUtil.ArgumentNotNull(assembly, nameof(assembly)); AssertUtil.ArgumentNotEmpty(typeName, nameof(typeName)); var resolvedType = assembly.GetType(typeName, false, false); if (resolvedType == null) { throw new ReflectionException($"Cannot load type '{typeName}' from assembly '{assembly}'."); } return(InstantiateType(resolvedType)); }
/// <summary> /// Match a String against the given patterns, supporting the following simple /// pattern styles: "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality. /// </summary> /// <param name="patterns"> /// the patterns to match against /// </param> /// <param name="text"> /// the String to match /// </param> /// <returns> /// whether the String matches any of the given patterns /// </returns> public static bool IsMatch(string[] patterns, string text) { AssertUtil.ArgumentNotEmpty(patterns, nameof(patterns)); AssertUtil.ArgumentNotEmpty(text, nameof(text)); for (int i = 0; i < patterns.Length; i++) { if (IsMatch(patterns[i], text)) { return(true); } } return(false); }
/// <summary> /// Gets if specified mail address has valid syntax. /// </summary> /// <param name="value">mail address, eg. [email protected].</param> /// <returns>Returns ture if address is valid, otherwise false.</returns> /// <exception cref="System.ArgumentNullException">Is raised when <b>value</b> is null.</exception> public static bool IsMailAddress(string value) { AssertUtil.ArgumentNotEmpty(value, nameof(value)); try { var mailAddr = new MailAddress(value); return(true); } catch { return(false); } }
/// <summary> /// Parses IPEndPoint from the specified string value. /// </summary> /// <param name="value">IPEndPoint string value.</param> /// <returns>Returns parsed IPEndPoint.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static IPEndPoint ParseIPEndPoint(string value) { AssertUtil.ArgumentNotEmpty(value, nameof(value)); try { string[] ip_port = value.Split(":", true, false, "[]"); if (ip_port[0].StartsWith('[')) { ip_port[0] = ip_port[0].TrimStart('[').TrimEnd(']'); } return(new IPEndPoint(IPAddress.Parse(ip_port[0]), Convert.ToInt32(ip_port[1]))); } catch (Exception ex) { throw new ArgumentException($"Argument '{value}' is not valid IPEndPoint value.", ex); } }
/// <summary> /// Parses x509 certificate from specified data. /// </summary> /// <param name="cert">Certificate data.</param> /// <returns>Returns parsed certificate.</returns> /// <exception cref="System.ArgumentNullException">Is raised when <b>cert</b> is null.</exception> public static X509Certificate2 ParseCertificate(object cert) { AssertUtil.ArgumentNotEmpty((byte[])cert, nameof(cert)); /* NOTE: MS X509Certificate2((byte[])) has serious bug, it will create temp file * and leaves it open. The result is temp folder will get full. */ string tmpFile = Path.GetTempFileName(); try { using (var fs = File.Open(tmpFile, FileMode.Open)) { fs.Write((byte[])cert, 0, ((byte[])cert).Length); } return(new X509Certificate2(tmpFile)); } finally { File.Delete(tmpFile); } }
/// <summary> /// Copies <b>source</b> stream data to <b>target</b> stream. /// </summary> /// <param name="source">Source stream. Reading starts from stream current position.</param> /// <param name="target">Target stream. Writing starts from stream current position.</param> /// <param name="buffer">Specifies transfer block buffer.</param> /// <returns>Returns number of bytes copied.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>source</b> or <b>target</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when <b>blockBuffer</b> is empty.</exception> public static long StreamCopy(Stream source, Stream target, byte[] buffer) { AssertUtil.ArgumentNotNull(source, nameof(source)); AssertUtil.ArgumentNotNull(target, nameof(target)); AssertUtil.ArgumentNotEmpty(buffer, nameof(buffer)); long totalReaded = 0; while (true) { int readedCount = source.Read(buffer, 0, buffer.Length); // We reached end of stream, we readed all data sucessfully. if (readedCount == 0) { return(totalReaded); } else { target.Write(buffer, 0, readedCount); totalReaded += readedCount; } } }
public static string Create(string userName, string password, Algorithm algorithm = Algorithm.MD5) { AssertUtil.ArgumentNotEmpty(userName, nameof(userName)); AssertUtil.ArgumentNotEmpty(password, nameof(password)); var random = new Random((int)DateTime.Now.Ticks); var salt = GenerateSalt(random.Next(16777215, int.MaxValue), 4) + GenerateSalt(random.Next(16777215, int.MaxValue), 4); string cpw = ""; switch (algorithm) { case Algorithm.SHA1: cpw = "{SHA}" + Encoding.ASCII.GetBytes(password).ComputeSHA1().ToBase64(); break; default: var buffer = new List <byte>(Encoding.ASCII.GetBytes(password + "$apr1$" + salt)); var hashBytes = Encoding.ASCII.GetBytes(password + salt + password).ComputeMD5(); buffer.AddRange(hashBytes.Take(password.Length)); for (var i = password.Length; i != 0; i >>= 1) { if ((i & 1) != 0) { buffer.Add((byte)0); } else { buffer.Add((byte)password[0]); } } List <byte> temp = null; hashBytes = buffer.ToArray().ComputeMD5(); for (var i = 0; i < 1000; i++) { temp = new List <byte>(); if ((i & 1) != 0) { temp.AddRange(Encoding.ASCII.GetBytes(password)); } else { temp.AddRange(hashBytes.Take(16)); } if ((i % 3) != 0) { temp.AddRange(Encoding.ASCII.GetBytes(salt)); } if ((i % 7) != 0) { temp.AddRange(Encoding.ASCII.GetBytes(password)); } if ((i & 1) != 0) { temp.AddRange(hashBytes.Take(16)); } else { temp.AddRange(Encoding.ASCII.GetBytes(password)); } hashBytes = temp.ToArray().ComputeMD5(); } cpw = "$apr1$" + salt + '$'; cpw += GenerateSalt((hashBytes[0] << 16) | (hashBytes[6] << 8) | hashBytes[12], 4); cpw += GenerateSalt((hashBytes[1] << 16) | (hashBytes[7] << 8) | hashBytes[13], 4); cpw += GenerateSalt((hashBytes[2] << 16) | (hashBytes[8] << 8) | hashBytes[14], 4); cpw += GenerateSalt((hashBytes[3] << 16) | (hashBytes[9] << 8) | hashBytes[15], 4); cpw += GenerateSalt((hashBytes[4] << 16) | (hashBytes[10] << 8) | hashBytes[5], 4); cpw += GenerateSalt(hashBytes[11], 2); break; } if (userName.Length + 1 + cpw.Length > 255) { throw new DataSizeExceededException($"The computing result is too long (> 255)."); } return(userName + ':' + cpw); }
/// <summary> /// Gets if the specified string value is IP address. /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified value is IP address.</returns> /// <exception cref="System.ArgumentNullException">Is raised when <b>value</b> is null.</exception> public static bool IsIPAddress(string value) { AssertUtil.ArgumentNotEmpty(value, nameof(value)); return(IPAddress.TryParse(value, out IPAddress ip)); }
/// <summary> /// Checks if specified string is integer(int/long). /// </summary> /// <param name="value">Value to check.</param> /// <returns>Returns true if specified string is integer.</returns> /// <exception cref="System.ArgumentNullException">Is raised when <b>value</b> is null.</exception> public static bool IsInteger(string value) { AssertUtil.ArgumentNotEmpty(value, nameof(value)); return(long.TryParse(value, out long l)); }
/// <summary> /// Fixes path separator, replaces / \ with platform separator char. /// </summary> public static string PathFix(string path) { AssertUtil.ArgumentNotEmpty(path, nameof(path)); return(path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar)); }
public static Stream BuildMultipartData(IDictionary formData, string boundary, Encoding encoding = null) { AssertUtil.ArgumentNotNull(formData, nameof(formData)); AssertUtil.ArgumentNotEmpty(boundary, nameof(boundary)); encoding = encoding == null ? Encoding.UTF8 : encoding; var stream = new MultiStream(); string keyValTemplate = $"--{boundary}\r\n" + "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n"; string fileValTemplate = $"--{boundary}\r\n" + "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n" + "\r\n"; foreach (var key in formData.Keys) { if (!(key is string)) { throw new ArgumentException("Key isnot typeof string."); } if (string.IsNullOrWhiteSpace((string)key)) { throw new ArgumentException("Key cannot be null or empty."); } if (formData[key] is IEnumerable) { foreach (var value in (IEnumerable)formData[key]) { if (value is FileStream) { var fileValStrm = new MemoryStream(); using (var writer = new SmartStream(fileValStrm, false)) { writer.Encoding = encoding; writer.Write(string.Format(fileValTemplate, ((string)key).Trim(), Path.GetFileName(((FileStream)value).Name))); writer.Flush(); } fileValStrm.Position = 0; stream.AppendStream(fileValStrm); stream.AppendStream((FileStream)value); stream.AppendStream(new MemoryStream(new byte[] { (byte)'\r', (byte)'\n' })); } else { var keyValStrm = new MemoryStream(); using (var writer = new SmartStream(keyValStrm, false)) { writer.Encoding = encoding; writer.Write(string.Format(keyValTemplate, ((string)key).Trim())); writer.Write(value.ToString()); writer.Write("\r\n"); writer.Flush(); } keyValStrm.Position = 0; stream.AppendStream(keyValStrm); } } } else { if (formData[key] is FileStream) { var fileValStrm = new MemoryStream(); using (var writer = new SmartStream(fileValStrm, false)) { writer.Encoding = encoding; writer.Write(string.Format(fileValTemplate, ((string)key).Trim(), Path.GetFileName(((FileStream)formData[key]).Name))); writer.Flush(); } fileValStrm.Position = 0; stream.AppendStream(fileValStrm); stream.AppendStream((FileStream)formData[key]); stream.AppendStream(new MemoryStream(new byte[] { (byte)'\r', (byte)'\n' })); } else { var keyValStrm = new MemoryStream(); using (var writer = new SmartStream(keyValStrm, false)) { writer.Encoding = encoding; writer.Write(string.Format(keyValTemplate, ((string)key).Trim())); writer.Write(formData[key]?.ToString()); writer.Write("\r\n"); writer.Flush(); } keyValStrm.Position = 0; stream.AppendStream(keyValStrm); } } } // add end boundary string line. stream.AppendStream(new MemoryStream(encoding.GetBytes($"--{boundary}--\r\n"))); return(stream); }
/// <summary> /// Gets if the specified IP address is in the range. /// </summary> /// <param name="ip">The IP address to check.</param> /// <param name="range">The IP address range.</param> /// <returns>Returns true if the IP address is in the range.</returns> public static bool IsIPAddressInRange(IPAddress ip, string range) { AssertUtil.ArgumentNotNull(ip, nameof(ip)); AssertUtil.ArgumentNotEmpty(range, nameof(range)); string ipString = ip.ToString(); if (ipString == range) { return(true); } if (ip.AddressFamily == AddressFamily.InterNetwork) { if (range.IndexOf('-') > 0) { string[] items = range.Split(new char[] { '-' }, 2); if (!IPAddress.TryParse(items[0], out IPAddress ipStart)) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } if (!int.TryParse(items[1], out int endValue) || endValue > 255) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } byte[] ipBytes = ip.GetAddressBytes(); byte[] startBytes = ipStart.GetAddressBytes(); for (int i = 0; i < 4; i++) { if (i == 3) { return(ipBytes[i] >= startBytes[i] && ipBytes[i] <= endValue); } else if (ipBytes[i] != startBytes[i]) { return(false); } } } else if (range.IndexOf('/') > 0) { string[] items = range.Split(new char[] { '/' }, 2); if (!IPAddress.TryParse(items[0], out IPAddress ipStart)) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } if (!int.TryParse(items[1], out int maskValue) || maskValue > 32) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } byte[] ipBytes = ip.GetAddressBytes(); byte[] startBytes = ipStart.GetAddressBytes(); for (int i = 0; i < 4; i++) { int endValue = startBytes[i]; if (((i + 1) * 8 - maskValue) > 0) { endValue += (int)Math.Pow(2, (i + 1) * 8 - maskValue) - 1; } if (ipBytes[i] < startBytes[i] || ipBytes[i] > endValue) { return(false); } } return(true); } } else if (ip.AddressFamily == AddressFamily.InterNetworkV6) { if (range.IndexOf('-') > 0) { string[] items = range.Split(new char[] { '-' }, 2); if (!IPAddress.TryParse(items[0], out IPAddress ipStart)) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } if (items[1].Length > 4) { throw new ArgumentException($"Agument '{range}' value is not valid ip range."); } byte[] last2Bytes = items[1].PadLeft(4, '0').FromHex(); byte[] ipBytes = ip.GetAddressBytes(); byte[] startBytes = ipStart.GetAddressBytes(); for (int i = 0; i < 16; i++) { if (i >= 14) { if (ipBytes[i] < startBytes[i] || ipBytes[i] > last2Bytes[i - 14]) { return(false); } } else if (ipBytes[i] != startBytes[i]) { return(false); } } return(true); } } return(false); }