Esempio n. 1
0
        /// <summary>
        /// Flush the data and check file size for rolling.
        /// </summary>
        private void FlushCheck()
        {
            lock (_lockerFlush)
            {
                // This is to flush the writer periodically after every N number of times.
                if (_iterativeFlushCount % _iterativeFlushPeriod == 0)
                {
                    _writer.Flush();
                    _iterativeFlushCount = 1;
                }
                else
                {
                    _iterativeFlushCount++;
                }

                // This rolls the log file. e.g. Creates a new log file if the current one
                // exceeds a logfile size.
                if (_rollFile && FileHelper.GetSizeInMegs(_filepath) > _maxFileSizeInMegs)
                {
                    Try.Catch(() =>
                    {
                        string searchPath = _filepath.Substring(0, _filepath.LastIndexOf('.'));
                        FileInfo file     = new FileInfo(_filepath);
                        string[] files    = Directory.GetFiles(file.DirectoryName, searchPath + "*", SearchOption.TopDirectoryOnly);

                        _filepathUnique = string.Format("{0}-part{1}{2}", searchPath, files.Length.ToString(), file.Extension);
                        _writer.Flush();
                        _writer.Close();
                        _writer = new StreamWriter(_filepathUnique);
                    });
                }
            }
        }
Esempio n. 2
0
 public static void Stop()
 {
     Try.Catch(() => { httpServer?.Stop(); });
     //Try.Catch(() => { webSocketServer?.Stop(); });
     Try.Catch(Logger.StopLoggingThreads);
     Try.Catch(() => { db?.Dispose(); });
 }
Esempio n. 3
0
 protected override void Dispose(bool disposing)
 {
     Try.Swallow(() => { pipe?.WaitForPipeDrain(); });
     Try.Catch(() => { pipe?.Dispose(); });
     Try.Catch(() => { pipeServer?.Dispose(); });
     isDisposed = true;
 }
Esempio n. 4
0
 public static void Stop()
 {
     isStopped = true;
     //Try.Catch(() => { httpServer?.Stop(); });
     Try.Catch(() => { webSocketServer?.Stop(); });
     Try.Catch(Logger.StopLoggingThreads);
     Try.Catch(() => { hostConnect?.Disconnect(); });
 }
Esempio n. 5
0
        private static ITry <int, PersonParsingError> ParseAge(string age)
        {
            var numericAge    = Try.Catch <int, Exception>(_ => Convert.ToInt32(age));
            var validAge      = numericAge.MapError(_ => PersonParsingError.AgeNotANumber);
            var positiveAge   = validAge.Where(a => a >= 0, _ => PersonParsingError.AgeNegative);
            var reasonableAge = positiveAge.Where(a => a < 140, _ => PersonParsingError.AgeTooHigh);

            return(reasonableAge);
        }
Esempio n. 6
0
        private static ITry <decimal, PersonParsingError> ParseHeight(string height)
        {
            var numericHeight    = Try.Catch <decimal, Exception>(_ => Convert.ToDecimal(height));
            var validHeight      = numericHeight.MapError(_ => PersonParsingError.HeightNotANumber);
            var positiveHeight   = validHeight.Where(h => h >= 0, _ => PersonParsingError.HeightNegative);
            var reasonableHeight = positiveHeight.Where(h => h < 300, _ => PersonParsingError.HeightTooHigh);

            return(reasonableHeight);
        }
Esempio n. 7
0
 /// <summary>
 /// Stop this timer and send notification that this task is complete.
 /// </summary>
 private void Stop()
 {
     Try.Catch(() => TimerInfo.Stop());
     if (OnTaskCompleted != null)
     {
         Task copy = Copy(this);
         OnTaskCompleted(copy);
     }
 }
Esempio n. 8
0
 /// <summary>
 /// Execute the action in try catch.
 /// </summary>
 /// <param name="action"></param>
 private void Execute(Action action)
 {
     try
     {
         action();
     }
     catch (Exception ex)
     {
         Try.Catch(() => Logging.Logger.Error("Unable to load/save settings", ex));
     }
 }
 private void PartialWakeNotifier_FormClosing(object sender, FormClosingEventArgs e)
 {
     Try.Catch(() =>
     {
         resetTopTimeout?.Cancel();
     });
     Try.Catch(() =>
     {
         resetTop2Timeout?.Cancel();
     });
 }
Esempio n. 10
0
 private void RaiseOnCloseEvent()
 {
     lock (closeLock)
     {
         if (closed)
         {
             return;
         }
         closed = true;
     }
     Try.Catch(() => { OnClose(this, new EventArgs()); });
 }
Esempio n. 11
0
        public void Catch()
        {
            var s = Try.Catch <int, Exception>(_ => 42);

            Assert.True(s.IsSuccess);
            Assert.Equal(42, s.Get());

            var e = Try.Catch <int, Exception>(_ => throw Exception);

            Assert.True(e.IsError);
            Assert.Throws <NotImplementedException>(() => e.Get());
        }
Esempio n. 12
0
        public void Stop()
        {
            Try.Catch(() => { thrCertificateMaintainer?.Abort(); });

            if (httpServer != null)
            {
                httpServer.Stop();
                httpServer.Join(1000);
            }
            // webSocketServer does not support closing/stopping
            webSocketServer = null;
        }
Esempio n. 13
0
        /// <summary>
        /// Runs the application provided.
        /// </summary>
        /// <param name="app">The application to run.</param>
        /// <param name="args">Command line arguments.</param>
        /// <param name="requireConfigFiles">Whether or not to throw error if the config files are not available.</param>
        /// <param name="decorations">Decorations around the application. e.g. "diagnostics,statusupdates"</param>
        public static BoolMessageItem Run(IApp app, string[] args, bool requireConfigFiles, string decorations)
        {
            // Validation.
            if (app == null)
            {
                throw new ArgumentNullException("ApplicationTemplate to run was not supplied.");
            }

            // Set the configfile requirement flag.
            app.Settings.RequireConfigs = requireConfigFiles;

            // Replace the application with the decorator.
            // This provides diagnostics, status updates out of the box, shutdown of logging. etc.
            app = new AppDecorator(decorations, app);

            BoolMessageItem result    = null;
            bool            validArgs = false;

            try
            {
                // Validate the arguments.
                result    = app.AcceptArgs(args);
                validArgs = result.Success;
                if (!result.Success)
                {
                    return(result);
                }

                // Initalize.
                app.Init();
                app.InitComplete();

                // Execute.
                result = app.Execute();
                app.ExecuteComplete();
            }
            catch (Exception ex)
            {
                Try.HandleException(ex);
            }
            finally
            {
                Try.Catch(() =>
                {
                    if (validArgs)
                    {
                        app.ShutDown();
                    }
                });
            }
            return(result);
        }
Esempio n. 14
0
        /// <summary>
        /// Whether or not the csv file can be loaded.
        /// </summary>
        /// <param name="text">The csv formatted text string.</param>
        /// <param name="hasHeaders">Whether or not the csv text has headers.</param>
        /// <param name="isReadOnly">Whether or not to make the parsed doc readonly.</param>
        /// <param name="parseMap">Whether or not to parse the data as a list of dictionaries.</param>
        /// <returns>A CsvDoc</returns>
        public static BoolMessageItem <CsvDoc> CanLoad(string text, bool hasHeaders, bool isReadOnly, string delimeter)
        {
            CsvDoc doc     = null;
            bool   loaded  = true;
            string message = string.Empty;

            Try.Catch(() => doc = Load(text, hasHeaders, isReadOnly, delimeter), (ex) =>
            {
                loaded  = false;
                message = ex.Message;
            });
            return(new BoolMessageItem <CsvDoc>(doc, loaded, message));
        }
Esempio n. 15
0
        public void TryCatch_1()
        {
            // Setup
            var mock = new Mock <ITryCatchFinally>();
            var m    = mock.Object;

            // Act
            Try.Catch(m.Try, m.Catch);

            // Assert
            mock.Verify(m => m.Try(), Times.Once);
            mock.Verify(m => m.Catch(It.IsAny <Exception>()), Times.Never);
        }
Esempio n. 16
0
        /// <summary>
        /// Persists a batch of log events to a database table
        /// </summary>
        public override void Flush()
        {
            lock (_uncommitedList)
            {
                Try.Catch(() =>
                {
                    // Let the Repository take care of CRUD actions.
                    _repo.Create(_uncommitedList);

                    // Clear the internal uncomitted log event list
                    _uncommitedList.Clear();
                });
            }
        }
Esempio n. 17
0
 private static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
 {
     try
     {
         screenCapturer?.DisplaySettingsChanged();
         Try.Catch(() => { dxgiDuplicator?.Dispose(); });
         dxgiDuplicator = new DxgiOutputDuplicator(0, 0);
         desktopInfo    = DxgiOutputDuplicator.GetDesktopInfo();
     }
     catch (Exception ex)
     {
         Logger.Debug(ex);
     }
 }
Esempio n. 18
0
 private static void Application_ApplicationExit(object sender, EventArgs e)
 {
     Logger.Info("Application_ApplicationExit event");
     isExiting = true;
     Try.Catch(() => { Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= SystemEvents_DisplaySettingsChanged; });
     // It really is highly unlikely for thrMain to exit on its own, as it blocks trying to read from shared memory
     Try.Catch(() => { thrMain?.Join(25); });
     Try.Catch(() => { thrMain?.Abort(); });
     Try.Catch(() => { thrMonitorService?.Abort(); });
     Try.Catch(() => { thrDesktopCapture?.Abort(); });
     Try.Catch(() => { screenCapturer?.Dispose(); });
     Try.Catch(() => { dxgiDuplicator?.Dispose(); });
     //Try.Catch(() => { inputEmulator?.Dispose(); });
 }
 public static void Stop()
 {
     isStopped = true;
     //Try.Catch(() => { httpServer?.Stop(); });
     Try.Catch(Logger.StopLoggingThreads);
     Try.Catch(() => { hostConnect?.Disconnect(); });
     lock (webSocketConnectionsLock)
     {
         foreach (SHRDWebSocketClientHandler clientHandler in webSocketConnections.Values)
         {
             clientHandler.CloseSocket();
         }
         webSocketConnections.Clear();
     }
 }
Esempio n. 20
0
        public static void HandlingExceptionsWithCatch(decimal number, decimal divisor)
        {
            // Catches any exception and stores the single exception into the try.
            // This is useful for handling individual errors, but cannot be aggregated.
            ITry <decimal, Exception> divisionHandlingAllExceptions = Try.Catch <decimal, Exception>(_ => number / divisor);

            // Only catches a specific exception. Notice that the error type is the specific type of exception, not a collection of exceptions.
            ITry <decimal, DivideByZeroException> divisionHandlingDividingByZero = Try.Catch <decimal, DivideByZeroException>(_ => number / divisor);

            // Catch also has an overload which allows recovering in case of exception. Serves as standard try/catch, but returns a value.
            decimal divisionResult = Try.Catch <decimal, DivideByZeroException>(
                _ => number / divisor,
                exception => 0
                );
        }
Esempio n. 21
0
 public static void SetProperty(object obj, PropertyInfo prop, object propVal, bool catchException)
 {
     if (prop != null && prop.CanWrite)
     {
         if (!catchException)
         {
             prop.SetValue(obj, propVal, null);
             return;
         }
         Try.Catch(delegate
         {
             prop.SetValue(obj, propVal, null);
         }, null);
     }
 }
Esempio n. 22
0
 /// <summary>
 /// Set the object properties using the prop name and value.
 /// </summary>
 /// <param name="obj">Object whose property will be set.</param>
 /// <param name="prop">Property information.</param>
 /// <param name="propVal">Property value to set.</param>
 /// <param name="catchException">Try to catch any exception and
 /// not throw it to the caller.</param>
 public static void SetProperty(object obj, PropertyInfo prop, object propVal, bool catchException)
 {
     // Correct property with write access
     if (prop != null && prop.CanWrite)
     {
         if (!catchException)
         {
             prop.SetValue(obj, propVal, null);
         }
         else
         {
             Try.Catch(() => prop.SetValue(obj, propVal, null), null);
         }
     }
 }
Esempio n. 23
0
        public void TryCatch_2()
        {
            // Setup
            var ex   = new Exception();
            var mock = new Mock <ITryCatchFinally>();

            mock.Setup(m => m.Try()).Throws(ex);

            var m = mock.Object;

            // Act
            Try.Catch(m.Try, m.Catch);

            // Assert
            mock.Verify(m => m.Try(), Times.Once);
            mock.Verify(
                m => m.Catch(It.Is <Exception>(e => ReferenceEquals(e, ex))),
                Times.Once);
        }
Esempio n. 24
0
 private static void desktopCaptureThreadRunner()
 {
     try
     {
         byte[] compressToBuffer = null;
         while (!isExiting && static_sm != null)
         {
             Thread.Sleep(1);
             DesktopCaptureTask task;
             while (!isExiting && static_sm != null && desktopCaptureTasks.TryDequeue(out task))
             {
                 turbojpegCLI.SubsamplingOption subsamp = GetSubsamplingOptionFromImgFlags(task.imgFlags);
                 FragmentedImage    img = CaptureRawDesktopImage(task.imgFlags.HasFlag(ImgFlags.Refresh));
                 SharedMemoryStream sm  = static_sm;
                 if (sm == null)
                 {
                     break;
                 }
                 lock (sm)
                 {
                     img.WriteToDataStream(static_sm, ref compressToBuffer, task.jpegQuality, subsamp);
                 }
             }
         }
     }
     catch (ThreadAbortException) { }
     catch (StreamDisconnectedException ex)
     {
         Logger.Info("Exiting because: " + ex.Message);
     }
     catch (Exception ex)
     {
         Logger.Debug(ex);
         Logger.Info("Exiting due to main thread runner exception");
     }
     finally
     {
         Try.Catch(() => { dxgiDuplicator?.Dispose(); });
         Try.Catch(() => { screenCapturer?.Dispose(); });
         //Try.Catch(() => { inputEmulator?.Dispose(); });
         RobustExit();
     }
 }
        public void TryCatch_3()
        {
            // Setup
            var ex   = new ArgumentOutOfRangeException();
            var mock = new Mock <ITryCatchFinally>();

            mock.Setup(m => m.Try()).Throws(ex);

            var m = mock.Object;

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                // Act
                Try.Catch <InvalidCastException>(m.Try, m.Catch);
            });

            // Assert
            mock.Verify(m => m.Try(), Times.Once);
            mock.Verify(m => m.Catch(It.IsAny <Exception>()), Times.Never);
        }
Esempio n. 26
0
File: IO.cs Progetto: sypbiz/core
 private static IEnumerable <Regex> GetIgnoreRegexes(string ignoreFilePath)
 {
     try
     {
         if (!File.Exists(ignoreFilePath))
         {
             return(new Regex[0]);
         }
         var lines   = File.ReadAllLines(ignoreFilePath);
         var regexes = lines
                       .Where(l => !l.IsNullOrWhiteSpace())
                       .Select(l => Try.Catch <Exception, Regex>(() => new Regex(l), ex => { Debug.WriteLine($"{nameof(GetIgnoreRegexes)}: {ex}"); return(null); }))
                       .NotNulls();
         return(new HashSet <Regex>(regexes));
     }
     catch (Exception ex)
     {
         Debug.WriteLine($"{nameof(GetIgnoreRegexes)}: {ex}");
         return(new Regex[0]);
     }
 }
Esempio n. 27
0
        void Success_Basic()
        {
            Func <string> lambda = () => "successful result.";
            Try <string>  succ   = lambda.Try();

            Assert.Equal("successful result.", succ.GetOrThrow());
            Assert.Equal("successful result..", succ.Convert((s) => s + ".", (e) => "boo"));
            Assert.Equal("successful result.", succ.Catch((Exception e) => "caught").GetOrThrow());
            Assert.Equal("successful result.!", succ.Then((s) => s + "!").GetOrThrow());

            Try <string> thend1 = succ.Then((s) => "S");

            Assert.Equal("S", thend1.GetOrThrow());

            Try <string> thend2 = succ.Then((s) => "S", (e) => "F");

            Assert.Equal("S", thend2.GetOrThrow());

            Try <string> failOnSuccess = succ.Then <string>((s) => { throw new TestException(); });

            Assert.Throws <TestException>(() => failOnSuccess.GetOrThrow());
        }
 public void Stop()
 {
     Try.Catch(() => { srv.Stop(); });
 }
Esempio n. 29
0
 protected override void stopServer()
 {
     Try.Catch(() => { thrFtpBackup?.Abort(); });
 }
Esempio n. 30
0
        private void readSharedMemory(object args)
        {
            SharedMemoryStream mySm = (SharedMemoryStream)args;

            try
            {
                while (sm == mySm)
                {
                    try
                    {
                        byte    cmdByte = (byte)sm.ReadByte();
                        Command cmd     = (Command)cmdByte;
                        // Handle message from Streamer process.
                        // TODO: Refactor the responses to use a generic wrapper class, e.g.
                        // AsyncLoadingObject<FragmentedImage> newFrame = ...;
                        // newFrame.Loaded(img);
                        // if (newFrame.Wait(abortFlag, out ...))
                        //	return ...;
                        switch (cmd)
                        {
                        case Command.GetScreenCapture:
                            FragmentedImage img = new FragmentedImage(sm);
                            newFrame.Produce(img);
                            break;

                        case Command.GetDesktopInfo:
                            DesktopInfo di = new DesktopInfo(sm);
                            newDesktopInfo.Produce(di);
                            break;

                        case Command.Error_SyntaxError:
                        case Command.Error_CommandCodeUnknown:
                        case Command.Error_Unspecified:
                        case Command.StartStreaming:
                        case Command.StopStreaming:
                        case Command.AcknowledgeFrame:
                        case Command.ReproduceUserInput:
                        case Command.SetStreamSettings:
                        case Command.GetStreamSettings:
                        default:
                            Logger.Info("Received unexpected byte from Streamer process: " + cmd);
                            // TODO: End the Streamer process now and start a new one, because we have just entered an undefined state.
                            break;
                        }
                    }
                    catch (ThreadAbortException) { throw; }
                    catch (StreamDisconnectedException) { throw; }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex);
                    }
                }
            }
            catch (ThreadAbortException) { }
            catch (StreamDisconnectedException)
            {
                Logger.Info("Read Shared Memory thread detected stream close (" + mySm.uniqueId + ")");
            }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
            finally
            {
                Try.Catch(() => { mySm?.Dispose(); });
                RaiseOnCloseEvent();
            }
        }