/// <summary> /// To the bytes. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="integerValue">The integer value.</param> /// <param name="fixedArrayLength">Length of the fixed array.</param> /// <param name="convert">The convert.</param> /// <returns></returns> private static byte[] ToBytes <T>(this T integerValue, int fixedArrayLength, Func <T, byte[]> convert) { try { convert.CheckNullObject(nameof(convert)); if (fixedArrayLength < 1) { ExceptionFactory.CreateInvalidObjectException(nameof(fixedArrayLength), fixedArrayLength); } var actualBytes = convert(integerValue); int length, destinationIndex; if (fixedArrayLength > actualBytes.Length) { length = actualBytes.Length; destinationIndex = fixedArrayLength - actualBytes.Length; } else { length = fixedArrayLength; destinationIndex = 0; } var result = new byte[fixedArrayLength]; Array.Copy(actualBytes, 0, result, destinationIndex, length); return(result); } catch (Exception ex) { throw ex.Handle(new { integerValue, fixedArrayLength }); } }
/// <summary> /// Converts list of <see cref="FinancialItemDetail" /> as <see cref="FinancialItemSummary" />. /// </summary> /// <param name="details">The details.</param> /// <param name="summaryName">Name of the summary.</param> /// <returns> /// FinancialItemSummary. /// </returns> public static FinancialItemSummary AsSummary(this IEnumerable <FinancialItemDetail> details, string summaryName) { FinancialItemSummary result = null; if (details.HasItem()) { result = new FinancialItemSummary { Name = summaryName, Currency = details.First().Currency.SafeToUpper() }; foreach (var one in details) { if (!one.Currency.MeaningfulEquals(result.Currency, System.StringComparison.InvariantCultureIgnoreCase)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(one.Currency), data: new { currency1 = result.Currency, currency2 = one.Currency }, reason: "Inconsistence currency."); } result.TotalPrice += one.TotalPrice; result.TotalDiscount += one.Discount; result.Amount += one.Amount; result.VAT += one.VAT; result.Details.Add(one); } } return(result); }
/// <summary> /// Parses the specified cloud protocol URI. /// </summary> /// <param name="cloudProtocolUri">The cloud protocol URI.</param> /// <returns>CloudResourceUri.</returns> /// <exception cref="InvalidObjectException">cloudProtocolUri;null</exception> public static CloudResourceUri Parse(string cloudProtocolUri) { try { cloudProtocolUri.CheckEmptyString("cloudProtocolUri"); var match = UriRegex.Match(cloudProtocolUri); if (match.Success) { return(new CloudResourceUri() { Type = match.Result("${Type}"), Container = match.Result("${Container}"), Identifier = match.Result("${Identifier}") }); } else { throw ExceptionFactory.CreateInvalidObjectException("cloudProtocolUri", data: cloudProtocolUri); } } catch (Exception ex) { throw ex.Handle(cloudProtocolUri); } }
/// <summary> /// Validates the specified cellphone number. /// </summary> /// <param name="cellphoneNumber">The cellphone number.</param> /// <param name="omitNationCode">if set to <c>true</c> [omit nation code].</param> public void Validate(CellphoneNumber cellphoneNumber, bool omitNationCode = false) { try { cellphoneNumber.CheckNullObject(nameof(cellphoneNumber)); if (!omitNationCode && !cellphoneNumber.NationCode.MeaningfulEquals(NationCode)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(cellphoneNumber.NationCode), new { expected = NationCode, actual = cellphoneNumber.NationCode }); } var regex = GetRegex(); regex.CheckNullObject(nameof(regex)); cellphoneNumber.Number.CheckEmptyString(nameof(cellphoneNumber.Number)); if (!regex.IsMatch(cellphoneNumber.Number)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(cellphoneNumber.Number), new { cellphoneNumber }); } } catch (Exception ex) { throw ex.Handle(new { cellphoneNumber, omitNationCode }); } }
/// <summary> /// Creates the instance. /// </summary> /// <param name="constructor">The constructor.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> public static object CreateInstance(this ConstructorInfo constructor, Dictionary <string, object> parameters = null) { if (constructor != null) { var constructorParameters = constructor.GetParameters(); var parameterValues = constructorParameters.Length > 0 ? new object[constructorParameters.Length] : null; int i = 0; foreach (var one in constructorParameters) { if (parameters?.ContainsKey(one.Name) ?? false) { parameterValues[i] = parameters[one.Name]; } else if (one.HasDefaultValue) { parameterValues[i] = one.DefaultValue; } else { throw ExceptionFactory.CreateInvalidObjectException(nameof(one.Name)); } i++; } return(constructor.Invoke(parameterValues)); } return(null); }
/// <summary> /// Checks the directory exist. /// </summary> /// <param name="directory">The directory.</param> public static void CheckDirectoryExist(this DirectoryInfo directory) { if (directory == null || !directory.Exists) { throw ExceptionFactory.CreateInvalidObjectException(nameof(directory), directory?.FullName); } }
/// <summary> /// Validates the key. /// </summary> /// <param name="key">The key.</param> protected void ValidateKey(TKey key) { if (!IsKeyValid(key)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(key), data: key); } }
/// <summary> /// Requireses the positive number. /// </summary> /// <param name="value">The value.</param> /// <param name="objectIdentifier">The object identifier.</param> /// <param name="acceptZero">if set to <c>true</c> [accept zero].</param> public static void RequiresPositiveNumber(this double value, string objectIdentifier, bool acceptZero = false) { if (acceptZero ? (value < 0) : (value <= 0)) { throw ExceptionFactory.CreateInvalidObjectException(objectIdentifier, reason: acceptZero ? "requires>=0" : "requires>0"); } }
/// <summary> /// Converts the format to regex. Like convert "Name: {name}" within constraints "[a-z0-9]+" to "Name:\s(?<name>([a-z0-9]+))" as <seealso cref="Regex" />. If no constraint specified, use ".+". /// </summary> /// <param name="format">The format.</param> /// <param name="constraints">The constraints.</param> /// <param name="regexOptions">The regex options.</param> /// <returns>Regex.</returns> public static Regex ConvertFormatToRegex(this string format, Dictionary <string, string> constraints = null, RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase) { var shards = ConvertFormatToShiftShard(format); if (shards == null) { return(null); } if (!shards.IsValid) { throw ExceptionFactory.CreateInvalidObjectException(nameof(shards), shards); } var builder = shards.CreateStringBuilder(); if (constraints == null) { constraints = new Dictionary <string, string>(); } for (var i = 0; i < shards.dynamicShards.Count; i++) { builder.Append(shards.staticShards[i].StaticStringToRegexPattern()); string constraintPattern; builder.Append(GetPlaceHolderPattern(shards.dynamicShards[i], constraints.TryGetValue(shards.dynamicShards[i], out constraintPattern) ? constraintPattern : defaultConstraint)); } builder.Append(shards.staticShards[shards.dynamicShards.Count]); return(new Regex(builder.ToString(), regexOptions)); }
/// <summary> /// Requireses the enum value. /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="enumValue">The enum value.</param> /// <param name="acceptances">The acceptances.</param> public static void RequiresEnumValue <TEnum>(this TEnum?enumValue, params TEnum[] acceptances) where TEnum : struct, IConvertible { if (acceptances.HasItem() && (!enumValue.HasValue || !acceptances.HasItem(enumValue.Value))) { throw ExceptionFactory.CreateInvalidObjectException(nameof(enumValue), new { enumValue, acceptances }, "Unacceptable"); } }
/// <summary> /// Initializes a new instance of the <see cref="Range{TCoordinate}" /> class. /// </summary> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <param name="fromValueReachable">if set to <c>true</c> [from value reachable].</param> /// <param name="toValueReachable">if set to <c>true</c> [to value reachable].</param> /// <param name="omitRangeValidation">if set to <c>true</c> [omit range validation].</param> public Range(TCoordinate?from = null, TCoordinate?to = null, bool fromValueReachable = true, bool toValueReachable = false, bool omitRangeValidation = false) { From = from; To = to; if (!omitRangeValidation && from.HasValue && to.HasValue && ((IComparable)From.Value).CompareTo(To.Value) >= 0) { throw ExceptionFactory.CreateInvalidObjectException(nameof(to), new { from, to }, "InvalidRange"); } }
/// <summary> /// Checks the RSA source. /// </summary> /// <param name="source">The source.</param> /// <param name="dwKeySize">Size of the dw key.</param> internal static void CheckRsaSource(byte[] source, int dwKeySize) { if (source != null) { var maxAllowedLength = GetMaxRsaBlockSize(dwKeySize); if (source.Length > maxAllowedLength) { throw ExceptionFactory.CreateInvalidObjectException(nameof(source), new { dataLength = source.Length, dwKeySize, maxAllowedLength }, "OverMaxAllowedEncryptionLength"); } } }
/// <summary> /// Compares to. /// </summary> /// <param name="obj">The object.</param> /// <returns></returns> public int CompareTo(object obj) { var currencyAmount = obj as CurrencyAmount; currencyAmount.CheckNullObject(nameof(currencyAmount)); if (!Currency.MeaningfulEquals(currencyAmount.Currency, StringComparison.OrdinalIgnoreCase)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(Currency), new { Self = Currency, Target = currencyAmount.Currency }, "CurrentDismatch"); } return(Amount.CompareTo(currencyAmount.Amount)); }
/// <summary> /// When overridden in a derived class, sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> public override void SetLength(long value) { if (value < 0) { throw ExceptionFactory.CreateInvalidObjectException(nameof(value), value); } var tmp = new byte[value]; var length = Math.Min(_source.Length, value); for (var i = 0; i < length; i++) { tmp[i] = _source[i]; } _source = tmp; }
/// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public virtual void Add(TKey key, TValue value) { try { if (!IsKeyValid(key)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(key)); } var list = GetCollectionByKey(key, true); list.Add(value); } catch (Exception ex) { throw ex.Handle(new { key, value }); } }
/// <summary> /// Initializes a new instance of the <see cref="HttpListenerServerBase"/> class. /// </summary> /// <param name="prefixes">The URL prefixes.</param> /// <param name="authenticationSchema">The authentication schema.</param> /// <exception cref="Beyova.Diagnostic.InvalidObjectException">prefixes</exception> /// <exception cref="InvalidObjectException">prefixes</exception> public HttpListenerServerBase(string[] prefixes, AuthenticationSchemes authenticationSchema = AuthenticationSchemes.Anonymous) { // URI prefixes are required, // for example "http://beyova.org:8080/index/". if (prefixes == null || prefixes.Length == 0) { throw ExceptionFactory.CreateInvalidObjectException(nameof(prefixes)); } // Add the prefixes. foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.AuthenticationSchemes = authenticationSchema; }
/// <summary> /// Reads as j token. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> public static JToken ReadAsJToken(this JsonReader reader) { JToken result = null; if (reader != null) { switch (reader.TokenType) { case JsonToken.Boolean: case JsonToken.Bytes: case JsonToken.Date: case JsonToken.Float: case JsonToken.Integer: case JsonToken.String: result = JToken.FromObject(reader.Value); reader.Read(); break; case JsonToken.Null: case JsonToken.Undefined: result = null; break; case JsonToken.StartArray: result = ReadAsArray(reader); break; case JsonToken.StartObject: result = ReadAsObject(reader); break; case JsonToken.PropertyName: case JsonToken.EndArray: case JsonToken.EndObject: case JsonToken.EndConstructor: throw ExceptionFactory.CreateInvalidObjectException(nameof(reader.TokenType), reader.TokenType.EnumToString()); default: break; } } return(result); }
/// <summary> /// Do SUM(item[N], byteItems[i][N]) by each byte wise /// </summary> /// <param name="item">The item.</param> /// <param name="byteItems">The byte items.</param> /// <returns></returns> public static byte[] ByteWiseSumWith(this byte[] item, params byte[][] byteItems) { try { item.CheckNullOrEmptyCollection(nameof(item)); if (byteItems == null || byteItems.Length == 0) { return(item); } int index = 0; foreach (var one in byteItems) { if (one.Length != item.Length) { throw ExceptionFactory.CreateInvalidObjectException(nameof(byteItems), data: new { index }, reason: "LengthDismatch"); } index++; } var result = new byte[item.Length]; for (var i = 0; i < item.Length; i++) { var sum = Convert.ToInt32(item[i]); foreach (var one in byteItems) { sum += Convert.ToInt32(one[i]); } result[i] = Convert.ToByte(sum); } return(result); } catch (Exception ex) { throw ex.Handle(new { item, byteItems }); } }
/// <summary> /// Reads the file bytes. /// </summary> /// <param name="path">The path.</param> /// <returns>System.Byte[].</returns> public static byte[] ReadFileBytes(this string path) { try { path.CheckEmptyString(nameof(path)); if (!File.Exists(path)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(path), data: new { path }, reason: "NotFound"); } using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { return(stream.ReadStreamToBytes(true)); } } catch (Exception ex) { throw ex.Handle(path); } }
/// <summary> /// Randoms the specified byte length. /// </summary> /// <param name="byteLength">Length of the byte.</param> /// <returns></returns> public static CryptoKey Random(int byteLength) { try { if (byteLength < 1) { throw ExceptionFactory.CreateInvalidObjectException(nameof(byteLength)); } Random rnd = new Random(); Byte[] b = new Byte[byteLength]; rnd.NextBytes(b); return(new CryptoKey(b)); } catch (Exception ex) { throw ex.Handle(new { byteLength }); } }
/// <summary> /// Initials the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="container">The container.</param> public virtual void Initial(TKey key, TContainer container) { //NOTES: In case like MatrixList<TKey, Object>. Method Add would hard to tell which method is right to call (Add(key, value) of Dictionary or Add(key, List<Value>)) try { if (!IsKeyValid(key)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(key)); } if (!ContainsKey(key)) { Add(key, container); } } catch (Exception ex) { throw ex.Handle(new { key, container }); } }
/// <summary> /// Reads the bytes to stream. /// </summary> /// <param name="path">The path.</param> /// <param name="destinationStream">The destination stream.</param> public static void ReadBytesToStream(this string path, Stream destinationStream) { try { path.CheckEmptyString(nameof(path)); destinationStream.CheckNullObject(nameof(destinationStream)); if (!File.Exists(path)) { throw ExceptionFactory.CreateInvalidObjectException(nameof(path), data: new { path }, reason: "NotFound"); } using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { stream.CopyTo(destinationStream); } } catch (Exception ex) { throw ex.Handle(path); } }
/// <summary> /// Applies the injection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="staticType">Type of the static.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="injectionCandidate">The injection candidate.</param> /// <param name="expectAsLowPriority">if set to <c>true</c> [expect as low priority].</param> public static void ApplyInjection <T>(Type staticType, string propertyName, ParameterlessFunctionInjection <T> injectionCandidate, bool expectAsLowPriority = false) { if (staticType != null && !string.IsNullOrWhiteSpace(propertyName) && injectionCandidate != null) { var hitProperty = staticType.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty).FirstOrDefault(x => x.Name == propertyName); if (hitProperty != null) { if (typeof(ParameterlessPrioritizedFunctionInjection <T>).IsAssignableFrom(hitProperty.PropertyType)) { ParameterlessPrioritizedFunctionInjection <T> existed = hitProperty.GetValue(null) as ParameterlessPrioritizedFunctionInjection <T>; if (existed == null) { if (hitProperty.SetMethod != null) { existed = new ParameterlessPrioritizedFunctionInjection <T>(); hitProperty.SetValue(null, existed); } else { throw ExceptionFactory.CreateInvalidObjectException(hitProperty?.Name, new { type = staticType?.FullName, property = hitProperty?.Name }); } } if (expectAsLowPriority) { existed.Append(injectionCandidate); } else { existed.Prepend(injectionCandidate); } } else if (hitProperty.PropertyType == typeof(ParameterlessFunctionInjection <>).MakeGenericType(typeof(T))) { hitProperty.SetValue(null, injectionCandidate); } } } }
/// <summary> /// Dexmlizes the specified XML. /// </summary> /// <param name="xml">The XML.</param> /// <returns> /// JToken. /// </returns> public static JToken Dexmlize(this XElement xml) { if (xml != null) { var version = xml.GetAttributeValue(attributeVersion); switch (version.ToLowerInvariant()) { case JsonXmlizer.VersionValue: return(InternalDexmlize(xml)); case "": case JsonXmlSerializer.VersionValue: return(JsonXmlSerializer.InternalToJToken(xml)); default: throw ExceptionFactory.CreateInvalidObjectException("version", version); } } return(null); }
/// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <param name="values">The values.</param> /// <returns>A <see cref="System.String" /> that represents this instance.</returns> public string ToString(IDictionary <string, string> values) { if (!IsValid) { throw ExceptionFactory.CreateInvalidObjectException(nameof(values), values); } StringBuilder builder = this.CreateStringBuilder(); values = values ?? new Dictionary <string, string>(); for (var i = 0; i < dynamicShards.Count; i++) { string replacedValue; builder.Append(staticShards[i]); builder.Append(values.TryGetValue(dynamicShards[i], out replacedValue) ? replacedValue : string.Empty); } builder.Append(staticShards[dynamicShards.Count]); return(builder.ToString()); }
/// <summary> /// Creates the method invoker. /// </summary> /// <param name="methodCodeFullName">Full name of the method code.</param> /// <returns></returns> public static MethodInvoker CreateMethodInvoker(string methodCodeFullName) { try { methodCodeFullName.CheckEmptyString(nameof(methodCodeFullName)); //TODO. Consider simple case in this stage. // No generic, no instance. Only static method. {namespace}+.{class}.{method} var lastDot = methodCodeFullName.LastIndexOf('.'); if (lastDot > -1) { string method = methodCodeFullName.Substring(lastDot); var typeFullName = methodCodeFullName.Substring(0, lastDot); var type = ReflectionExtension.SmartGetType(typeFullName, false); type.CheckNullObjectAsInvalid(nameof(methodCodeFullName), data: new { method, typeFullName }); var methodInfo = type.GetMethod(method); methodInfo.CheckNullObjectAsInvalid(nameof(methodCodeFullName), data: new { method, typeFullName }); return(new MethodInvoker(methodInfo)); } else { throw ExceptionFactory.CreateInvalidObjectException(nameof(methodCodeFullName), data: new { methodCodeFullName }); } } catch (BaseException bex) { throw bex; } catch (Exception ex) { throw ex.Handle(new { methodCodeFullName }); } }
/// <summary> /// Initializes static members of the <see cref="EnvironmentCore"/> class. /// </summary> static EnvironmentCore() { var baseDirectoryByAppDomain = AppDomain.CurrentDomain.BaseDirectory; var baseDirectoryByAssemblyLocation = Path.GetDirectoryName(typeof(EnvironmentCore).Assembly.Location); // NOTE: // In IIS Express cases, baseDirectoryByAssemblyLocation would be allocated into asp.net tmp folders, by each library. // In other cases, IIS or Console or Windows environments, baseDirectoryByAssemblyLocation should be correct. DirectoryInfo baseDirectory = new DirectoryInfo((baseDirectoryByAppDomain.StartsWith(baseDirectoryByAssemblyLocation, StringComparison.OrdinalIgnoreCase)) ? baseDirectoryByAssemblyLocation : Path.Combine(baseDirectoryByAppDomain, "bin")); if (baseDirectory?.Exists ?? false) { ApplicationBaseDirectory = baseDirectory.ToString(); } else { throw ExceptionFactory.CreateInvalidObjectException(nameof(baseDirectory), new { baseDirectory = baseDirectory?.ToString(), baseDirectoryByAppDomain, baseDirectoryByAssemblyLocation }); } LogDirectory = Path.Combine(ApplicationBaseDirectory, "logs"); ApplicationId = System.AppDomain.CurrentDomain.Id; var dependencyChain = ReflectionExtension.GetAppDomainAssemblies().GetAssemblyDependencyChain(true); AscendingAssemblyDependencyChain = new List <Assembly>(dependencyChain).AsReadOnly(); dependencyChain.Reverse(); DescendingAssemblyDependencyChain = dependencyChain.AsReadOnly(); CommonComponentInfo = typeof(EnvironmentCore).Assembly.GetCustomAttribute <BeyovaComponentAttribute>()?.UnderlyingObject; try { MachineName = Environment.MachineName; } catch { MachineName = string.Empty; } try { LocalMachineHostName = Dns.GetHostName(); var host = Dns.GetHostEntry(LocalMachineHostName); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { LocalMachineIpAddress = ip.ToString(); break; } } } catch { } try { ProductName = FindProductName(); if (string.IsNullOrWhiteSpace(ProductName)) { ProductName = Assembly.GetEntryAssembly()?.FullName; } if (string.IsNullOrWhiteSpace(ProductName) && AppDomain.CurrentDomain != null) { ProductName = AppDomain.CurrentDomain.FriendlyName; } } catch { ProductName = string.Empty; } }