Example #1
0
        // column by name
        public Boolean ReadY <T>(String filename, ref T[] dataY, ref String fileheader, String colYname)
        {
            filename = ValidFileOpen(filename);
            if (filename == null)
            {
                return(false);
            }

            try
            {
                TryParseMethod <T> TTryParse = FindTryParse <T>();
                ParseMethod <T>    TParse    = FindParse <T>();

                String[] strData = File.ReadAllLines(filename);
                Int32    firstData; Int32 lastData;

                fileheader = ReadHeaderAndFooter(strData, 1, out firstData, out lastData);
                String[] tmpStr = fileheader.Split(saDelimeters, StringSplitOptions.RemoveEmptyEntries);
                Int32    colY   = Array.IndexOf <String>(tmpStr, colYname) + 1;
                if (colY == 0)
                {
                    throw new ArgumentException("Column " + colYname + " not found");
                }
                dataY = ReadDataOne <T>(ref strData, colY, TParse, firstData, lastData);
            }

            catch (Exception e)
            {
                MessageBox.Show("Error in " + this.ToString() + ":\n" + e.Message + "\nIn file: " + filename,
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
Example #2
0
        // column by number
        public Boolean ReadZ <T>(String filename, ref T[,] dataZ, ref String fileheader)
        {
            filename = ValidFileOpen(filename);
            if (filename == null)
            {
                return(false);
            }

            try
            {
                TryParseMethod <T> TTryParse = FindTryParse <T>();
                ParseMethod <T>    TParse    = FindParse <T>();

                String[] strData = File.ReadAllLines(filename);
                Int32    firstData; Int32 lastData;

                fileheader = ReadHeaderAndFooter(strData, 1, out firstData, out lastData);
                dataZ      = ReadDataAll <T>(ref strData, TParse, firstData, lastData);
            }

            catch (Exception e)
            {
                MessageBox.Show("Error in " + this.ToString() + ":\n" + e.Message + "\nIn file: " + filename,
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
Example #3
0
        // columns by name
        public Boolean ReadXY <T>(String filename, ref T[] dataX, ref T[] dataY, ref String fileheader, String colXname, String colYname)
        {
            filename = ValidFileOpen(filename);
            if (filename == null)
            {
                return(false);
            }

            try
            {
                TryParseMethod <T> TTryParse = FindTryParse <T>();
                ParseMethod <T>    TParse    = FindParse <T>();

                String[] strData = File.ReadAllLines(filename);
                Int32    firstData; Int32 lastData;

                fileheader = ReadHeaderAndFooter(strData, 2, out firstData, out lastData);
                String[] tmpStr = fileheader.Split(saDelimeters, StringSplitOptions.RemoveEmptyEntries);
                Int32    colX   = Array.IndexOf <String>(tmpStr, colXname) + 1;
                if (colX == 0)
                {
                    throw new ArgumentException("Column \"" + colXname + "\" not found");
                }
                Int32 colY = Array.IndexOf <String>(tmpStr, colYname) + 1;
                if (colY == 0)
                {
                    throw new ArgumentException("Column \"" + colYname + "\" not found");
                }

                T[,] dataXY = ReadDataMany <T>(ref strData, new Int32[] { colX, colY }, TParse, firstData, lastData);

                dataX = new T[dataXY.GetLength(0)];
                dataY = new T[dataXY.GetLength(0)];
                for (Int32 i = 0; i < dataXY.GetLength(0); i++)
                {
                    dataX[i] = dataXY[i, 0];
                }
                for (Int32 i = 0; i < dataXY.GetLength(0); i++)
                {
                    dataY[i] = dataXY[i, 1];
                }
            }

            catch (Exception e)
            {
                MessageBox.Show("Error in " + this.ToString() + ":\n" + e.Message + "\nIn file: " + filename,
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
Example #4
0
 static ParserMethod Create <T>(TryParseMethod <T> tryParse) where T : IFormattable
 {
     return((value, numberStyle, inCulture, outCulture) =>
     {
         if (tryParse(value, numberStyle, inCulture, out T result))
         {
             return result;
         }
         else
         {
             return "";
         }
     });
 }
Example #5
0
        private static T?ParseValueType <T>(XElement element, string attributeName, TryParseMethod <T> tryParseMethod)
            where T : struct
        {
            var attribute = element.Attribute(attributeName);

            if (attribute == null)
            {
                return(null);
            }

            if (tryParseMethod(attribute.Value, out var parseResult))
            {
                return(parseResult);
            }

            throw new FormatException($"{GetLineInfo(element)}Error parsing '{attribute.Name}' value '{attribute.Value}'.");
        }
Example #6
0
        /// <summary>
        /// Converts the supplied string to the Type specified using the supplied parseMethod
        /// </summary>
        /// <param name="toParse">
        /// The string to convert into a byte
        /// </param>
        /// <param name="tryParseMethod">
        /// The method that will be used to parse the string value
        /// </param>
        /// <typeparam name="T">
        /// The type that the string will be parsed into
        /// </typeparam>
        /// <returns>
        /// If conversion succeeded then the return value is a nullable object
        /// wrapping the T value.  If conversion failed then the return value
        /// is null
        /// </returns>
        public static T?ToAny <T>(string toParse, TryParseMethod <T> tryParseMethod) where T : struct
        {
            #region Input validation

            Insist.IsNotNull(tryParseMethod, "tryParseMethod");

            #endregion

            T val = default(T);
            if (tryParseMethod(toParse, out val))
            {
                return(new Nullable <T>(val));
            }
            else
            {
                return(new Nullable <T>());
            }
        }
Example #7
0
        /// <summary>
        /// Tries to get the value of the specified object as the specified type.
        /// </summary>
        /// <typeparam name="T">A T that is the type that the object will be cast as.</typeparam>
        /// <param name="Value">An object that is the object to be cast.</param>
        /// <param name="value">A T that is the cast object, or the default value of T.</param>
        /// <returns>A bool indicating success.</returns>
        public static bool GetObjectAsValue <T>(object Value, out T value)
        {
            bool returnValue = false;

            // Defaults
            value = default;

            if (Value != null)
            {
                if (Value is T)
                {
                    value       = (T)Value;
                    returnValue = true;
                }
                else if (typeof(T).IsEnum)
                {
                    value       = (T)Enum.Parse(typeof(T), Value.ToString());
                    returnValue = true;
                }
                else
                {
                    MethodInfo TryParseMethod;

                    TryParseMethod = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });
                    if (TryParseMethod != null)
                    {
                        object   result;
                        object[] tryParseParams;

                        tryParseParams = new object[] { Value.ToString(), null };
                        result         = TryParseMethod.Invoke(null, tryParseParams);
                        if (result != null && result is bool && (bool)result)
                        {
                            value       = (T)tryParseParams[1];
                            returnValue = true;
                        }
                    }
                }
            }

            return(returnValue);
        }
Example #8
0
        // columns by number
        public Boolean ReadXY <T>(String filename, ref T[] dataX, ref T[] dataY, ref String fileheader, Int32 colX, Int32 colY)
        {
            filename = ValidFileOpen(filename);
            if (filename == null)
            {
                return(false);
            }

            try
            {
                TryParseMethod <T> TTryParse = FindTryParse <T>();
                ParseMethod <T>    TParse    = FindParse <T>();

                String[] strData = File.ReadAllLines(filename);
                Int32    firstData; Int32 lastData;

                fileheader = ReadHeaderAndFooter(strData, colY, out firstData, out lastData);

                T[,] dataXY = ReadDataMany <T>(ref strData, new Int32[] { colX, colY }, TParse, firstData, lastData);

                dataX = new T[dataXY.GetLength(0)];
                dataY = new T[dataXY.GetLength(0)];
                for (Int32 i = 0; i < dataXY.GetLength(0); i++)
                {
                    dataX[i] = dataXY[i, 0];
                }
                for (Int32 i = 0; i < dataXY.GetLength(0); i++)
                {
                    dataY[i] = dataXY[i, 1];
                }
            }

            catch (Exception e)
            {
                MessageBox.Show("Error in " + this.ToString() + ":\n" + e.Message + "\nIn file: " + filename,
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
Example #9
0
 public TryParser(TryParseMethod <T> parsingMethod)
 {
     _parsingMethod = parsingMethod;
 }
Example #10
0
        /// <summary>
        /// Validates a value for range constraints
        /// </summary>
        /// <typeparam name="T">Type of object to be validated (int, double,...etc)</typeparam>
        /// <param name="e">e.Cancel should be set to true if validation fails</param>
        /// <param name="method">Delegate to try parsing the Text property</param>
        private void ValidateValueRange <T>(CancelEventArgs e, TryParseMethod <T> tryParseMethod) where T : struct, IComparable, IConvertible
        {
            bool parseError = false;
            T    val;

            if (tryParseMethod.Invoke(Text, out val))
            {
                T minimumValue, maximumValue;

                // Minimum
                if (!string.IsNullOrEmpty(MinimumValue))
                {
                    if (tryParseMethod.Invoke(MinimumValue, out minimumValue))
                    {
                        if (MinimumValueIncluded)
                        {
                            e.Cancel = val.CompareTo(minimumValue) < 0;
                        }
                        else
                        {
                            e.Cancel = val.CompareTo(minimumValue) < 0 || val.CompareTo(minimumValue) == 0;
                        }
                        if (e.Cancel)
                        {
                            ErrorProvider.SetError(this, ActualBelowMinimumErrorMessage);
                            return;
                        }
                    }
                    else
                    {
                        parseError = true;
                    }
                }

                // Maximum
                if (!string.IsNullOrEmpty(MaximumValue))
                {
                    if (tryParseMethod.Invoke(MaximumValue, out maximumValue))
                    {
                        if (MaximumValueIncluded)
                        {
                            e.Cancel = val.CompareTo(maximumValue) > 0;
                        }
                        else
                        {
                            e.Cancel = val.CompareTo(maximumValue) > 0 || val.CompareTo(maximumValue) == 0;
                        }
                        if (e.Cancel)
                        {
                            ErrorProvider.SetError(this, ActualAboveMaximumErrorMessage);
                            return;
                        }
                    }
                    else
                    {
                        parseError = true;
                    }
                }
            }
            else
            {
                parseError = true;
            }

            if (parseError)
            {
                e.Cancel = true;
                ErrorProvider.SetError(this, Messages.InvalidInput);
            }
        }
Example #11
0
        // columns by name
        public Boolean ReadXY <T>(String[] filenames, ref T[] dataX, ref T[] dataY, ref String fileheader, String colXname, String colYname)
        {
            if (filenames == null || (filenames.Length == 0))
            {
                filenames = ValidManyFiles(null);
            }
            else if (filenames.Length == 1)
            {
                filenames = ValidManyFiles(filenames[0]);
            }

            if (filenames == null || (filenames.Length == 0))
            {
                return(false);
            }

            ProgressForm sa_pf = new ProgressForm(filenames);

            if (saShowProgress)
            {
                sa_pf.Show();
                sa_pf.Count = 0;
            }
            T[][,] tmpData;
            String[] strData;

            Int32 i = 0;

            try
            {
                TryParseMethod <T> TTryParse = FindTryParse <T>();
                ParseMethod <T>    TParse    = FindParse <T>();

                Int32 firstData; Int32 lastData;

                strData = File.ReadAllLines(filenames[0]);
                tmpData = new T[filenames.Length][, ];

                fileheader = ReadHeaderAndFooter(strData, 1, out firstData, out lastData);
                String[] tmpStr = fileheader.Split(saDelimeters, StringSplitOptions.RemoveEmptyEntries);
                Int32    colX   = Array.IndexOf <String>(tmpStr, colXname) + 1;
                if (colX == 0)
                {
                    throw new ArgumentException("Column \"" + colXname + "\" not found");
                }
                Int32 colY = Array.IndexOf <String>(tmpStr, colYname) + 1;
                if (colY == 0)
                {
                    throw new ArgumentException("Column \"" + colYname + "\" not found");
                }

                tmpData[0] = ReadDataMany <T>(ref strData, new Int32[] { colX, colY }, TParse, firstData, lastData);

                Int32[] recordlengths = new Int32[filenames.Length];
                recordlengths[0] = lastData - firstData + 1;
                Int32 totallength = lastData - firstData + 1;

                for (i = 1; i < filenames.Length; i++)
                {
                    sa_pf.Count = i;
                    strData     = File.ReadAllLines(filenames[i]);
                    ReadHeaderAndFooter(strData, colY, out firstData, out lastData);
                    tmpData[i]       = ReadDataMany <T>(ref strData, new Int32[] { colX, colY }, TParse, firstData, lastData);
                    recordlengths[i] = lastData - firstData + 1;
                    totallength     += lastData - firstData + 1;
                }

                dataX = new T[totallength];
                dataY = new T[totallength];
                Int32 j = 0;

                for (i = 0; i < filenames.Length; i++)
                {
                    for (Int32 k = 0; k < tmpData[i].GetLength(0); k++)
                    {
                        dataX[k + j] = tmpData[i][k, 0];
                    }
                    for (Int32 k = 0; k < tmpData[i].GetLength(0); k++)
                    {
                        dataY[k + j] = tmpData[i][k, 1];
                    }
                    j += recordlengths[i];
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in " + this.ToString() + ":\n" + e.Message + "\nIn file: " + filenames[i],
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            finally
            {
                if (saShowProgress)
                {
                    sa_pf.Close();
                }
                sa_pf.Dispose();
            }
            return(true);
        }
Example #12
0
        // column by number
        public Boolean ReadY <T>(String[] filenames, ref T[] dataY, ref String fileheader, Int32 colY)
        {
            if (filenames == null || (filenames.Length == 0))
            {
                filenames = ValidManyFiles(null);
            }
            else if (filenames.Length == 1)
            {
                filenames = ValidManyFiles(filenames[0]);
            }

            if (filenames == null || (filenames.Length == 0))
            {
                return(false);
            }

            ProgressForm sa_pf = new ProgressForm(filenames);

            if (saShowProgress)
            {
                sa_pf.Show();
                sa_pf.Count = 0;
            }
            T[][]    tmpData;
            String[] strData;

            Int32 i = 0;

            try
            {
                TryParseMethod <T> TTryParse = FindTryParse <T>();
                ParseMethod <T>    TParse    = FindParse <T>();

                Int32 firstData; Int32 lastData;

                strData = File.ReadAllLines(filenames[0]);
                tmpData = new T[filenames.Length][];

                fileheader = ReadHeaderAndFooter(strData, colY, out firstData, out lastData);
                tmpData[0] = ReadDataOne <T>(ref strData, colY, TParse, firstData, lastData);

                Int32[] recordlengths = new Int32[filenames.Length];
                recordlengths[0] = lastData - firstData + 1;
                Int32 totallength = lastData - firstData + 1;

                for (i = 1; i < filenames.Length; i++)
                {
                    sa_pf.Count = i;
                    strData     = File.ReadAllLines(filenames[i]);
                    ReadHeaderAndFooter(strData, colY, out firstData, out lastData);
                    tmpData[i]       = ReadDataOne <T>(ref strData, colY, TParse, firstData, lastData);
                    recordlengths[i] = lastData - firstData + 1;
                    totallength     += lastData - firstData + 1;
                }

                dataY = new T[totallength];
                Int32 j = 0;
                for (i = 0; i < filenames.Length; i++)
                {
                    Array.Copy(tmpData[i], 0, dataY, j, recordlengths[i]);
                    j += recordlengths[i];
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in " + this.ToString() + ":\n" + e.Message + "\nIn file: " + filenames[i],
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            finally
            {
                if (saShowProgress)
                {
                    sa_pf.Close();
                }
                sa_pf.Dispose();
            }
            return(true);
        }
Example #13
0
        private static string RewriteUnsigned <TFrom, TTo>(int line, string file, string new_body, TryParseMethod <TFrom> try_parse, Converter <TFrom, TTo> converter)
            where TFrom : struct
            where TTo : struct
        {
            // see https://msdn.microsoft.com/en-us/library/aa664674%28v=vs.71%29.aspx for C# details
            // see http://en.cppreference.com/w/cpp/language/integer_literal for C++ details
            // C++ writer: please note that C# DOES NOT have octal, nor binary, integer literals.

            new_body = Regex.Replace(new_body, @"\b(0X)?([0-9a-f]+)([UL]+)\b", // find all integers. \b is a word boundary
                                     (m) =>
            {
                string prefix = m.Groups[1].Value; // 0x || 0X
                string number = m.Groups[2].Value; // 1234...
                string suffix = m.Groups[3].Value; // u || U

                if (number.StartsWith("0") && number.Length > 1 && !string.IsNullOrEmpty(number.Replace("0", "")))
                {
                    const string no_octals = "No octal or binary integer literals in CSharp";
                    Program.VsSendConsoleMessage(true, file, line, 3, no_octals);
                    return("\n\n#error " + no_octals + "\n\n");
                }

                NumberStyles style = string.IsNullOrEmpty(prefix) ?
                                     NumberStyles.None : NumberStyles.AllowHexSpecifier;

                TFrom parsed;
                if (try_parse(number, style, null, out parsed))
                {
                    //if (parsed <= int.MaxValue && string.IsNullOrEmpty(prefix) && string.IsNullOrEmpty(suffix))
                    //  return m.Value; // do not edit values that are already fine

                    TTo as_int           = converter(parsed);
                    string as_int_string = as_int.ToString();
                    string comment       = string.Empty;
                    if (!string.IsNullOrEmpty(prefix) || number != as_int_string)
                    {
                        comment = " /" + "* C++: " + m.Value + "*" + "/";
                    }

                    return(as_int_string + comment);
                }
                else
                {
                    return(m.Value); //cannot parse. bail out
                }
            }
                                     , RegexOptions.Multiline | RegexOptions.IgnoreCase);
            return(new_body);
        }
Example #14
0
 public static void AddParser <T>(TryParseMethod <T> parseMethod)
 {
     Parsers.Add(typeof(T), new TryParser <T>(parseMethod));
 }
Example #15
0
 public ConvertToFromString(TryParseMethod <TYPE> tryParse, Converter <TYPE, String> toString)
 {
     this.TryParse = tryParse;
     this.ToString = toString;
 }
Example #16
0
 /// <summary>
 /// Adds a converter for the type TYPE that can transform the TYPE to and from a string
 /// </summary>
 /// <typeparam name="TYPE">The type that can be transformed by the delegates</typeparam>
 /// <param name="tryParse">A delegate method to convert from a string</param>
 /// <param name="toString">A delegate method to convert to a string</param>
 public void Add <TYPE>(TryParseMethod <TYPE> tryParse, Converter <TYPE, String> toString)
 {
     _converters[typeof(TYPE)] = new ConvertToFromString <TYPE>(Check.NotNull(tryParse), Check.NotNull(toString));
 }