/// <summary> /// Converts a timespan in seconds into a localized version. /// </summary> /// <remarks> /// This is a wrapper for TimeSpan.ToString("c") /// </remarks> /// <param name="localeId">The locale ID.</param> /// <param name="seconds">The duration in seconds.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The timespan-string.</returns> public static string GetFormattedSeconds(string localeId, long seconds) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); var span = TimeSpan.FromSeconds(seconds); return(span.ToString("c", new CultureInfo(localeId))); }
/// <summary> /// Checks, if a certain <paramref name="port" /> is opened on the local machine. /// </summary> /// <remarks> /// <para> /// Original version found at /// <see>http://stackoverflow.com/questions/570098/in-c-how-to-check-if-a-tcp-port-is-available/></see>. /// </para> /// </remarks> /// <exception cref="ArgumentException"> /// Is thrown if the <paramref name="port" /> parameter contains a value less or equal /// than 0. /// </exception> /// <param name="port">The number of the port to check.</param> /// <returns><c>True</c> if the port is opened, otherwise <c>false.</c></returns> public static bool IsPortOpened(int port) { CheckUtil.ThrowIfZeroOrNegative(() => port); var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners(); return(tcpConnInfoArray.Any(ep => ep.Port == port)); }
/// <summary> /// Converts meters to m or ft depending on the <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="meters">The amount of altitude.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The converted amount of altitude.</returns> public static double GetAltitude(string localeId, double meters) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); if (Math.Abs(meters) < CompareTolerance) { return(meters); } return(GetRegion(localeId).IsMetric ? meters : UnitConversionCalculator.ConvertMetersToFeet(meters)); }
/// <summary> /// Converts meters to km or miles depending on the <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="meters">The amount of distance.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The converted amount of distance.</returns> public static double GetDistance(string localeId, double meters) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); if (Math.Abs(meters) < CompareTolerance) { return(meters); } return(GetRegion(localeId).IsMetric ? meters * Constants.KilometersPerMeter : UnitConversionCalculator.ConvertMetersToMiles(meters)); }
/// <summary> /// Converts kilograms to kg or pound depending on the <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="kiloGrams">The amount of weight.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <exception cref="CultureNotFoundException">Is thrown if the <paramref name="localeId"/> is not a valid culture.</exception> /// <returns>The converted amount of weight.</returns> public static double GetWeight(string localeId, double kiloGrams) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); if (Math.Abs(kiloGrams) < CompareTolerance) { return(0); } return(GetRegion(localeId).IsMetric ? kiloGrams : UnitConversionCalculator.ConvertKilogramToPounds(kiloGrams)); }
/// <summary> /// Wrapper for methods in this type which will return formatted values depending on <paramref name="localeId" /> and /// <paramref name="decimalPlaces" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="value">The value to convert and format.</param> /// <param name="calcMethod">A delegate for a method that performs the value calculation.</param> /// <param name="unit">The already resolved unit.</param> /// <param name="decimalPlaces">The optional amount of decimal places for the output (defaults to 0).</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> or <paramref name="calcMethod"/> are <c>null</c> or empty.</exception> /// <exception cref="CultureNotFoundException">Is thrown if the <paramref name="localeId"/> is not a valid culture.</exception> /// <returns>The returnable text-representation of the calculated value.</returns> private static string GetFormattedValue(string localeId, double value, Func <string, double, double> calcMethod, string unit, int decimalPlaces = 0) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); CheckUtil.ThrowIfNull(() => calcMethod); var culture = new CultureInfo(localeId); var formatPattern = "{0:N" + decimalPlaces + "} {1}"; var formatted = calcMethod(localeId, value).ToString(formatPattern, culture); return(string.Format(culture, "{0} {1}", formatted, unit)); }
/// <summary> /// Converts meters/s to km/h or miles/h depending on the <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="metersPerSecond">The amount of speed.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The converted amount of speed.</returns> public static double GetSpeed(string localeId, double metersPerSecond) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); if (Math.Abs(metersPerSecond) < CompareTolerance) { return(0); } return(GetRegion(localeId).IsMetric ? UnitConversionCalculator.ConvertMetersPerSecondToKilometersPerHour(metersPerSecond) : UnitConversionCalculator.ConvertMetersPerSecondToMilesPerHour(metersPerSecond)); }
/// <summary> /// Retrieves either the <see cref="RegionInfo" /> for <paramref name="localeId" />. /// </summary> /// <param name="localeId">The specific culture ID in the form xx-XX.</param> /// <exception cref="CultureNotFoundException">Is thrown if the <paramref name="localeId"/> is not a valid culture.</exception> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <exception cref="ArgumentException">Is thrown if the <paramref name="localeId"/> maps to a neutral culture.</exception> /// <returns>A usable region info.</returns> private static RegionInfo GetRegion(string localeId) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); var culture = new CultureInfo(localeId); if (culture.IsNeutralCulture) { // Try to get the specific culture throw new ArgumentException("Provided culture not specific!", nameof(localeId)); } var result = new RegionInfo(localeId); return(result); }
/// <summary> /// Calls <see cref="GetDistance" /> and <see cref="GetDistanceUnit" /> and merges the results to a completely /// formatted distance depending on the given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="meters">The amount of distance.</param> /// <param name="enforceBigUnit"> /// If set to <c>true</c>, no automatic switch between small and big distances will be applied. /// </param> /// <param name="decimalPlaces">The optional amount of decimal places for the output (defaults to 0).</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The formatted distance-text.</returns> public static string GetFormattedDistance(string localeId, double meters, bool enforceBigUnit, int decimalPlaces = 0) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); var distance = GetDistance(localeId, meters); var unit = GetDistanceUnit(localeId); if (distance < 1 && !enforceBigUnit) { distance = GetSmallDistance(localeId, meters); unit = GetSmallDistanceUnit(localeId); } var formatPattern = "{0:N" + decimalPlaces + "} {1}"; return(string.Format(new CultureInfo(localeId), formatPattern, distance, unit)); }
/// <summary> /// Generates a speaking text for a given amount of <paramref name="seconds" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="seconds">The amount of seconds representing the amount of time.</param> /// <param name="resourceResolver">An optional function that this method uses to retrieve resource-strings.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The speaking text.</returns> public static string GetSpeakingTimeString(string localeId, long seconds, Func <string, string> resourceResolver = null) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); if (resourceResolver == null) { resourceResolver = key => "?"; } var span = TimeSpan.FromSeconds(seconds); var builder = new StringBuilder(); string resourceKey; if (span.Days > 365) { var years = span.Days / 365; span = span.Subtract(TimeSpan.FromSeconds(years * Constants.SecondsPerYear)); resourceKey = years != 1 ? "TimePartYearPlural" : "TimePartYearSingular"; builder.AppendFormat("{0} {1} ", years, resourceResolver(resourceKey)); } if (span.Days > 29) { var months = span.Days / 30; span = span.Subtract(TimeSpan.FromSeconds(months * Constants.SecondsPerMonth)); resourceKey = months != 1 ? "TimePartMonthPlural" : "TimePartMonthSingular"; builder.AppendFormat("{0} {1} ", months, resourceResolver(resourceKey)); } if (span.Days > 6) { var weeks = span.Days / 7; span = span.Subtract(TimeSpan.FromSeconds(weeks * Constants.SecondsPerWeek)); resourceKey = weeks != 1 ? "TimePartWeekPlural" : "TimePartWeekSingular"; builder.AppendFormat("{0} {1} ", weeks, resourceResolver(resourceKey)); } if (span.Days >= 1) { resourceKey = span.Days != 1 ? "TimePartDayPlural" : "TimePartDaySingular"; builder.AppendFormat("{0} {1} ", span.Days, resourceResolver(resourceKey)); span = span.Subtract(TimeSpan.FromSeconds(span.Days * Constants.SecondsPerDay)); } resourceKey = span.Hours != 1 ? "TimePartHourPlural" : "TimePartHourSingular"; builder.AppendFormat("{0} {1} ", span.Hours, resourceResolver(resourceKey)); span = span.Subtract(TimeSpan.FromSeconds(span.Hours * 60 * 60)); resourceKey = span.Minutes != 1 ? "TimePartMinutePlural" : "TimePartMinuteSingular"; builder.AppendFormat("{0} {1} ", span.Minutes, resourceResolver(resourceKey)); span = span.Subtract(TimeSpan.FromSeconds(span.Hours * 60)); resourceKey = span.Seconds != 1 ? "TimePartSecondPlural" : "TimePartSecondSingular"; builder.AppendFormat("{0} {1} ", span.Seconds, resourceResolver(resourceKey)); return(builder.ToString().Trim()); }
/// <summary> /// Uses <see cref="StreamReader" /> to automatically determine the encoding used for a given <paramref name="fileUri" /> /// using the BOM. /// </summary> /// <param name="fileUri">The absolute path to the file.</param> /// <exception cref="ArgumentException">Is thrown if <paramref name="fileUri" /> is invalid.</exception> /// <exception cref="FileNotFoundException"> /// Is thrown if the provided <paramref name="fileUri" /> is not found in file /// system. /// </exception> /// <exception cref="InvalidOperationException">Is thrown if any exception occurs during the operation.</exception> /// <returns>The detected encoding.</returns> public static Encoding GetEncoding(string fileUri) { CheckUtil.ThrowIfNullOrEmpty(() => fileUri); if (!File.Exists(fileUri)) { throw new FileNotFoundException("Provided file not found.", fileUri); } try { using (var reader = new StreamReader(fileUri, true)) { return(reader.CurrentEncoding); } } catch (Exception ex) { throw new InvalidOperationException("Could not determine encoding. See inner exception for details.", ex); } }
/// <summary> /// Generates a speaking text for a given amount of <paramref name="seconds" /> with abbreviations for HTML-output. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="seconds">The amount of seconds representing the amount of time.</param> /// <param name="classNameUnits">The name of the CSS-class to format the units with.</param> /// <param name="resourceResolver">An optional function that this method uses to retrieve resource-strings.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The speaking text in HTML.</returns> public static string GetSpeakingTimeStringShortHtml(string localeId, long seconds, string classNameUnits, Func <string, string> resourceResolver = null) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); if (resourceResolver == null) { resourceResolver = key => "?"; } var span = TimeSpan.FromSeconds(seconds); var builder = new StringBuilder(); if (span.Days > 365) { var years = span.Days / 365; span = span.Subtract(TimeSpan.FromSeconds(years * Constants.SecondsPerYear)); builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", years, classNameUnits, resourceResolver("TimePartYearShort")); } if (span.Days > 29) { var months = span.Days / 30; span = span.Subtract(TimeSpan.FromSeconds(months * Constants.SecondsPerMonth)); builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", months, classNameUnits, resourceResolver("TimePartMonthShort")); } if (span.Days > 6) { var weeks = span.Days / 7; span = span.Subtract(TimeSpan.FromSeconds(weeks * Constants.SecondsPerWeek)); builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", weeks, classNameUnits, resourceResolver("TimePartWeekShort")); } if (span.Days >= 1) { builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", span.Days, classNameUnits, resourceResolver("TimePartDayShort")); span = span.Subtract(TimeSpan.FromSeconds(span.Days * Constants.SecondsPerDay)); } builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", span.Hours, classNameUnits, resourceResolver("TimePartHourShort")); span = span.Subtract(TimeSpan.FromSeconds(span.Hours * 60 * 60)); builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", span.Minutes, classNameUnits, resourceResolver("TimePartMinuteShort")); span = span.Subtract(TimeSpan.FromSeconds(span.Hours * 60)); builder.AppendFormat("{0}<span class=\"{1}\">{2}</span>", span.Seconds, classNameUnits, resourceResolver("TimePartSecondShort")); return(builder.ToString().Trim()); }
/// <summary> /// Calls <see cref="GetAltitude" /> and <see cref="GetAltitudeUnit" /> and merges the results to a completely /// formatted altitude depending on the given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="meters">The amount of altitude.</param> /// <param name="decimalPlaces">The optional amount of decimal places for the output (defaults to 0).</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The formatted altitude-text.</returns> public static string GetFormattedAltitude(string localeId, double meters, int decimalPlaces = 0) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetFormattedValue(localeId, meters, GetAltitude, GetAltitudeUnit, decimalPlaces)); }
/// <summary> /// Retrieves the correct distance unit text for a given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The correct unit.</returns> public static string GetDistanceUnit(string localeId) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetRegion(localeId).IsMetric ? MetricDistanceUnit : ImperialDistanceUnit); }
/// <summary> /// Calls <see cref="GetSpeed" /> and <see cref="GetSpeedUnit" /> and merges the results to a completely /// formatted speed depending on the given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="metersPerSecond">The amount of speed.</param> /// <param name="decimalPlaces">The optional amount of decimal places for the output (defaults to 0).</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The formatted speed-text.</returns> public static string GetFormattedSpeed(string localeId, double metersPerSecond, int decimalPlaces = 0) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetFormattedValue(localeId, metersPerSecond, GetSpeed, GetSpeedUnit, decimalPlaces)); }
/// <summary> /// Converts meters to km or yards depending on the <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="meters">The amount of distance.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The converted amount of distance.</returns> public static double GetSmallDistance(string localeId, double meters) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetRegion(localeId).IsMetric ? meters : UnitConversionCalculator.ConvertMetersToYards(meters)); }
/// <summary> /// Converts centimeters to cm or inch depending on the <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="centiMeters">The amount of height.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The converted amount of height.</returns> public static double GetHeight(string localeId, double centiMeters) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetRegion(localeId).IsMetric ? centiMeters : UnitConversionCalculator.ConvertCentimetersToInches(centiMeters)); }
/// <summary> /// Calls <see cref="GetWeight" /> and <see cref="GetWeightUnit" /> and merges the results to a completely /// formatted weight depending on the given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="kiloGrams">The amount of weight.</param> /// <param name="decimalPlaces">The optional amount of decimal places for the output (defaults to 0).</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The formatted weight-text.</returns> public static string GetFormattedWeight(string localeId, double kiloGrams, int decimalPlaces = 0) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetFormattedValue(localeId, kiloGrams, GetWeight, GetWeightUnit, decimalPlaces)); }
/// <summary> /// Retrieves a timespan formatted in a given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="value">The time part.</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The formatted altitude-text.</returns> public static string GetFormattedTimespan(string localeId, TimeSpan value) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(value.ToString("c", new CultureInfo(localeId))); }
/// <summary> /// Retrieves the value for a given <paramref name="itemName"/> inside a <paramref name="groupName"/> from a <paramref name="fileName"/>. /// </summary> /// <param name="fileName">The full path to the INI-file.</param> /// <param name="groupName">The name of the group in which the setting is expected or <c>null</c> if the item is in no group.</param> /// <param name="itemName">The name of the item.</param> /// <param name="defaultValue">A default value if no value could be found.</param> /// <typeparam name="T">The type of the result.</typeparam> /// <returns>The value associated with the <paramref name="itemName"/>.</returns> /// <exception cref="FileNotFoundException">Is thrown if the file could not be found.</exception> /// <exception cref="InvalidOperationException">Is thrown in case of any other exception.</exception> public static T GetValue <T>(string fileName, string groupName, string itemName, T defaultValue = default(T)) { CheckUtil.ThrowIfNullOrEmpty(() => fileName); CheckUtil.ThrowIfNullOrEmpty(() => itemName); if (!File.Exists(fileName)) { throw new FileNotFoundException("Provided file not found.", fileName); } string[] linesInFile; try { linesInFile = File.ReadAllLines(fileName); } catch (Exception ex) { throw new InvalidOperationException("Error during read of file.", ex); } if (linesInFile == null || !linesInFile.Any()) { throw new InvalidOperationException("Could not read from file."); } var groupSearch = string.Format(CultureInfo.InvariantCulture, "[{0}]", groupName); var groupFound = !string.IsNullOrEmpty(groupName) && linesInFile.Any(line => line.Equals(groupSearch, StringComparison.OrdinalIgnoreCase)); if (!groupFound) { return(defaultValue); } var inGroup = !string.IsNullOrEmpty(groupName); var retVal = defaultValue; linesInFile.ToList().ForEach( line => { if (line.StartsWith("[")) { // check if we will start the parsing or if we stop the complete process if (inGroup) { // we where already inside the desired group return; } inGroup = line.Equals(groupSearch, StringComparison.OrdinalIgnoreCase); } else { if (!inGroup || !line.StartsWith(itemName, StringComparison.OrdinalIgnoreCase)) { return; } // this is the item we are looking for var value = line.Split('=')[1].Trim(); if (value.IsNullOrEmpty()) { return; } try { retVal = (T)Convert.ChangeType(value, typeof(T)); } catch (Exception ex) { TraceUtil.WriteTraceError(ex.Message); } } }); return(retVal); }
/// <summary> /// Calls <see cref="GetHeight" /> and <see cref="GetHeightUnit" /> and merges the results to a completely /// formatted height depending on the given <paramref name="localeId" />. /// </summary> /// <param name="localeId">The locale ID.</param> /// <param name="centiMeters">The amount of height.</param> /// <param name="decimalPlaces">The optional amount of decimal places for the output (defaults to 0).</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="localeId"/> is <c>null</c> or empty.</exception> /// <returns>The formatted height-text.</returns> public static string GetFormattedHeight(string localeId, double centiMeters, int decimalPlaces = 0) { CheckUtil.ThrowIfNullOrEmpty(() => localeId); return(GetFormattedValue(localeId, centiMeters, GetHeight, GetHeightUnit, decimalPlaces)); }