/// <summary>
        /// Converts the specified from unit to the specified unit.
        /// </summary>
        /// <param name="fromUnit">Covert from unit.</param>
        /// <param name="toUnit">Covert to unit.</param>
        /// <param name="fromValue">Covert from value.</param>
        /// <returns>The converted value.</returns>
        public static double Convert(
            TemperatureUnit fromUnit,
            TemperatureUnit toUnit,
            double fromValue)
        {
            if (fromUnit == toUnit)
                return fromValue;

            double result = 0;

            if (fromUnit == TemperatureUnit.Celsius)
            {
                if (toUnit == TemperatureUnit.Kelvin)
                    result = fromValue + 273.15d;
                else if (toUnit == TemperatureUnit.Fahrenheit)
                    //(9/5 * C) + 32 = F
                    result = (9.0d/5.0d*fromValue) + 32d;
            }
            else if (fromUnit == TemperatureUnit.Kelvin)
            {
                if (toUnit == TemperatureUnit.Celsius)
                    result = fromValue - 273.15d;
                else if (toUnit == TemperatureUnit.Fahrenheit)
                    result = 5.0d/9.0d*((fromValue - 273.15d) + 32d);
            }
            else if (fromUnit == TemperatureUnit.Fahrenheit)
            {
                if (toUnit == TemperatureUnit.Celsius)
                    //(F - 32) * 5/9 = C
                    result = 5.0d/9.0d*(fromValue - 32d);
                else if (toUnit == TemperatureUnit.Kelvin)
                    result = (5.0d/9.0d*(fromValue - 32d)) + 273.15;
            }
            return result;
        }
Esempio n. 2
0
 public double ConvertTemp(double Temperature, TemperatureUnit FromUnit, TemperatureUnit ToUnit) {
     object[] results = this.Invoke("ConvertTemp", new object[] {
                 Temperature,
                 FromUnit,
                 ToUnit});
     return ((double)(results[0]));
 }
Esempio n. 3
0
        public void ConvertTemperature(TemperatureUnit unitOfMeasurement)
        {
            if (TemperatureUnit == unitOfMeasurement) return;

            Temperature = UnitsNet.Temperature.From(Temperature, TemperatureUnit).As(unitOfMeasurement).Round();
            TemperatureUnit = unitOfMeasurement;
        }
Esempio n. 4
0
        public double Convert(double sourceValue, TemperatureUnit sourceUnit, TemperatureUnit targetUnit)
        {
            double targetValue = double.NaN;

            ITemperatureUnitConverter temperatureUnitConverter;
            if (_temperatureConverters.TryGetValue(sourceUnit, out temperatureUnitConverter))
            {
                try
                {
                    targetValue = temperatureUnitConverter.Convert(sourceValue, sourceUnit, targetUnit);
                }
                catch (ArgumentException ex)
                {
                    // OK the above sourceUnit-related converter could not convert to teh target unit,
                    // so try the targetUnit-related converter instead
                    if (_temperatureConverters.TryGetValue(targetUnit, out temperatureUnitConverter))
                    {
                        try
                        {
                            targetValue = temperatureUnitConverter.Convert(sourceValue, sourceUnit, targetUnit);
                        }
                        catch (ArgumentException ex2)
                        {
                            LoggerManager.WriteError(typeof(UnitConverter), ex2.Message);
                        }
                    }
                }
            }

            return targetValue;
        }
        /// <summary>
        ///  Tempature Service Consume using async
        /// </summary>
        /// <param name="searchTerm"></param>
        /// <returns></returns>
        public async Task<ViewResult> Contact(string searchTerm = null)
        {
            ViewBag.Message = "Your contact page.";

            TemperatureConversionService.ConvertTemperatureSoapClient service = new ConvertTemperatureSoapClient();

            TemperatureUnit temperature = new TemperatureUnit();
            TemperateVeiw model = new TemperateVeiw();
            double tempinput;

            if (searchTerm != null )
            {
                if (Double.TryParse(searchTerm, out tempinput))
                {
                    var todoItems =
                        await
                            service.ConvertTempAsync(tempinput, TemperatureUnit.degreeFahrenheit,
                                TemperatureUnit.degreeCelsius);

                    model.Temperature = todoItems;
                }
            }

            return View(model);
        }
        /// <summary>
        /// This first "converter" only knows about degC and therefore no actual conversion is needed.
        /// </summary>
        /// <param name="sourceValue"></param>
        /// <param name="sourceUnit"></param>
        /// <param name="targetUnit"></param>
        /// <returns></returns>
        public double Convert(double sourceValue, TemperatureUnit sourceUnit, TemperatureUnit targetUnit)
        {
            if (sourceUnit != TemperatureUnit.Celsius) throw new ArgumentException("Unexpected source unit");

            if (targetUnit != TemperatureUnit.Celsius) throw new ArgumentException("Unexpected target unit");

            return sourceValue;
        }
 public void TemperatureConversions(double value1, TemperatureUnit units1, double value2, TemperatureUnit units2)
 {
     new Temperature(value1, units1) {
         Units = units2
     }.Value.ShouldBeWithinEpsilonOf(value2);
     new Temperature(value2, units2) {
         Units = units1
     }.Value.ShouldBeWithinEpsilonOf(value1);
 }
Esempio n. 8
0
        public void ConvertsUnitsOfMeasurement(TemperatureUnit tempBefore, TemperatureUnit tempAfter, SpeedUnit windBefore, SpeedUnit windAfter)
        {
            var weatherResult = TestData.GetTestWeatherResult(tempBefore, windBefore);

            weatherResult.ConvertTemperature(tempAfter);
            weatherResult.ConvertWindSpeed(windAfter);

            weatherResult.TemperatureUnit.Should().Be(tempAfter);
            weatherResult.WindSpeedUnit.Should().Be(windAfter);
        }
Esempio n. 9
0
        public SensorInfo(
			string name,
			SpeedUnit speedUnit,
			TemperatureUnit tempUnit,
			PressureUnit pressureUnit
		)
        {
            Name = name;
            SpeedUnit = speedUnit;
            TemperatureUnit = tempUnit;
            PressureUnit = pressureUnit;
        }
Esempio n. 10
0
        public static WeatherApiResult GetTestWeatherResult(TemperatureUnit tempUnit, SpeedUnit speedUnit)
        {
            var random = new Random();

            return new WeatherApiResult
            {
                Location = "Liverpool",
                Temperature = random.Next(0, 40),
                WindSpeed = random.Next(0, 40),
                TemperatureUnit = tempUnit,
                WindSpeedUnit = speedUnit
            };
        }
        public static Uri GetRequestUri(double latitude, double longitude, TemperatureUnit temperature)
        {
            StringBuilder url = new StringBuilder();

            url.Append("http://www.7timer.com/v4/bin/astro.php");
            url.Append("?lat=" + latitude.ToString("0.000").Replace(",", "."));
            url.Append("&lon=" + longitude.ToString("0.000").Replace(",", "."));
            if (temperature == TemperatureUnit.C)
                url.Append("&unit=metric");
            else if (temperature == TemperatureUnit.F)
                url.Append("&unit=british");
            url.Append("&output=json");

            return new Uri(url.ToString());
        }
Esempio n. 12
0
        protected SensorInfo AddSensor(
			Data.DbDataStore store = null,
			string name = "Sensor",
			SpeedUnit speedUnit = SpeedUnit.MetersPerSec,
			TemperatureUnit tempUnit = TemperatureUnit.Celsius,
			PressureUnit pressUnit = PressureUnit.KiloPascals
		)
        {
            if (null == store)
                store = Store;
            Assert.IsNotNull(store, "no store");
            var sensor = new SensorInfo(name, speedUnit, tempUnit, pressUnit);
            var sensorAdded = store.AddSensor(sensor);
            Assert.IsTrue(sensorAdded, "sensor add failed");
            return sensor;
        }
Esempio n. 13
0
        private static string ToGBX(this TemperatureUnit temperatureUnit)
        {
            switch (temperatureUnit)
            {
            case TemperatureUnit.Celcius:
                return("C");

            case TemperatureUnit.Fahrenheit:
                return("F");

            case TemperatureUnit.Kelvin:
                return("K");

            case TemperatureUnit.Rankine:
                return("R");

            default:
                return("C");
            }
        }
Esempio n. 14
0
 public HndzProject(Person owner, Person designer, Person consultant,
                    Person contractor, HndzCity location, /*HndzLengthUnitSystem units,*/ ICollection <HndzBuilding> buildings,
                    HndzWCS globalCoordinateSystem, HndzSite site, LengthUnit lengthUnit, AreaUnit areaUnit,
                    TemperatureUnit temperatureUnit, MassUnit massUnit, ForceUnit forceUnit) : base(HndzResources.DefaultName, HndzResources.DefaultDescription)
 {
     Owner      = owner;
     Designer   = designer;
     Consultant = consultant;
     Contractor = contractor;
     Location   = location;
     //Units = units;
     Buildings = buildings;
     GlobalCoordinateSystem = globalCoordinateSystem;
     Site            = site;
     LengthUnit      = lengthUnit;
     AreaUnit        = areaUnit;
     TemperatureUnit = temperatureUnit;
     MassUnit        = massUnit;
     ForceUnit       = forceUnit;
 }
Esempio n. 15
0
        /// <summary>
        /// Convert the given input, reading, based on the from and to temperature unit
        /// </summary>
        /// <param name="reading"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public double ConvertToNewReading(double reading, TemperatureUnit from, TemperatureUnit to)
        {
            if (from == to)
            {
                return(reading);
            }

            if (from == TemperatureUnit.Celsius && to == TemperatureUnit.Fahrenheit)
            {
                return(FromCelsiusToFahrenheit(reading));
            }
            else if (from == TemperatureUnit.Fahrenheit && to == TemperatureUnit.Celsius)
            {
                return(FromFahrenheitToCelsius(reading));
            }
            else
            {
                return(reading);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Method to convert Weights
        /// </summary>
        /// <param name="unit">defines which unit used</param>
        /// <param name="temperature">defines which type of temperature</param>
        /// <returns>return calculated temperature</returns>
        public double ConvertTemperature(TemperatureUnit unit, double temperature)
        {
            try
            {
                if (unit.Equals(TemperatureUnit.CelsiusToFahrenheit))
                {
                    return(CelsiusToFahrenheit + (temperature * 1.8) - 1.8);
                }

                return(temperature);
            }
            catch (QuantityException e)
            {
                throw new QuantityException(QuantityException.ExceptionType.InvalidData, e.Message);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 17
0
        public static double ConvertTemperature(double temperature, TemperatureUnit from, TemperatureUnit to)
        {
            if (from == to)
            {
                return(temperature);
            }

            if (from == TemperatureUnit.Celsius && to == TemperatureUnit.Fahrenheit)
            {
                var result = temperature * 1.8 + 32;
                return(result);
            }
            if (from == TemperatureUnit.Fahrenheit && to == TemperatureUnit.Celsius)
            {
                var result = (temperature - 32) / 1.8;
                return(result);
            }

            return(temperature);
        }
Esempio n. 18
0
        public static bool IsBelowAbsoluteZero(decimal value, TemperatureUnit unit)
        {
            switch (unit)
            {
            case TemperatureUnit.F:
                return(value < -459.67M);

            case TemperatureUnit.C:
                return(value < -273.15M);

            case TemperatureUnit.K:
                return(value < 0M);

            case TemperatureUnit.R:
                return(value < 0M);

            default:
                return(false);
            }
        }
Esempio n. 19
0
        /// <summary>
        ///     Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;".
        /// </summary>
        /// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
        /// <param name="culture">Format to use when parsing number and unit. If it is null, it defaults to <see cref="NumberFormatInfo.CurrentInfo"/> for parsing the number and <see cref="CultureInfo.CurrentUICulture"/> for parsing the unit abbreviation by culture/language.</param>
        /// <example>
        ///     Length.Parse("5.5 m", new CultureInfo("en-US"));
        /// </example>
        /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
        /// <exception cref="ArgumentException">
        ///     Expected string to have one or two pairs of quantity and unit in the format
        ///     "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in"
        /// </exception>
        /// <exception cref="AmbiguousUnitParseException">
        ///     More than one unit is represented by the specified unit abbreviation.
        ///     Example: Volume.Parse("1 cup") will throw, because it can refer to any of
        ///     <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
        /// </exception>
        /// <exception cref="UnitsNetException">
        ///     If anything else goes wrong, typically due to a bug or unhandled case.
        ///     We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
        ///     Units.NET exceptions from other exceptions.
        /// </exception>
        public static Temperature Parse(string str, [CanBeNull] Culture culture)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }

#if WINDOWS_UWP
            IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture);
#else
            IFormatProvider formatProvider = culture;
#endif
            return(UnitParser.ParseUnit <Temperature>(str, formatProvider,
                                                      delegate(string value, string unit, IFormatProvider formatProvider2)
            {
                double parsedValue = double.Parse(value, formatProvider2);
                TemperatureUnit parsedUnit = ParseUnit(unit, formatProvider2);
                return From(parsedValue, parsedUnit);
            }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)));
        }
Esempio n. 20
0
        /// <summary>
        ///     Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;".
        /// </summary>
        /// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
        /// <param name="culture">Format to use when parsing number and unit. If it is null, it defaults to <see cref="NumberFormatInfo.CurrentInfo"/> for parsing the number and <see cref="CultureInfo.CurrentUICulture"/> for parsing the unit abbreviation by culture/language.</param>
        /// <example>
        ///     Length.Parse("5.5 m", new CultureInfo("en-US"));
        /// </example>
        /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
        /// <exception cref="ArgumentException">
        ///     Expected string to have one or two pairs of quantity and unit in the format
        ///     "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in"
        /// </exception>
        /// <exception cref="AmbiguousUnitParseException">
        ///     More than one unit is represented by the specified unit abbreviation.
        ///     Example: Volume.Parse("1 cup") will throw, because it can refer to any of
        ///     <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
        /// </exception>
        /// <exception cref="UnitsNetException">
        ///     If anything else goes wrong, typically due to a bug or unhandled case.
        ///     We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
        ///     Units.NET exceptions from other exceptions.
        /// </exception>
        public static Temperature Parse(string str, [CanBeNull] Culture culture)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }

            // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx
#if WINDOWS_UWP
            IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture);
#else
            IFormatProvider formatProvider = culture;
#endif
            return(QuantityParser.Parse <Temperature, TemperatureUnit>(str, formatProvider,
                                                                       delegate(string value, string unit, IFormatProvider formatProvider2)
            {
                double parsedValue = double.Parse(value, formatProvider2);
                TemperatureUnit parsedUnit = ParseUnit(unit, formatProvider2);
                return From(parsedValue, parsedUnit);
            }, (x, y) => FromKelvins(x.Kelvins + y.Kelvins)));
        }
Esempio n. 21
0
        public string ToString(TemperatureUnit unit, [CanBeNull] Culture culture, [NotNull] string format,
                               [NotNull] params object[] args)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

#if WINDOWS_UWP
            IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture);
#else
            IFormatProvider formatProvider = culture;
#endif
            double   value      = As(unit);
            object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args);
            return(string.Format(formatProvider, format, formatArgs));
        }
Esempio n. 22
0
        public string ToString(TemperatureUnit unit, [CanBeNull] Culture culture, [NotNull] string format,
                               [NotNull] params object[] args)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx
#if WINDOWS_UWP
            IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture);
#else
            IFormatProvider formatProvider = culture;
#endif
            double   value      = As(unit);
            object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args);
            return(string.Format(formatProvider, format, formatArgs));
        }
        public WeatherData GetWeatherData(string latitude, string longitude, TemperatureUnit unit)
        {
            _logger.Info($"Location coordinates: ({latitude}, {longitude})");

            var weatherData = new WeatherData
            {
                Unit = unit
            };

            WebResponse response     = GetResponse(latitude, longitude, weatherData);
            string      responseData = string.Empty;

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                responseData = sr.ReadToEnd();
                _logger.Debug($"The response from the weather server: `{responseData}`");
            }

            ParseResponse(weatherData, responseData);

            return(weatherData);
        }
Esempio n. 24
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(0);
            }

            TemperatureUnit targetUnit = (TemperatureUnit)parameter;
            float           kelvin     = (float)value;

            switch (targetUnit)
            {
            case TemperatureUnit.Celsius:
                return(kelvin - 273.15f);

            case TemperatureUnit.Fahrenheit:
                return(kelvin * 9 / 5 - 459.67f);

            default:
                return(kelvin);
            }
        }
        /// <summary>
        /// Convert from Celsius to Fahrenheit and vice-versa
        /// Celsius    to Fahrenheit:   (°C × 9/5) + 32 = °F
        /// Fahrenheit to Celsius:      (°F − 32) x 5/9 = °C
        /// </summary>
        /// <param name="sourceValue"></param>
        /// <param name="sourceUnit"></param>
        /// <param name="targetUnit"></param>
        /// <returns></returns>
        public double Convert(double sourceValue, TemperatureUnit sourceUnit, TemperatureUnit targetUnit)
        {
            double targetValue = sourceValue;

            // If this is the same unit, then return the same value
            if (targetUnit == sourceUnit) return targetValue;

            if (targetUnit == TemperatureUnit.Celsius)
            {
                if (sourceUnit == TemperatureUnit.Fahrenheit)
                {
                    // Fahrenheit to Celsius: (°F − 32) x 5/9 = °C
                    targetValue = ((sourceValue - 32.0) * 5.0) / 9.0;
                }
                else
                {
                    throw new ArgumentException("Unexpected source unit");
                }
            }
            else if (targetUnit == TemperatureUnit.Fahrenheit)
            {
                if (sourceUnit == TemperatureUnit.Celsius)
                {
                    // Celsius    to Fahrenheit:   (°C × 9/5) + 32 = °F
                    targetValue = 32.0 + ((sourceValue * 9.0) / 5.0);
                }
                else
                {
                    throw new ArgumentException("Unexpected source unit");
                }
            }
            else
            {
                throw new ArgumentException("Unexpected source/target unit");
            }

            return targetValue;
        }
        public static string GetTemperatureUnitString(TemperatureUnit unit)
        {
            var unitString = string.Empty;
            var degSymbol  = (char)176;

            switch (unit)
            {
            case TemperatureUnit.Imperial:
                unitString = $"{degSymbol}F";
                break;

            case TemperatureUnit.Metric:
                unitString = $"{degSymbol}C";
                break;

            case TemperatureUnit.Default:
            default:
                unitString = "K";
                break;
            }

            return(unitString);
        }
Esempio n. 27
0
        public static double Convert(double Value, TemperatureUnit FromUnit, TemperatureUnit ToUnit)
        {
            if (FromUnit == ToUnit || double.IsNaN(Value))
            {
                return(Value);
            }
            double result;

            switch (FromUnit)
            {
            case TemperatureUnit.degC:
                result = Value * 1.8 + 32.0;
                break;

            case TemperatureUnit.degF:
                result = (Value - 32.0) / 1.8;
                break;

            default:
                throw new InvalidOperationException("Convert: Illegal Temperature Unit");
            }
            return(result);
        }
Esempio n. 28
0
        public static WeatherApiResult AverageWeatherResults(this IEnumerable<WeatherApiResult> weatherResults, TemperatureUnit temperatureMeasurement, SpeedUnit windSpeedMeasurement)
        {
            if (weatherResults == null) throw new ArgumentNullException("weatherResults");

            var weatherApiResults = weatherResults.ToList();

            if (weatherApiResults.Count == 0)
                return null;

            foreach (var weatherApiResult in weatherApiResults)
            {
                weatherApiResult.ConvertTemperature(temperatureMeasurement);
                weatherApiResult.ConvertWindSpeed(windSpeedMeasurement);
            }

            return new WeatherApiResult
            {
                Location = weatherApiResults.First().Location,
                TemperatureUnit = temperatureMeasurement,
                WindSpeedUnit = windSpeedMeasurement,
                WindSpeed = weatherApiResults.Average(o => o.WindSpeed),
                Temperature = weatherApiResults.Average(o => o.Temperature)
            };
        }
Esempio n. 29
0
 private void value_panel_Tapped(object sender, TappedRoutedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(value.Text) && value.Text != "N/A")
     {
         if (currentTempUnit == TemperatureUnit.Celcius)
         {
             currentTempUnit = TemperatureUnit.Fahrenheit;
             value.Text      = ConvertTemperature(Double.Parse(value.Text), TemperatureUnit.Celcius, TemperatureUnit.Fahrenheit).ToString("0.00");
             unit.Text       = "°F";
         }
         else if (currentTempUnit == TemperatureUnit.Fahrenheit)
         {
             currentTempUnit = TemperatureUnit.Kelvin;
             value.Text      = ConvertTemperature(Double.Parse(value.Text), TemperatureUnit.Fahrenheit, TemperatureUnit.Kelvin).ToString("0.00");
             unit.Text       = "K";
         }
         else if (currentTempUnit == TemperatureUnit.Kelvin)
         {
             currentTempUnit = TemperatureUnit.Celcius;
             value.Text      = ConvertTemperature(Double.Parse(value.Text), TemperatureUnit.Kelvin, TemperatureUnit.Celcius).ToString("0.00");
             unit.Text       = "°C";
         }
     }
 }
Esempio n. 30
0
        public Temperature(float value, TemperatureUnit unit)
        {
            Unit  = unit;
            Value = value;

            if (float.IsNaN(value) || float.IsInfinity(value))
            {
                throw new ArgumentOutOfRangeException(nameof(value), value, "Non finite value provided.");
            }

#if CHECK_ON_INITIALIZATION_IF_TEMPERATURE_IS_NOT_BELOW_ABSOLUTE_ZERO
            const string exceptionMessage = "Temperature value can't be below absolute zero.";

            switch (unit)
            {
            case TemperatureUnit.Kelvin:
                if (value < 0f)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), value, exceptionMessage);
                }

                break;

            case TemperatureUnit.Celsius:
                if (value < AbsoluteZero.Value)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), value, exceptionMessage);
                }

                break;

            default:
                throw new NotImplementedException();
            }
#endif
        }
Esempio n. 31
0
        /// <summary>
        ///     Dynamically convert from value and unit enum <see cref="TemperatureUnit" /> to <see cref="Temperature" />.
        /// </summary>
        /// <param name="value">Value to convert from.</param>
        /// <param name="fromUnit">Unit to convert from.</param>
        /// <returns>Temperature unit value.</returns>
        public static Temperature?From(double?value, TemperatureUnit fromUnit)
        {
            if (!value.HasValue)
            {
                return(null);
            }
            switch (fromUnit)
            {
            case TemperatureUnit.DegreeCelsius:
                return(FromDegreesCelsius(value.Value));

            case TemperatureUnit.DegreeDelisle:
                return(FromDegreesDelisle(value.Value));

            case TemperatureUnit.DegreeFahrenheit:
                return(FromDegreesFahrenheit(value.Value));

            case TemperatureUnit.DegreeNewton:
                return(FromDegreesNewton(value.Value));

            case TemperatureUnit.DegreeRankine:
                return(FromDegreesRankine(value.Value));

            case TemperatureUnit.DegreeReaumur:
                return(FromDegreesReaumur(value.Value));

            case TemperatureUnit.DegreeRoemer:
                return(FromDegreesRoemer(value.Value));

            case TemperatureUnit.Kelvin:
                return(FromKelvins(value.Value));

            default:
                throw new NotImplementedException("fromUnit: " + fromUnit);
            }
        }
Esempio n. 32
0
 Temperature(double numericValue, TemperatureUnit unit)
 {
     _value = numericValue;
     _unit  = unit;
 }
Esempio n. 33
0
        public void ConvertsAllUnitsOfMeasurement(TemperatureUnit tempBefore, TemperatureUnit tempAfter, SpeedUnit speedBefore, SpeedUnit speedAfter)
        {
            WeatherApiResult resultA = TestData.GetTestWeatherResult(tempBefore, speedBefore);
            WeatherApiResult resultB = TestData.GetTestWeatherResult(tempBefore, speedBefore);
            WeatherApiResult resultc = TestData.GetTestWeatherResult(TemperatureUnit.DegreeCelsius, SpeedUnit.MilePerHour);
            WeatherApiResult resultd = TestData.GetTestWeatherResult(TemperatureUnit.DegreeFahrenheit, SpeedUnit.KilometerPerHour);

            var weatherResults = new List<WeatherApiResult>() { resultA, resultB, resultc, resultd };
            var averaged = weatherResults.AverageWeatherResults(tempAfter, speedAfter);

            weatherResults.TrueForAll(o => o.TemperatureUnit == tempAfter && o.WindSpeedUnit == speedAfter);
        }
        public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] IFormatProvider provider)
        {
            provider = provider ?? UnitSystem.DefaultCulture;

            return(UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit));
        }
Esempio n. 35
0
 public TemperatureRange(TemperatureUnit temperatureUnit, int min, int max) {
     this.min = new Temperature(min, temperatureUnit);
     this.max = new Temperature(max, temperatureUnit);
 }
Esempio n. 36
0
        /// <summary>
        ///     Multiply temperature with a <paramref name="factor" /> in a given <paramref name="unit" />.
        /// </summary>
        /// <remarks>
        ///     Due to different temperature units having different zero points, we cannot simply
        ///     multiply or divide a temperature by a factor. We must first convert to the desired unit, then perform the
        ///     calculation.
        /// </remarks>
        /// <param name="factor">Factor to multiply by.</param>
        /// <param name="unit">Unit to perform multiplication in.</param>
        /// <returns>The resulting <see cref="Temperature" />.</returns>
        public Temperature Multiply(double factor, TemperatureUnit unit)
        {
            double resultInUnit = As(unit) * factor;

            return(From(resultInUnit, unit));
        }
Esempio n. 37
0
 public string ToString(TemperatureUnit unit, CultureInfo culture = null, int significantDigitsAfterRadix = 2)
 {
     return(ToString(unit, culture, UnitFormatter.GetFormat(As(unit), significantDigitsAfterRadix)));
 }
Esempio n. 38
0
 public int GetTemperature(TemperatureUnit unit) {
     return ConvertTemperature(value, this.unit, unit);
 }
Esempio n. 39
0
 public static string GetAbbreviation(TemperatureUnit unit)
 {
     return(GetAbbreviation(unit, null));
 }
Esempio n. 40
0
		private static double ConvertTemperatureValue(TemperatureUnit unit, double temperatureInCelcius)
		{
			switch (unit)
			{
				case TemperatureUnit.Celcius:
					return temperatureInCelcius;

				case TemperatureUnit.Fahrenheit:
					return temperatureInCelcius * 9 / 5 + 32;

				case TemperatureUnit.Kelvin:
					return temperatureInCelcius + 273.15;

				default:
					throw new ArgumentOutOfRangeException();
			}
		}
Esempio n. 41
0
		private static string GetUnitText(TemperatureUnit unit)
		{
			switch (unit)
			{
				case TemperatureUnit.Celcius:
					return "\u00B0C"; // Where "\u00B0" is the degree-symbol.

				case TemperatureUnit.Fahrenheit:
					return "\u00B0F"; // Where "\u00B0" is the degree-symbol.

				case TemperatureUnit.Kelvin:
					return "K";

				default:
					throw new ArgumentOutOfRangeException();
			}
		}
Esempio n. 42
0
 public WeatherInfo(DateTime date, TemperatureUnit unit, int temperatureLow, int temperatureHi, Cloudiness cloudiness,
     Rain rain, bool snow, bool fog, bool hail) {
     if(temperatureHi < temperatureLow)
         throw new ArgumentException("temperatureHi < temperatureLow");
     this.date = date;
     this.temperatureLow = new Temperature(temperatureLow, unit);
     this.temperatureHi = new Temperature(temperatureHi, unit);
     this.cloudiness = cloudiness;
     this.rain = rain;
     this.snow = snow;
     this.fog = fog;
     this.hail = hail;
 }
Esempio n. 43
0
 public Temperature(int value, TemperatureUnit unit) {
     this.value = value;
     this.unit = unit;
 }
            public Temperature ConvertTo(TemperatureUnit anotherUnit)
            {
                if(this.Unit == anotherUnit)
                {
                    return this;
                }

                if(this.Unit == TemperatureUnit.Celsius && anotherUnit == TemperatureUnit.Kelvin)
                {
                    return new Temperature(TemperatureConversions.CelsiusToKelvin.Convert(this.Value), anotherUnit);
                }

                if(this.Unit == TemperatureUnit.Celsius && anotherUnit == TemperatureUnit.Fahrenheit)
                {
                    return new Temperature(TemperatureConversions.CelsiusToFahrenheit.Convert(this.Value), anotherUnit);
                }

                if(this.Unit == TemperatureUnit.Kelvin && anotherUnit == TemperatureUnit.Celsius)
                {
                    return new Temperature(TemperatureConversions.CelsiusToKelvin.ConvertBack(this.Value), anotherUnit);
                }

                if (this.Unit == TemperatureUnit.Fahrenheit && anotherUnit == TemperatureUnit.Celsius)
                {
                    return new Temperature(TemperatureConversions.CelsiusToFahrenheit.ConvertBack(this.Value), anotherUnit);
                }

                throw new TemperatureConversionNotSupportedException(
                    String.Format("Cannot convert from {0} to {1}", this.Unit, anotherUnit));
            }
Esempio n. 45
0
 public string GetLabel(TemperatureUnit unit) {
     return "&deg;" + (unit == TemperatureUnit.Celsius ? "C" : "F");
 }
Esempio n. 46
0
 public static Temperature From(double value, TemperatureUnit fromUnit)
Esempio n. 47
0
        public static Temperature From(QuantityValue value, TemperatureUnit fromUnit)
#endif
        {
            return(new Temperature((double)value, fromUnit));
        }
Esempio n. 48
0
 public string ToString(TemperatureUnit temperatureUnit) {
     return GetTemperature(temperatureUnit).ToString() + GetLabel(temperatureUnit);
 }
Esempio n. 49
0
        public static string GetAbbreviation(
            TemperatureUnit unit,
#if WINDOWS_UWP
            [CanBeNull] string cultureName)
		public async Task<double> ConvertAsync(double temp, TemperatureUnit from, TemperatureUnit to)
		{
			var result = await client.ConvertTempAsync(temp, from, to);

			return result;
		}
Esempio n. 51
0
 public static string GetAbbreviation(TemperatureUnit unit, CultureInfo culture = null)
 {
     return(UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit));
 }
Esempio n. 52
0
 public WeatherInfoControl(WeatherInfo info, TemperatureUnit temperatureUnit) {
     this.info = info;
     this.temperatureUnit = temperatureUnit;
 }
Esempio n. 53
0
 public string ToString(TemperatureUnit unit, CultureInfo culture, string format, params object[] args)
 {
     return(string.Format(culture, format, UnitFormatter.GetFormatArgs(unit, As(unit), culture, args)));
 }
            public Temperature ConvertTo(TemperatureUnit anotherUnit)
            {
                if (this.Unit == anotherUnit)
                {
                    return this;
                }

                LinearConversion conversion =
                    conversions.SingleOrDefault(p => p.Key.Key == this.Unit && p.Key.Value == anotherUnit).Value;

                if (conversion == null)
                {
                    throw new TemperatureConversionNotSupportedException(
                        String.Format("Cannot convert from {0} to {1}", this.Unit, anotherUnit));
                }

                return new Temperature(conversion.Convert(this.Value), anotherUnit);
            }
Esempio n. 55
0
        /// <summary>
        ///     Divide temperature by a <paramref name="divisor" /> in a given <paramref name="unit" />.
        /// </summary>
        /// <remarks>
        ///     Due to different temperature units having different zero points, we cannot simply
        ///     multiply or divide a temperature by a factor. We must first convert to the desired unit, then perform the
        ///     calculation.
        /// </remarks>
        /// <param name="divisor">Factor to multiply by.</param>
        /// <param name="unit">Unit to perform multiplication in.</param>
        /// <returns>The resulting <see cref="Temperature" />.</returns>
        public Temperature Divide(double divisor, TemperatureUnit unit)
        {
            double resultInUnit = As(unit) / divisor;

            return(From(resultInUnit, unit));
        }
 public Temperature(double value, TemperatureUnit unit)
 {
     this.Value = value;
     this.Unit = unit;
 }
 /// <summary>
 ///     Dynamically convert from value and unit enum <see cref="TemperatureUnit" /> to <see cref="Temperature" />.
 /// </summary>
 /// <param name="value">Value to convert from.</param>
 /// <param name="fromUnit">Unit to convert from.</param>
 /// <returns>Temperature unit value.</returns>
 public static Temperature?From(QuantityValue?value, TemperatureUnit fromUnit)
 {
     return(value.HasValue ? new Temperature((double)value.Value, fromUnit) : default(Temperature?));
 }
Esempio n. 58
0
 public UnitManager(PersistentSettings settings)
 {
     this.settings = settings;
       this.temperatureUnit = (TemperatureUnit)settings.GetValue("TemperatureUnit",
     (int)TemperatureUnit.Celsius);
 }
 /// <summary>
 ///     Get string representation of value and unit. Using two significant digits after radix.
 /// </summary>
 /// <param name="unit">Unit representation to use.</param>
 /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param>
 /// <returns>String representation.</returns>
 public string ToString(TemperatureUnit unit, [CanBeNull] IFormatProvider provider)
 {
     return(ToString(unit, provider, 2));
 }
Esempio n. 60
0
 private static int ConvertTemperature(int value, TemperatureUnit inputUnit, TemperatureUnit outputUnit) {
     if(inputUnit == outputUnit)
         return value;
     else
         return (int)Math.Round(inputUnit == TemperatureUnit.Fahrenheit ? (5.0 * (value - 32) / 9.0) : (1.8 * value + 32));
 }