Exemplo n.º 1
0
 /// <summary>
 /// Метод, которое сплитит строку и возвращает результат выражения.
 /// </summary>
 /// <param name="expr"> Строка с ппримером. </param>
 /// <returns></returns>
 public double Calculate(string expr)
 {
     try
     {
         string[] problem = expr.Split(' ');
         double   a       = double.Parse(problem[0].ToString());
         double   b       = double.Parse(problem[2].ToString());
         if (double.IsNaN(Math.Round(operations[problem[1]](a, b), 3)))
         {
             throw new Exception("Результат не является числом.");
         }
         else if (problem[1] == "/" && b == 0)
         {
             throw new Exception("Деление на 0.");
         }
         else if (!operations.ContainsKey(problem[1]))
         {
             throw new Exception("Некорректно введенная операция.");
         }
         return(operations[problem[1]](a, b));
     }
     catch (Exception ex)
     {
         // Вызов события. Можно вызвать без точки, но так безопаснее.
         ErrorNotification?.Invoke(ex.Message);
         throw ex;
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Method to add exercises to user tracker
        /// </summary>
        /// <param name="user">User to which you want to add exercise</param>
        /// <param name="exercise">Exercise you want to add</param>
        /// <param name="exerciseStart">Date when you have done exercise</param>
        /// <param name="exerciseEnd">Date when you have finished exercise</param>
        /// <param name="units">Specific unit of exercise (distance\times etc.)</param>
        public void AddNewExercise(User user, Exercises exercise, DateTime exerciseStart, DateTime exerciseEnd, double units)
        {
            var statisticService = new StatisticService();

            statisticService.StatusNotification += NotificationManager.SendStatusNotification;
            statisticService.ErrorNotification  += NotificationManager.SendErrorNotification;

            switch (exercise)
            {
            case Exercises.PushUps:
                var newPushUps = new PushUpSeries
                {
                    Name             = $"PushUps #{user.PushUps.Count + 1}",
                    ExerciseStart    = exerciseStart,
                    ExerciseEnd      = exerciseEnd,
                    ExerciseTimeSpan = exerciseEnd - exerciseStart,
                    Count            = (int)units,
                };
                user.PushUps.Add(newPushUps);
                StatusNotification?.Invoke($"Push Ups #{user.PushUps.Count} for user {user.Name} successfully added!");
                user.AvaragePushUps = statisticService.GetAverageStatistic(user, exercise);
                break;

            case Exercises.Run:
                var newRun = new Run
                {
                    Name             = $"Run #{user.Runs.Count + 1}",
                    ExerciseStart    = exerciseStart,
                    ExerciseEnd      = exerciseEnd,
                    ExerciseTimeSpan = exerciseEnd - exerciseStart,
                    Distance         = units,
                };
                user.Runs.Add(newRun);
                StatusNotification?.Invoke($"Run #{user.Runs.Count} for user {user.Name} successfully added!");
                user.AvarageRunDistance = statisticService.GetAverageStatistic(user, exercise);
                break;

            case Exercises.Squats:
                var newSquats = new SquatSeries
                {
                    Name             = $"Squats #{user.Squats.Count + 1}",
                    ExerciseStart    = exerciseStart,
                    ExerciseEnd      = exerciseEnd,
                    ExerciseTimeSpan = exerciseEnd - exerciseStart,
                    Count            = (int)units,
                };
                user.Squats.Add(newSquats);
                StatusNotification?.Invoke($"Squats #{user.Squats.Count} for user {user.Name} successfully added!");
                user.AvarageSquats = statisticService.GetAverageStatistic(user, exercise);
                break;

            default:
                ErrorNotification?.Invoke("No such Exercise!");
                break;
            }
            user.AvarageExercisePulse = statisticService.GetPulsePerMinute(user, exercise);
        }
        private void HandleRead()
        {
            int readSize = Handle.UserSocket.Available;

            readData = new byte[readSize];
            try
            {
                int recvSize = Handle.Receive(readData, 0, readSize, SocketFlags.None);
            }
            catch (SocketException se)
            {
                log.Error(se, "Socket Exception Error.");
                ErrorNotification?.Invoke(this, se);
                this.Dispose();
            }
            ReadComplete();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Method to get avarage statistic about User in exercises
        /// </summary>
        /// <param name="user">User whose avarage statistic you whant to get</param>
        /// <returns></returns>
        public double GetAverageStatistic(User user, Exercises exercise)
        {
            switch (exercise)
            {
            case Exercises.PushUps:
                return(user.PushUps.Average(a => a.Count));

            case Exercises.Run:
                return(user.Runs.Average(a => a.Distance));

            case Exercises.Squats:
                return(user.Squats.Average(a => a.Count));

            default:
                ErrorNotification?.Invoke("No such exercise!");
                return(-1);
            }
        }
 private void HandleWrite()
 {
     if (writeData != null)
     {
         int writeSize = writeData.Length;
         try
         {
             int sentSize = Handle.Send(writeData, 0, writeData.Length, SocketFlags.None);
         }
         catch (SocketException se)
         {
             log.Error(se, "Socket Exception Error.");
             ErrorNotification?.Invoke(this, se);
             this.Dispose();
         }
         WriteComplete();
     }
 }
        private void OnTimerEvent(object sender, ElapsedEventArgs args)
        {
            if (writeData == null)
            {
                writeData = new byte[0];
                log.Info("SockServiceHandler - Keep Alive message queued");
            }
            Timer tempTimer = sender as Timer;

            lastReceivedTime += tempTimer.Interval;
            if (lastReceivedTime > (2 * tempTimer.Interval))
            {
                var errorString = String.Format("Keep Alive packet not received within {0} ms. Connection closed as invalid.", lastReceivedTime);
                log.Error(errorString);
                ErrorNotification?.Invoke(this, new OutOfTimeException(errorString));
                this.Dispose();
            }
        }
 private void HandleRead()
 {
     try
     {
         using (MemoryStream ms = new MemoryStream())
         {
             // 1 byte buffer
             // TODO: consider making this variable depending on encoding (currently will only work for UTF8)
             // ALSO: consider situation of CRLF from unix systems
             byte[] tempBuffer = new byte[1];
             tempBuffer[0] = 0x00;
             while (tempBuffer[0] != END_OF_LINE)
             {
                 int recvBytes = Handle.Receive(tempBuffer, 0, 1, SocketFlags.None);
                 if (recvBytes == 0)
                 {
                     CloseEventNotification?.Invoke(this);
                     this.Dispose();
                     return;
                 }
                 ms.Write(tempBuffer, 0, 1);
             }
             readData = ms.ToArray();
             ReadComplete();
         }
     }
     catch (SocketException se)
     {
         if (se.ErrorCode == 10054)
         {
             // socket connection forcibly closed by remote peer
             log.Error("Socket Exception Error 10054, socket connection was forcibly closed by the remote peer.");
             ErrorNotification?.Invoke(this, se);
             this.Dispose();
         }
         else
         {
             log.Error(se, "Socket Exception Error");
             ErrorNotification?.Invoke(this, se);
             this.Dispose();
         }
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Сравнение значений с референсными из файла.
        /// </summary>
        /// <param name="path1"></param>
        /// <param name="path2"></param>
        /// <param name="path3"></param>
        public static void Check(string path1, string path2, string path3)
        {
            string[] check   = new string[0];
            string[] answers = new string[0];
            string   output  = string.Empty;

            // Счетчик ошибок.
            int errors = 0;

            // Стандартное чтение.
            try
            {
                check   = File.ReadAllLines(path1);
                answers = File.ReadAllLines(path2);
            }
            catch (UnauthorizedAccessException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (System.Security.SecurityException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (IOException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (Exception e)
            {
                ErrorNotification?.Invoke(e.Message);
            }

            // Сравнение длин массивов.
            if (check.Length == answers.Length)
            {
                // Сравнение значений через жеппу (там какие-то проблемы с парсом "не числа").
                for (int i = 0; i < check.Length; i++)
                {
                    if (answers[i].Contains("число"))
                    {
                        if (check[i].Contains("число"))
                        {
                            output += "OK" + Environment.NewLine;
                        }
                        else
                        {
                            output += "Error" + Environment.NewLine;
                            errors++;
                        }
                    }
                    else
                    {
                        double res;
                        double chk;
                        if (double.TryParse(answers[i], out res) & double.TryParse(check[i], out chk))
                        {
                            if (res == chk)
                            {
                                output += "OK" + Environment.NewLine;
                            }
                            else
                            {
                                output += "Error" + Environment.NewLine;
                                errors++;
                            }
                        }
                        else
                        {
                            if (answers[i] == check[i])
                            {
                                output += "OK" + Environment.NewLine;
                            }
                            else
                            {
                                output += "Error" + Environment.NewLine;
                                errors++;
                            }
                        }
                    }
                }
                // Добавление в конец вывода количества ошибок.
                output += errors;

                try
                {
                    File.WriteAllText(path3, output);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Console.WriteLine($"Sizes do not match: answers size is {answers.Length}, check size is {check.Length}");
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Чтение выражений из файла, счет и запись результатов в другой файл.
        /// </summary>
        /// <param name="path1"></param>
        /// <param name="path2"></param>
        public static void ReadAndWrite(string path1, string path2)
        {
            string[] lines  = new string[0];
            string   output = string.Empty;

            // Стандартная дичь.
            try
            {
                lines = File.ReadAllLines(path1);
            }
            catch (UnauthorizedAccessException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (System.Security.SecurityException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (IOException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (Exception e)
            {
                ErrorNotification?.Invoke(e.Message);
            }

            // Подсчет значений в строках.
            for (int i = 0; i < lines.Length; i++)
            {
                try
                {
                    output += $"{Calculate(lines[i]):F3}{Environment.NewLine}";
                }
                catch (Exception e)
                {
                    ErrorNotification(e.Message);
                }
            }

            // Стандартная запись в файл.
            try
            {
                File.WriteAllText(path2, output);
            }
            catch (UnauthorizedAccessException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (System.Security.SecurityException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (IOException e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
            catch (Exception e)
            {
                ErrorNotification?.Invoke(e.Message);
            }
        }
Exemplo n.º 10
0
 public void ErrorMessageTriger(string message)
 {
     ErrorNotification?.Invoke(message);
 }
        private void HandleRead()
        {
            try
            {
                if (!recvHeader)
                {
                    byte[] headerData       = new byte[HEADER_SIZE];
                    int    headerSize       = headerData.Length;
                    int    headerLeftToRecv = headerSize;
                    int    headerSizeRecv   = 0;

                    while (headerSizeRecv != headerSize)
                    {
                        int recv = Handle.Receive(headerData, headerSizeRecv, headerLeftToRecv, SocketFlags.None);

                        // 0 value for recv means socket has closed from other end
                        if (recv != 0)
                        {
                            headerSizeRecv   += recv;
                            headerLeftToRecv -= recv;
                            lastReceivedTime  = 0;
                        }
                        else
                        {
                            CloseEventNotification?.Invoke(this);
                            this.Dispose();
                            return;
                        }
                    }

                    int headerDataValue = BitConverter.ToInt32(headerData, 0);

                    if (headerDataValue == 0)
                    {
                        // if received a keep alive packet, ignore and exit
                        log.Info("SockServiceHandler keep alive packet received.");
                        return;
                    }
                    else
                    {
                        readData   = new byte[headerDataValue];
                        recvSize   = headerDataValue;
                        leftToRecv = recvSize;
                        dataRecv   = 0;
                        recvHeader = true;
                    }
                }
                else
                {
                    int recv = Handle.Receive(readData, dataRecv, leftToRecv, SocketFlags.None);
                    if (recv == 0)
                    {
                        CloseEventNotification?.Invoke(this);
                        this.Dispose();
                        return;
                    }
                    dataRecv   += recv;
                    leftToRecv -= recv;

                    if (dataRecv == recvSize)
                    {
                        ReadComplete();
                    }
                }
            }
            catch (SocketException se)
            {
                if (se.ErrorCode == 10054)
                {
                    // socket connection forcibly closed by remote peer
                    log.Error("Socket Exception Error 10054, socket connection was forcibly closed by the remote peer.");
                    ErrorNotification?.Invoke(this, se);
                    this.Dispose();
                }
                else
                {
                    log.Error(se, "Socket Exception Error");
                    ErrorNotification?.Invoke(this, se);
                    this.Dispose();
                }
            }
        }
        private void HandleWrite()
        {
            if (writeData != null)
            {
                if (!sentHeader)
                {
                    try
                    {
                        byte[] header           = BitConverter.GetBytes(writeData.Length);
                        int    headerSize       = header.Length;
                        int    headerSizeSent   = 0;
                        int    headerLeftToSend = headerSize;

                        while (headerSizeSent != headerSize)
                        {
                            int sent = Handle.Send(header, headerSizeSent, headerLeftToSend, System.Net.Sockets.SocketFlags.None);
                            headerSizeSent   += sent;
                            headerLeftToSend -= sent;
                        }

                        ResetKeepAliveTimer();

                        if (writeData.Length > 0)
                        {
                            sendSize   = writeData.Length;
                            leftToSend = sendSize;
                            dataSent   = 0;
                            sentHeader = true;
                        }
                        else
                        {
                            // if writeDataLength is 0 it is a keep alive message so reset
                            writeData = null;
                        }
                    }
                    catch (SocketException se)
                    {
                        // deal with remote disconnection event. Raise a close event notification
                        log.Error(se, "Socket Exception Error");
                        ErrorNotification?.Invoke(this, se);
                        this.Dispose();
                    }
                }
                else
                {
                    try
                    {
                        int sent = Handle.Send(writeData, dataSent, leftToSend, SocketFlags.None);
                        dataSent   += sent;
                        leftToSend -= sent;
                        ResetKeepAliveTimer();

                        if (dataSent == sendSize)
                        {
                            WriteComplete();
                        }
                    }
                    catch (SocketException se)
                    {
                        // deal with remote disconnection event. Raise a close event notification
                        log.Error(se, "Socket Exception Error");
                        ErrorNotification?.Invoke(this, se);
                        this.Dispose();
                    }
                }
            }
        }