Beispiel #1
0
        private static int ReadDayCodeLine(string line)
        {
            CheckNullLine(line, "day code");
            LoggedException.RaiseIf(line[0] != '-' || line.Length != 6, nameof(PASReader), "Invalid day code format");

            return(int.Parse(line.Substring(1, 5)));
        }
Beispiel #2
0
        private ConstructorInfo AddCtor(Type t)
        {
            Log.Verbose(nameof(ReflectionCache), $"Adding constructor for type '{t.Name}' to cache");
            ConstructorInfo result = t.GetConstructor(ctorTypes);

            LoggedException.RaiseIf(result == null, $"Cannot find serializable constructor for type: '{t.Name}'");
            ctors = ctors.Concat(result);
            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// Removes an item at the specified index.
        /// </summary>
        /// <param name="index"> The specified index. </param>
        /// <exception cref="LoggedException"> The index was out of range. </exception>
        public void RemoveAt(int index)
        {
            LoggedException.RaiseIf(index >= Count, nameof(ThreadSafeList <T>), "index out of range");
            EnterWriteLock();

            ShiftLeft(index);
            --size;

            ExitWriteLock();
        }
Beispiel #4
0
        /// <summary>
        /// Inserts an item at the specified index.
        /// </summary>
        /// <param name="index"> The position of the new item. </param>
        /// <param name="item"> The item to be added. </param>
        /// <exception cref="LoggedException"> The index was out of range. </exception>
        public void Insert(int index, T item)
        {
            LoggedException.RaiseIf(index >= Count, nameof(ThreadSafeList <T>), "index out of range");
            EnterWriteLock();

            ShiftRight(index);
            data[index] = item;
            ++size;

            ExitWriteLock();
        }
Beispiel #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StopableThread"/> class.
 /// </summary>
 /// <param name="init"> The function to call when initialzing the run loop (can be <see langword="null"/>). </param>
 /// <param name="term"> The function to call when terminating the run loop (can be <see langword="null"/>). </param>
 /// <param name="tick"> The function that handles the thread tick, cannot be <see langword="null"/>. </param>
 /// <param name="name"> The name of the thread. </param>
 public StopableThread(ThreadStart init, ThreadStart term, ThreadStart tick, string name = null)
 {
     LoggedException.RaiseIf(tick == null, nameof(StopableThread), "Unable to create thread!", new ArgumentNullException("tick", "tick cannot be null!"));
     TickCooldown = 10;
     this.init    = init;
     this.term    = term;
     this.tick    = tick;
     Name         = name;
     nameSet      = !string.IsNullOrEmpty(name);
     thread       = ThreadBuilder.CreateSTA(Run, name);
 }
Beispiel #6
0
        private static RouteStop ReadStopStartLine(string line)
        {
            CheckNullLine(line, "route start line");
            LoggedException.RaiseIf(line[0] != '>' || line[8] != ',' || line.Length != 13, nameof(PASReader), "Invalid route start format");

            RouteStop result = new RouteStop {
                Id = line.Substring(1, 6)
            };

            result.SetLeaveFromString(line.Substring(9, 4));
            return(result);
        }
Beispiel #7
0
        private static BigRouteStop ReadBigStopLine(string line)
        {
            CheckNullLine(line, "big route line");
            LoggedException.RaiseIf(line[0] != '+' || line[8] != ',' || line.Length != 18, nameof(PASReader), "Invalid big route format");

            BigRouteStop result = new BigRouteStop {
                Id = line.Substring(1, 6)
            };

            result.SetLeaveFromString(line.Substring(9, 4));
            result.SetArriveFromString(line.Substring(14, 4));
            return(result);
        }
Beispiel #8
0
        private static void CheckValidity(string line)
        {
            CheckNullLine(line, "validity");
            LoggedException.RaiseIf(line[0] != '&' || line[9] != '-' || line.Length != 18, nameof(PASReader), "Invalid validity format");

            DateTime start = DateTime.ParseExact(line.Substring(1, 8), "ddMMyyyy", CultureInfo.InvariantCulture);
            DateTime end   = DateTime.ParseExact(line.Substring(10, 8), "ddMMyyyy", CultureInfo.InvariantCulture);

            if (start > DateTime.Now)
            {
                Log.Warning(nameof(PASReader), $"Validty is not yet active ({start})");
            }
            if (end < DateTime.Now)
            {
                Log.Warning(nameof(PASReader), $"Validity is no longer active ({end})");
            }
        }
Beispiel #9
0
        private static RETRoute ReadRouteLine(string line)
        {
            CheckNullLine(line, "route");
            LoggedException.RaiseIf(line[0] != '#' || line[2] != ',' || line[9] != ',' ||
                                    line[13] != ',' || line[15] != ',' || line.Length != 21, nameof(PASReader), "Invalid route line format");

            RETRoute result = new RETRoute
            {
                CompanyId = int.Parse(line.Substring(3, 5)),
                LineNum   = int.Parse(line.Substring(10, 2)),
                Direction = (Direction)Convert.ToInt32(line[14]),
                RouteNum  = int.Parse(line.Substring(16, 4))
            };

            result.SetTypeFromChar(line[1]);

            return(result);
        }
Beispiel #10
0
        /// <summary>
        /// Reads specified types from a specified file.
        /// </summary>
        /// <typeparam name="T"> The type attempt to serialize to. </typeparam>
        /// <param name="fileName"> A absolute or relative path to the file. </param>
        /// <param name="ctor"> A function to user as the types constructor. </param>
        /// <returns> A list of serialized objects. </returns>
        private static List <T> ReadTypeFromFile <T>(string fileName)
            where T : ISerializable, new()
        {
            fileName = $"{Settings.Default.DataDirectory}{fileName}";                   // Get the full path to the file.
            List <T> result = new List <T>();

            curLine = 0;

            LoggedException.RaiseIf(!(fileName.EndsWith(".csv") || fileName.EndsWith(".HLT")), nameof(CSVReader),      // Raise an exception if the files isn't a .csv file.
                                    $"Cannot open file with extension {Path.GetExtension(fileName)}, supply .csv file");

            try
            {
                using (StreamReader sr = new StreamReader(fileName))                    // Open a read stream to the file.
                {
                    Log.Verbose(nameof(CSVReader), $"Started parsing file: '{Path.GetFileName(fileName)}'");
                    char[] splitChars = fileName.EndsWith(".csv") ? new char[] { ';' } : new char[] { ',' };

                    string line;
                    while ((line = sr.ReadLine()) != null)                              // Read all lines.
                    {
                        ++curLine;                                                      // Increment the current line.

                        T cur;
                        if (DeserializeType(line, splitChars, out cur))
                        {
                            result.Add(cur);                                                        // Deserialzie a type from the current line.
                        }
                    }

                    Log.Info(nameof(CSVReader), $"File contains {result.Count} readable entries");
                }
            }
            catch (Exception e)
            {
                Log.Fatal(nameof(CSVReader), new FileLoadException($"An unhandled exception was raised during the processing of file: '{Path.GetFullPath(fileName)}'", e));
            }

            Log.Verbose(nameof(CSVReader), $"Finished parsing file: '{Path.GetFileName(fileName)}'");
            return(result);
        }
Beispiel #11
0
        /// <summary>
        /// Gets or sets a value at the specified index.
        /// </summary>
        /// <param name="index"> The secified index. </param>
        /// <returns> The value at the specified index. </returns>
        /// <exception cref="LoggedException"> The index was out of range. </exception>
        public T this[int index]
        {
            get
            {
                LoggedException.RaiseIf(index >= Count, nameof(ThreadSafeList <T>), "index out of range");

                EnterReadLock();
                T result = data[index];
                ExitReadLock();

                return(result);
            }
            set
            {
                LoggedException.RaiseIf(index >= Count, nameof(ThreadSafeList <T>), "index out of range");

                EnterWriteLock();
                data[index] = value;
                ExitWriteLock();
            }
        }
Beispiel #12
0
 internal static void AddLogger(IDisposable sender)
 {
     LoggedException.RaiseIf(loggerActive, nameof(ConsoleLogger), "A logger is already active!");
     loggerActive   = true;
     loggerDispose += sender.Dispose;
 }
Beispiel #13
0
 /// <summary>
 /// Attemps to enter a write lock.
 /// </summary>
 /// <exception cref="LoggedException"> Method timed out. </exception>
 protected void EnterWriteLock()
 {
     LoggedException.RaiseIf(!locker.TryEnterWriteLock(LockTimeout), nameof(LockableObject), "Unable to enter write lock");
     writeActive = true;
 }
Beispiel #14
0
 /// <summary>
 /// Attempts to enter a read lock.
 /// </summary>
 /// <exception cref="LoggedException"> Method timed out. </exception>
 protected void EnterReadLock()
 {
     LoggedException.RaiseIf(!locker.TryEnterReadLock(LockTimeout), nameof(LockableObject), "Unable to enter read lock");
     readActive = true;
 }
Beispiel #15
0
 private static void CheckOverflow(string func, int check, int max)
 {
     LoggedException.RaiseIf(check <1 || check> max, nameof(BitWriter), $"{func} can only write between 1 and {max} bits");
 }
Beispiel #16
0
 private static void CheckFormat(string line)
 {
     CheckNullLine(line, "format");
     LoggedException.RaiseIf(line != "!RETPAS1", nameof(PASReader), "Unknown PAS format");
 }
Beispiel #17
0
        public static List <RETRoute> ReadRoutesFromFile(string fileName)
        {
            fileName = $"{Settings.Default.DataDirectory}{fileName}";
            List <RETRoute> result = new List <RETRoute>();

            curLine = 0;

            LoggedException.RaiseIf(!fileName.EndsWith(".PAS"), nameof(PASReader),
                                    $"Cannot open file with extension {Path.GetExtension(fileName)}, supply .pas file");

            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    Log.Verbose(nameof(CSVReader), $"Started parsing file: '{Path.GetFileName(fileName)}'");
                    RETRoute cur = null;

                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        ++curLine;

                        try
                        {
                            switch (line[0])
                            {
                            case ('!'):
                                CheckFormat(line);
                                break;

                            case ('&'):
                                CheckValidity(line);
                                break;

                            case ('#'):
                                cur = ReadRouteLine(line);
                                break;

                            case ('-'):
                                Log.Debug(nameof(PASReader), "Skipped day code line (Useless)");
                                ReadDayCodeLine(line);
                                break;

                            case ('>'):
                                if (cur == null)
                                {
                                    Log.Error(nameof(PASReader), $"Floating stop at line: {curLine} (Ignored)");
                                }
                                else if (cur.Stops.Count > 0)
                                {
                                    Log.Error(nameof(PASReader), $"Second start stop at line: {curLine} (Ignored)");
                                }
                                else
                                {
                                    cur.Stops.Add(ReadStopStartLine(line));
                                }
                                break;

                            case ('.'):
                                if (cur == null)
                                {
                                    Log.Error(nameof(PASReader), $"Floating stop at line: {curLine} (Ignored)");
                                }
                                else if (cur.Stops.Count < 1)
                                {
                                    Log.Error(nameof(PASReader), $"Intermediate stop with no start at line: {curLine} (Ignored)");
                                }
                                else
                                {
                                    cur.Stops.Add(ReadStopLine(line));
                                }
                                break;

                            case ('+'):
                                if (cur == null)
                                {
                                    Log.Error(nameof(PASReader), $"Floating big stop at line: {curLine} (Ignored)");
                                }
                                else if (cur.Stops.Count < 1)
                                {
                                    Log.Error(nameof(PASReader), $"Big stop with no start at line: {curLine} (Ignored)");
                                }
                                else
                                {
                                    cur.Stops.Add(ReadBigStopLine(line));
                                }
                                break;

                            case ('<'):
                                if (cur == null)
                                {
                                    Log.Error(nameof(PASReader), $"Floating stop at line: {curLine} (Ignored)");
                                }
                                else if (cur.Stops.Count < 1)
                                {
                                    Log.Error(nameof(PASReader), $"End stop with no start at line: {curLine} (Ignored)");
                                }
                                else
                                {
                                    cur.Stops.Add(ReadStopEndLine(line));
                                }

                                result.Add(cur);
                                cur = null;
                                break;

                            default:
                                Log.Warning(nameof(PASReader), $"Unknown line type at line: {curLine}");
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            LoggedException.Raise(nameof(PASReader), $"An unhandled excpetion was raised at line: {curLine}", e);
                        }
                    }

                    Log.Info(nameof(CSVReader), $"File contains {result.Count} readable entries");
                }
            }
            catch (Exception e)
            {
                Log.Fatal(nameof(CSVReader), new FileLoadException($"An unhandled exception was raised during the processing of file: '{Path.GetFullPath(fileName)}'", e));
            }

            Log.Verbose(nameof(CSVReader), $"Finished parsing file: '{Path.GetFileName(fileName)}'");
            return(result);
        }
Beispiel #18
0
 private void CheckDisposed()
 {
     LoggedException.RaiseIf(Disposed, nameof(ArrayEnumerator), "Cannot excecute method!", new ObjectDisposedException("ArrayEnumerator"));
 }
Beispiel #19
0
 private static void CheckNullLine(string line, string type)
 {
     LoggedException.RaiseIf(string.IsNullOrEmpty(line), nameof(PASReader), $"Unable to read {type} line", new NullReferenceException());
 }