예제 #1
0
 /// <summary> Protected parameterless constructor engineering unit base constructor </summary>
 protected NotifyUnit()
 {
     _systemValue = 0;
     _userValue = 0;
     _systemUnitType = AutoUnitsConfig.GetSystemUnit(this);
     _userUnitType = AutoUnitsConfig.GetUserUnit(this);
     Converter = AutoUnitsConfig.GetConversions(this);
 }
예제 #2
0
 /// <summary> Protected engineering unit base constructor </summary>
 /// <param name="systemValue">Initial system value</param>
 /// <param name="systemUnitType">Initial system unit type</param>
 /// <param name="converter">Converter</param>
 protected NotifyUnit(double systemValue, string systemUnitType, ConversionBase converter)
 {
     _systemValue = systemValue;
     _systemUnitType = systemUnitType;
     _userValue = systemValue;
     _userUnitType = systemUnitType;
     Converter = converter;
 }
예제 #3
0
 /// <summary>
 /// Attempts to transform a string containing binary, octal, decimal, hexadecimal or base64 values into a byte array.
 /// </summary>
 /// <param name="source">The string to transform.</param>
 /// <param name="conversionBase">The numeric base the string values represents.</param>
 /// <param name="convertedByteArray">A byte array containing the byte values in the <paramref name="source"/> string.</param>
 /// <param name="exception">The <see cref="Exception"/> generated if this function returns <b>false</b>.</param>
 /// <returns>Whether the conversion was successful or not. <b>True</b> indicates successful conversion, <b>false</b> indicates a failure and the <paramref name="exception"/> will contain the error generated.</returns>
 public static bool TryConvertStringToByteArray(string source,
                                                ConversionBase conversionBase,
                                                out byte[] convertedByteArray,
                                                out Exception exception)
 {
     try
     {
         convertedByteArray = ConvertStringToByteArray(source, conversionBase);
         exception          = null;
         return(true);
     }
     catch (Exception ex)
     {
         convertedByteArray = new byte[0];
         exception          = ex;
         return(false);
     }
 }
예제 #4
0
        // ----------------
        /// <summary>
        /// Will transform a byte array into a string containing either binary, octal, decimal, hexadecimal or base64 values.
        /// </summary>
        /// <param name="source">The byte array to transform.</param>
        /// <param name="conversionBase">The numeric base to convert the byte array values into.</param>
        /// <param name="byteInterstitialSpacing">The string which will be inserted between each byte value.</param>
        /// <returns>A string containing either binary, octal, decimal, hexadecimal or base64 values of the bytes in the <paramref name="source"/> byte array.</returns>
        /// <remarks>
        /// For example:
        /// <code>
        /// Source Value (byte[]) = 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0F
        ///
        /// Returned Value (binary) = "00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001011 00001100 00001101 00001110 00001111"
        /// Returned Value (octal) = "000 001 002 003 004 005 006 007 010 011 012 013 014 015 016 017"
        /// Returned Value (decimal) = "000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015"
        /// Returned Value (hexadecimal) = "00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"
        /// Returned Value (base64) = "AAECAwQFBgcICQoLDA0ODw=="
        /// </code>
        /// </remarks>
        public static string ConvertByteArrayToString(byte[] source,
                                                      ConversionBase conversionBase,
                                                      string byteInterstitialSpacing = null)
        {
            // convert Base64
            if (conversionBase == ConversionBase.Base64)
            {
                return(Convert.ToBase64String(source));
            }
            else
            {
                // fix the interstitial characters
                if (byteInterstitialSpacing == null)
                {
                    byteInterstitialSpacing = "";
                }
                // get the string width of each byte representation
                var width = 2;
                switch (conversionBase)
                {
                case ConversionBase.Binary:
                    width = 8;
                    break;

                case ConversionBase.Octal:
                    width = 3;
                    break;

                case ConversionBase.Decimal:
                    width = 3;
                    break;

                case ConversionBase.Hexadecimal:
                    width = 2;
                    break;

                default:
                    break;
                }
                // convert each byte into the desired base value, padded with leading zeros to the proper string width and separate each one with the interstitial characters
                return(string.Join(byteInterstitialSpacing,
                                   source.Select(x => Convert.ToString(x, (int)conversionBase).ToUpper().PadLeft(width, '0'))));
            }
        }
예제 #5
0
 /// <summary>
 /// Attempts to transform a byte array into a string containing either binary, octal, decimal, hexadecimal or base64 values.
 /// </summary>
 /// <param name="source">The byte array to transform.</param>
 /// <param name="conversionBase">The numeric base to convert the byte array values into.</param>
 /// <param name="convertedString">The string containing the byte values in the <paramref name="source"/> byte array.</param>
 /// <param name="exception">The <see cref="Exception"/> generated if this function returns <b>false</b>.</param>
 /// <param name="byteInterstitialSpacing">The string which will be inserted between each byte value.</param>
 /// <returns>Whether the conversion was successful or not. <b>True</b> indicates successful conversion, <b>false</b> indicates a failure and the <paramref name="exception"/> will contain the error generated.</returns>
 public static bool TryConvertByteArrayToString(byte[] source,
                                                ConversionBase conversionBase,
                                                out string convertedString,
                                                out Exception exception,
                                                string byteInterstitialSpacing = null)
 {
     try
     {
         convertedString = ConvertByteArrayToString(source, conversionBase, byteInterstitialSpacing);
         exception       = null;
         return(true);
     }
     catch (Exception ex)
     {
         convertedString = "";
         exception       = ex;
         return(false);
     }
 }
예제 #6
0
        // GET api/values/5
        public decimal?GetConvertedRate(decimal amount, string fromCurrency, string toCurrency)
        {
            WebClient web = new WebClient();

            //below link was working before but somehow later it was blocked.
            //However it does work from within browser.
            //string url = string.Format("https://www.google.com/finance/converter?a={0}&from={1}&to={2}", amount, fromCurrency.ToUpper(), toCurrency.ToUpper());

            //now using below only available free(without any conditions of use) api on internet.
            string url = string.Format("https://api.fixer.io/latest?base={0}", fromCurrency.ToUpper());

            try
            {
                string response          = web.DownloadString(url);
                JavaScriptSerializer oJS = new JavaScriptSerializer();
                ConversionBase       objConversionBase = new ConversionBase();

                //first deserializing the response by using dynamic type
                var dict = oJS.Deserialize <dynamic>(response);

                //getting the same into a strong typed object
                objConversionBase.Base  = dict["base"];
                objConversionBase.Date  = Convert.ToDateTime(dict["date"]);
                objConversionBase.Rates = new Dictionary <string, decimal>();
                foreach (var item in dict["rates"])
                {
                    objConversionBase.Rates.Add(item.Key, item.Value);  //item.Key, item.Value);
                }

                //getting the target rate from the list of converstion rates for the base(fromCurrency) currency.
                KeyValuePair <string, decimal> currentTargetRate =
                    objConversionBase.Rates.Where(kv => kv.Key == toCurrency.ToUpper()).FirstOrDefault();

                decimal?rate = amount * currentTargetRate.Value;
                return(rate);
            }
            catch (Exception)
            {
                return(null);
            }
            //final conversion
        }
 protected override void CopySourceDataToDestination(ConversionBase <Database> .ConversionHandler conversionHandler)
 {
     throw new NotImplementedException();
 }
 protected override void ConvertSourceDatabaseToDestination(ConversionBase <Database> .ConversionHandler conversionHandler, ConversionBase <Database> .TableSelectionHandler tableSelectionHandler, ConversionBase <Database> .FailedViewDefinitionHandler failedViewDefinitionHandler, bool createTriggers)
 {
     throw new NotImplementedException();
 }
예제 #9
0
        /// <summary>
        /// Will transform a string containing binary, octal, decimal, hexadecimal or base64 values into a byte array.
        /// </summary>
        /// <param name="source">The string to transform.</param>
        /// <param name="conversionBase">The numeric base the string values represents.</param>
        /// <returns>A byte array containing the byte values in the string.</returns>
        /// <remarks>
        /// This method assumes that the string provided is made up of sets of numeric representations of either binary, octal, decimal, hexadecimal or base64 values.
        /// <para/><para/>
        /// For example:
        /// <code>
        /// Source Value (binary) = "00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001011 00001100 00001101 00001110 00001111"
        /// Source Value (octal) = "000 001 002 003 004 005 006 007 010 011 012 013 014 015 016 017"
        /// Source Value (decimal) = "000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015"
        /// Source Value (hexadecimal) = "00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"
        /// Source Value (base64) = "AAECAwQFBgcICQoLDA0ODw=="
        ///
        /// Returned Value (byte[]) = 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0F
        /// </code>
        /// </remarks>
        public static byte[] ConvertStringToByteArray(string source,
                                                      ConversionBase conversionBase)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                // return empty byte array if source is null or empty
                return(new byte[0]);
            }
            // convert Base64
            if (conversionBase == ConversionBase.Base64)
            {
                return(Convert.FromBase64String(source));
            }
            else
            {
                // get the string width of each byte representation and get a set of valid characters
                var width           = 2;
                var validCharacters = "";
                switch (conversionBase)
                {
                case ConversionBase.Binary:
                    width           = 8;
                    validCharacters = "01";
                    break;

                case ConversionBase.Octal:
                    width           = 3;
                    validCharacters = "01234567";
                    break;

                case ConversionBase.Decimal:
                    width           = 3;
                    validCharacters = "0123456789";
                    break;

                case ConversionBase.Hexadecimal:
                    width           = 2;
                    validCharacters = "0123456789abcdefABCDEF";
                    break;

                default:
                    break;
                }
                // remove all non-valid characters
                var sourceHold = new StringBuilder(source.Length);
                for (int i = 0; i < source.Length; i++)
                {
                    if (validCharacters.Contains(source[i]))
                    {
                        sourceHold.Append(source[i]);
                    }
                }
                var source2 = sourceHold.ToString();
                // check
                if (!string.IsNullOrWhiteSpace(source2))
                {
                    if ((source2.Length % width) == 0)
                    {
                        // process string: convert to byte array
                        return(Enumerable.Range(0, int.MaxValue / width)                        // iterate the maximum length of a string divided by (width) (because there are (width) characters for each byte segment)
                               .Select(i => i * width)                                          // get the starting index for each the char segment (step by (width) characters each time)
                               .TakeWhile(i => i < source2.Length)                              // only work the length of the source string
                               .Select(i => source2.Substring(i, width))                        // get the binary string segments (take the next (width) characters)
                               .Select(s => Convert.ToByte(s, (int)conversionBase))             // convert to byte (convert the (width) characters into a byte)
                               .ToArray());                                                     // put it all into a byte array (put the byte into an array) }
                    }
                    else
                    {
                        throw new InvalidOperationException($"Input string length is invalid. Length={source.Length:N0}. Must be divisible by {width}. (not counting invalid characters, which are ignored)");
                    }
                }
                else
                {
                    throw new InvalidOperationException($"Input string is invalid. Must contain fixed-sized blocks of the following characters: \"{validCharacters}\"; Character Block Size={width}");
                }
            }
        }