Ejemplo n.º 1
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                client = new APIClient();

                allTours = await client.GetTours();

                allTourEvents = await client.GetTourEvents();

                allClients = await client.GetClients();

                allBookings = await client.GetBookings();

                tourEventsView = (from t in allTours
                                  join te in allTourEvents
                                  on t.TourID equals te.TourID
                                  select new TourEventView
                {
                    Name = t.Name,
                    Description = t.Description,
                    EventDay = te.EventDay,
                    EventMonth = te.EventMonth,
                    EventYear = te.EventYear,
                    Fee = te.Fee,
                    EventID = te.EventID
                }).ToList();

                dgrTourEvents.ItemsSource = tourEventsView;
            }
            catch (Exception ex)
            {
                logger.Fatal("Unknown error.");
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            _logger.Info("Start");
            try
            {
                var content = DownloadWithRetryForever("http://plawgo.pl");

                _logger.Info("Success");
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex, "Error");
            }
            _logger.Info("End");
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Logger.Fatal()
                .Message("2 arguments required - DAT file path & decrypting key file path")
                .Write();
                Environment.Exit(1);
            }

#if (!DEBUG)
            try
            {
#endif
            Run(args[0], args[1]);
#if (!DEBUG)
        }
        catch (Exception e)
        {
            Logger.Fatal(e, "Uncaught exception occurred");
            throw;
        }
#endif
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a BaslerManager object.
        /// </summary>
        public Basler(ProjectManager projectMgr)
        {
            project = projectMgr;


            logger.Info("Initializing Pylon library...");


            try {
                Pylon.Initialize();
            }
            catch (Exception ex) {
                logger.Fatal("Pylon library load failed, Exception: " + ex.ToString());

                Loaded = false;
            }
            finally {
                logger.Info("Pylon library successfully initialized.");

                Loaded = true;

                Initialize();
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Stop the ZeroMQ Server and release all resources (including the NetMQ Cleanup)
 /// </summary>
 public void Stop()
 {
     Logger.Info("stopping server");
     Poller.Stop();
     PollTask.Wait();
     try
     {
         Poller.Dispose();
     } catch (Exception ex)
     {
         Logger.Fatal(ex, "could not dispose Poller");
     }
     Server.Dispose();
     NetMQConfig.Cleanup();
 }
Ejemplo n.º 6
0
 public static void LoadBaseParameters()
 {
     try {
         MainSupport.BaseParameters = new BaseParam(QSMain.ConnectionDB);
     } catch (MySql.Data.MySqlClient.MySqlException e) {
         logger.Fatal(e, "Не удалось получить информацию о версии базы данных.", e);
         MessageDialog BaseError = new MessageDialog(QSMain.ErrorDlgParrent, DialogFlags.DestroyWithParent,
                                                     MessageType.Warning,
                                                     ButtonsType.Close,
                                                     "Не удалось получить информацию о версии базы данных.");
         BaseError.Run();
         BaseError.Destroy();
         Environment.Exit(0);
     }
 }
Ejemplo n.º 7
0
        public bool StartMonitoring()
        {
            if (TaskWatcher.HasSubscriber())
            {
                var subfolderController = CreateFileController();
                subfolderController.PipelineStarted += _dataFlowSynchronizer.OnPipelineStarted;
                subfolderController.PipelineStarted += OnPipelineStarted;
                var baseFolderController = CreateBaseFolderController(subfolderController);

                baseFolderController.StartFolderMonitor();
                return(true);
            }

            Logger.Fatal("No errorhandler is subscribed.");
            return(false);
        }
        public void OnConsoleLogEvent(string message, Exception ex)
        {
            if (ex == null)
            {
                logger.Debug(message);
            }
            else
            {
                logger.Fatal(ex, message);
            }

            if (this.ConsoleLogEvent != null)
            {
                this.ConsoleLogEvent(this, new ConsoleLogEventArgs(message, ex));
            }
        }
Ejemplo n.º 9
0
        private void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exception = e.ExceptionObject as Exception;

            if (exception != null)
            {
                logger.Fatal("Unhandled exception: {0} at {1}", exception.Message, exception.StackTrace);
            }

            if (_drive != null)
            {
                // it is critically important to release the virtual drive
                _drive.Unmount();
                File.Delete(DriveLockPath);
            }
        }
Ejemplo n.º 10
0
        public async void EstablishConnectionAsync(int frequency, int timeout)
        {
            Logger.Trace("Begin EstablishConnectionAsync");

            const int port       = 8888;
            var       ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            var       ipAddress  = ipHostInfo.AddressList.FirstOrDefault(t => t.AddressFamily == AddressFamily.InterNetwork);

            if (ipAddress == null)
            {
                throw new Exception("Unable to find an IPv4 server address");
            }

            Logger.Info("Connecting to server on {0}:{1}", ipAddress, port);
            ClientSocket = new TcpClient();

            try
            {
                var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(timeout));
                var token       = tokenSource.Token;
                await Task.Run(async() =>
                {
                    while (!ClientSocket.Connected)
                    {
                        try
                        {
                            await ClientSocket.ConnectAsync(ipAddress, port);
                            NetworkStream = ClientSocket.GetStream();
                            ReadFromStreamAsync();
                            Logger.Info("Established connection to server");
                        }
                        catch (Exception e)
                        {
                            token.ThrowIfCancellationRequested();

                            Logger.Debug(e, "Unable to connect to server, retrying in 10s");
                            await Task.Delay(TimeSpan.FromSeconds(frequency), token);
                        }
                    }
                }, token);
            }
            catch (OperationCanceledException e)
            {
                Logger.Fatal(e, "Timeout while connecting to server");
            }
            Logger.Trace("End EstablishConnectionAsync");
        }
        void OnLogEventHandler(string message, Exception ex)
        {
            if (ex == null)
            {
                logger.Debug(message);
            }
            else
            {
                logger.Fatal(message, ex);
            }


            if (this.LogEvent != null)
            {
                LogEvent(message, ex);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// trigger the Tokenizing calculation
        /// </summary>
        private void ExecuteTokenize()
        {
            //clear
            Items = null;

            try
            {
                //retrieve result from the associated Service
                Items = _TokenizerService.TokenizeAndConvert(_Text);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex.Message);       //Log Exception
                MessageBox.Show("Unexpected Error. Please contact support!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                throw;
            }
        }
Ejemplo n.º 13
0
        protected override void OnStartup(StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                var ex = args.ExceptionObject is Exception exception ? exception : new Exception("Domain exception");

                Logger.Fatal(ex);
                GlobalVariables.BugSnagClient.Notify(ex);

                Clipboard.SetText("Message: " + (args.ExceptionObject as Exception)?.FlattenToString());
                MessageBox.Show(StringResources.UnhandledExceptionOccured);
            };

            DispatcherUnhandledException += (sender, args) =>
            {
                Logger.Error(args.Exception);
                GlobalVariables.BugSnagClient.Notify(args.Exception);

                Clipboard.SetText(args.Exception.ToString());
                MessageBox.Show(string.Format(StringResources.ExceptionOccured, args.Exception.FlattenToString()));
#if !DEBUG
                args.Handled = true;
#endif
            };

            if (e.Args.FirstOrDefault() == "update")
            {
                new DownloadWindow().Show();
                return;
            }

            CommonUtils.LoadSettings();

#if !DEBUG
            if (!GlobalVariables.Portable)
#endif
            CommonUtils.CheckForUpdate();

            if (string.IsNullOrEmpty(GlobalVariables.AppSettings.ApktoolVersion))
            {
                Logger.Error("Apktool not found");
                MessBox.ShowDial(StringResources.ApktoolNotFound);
            }

            WindowManager.ActivateWindow <MainWindow>();
        }
Ejemplo n.º 14
0
        private static bool ExitWindows(ExitReason exitWindows, ShutdownReason reason, bool ajustToken)
        {
            try
            {
                if (ajustToken && !TokenAdjuster.EnablePrivilege("SeShutdownPrivilege", true))
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex, "Failed to adjust token");
                return(false);
            }

            return(ExitWindowsEx(exitWindows, reason) != 0);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Reads a text from user input, tokenizes it, produces a custom output
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //retrieve the logging instance
            NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

            Logger.Info("Application started");
            Console.WriteLine("#### Text Tokenizer - Willkommen ####");

            //retrieve the associated service
            ITokenizerService _TokenizerService = new TokenizerService();

            // iterate logic until user stops execution
            do
            {
                Console.Write("Enter some text: ");
                string text = Console.ReadLine();

                IEnumerable <string> result = null;

                try {
                    //retrieve result from the associated Service
                    result = _TokenizerService.TokenizeAndConvert(text);
                }
                catch (Exception ex)
                {
                    Logger.Fatal(ex.Message);       //Log Exception
                    throw;
                }

                //just forward to console
                foreach (var item in result)
                {
                    Console.WriteLine(item);
                }

                // get the user input for every iteration, allowing to exit at will
                Console.Write("Continue [y|n]?");
                text = Console.ReadLine();
                if (text.Equals("n"))
                {
                    // exit the method.
                    break;
                }
            }while (true);
        }
Ejemplo n.º 16
0
        public void ParseMenuItemAction(string Action)
        {
            if (Type == Enums.LibraryType.SLM)
            {
                switch (Action.ToLowerInvariant())
                {
                // Opens game installation path in explorer
                case "disk":
                    if (DirectoryInfo.Exists)
                    {
                        Process.Start(DirectoryInfo.FullName);
                    }

                    break;

                // Removes a backup library from list
                case "removefromlist":
                    try
                    {
                        if (Type == Enums.LibraryType.SLM)
                        {
                            List.Libraries.Remove(this);

                            if (SLM.CurrentSelectedLibrary == this)
                            {
                                Main.FormAccessor.AppView.AppPanel.ItemsSource = null;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Fatal(ex);
                    }
                    break;
                }
            }
            else if (Type == Enums.LibraryType.Steam)
            {
                Steam.ParseMenuItemActionAsync(Action);
            }
            else if (Type == Enums.LibraryType.Origin)
            {
                Origin.ParseMenuItemActionAsync(Action);
            }
        }
Ejemplo n.º 17
0
        private static bool SqlConnectionValid()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["DestinationData"].ConnectionString;

            using (var conn = new SqlConnection(connectionString))
            {
                try
                {
                    conn.Open();
                    return(true);
                }
                catch (Exception e)
                {
                    Logger.Fatal(e);
                    return(false);
                }
            }
        }
Ejemplo n.º 18
0
 static void Main()
 {
     for (int i = 0; i < 1000; i++)
     {
         log.Trace("Trace message {0}", i);
         Thread.Sleep(random.Next(100));
         log.Debug("Debug message {0}", i);
         Thread.Sleep(random.Next(100));
         log.Warn("Warn message {0}", i);
         Thread.Sleep(random.Next(100));
         log.Info("Info message {0}", i);
         Thread.Sleep(random.Next(100));
         log.Error("Error message {0}", i);
         Thread.Sleep(random.Next(100));
         log.Fatal("Fatal message {0}", i);
         Thread.Sleep(random.Next(100));
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 分发事件
        /// </summary>
        public void DispatchEvent(int evtType, Param param = null)
        {
            if (HotfixMgr.IsFromHotfix(param))
            {
                LOGGER.Fatal($"不能添加hotfix工程的类型作为参数 DispatchEvent {param.GetType()}");
                return;
            }

            Event evt = new Event();

            evt.EventId = evtType;
            evt.Data    = param;

            if (eventHandlers.ContainsKey(evtType))
            {
                var list = eventHandlers[evtType];
                foreach (var handlerType in list)
                {
                    try
                    {
                        var handler   = HotfixMgr.GetInstance <IEventListener>(handlerType);
                        var agentType = handler.GetType().BaseType.GenericTypeArguments[1];
                        if (agentType.GetInterface(typeof(IComponentActorAgent).FullName) != null)
                        {
                            //actor
                            ownerActor.SendAsync(() => handler.InternalHandleEvent(ownerActor.GetAgent(agentType), evt));
                        }
                        else if (agentType.GetInterface(typeof(IComponentAgent).FullName) != null)
                        {
                            //component
                            var compType = agentType.BaseType.GenericTypeArguments[0];
                            ownerActor.SendAsync(async() => {
                                var comp = await ownerActor.GetComponent(compType);
                                await handler.InternalHandleEvent(comp.GetAgent(agentType), evt);
                            }, false);
                        }
                    }
                    catch (Exception e)
                    {
                        LOGGER.Error(e.ToString());
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public static bool?BrowseFile(OpenFileDialog dialog)
        {
            NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
            bool?       result = false;

            try
            {
                dialog.DefaultExt = Constants.DEFAULT_EXTENSION;
                dialog.Filter     = Constants.FILTER;
                result            = dialog.ShowDialog();
            }

            catch (Exception ex)
            {
                logger.Fatal(ex.ToString());
            }

            return(result);
        }
Ejemplo n.º 21
0
        public static void LoadLinkProperties(TextBlock btnDeleteGrid)
        {
            NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

            try
            {
                btnDeleteGrid.Text                = "Delete Out of Stock Items";
                btnDeleteGrid.Cursor              = Cursors.Hand;
                btnDeleteGrid.FontWeight          = FontWeights.Bold;
                btnDeleteGrid.Foreground          = HexColors.DELETE_BUTTON;
                btnDeleteGrid.TextDecorations     = TextDecorations.Underline;
                btnDeleteGrid.HorizontalAlignment = HorizontalAlignment.Center;
            }

            catch (Exception ex)
            {
                logger.Fatal(ex.ToString());
            }
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            var config = LogManager.Configuration;

#if !NET35 && !NET40
            var memory = config.AllTargets.OfType <LimitedMemoryTarget>().FirstOrDefault();
            if (memory != null)
            {
                memory.Limit = 5;
            }
#endif

            int k = 42;
            int l = 100;

            _logger.Trace("Sample trace message, k={0}, l={1}", k, l);
            _logger.Debug("Sample debug message, k={0}, l={1}", k, l);
            _logger.Info("Sample informational message, k={0}, l={1}", k, l);
            _logger.Warn("Sample warning message, k={0}, l={1}", k, l);
            _logger.Error("Sample error message, k={0}, l={1}", k, l);
            _logger.Fatal("Sample fatal error message, k={0}, l={1}", k, l);
            _logger.Log(LogLevel.Info, "Sample fatal error message, k={0}, l={1}", k, l);

            _logger.Info()
            .Message("Sample informational message, k={0}, l={1}", k, l)
            .Property("Test", "Tesing properties")
            .Write();

            string path = "blah.txt";
            try
            {
                string text = File.ReadAllText(path);
            }
            catch (Exception ex)
            {
                _logger.Error()
                .Message("Error reading file '{0}'.", path)
                .Exception(ex)
                .Property("Test", "ErrorWrite")
                .Write();
            }
        }
Ejemplo n.º 23
0
        public static void Main(string[] Args)
        {
            try
            {
                Logger.Info("Hello world");
                Logger.Debug("Hello debug world");
                Logger.Error("Hello error world");
                Logger.Fatal("Hello fatal world");


                //Worker w = new Worker();
                //w.DoStuff();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Goodbye cruel world");
            }

            System.Console.ReadKey();
        }
Ejemplo n.º 24
0
        public static double[] SortPrices(Book[] sortedPrices)
        {
            double[]    priceList = new double[3];
            NLog.Logger logger    = NLog.LogManager.GetCurrentClassLogger();

            try
            {
                int medianIndex = sortedPrices.Length / 2;
                priceList[PriceDistribution.MINPRICE]    = sortedPrices[0].Price;
                priceList[PriceDistribution.MAXPRICE]    = sortedPrices[sortedPrices.Length - 1].Price;
                priceList[PriceDistribution.MEDIANPRICE] = sortedPrices[medianIndex].Price;
            }

            catch (Exception ex)
            {
                logger.Fatal(ex.ToString());
            }

            return(priceList);
        }
Ejemplo n.º 25
0
        public static void Main(string[] args)
        {
            NLog.Logger logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
            ConfigureNLogDiscord();

            try
            {
                logger.Info("Initialization...");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }
        }
Ejemplo n.º 26
0
        private void LogUnhandledException(Exception ex, string source)
        {
            string message = $"Unhandled exception ({source})";

            try
            {
                System.Reflection.AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
                message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
            }
            catch (Exception e)
            {
                logger.Error(e, "Exception in LogUnhandledException");
            }
            finally
            {
                logger.Fatal(ex, message);
                MessageBox.Show("Due to an unexpected error this application is going to close. If you are able to send the log file via email, that would be appreciated.", "An unexpected error ocurred.", MessageBoxButton.OK, MessageBoxImage.Error);
                System.Windows.Application.Current.Shutdown(1);
            }
        }
Ejemplo n.º 27
0
        private void restartWithPerms(string[] args)
        {
            var psi = new ProcessStartInfo();

            psi.FileName  = System.Reflection.Assembly.GetExecutingAssembly().Location;
            psi.Verb      = "runas";
            psi.Arguments = String.Join(" ", args);

            _log.Info("Restarting app at \"" + psi.FileName + "\" with parameters \"" + psi.Arguments + "\"...");
            try
            {
                var proc = Process.Start(psi);
            } catch (Exception e)
            {
                _log.Fatal("Could not restart app: " + e.ToString());
                MessageBox.Show("Could not restart app.\nIf the error recurs please contact our team.\n" + e.ToString(), "Restart Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Application.Exit();
            return;
        }
Ejemplo n.º 28
0
 public static void Main(string[] args)
 {
     try
     {
         _logger.Info("Programa sendo iniciado");
         AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
         CreateHostBuilder(args)
         .Build()
         .Run();
     }
     catch (Exception e)
     {
         _logger.Fatal(e, "Stopped program because of exception");
         throw;
     }
     finally
     {
         NLog.LogManager.Shutdown();
     }
 }
Ejemplo n.º 29
0
        public BE_Product CreateProduct(BE_Product bE_Product)
        {
            string strError_Mensaje = string.Empty;
            bool   boResultado      = false;

            try
            {
                logger.Debug("In CreateProduct(bE_Product) ");
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("_code", bE_Product.code);
                parameters.Add("_name", bE_Product.name);
                parameters.Add("_productTypeId", bE_Product.productTypeId);
                parameters.Add("_productCategoryId", (bE_Product.productCategoryId == 0) ? DBNull.Value : (object)bE_Product.productCategoryId);
                parameters.Add("_cost", bE_Product.cost);
                parameters.Add("_salePrice", bE_Product.salePrice);
                parameters.Add("_quantity", (bE_Product.quantity == 0) ? DBNull.Value : (object)bE_Product.quantity);
                parameters.Add("_measuredUnitId", (bE_Product.measuredUnitId == 0) ? DBNull.Value : (object)bE_Product.measuredUnitId);
                parameters.Add("_dietId", (bE_Product.dietId == 0) ? DBNull.Value : (object)bE_Product.dietId);
                parameters.Add("_headquartersId", (bE_Product.headquartersId == 0) ? DBNull.Value : (object)bE_Product.headquartersId);
                parameters.Add("_kcalTotal", (bE_Product.kcalTotal == 0) ? DBNull.Value : (object)bE_Product.kcalTotal);

                parameters.Add("_waste", bE_Product.waste);
                parameters.Add("_costbyRecipeMeasureUnit", bE_Product.costbyRecipeMeasureUnit);
                parameters.Add("_RecipeMeasureUnitId", (bE_Product.RecipeMeasureUnitId == 0) ? DBNull.Value : (object)bE_Product.RecipeMeasureUnitId);

                var productId = _database.ExecuteSPGetId("sp_createProduct", parameters);

                boResultado = (productId != null);
                if (boResultado)
                {
                    bE_Product.productId = int.Parse(productId.ToString());
                    return(bE_Product);
                }
                return(null);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "CreateProduct(bE_Product) Exception: " + ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 30
0
        public override IEnumerable <string> SplitUpMultipleHands(string rawHandHistories)
        {
            //Remove XML headers if necessary
            rawHandHistories = rawHandHistories.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", "");

            //Two Cases - Case 1, we have a single <session> tag holding multiple <game> tags
            //            Case 2, we have multiple <session> tags each holding a single <game> tag.
            //            We need our enumerable to have only case 2 representations for parsing

            if (rawHandHistories.IndexOf("<session") == rawHandHistories.LastIndexOf("<session"))
            {
                //We are case 1 - convert to case 2

                int endOfGeneralInfoIndex = rawHandHistories.IndexOf("</general>");

                if (endOfGeneralInfoIndex == -1)
                {
                    // log the first 1000 chars of the file, so we can at least guess what's the problem
                    logger.Fatal("IPokerFastParserImpl.SplitUpMultipleHands(): Encountered a weird file\r\n{0}", rawHandHistories.Substring(0, 1000));
                }

                string generalInfoString = rawHandHistories.Substring(0, endOfGeneralInfoIndex + 10);

                MatchCollection gameMatches = GameGroupRegex.Matches(rawHandHistories, endOfGeneralInfoIndex + 9);
                foreach (Match gameMatch in gameMatches)
                {
                    string fullGameString = generalInfoString + "\r\n" + gameMatch.Value + "\r\n</session>";
                    yield return(fullGameString);
                }
            }
            else
            {
                //We are case 2
                MatchCollection matches = SessionGroupRegex.Matches(rawHandHistories);

                foreach (Match match in matches)
                {
                    yield return(match.Value);
                }
            }
        }
Ejemplo n.º 31
0
    public void SetUp()
    {
      try
      {
        Logger = NLog.LogManager.GetCurrentClassLogger();

        DbManager1 = new MockDbManager
                       {
                         Description = new DbDescription
                                         {
                                           XmlRoot = DbDescriptions.Valid,
                                           ConnectionInfo = new MockDbConnectionInfo
                                                              {
                                                                ConnectionStringName = "Test1"
                                                              }
                                         }
                       };
      }
      catch (Exception e)
      {
        if (Logger != null) Logger.Fatal(e, string.Format("SetUp : {0} : {1}", e.GetType(), e.Message));
        throw;
      }
    }