Info() публичный Метод

public Info ( string message ) : void
message string
Результат void
        static void Main(string[] args)
        {
            log = LogManager.GetCurrentClassLogger();

            log.Info("Version: {0}", RocksmithToolkitLib.ToolkitVersion.version);
            log.Info("OS: {0}", Environment.OSVersion.ToString());
            log.Info("Command: {0}", Environment.CommandLine.ToString());

            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                var exception = (Exception)e.ExceptionObject;
                MessageBox.Show(String.Format("Application.ThreadException\n{0}\n{1}\nPlease send us \"_RSToolkit_{2}.log\", you can find it in Toolkit folder.",
                    exception.ToString(), exception.Message.ToString(), DateTime.Now.ToString("yyyy-MM-dd")), "Unhandled Exception catched!");
                log.ErrorException(String.Format("\n{0}\n{1}\nException catched:\n{2}\n", exception.Source, exception.TargetSite, exception.InnerException), exception);
            };

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // UI thread exceptions handling.
            Application.ThreadException += (s, e) =>
            {
                var exception = (Exception)e.Exception;
                MessageBox.Show(String.Format("Application.ThreadException\n{0}\n{1}\nPlease send us \"_RSToolkit_{2}.log\", you can find it in Toolkit folder.",
                    exception.ToString(),  exception.Message.ToString(), DateTime.Now.ToString("yyyy-MM-dd")), "Thread Exception catched!");
                log.ErrorException(String.Format("\n{0}\n{1}\nException catched:\n{2}\n", exception.Source, exception.TargetSite, exception.InnerException), exception);
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Application.Run(new MainForm(args));
        }
Пример #2
0
 public static void ProcessResults(JSONDiff jd, Logger l)
 {
     if (jd.Messages.Any())
     {
         l.Info("--Issues--");
         jd.Messages.ForEach(s2 =>
         {
             var mess = s2.Message?.Trim();
             var exp = s2.Exception?.Trim();
             var m = $"{s2.ProblemType} | {mess} | {exp}";
             m = m.Replace("\r\n", "");
             switch (s2.WarnLevel)
             {
                 case JSONWarnLevel.Warn:
                     l.Warn(m);
                     break;
                 case JSONWarnLevel.Error:
                     l.Error(m);
                     break;
                 case JSONWarnLevel.Fatal:
                     l.Fatal(m);
                     break;
                 default:
                     throw new ArgumentOutOfRangeException();
             }
         });
         l.Info("-----------");
     }
     else
     {
         l.Info("--Success--");
         l.Info("-----------");
     }
 }
Пример #3
0
        public static Job GetJob(int jobId, Logger defaultLogger)
        {
            Job currentJob;
            using (var repo = new JobRepository())
            {
                defaultLogger.Info("Passed job with ID of {0}", jobId);

                currentJob = repo.GetJobById(jobId);

                if (currentJob == null)
                {
                    defaultLogger.Warn("Job not found");
                    return null;
                }

                defaultLogger.Info("Job found. URL is {0} and branch is {1}", currentJob.Url, currentJob.Branch);

                if (currentJob.State != JobState.Pending)
                {
                    defaultLogger.Warn("Cannot start job. Current state is {0}", currentJob.State);
                    return null;
                }

                repo.UpdateStateForJob(currentJob, JobState.Running);
            }

            return currentJob;
        }
Пример #4
0
        public CollectorService()
        {
            this.ServiceName = AscMailCollectionServiceName;
            this.EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            this.CanHandlePowerEvent = false;
            this.CanHandleSessionChangeEvent = false;
            this.CanPauseAndContinue = false;
            this.CanShutdown = true;
            this.CanStop = true;
            try
            {
                _log = LogManager.GetLogger("CollectorService");
                _log.Info("Connecting to db...");
                _manger = new MailBoxManager(ConfigurationManager.ConnectionStrings["mail"], 25);
                _log.Info("Creating collector service...");
                _collector = new Collector(_manger, MailQueueSettings.FromConfig);
                _log.Info("Service is ready.");

                AggregatorLogger.Instance.Initialize(_manger, GetServiceIp());
                _log.Info("Aggregator logger initialized.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under constuct: {0}", ex.ToString());
            }
        }
Пример #5
0
        /// <summary>
        /// Keep track if we have sent an error popup notification, if so use this value to supress future popups, under the assumption that the first one is the most important and probably the originator of the future popups.
        /// </summary>
        public MainForm()
        {
            // Machine number
            m_strMachineNumber = System.Configuration.ConfigurationManager.AppSettings["machineNumber"];

            //Setup the Logging system
            m_logAndErr = new LogAndErrorsUtils(AutoDialIcon, ToolTipIcon.Error);
            m_imgManUtils = new ImageManipulationUtils(m_logAndErr);
            m_logger = m_logAndErr.getLogger();

            // Give the admins a chance to change the path of tessdata
            string TESSERACT_DATA_PATH = System.Configuration.ConfigurationManager.AppSettings["tessdataPath"];
            if (TESSERACT_DATA_PATH == null)
            {

                TESSERACT_DATA_PATH = @"C:\\Autodial\\Dialing\\tessdata";
                m_logger.Error("No Config Tesseract path. Setting to: {0}", TESSERACT_DATA_PATH);
            }

            // Initilialise event for timer tick
            m_timer.Tick += new EventHandler(timerTick);

            //Initialise the Form
            InitializeComponent();

            m_logger.Info("###################################################################");
            m_logger.Info("Starting Program");

            // Checking for tesseract data path
            if (!System.IO.Directory.Exists(TESSERACT_DATA_PATH))
            {
                string strError = "Couldn't find tesseract in " + TESSERACT_DATA_PATH;
                m_logger.Error(strError);
                m_logger.Info(MailUtils.MailUtils.sendit("*****@*****.**", m_strMachineNumber, strError, m_strDailyLogFilename));
            }

            // Set the Talk Log Monitor Util
            Regex regEx = new Regex("answered|disconnected");
            string strTalkLogPath = System.Configuration.ConfigurationManager.AppSettings["talkLogPath"];
            m_logger.Info("Talk Log path: " + strTalkLogPath);
            string strLogFilePath = TalkLogMonitorUtil.getTalkLogFileNameFromTalkLogDirectory(DateTime.Today, strTalkLogPath);
            m_logger.Info("Talk File Log path: " + strLogFilePath);
            m_talkLogMonitor = new TalkLogMonitorUtil(strLogFilePath, stopAlertTimer, regEx);

            string strYear = DateTime.Today.Year.ToString();
            string strMonth = (DateTime.Today.Month < 10) ? ("0" + DateTime.Today.Month.ToString()) : DateTime.Today.Month.ToString();
            string strDay = (DateTime.Today.Day < 10) ? ("0" + DateTime.Today.Day.ToString()) : DateTime.Today.Day.ToString();

            m_strDailyLogFilename = @"C:\AutoDial\Log\AutoDial_" +
                                    strYear + "-" +
                                    strMonth + "-" +
                                    strDay + "_trace.log"; // AutoDial_2015-10-28_trace.log

            registerHotkey();
            customHide();
        }
Пример #6
0
        /// <summary>
        /// Point d'entrée.
        /// </summary>
        static void Main(string[] args)
        {
            _logger = LogManager.GetLogger("Program");
            if (!Environment.UserInteractive)
            {
                #region Considère un contexte de service
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new Service.MemcachedService()
                };
                ServiceBase.Run(ServicesToRun);
                #endregion
            }
            else
            {
                #region Considère un contexte utilisateur (interactif)
                _logger.Trace("Mode interactif");
                int exitCode = 0;
                try
                {
                    #region Parse la ligne de commande
                    Options options = new Options();
                    ICommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(false, true, Console.Error));
                    bool parserSucceed = parser.ParseArguments(args, options);
                    #endregion

                    if (options.Install || options.Uninstall)
                    {
                        if (!parserSucceed)
                            throw new ArgumentException("Ligne de commande invalide.");
                        Service.MemcachedServiceInstaller.Install(options.Uninstall, args);
                        return;
                    }

                    using (var service = new Service.MemcachedService())
                    {
                        service.SetUp(!parserSucceed ? args.Length != 0 ? args : AppSettings.GetMemcachedArguments() : AppSettings.GetMemcachedArguments());
                        _logger.Info("Service démarré. Appuyez sur ECHAP pour mettre fin au service...");

                        while (!NativeMethods.PeekEscapeKey()) { }
                        _logger.Info("[ESC]");
                        service.TearDown();
                    }
                }
                catch (Exception ex)
                {
                    _logger.Fatal(ex.ToString());
                    exitCode = -1;
                }
                Environment.Exit(exitCode);
                #endregion
            }
        }
 public SensuClientConfigurationReader(IConfigurationPathResolver configurationPathResolver)
 {
     _configurationPathResolver = configurationPathResolver;
     _log = LogManager.GetCurrentClassLogger();
     _configfile = configurationPathResolver.ConfigFileName();
     _configdir = configurationPathResolver.Configdir();
     _log.Info("Configuration file: {0}", _configfile);
     _log.Info("Configuration directory: {0}",_configdir);
     rwlock = new ReaderWriterLockSlim();
     InitFileSystemWatcher();
     
 }
        public static SyntheticCountersReporter createDefaultReporter(Logger _log, ICounterSamplingConfiguration counterSamplingConfig)
        {
            string signalFxCategory = "SignalFX";

            try
            {
                System.Diagnostics.CounterCreationDataCollection CounterDatas =
                   new System.Diagnostics.CounterCreationDataCollection();

                createCounterIfNotExist(signalFxCategory, "UsedMemory", "Total used memory", System.Diagnostics.PerformanceCounterType.NumberOfItems64, CounterDatas);

                if (CounterDatas.Count != 0)
                {
                    System.Diagnostics.PerformanceCounterCategory.Create(
                        signalFxCategory, "SignalFx synthetic counters.",
                        System.Diagnostics.PerformanceCounterCategoryType.SingleInstance, CounterDatas);
                }
            }
            catch (Exception e)
            {
                _log.Info(e.ToString());
                return null;
            }

            SyntheticCountersReporter reporter = new SyntheticCountersReporter(counterSamplingConfig);
            reporter._sfxCountersUpdateMethods.Add("UsedMemory", updateUsedMemoryCounter);
            return reporter;
        }
Пример #9
0
        private void TraceMessageInternal(LogLvl level, string message)
        {
            if (level > desiredLogLevel)
            {
                return;
            }

            switch (level)
            {
            case LogLvl.Debug:
                variableLogger?.Debug(message);
                break;

            case LogLvl.Info:
                variableLogger?.Info(message);
                break;

            case LogLvl.Warning:
                variableLogger?.Warn(message);
                break;

            case LogLvl.Error:
                variableErrorLogger?.Error(message);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }
Пример #10
0
        public TaskCoordinator(IScheduler scheduler, Logger logger)
        {
            _logger = logger;
            _scheduler = scheduler;

            _logger.Info("TaskCoordincator started with scheduler: {0}", scheduler.SchedulerInstanceId);
        }
Пример #11
0
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler"/> when a <see cref="T:Quartz.ITrigger"/>
        ///             fires that is associated with the <see cref="T:Quartz.IJob"/>.
        /// </summary>
        /// <remarks>
        /// The implementation may wish to set a  result object on the
        ///             JobExecutionContext before this method exits.  The result itself
        ///             is meaningless to Quartz, but may be informative to
        ///             <see cref="T:Quartz.IJobListener"/>s or
        ///             <see cref="T:Quartz.ITriggerListener"/>s that are watching the job's
        ///             execution.
        /// </remarks>
        /// <param name="context">The execution context.</param>
        public void Execute(IJobExecutionContext context)
        {
            _logger = LogManager.GetCurrentClassLogger();

            JobDataMap dataMap = context.JobDetail.JobDataMap;
            EconomicReleaseUpdateJobSettings settings;
            try
            {
                settings = JsonConvert.DeserializeObject<EconomicReleaseUpdateJobSettings>((string)dataMap["settings"]);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Failed to deserialize data update job settings");
                return;
            }

            _logger.Info($"Data Update job {settings.Name} triggered.");

            _broker.Error += _broker_Error;

            var startDate = DateTime.Now.AddBusinessDays(-settings.BusinessDaysBack);
            var endDate = DateTime.Now.AddBusinessDays(settings.BusinessDaysAhead);
            var req = new EconomicReleaseRequest(startDate, endDate, dataLocation: DataLocation.ExternalOnly, dataSource: settings.DataSource);
            var releases = _broker.RequestEconomicReleases(req).Result; //no async support in Quartz, and no need for it anyway, this runs on its own thread
            _logger.Trace($"Economic release update job downloaded {releases.Count} items");

            JobComplete();
        }
Пример #12
0
		private static HashSet<string> RegisterScriptEvents(IEnumerable<PluginBase> plugins, Logger logger)
		{
			var scriptEvents = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase);
			
			foreach (var plugin in plugins)
			{
				var properties = plugin.GetType()
					.GetProperties()
					.Where(m => m.PropertyType == typeof(ScriptEventHandlerDelegate[]))
					.ToList();

				foreach (var member in properties)
				{
					var eventInfo = member.GetCustomAttributes<ScriptEventAttribute>().SingleOrDefault();

					if (eventInfo != null)
					{
						logger.Info("register script event '{0}' ({1})", eventInfo.EventAlias, member);

						if (scriptEvents.Contains(eventInfo.EventAlias))
						{
							var message = string.Format("duplicate event alias: '{0}'", eventInfo.EventAlias);
							throw new Exception(message);
						}

						scriptEvents.Add(eventInfo.EventAlias);
					}
				}
			}

			return scriptEvents;
		}
Пример #13
0
 static void Exit(Logger logger, CancellationTokenSource src, ExtensionRunnerExitCode exitCode)
 {
     if(logger != null)
         logger.Info("Exiting (code: " + exitCode + ")");
     src.Cancel();
     Environment.Exit((int)exitCode);
 }
Пример #14
0
        public static IWebDriver ClosePopupWindows(this IWebDriver driver, Logger logger)
        {
            var parentWindowHandle = driver.CurrentWindowHandle;
            logger.Info("Closing popups windows");

            try
            {
                var popUp = string.Empty;

                while ((popUp = driver.WindowHandles.FirstOrDefault(x => x != parentWindowHandle)) != null)
                {
                    driver.SwitchTo().Window(popUp).Close();
                }
            }
            catch(Exception e)
            {
                // Notes: No popups ?
                var error = e.Message;
            }
            finally
            {
                driver.SwitchTo().Window(parentWindowHandle);
            }

            return driver;
        }
Пример #15
0
 public static OperationCountDelegate DefaultAction(Logger logger,string preamble)
 {
     return (value, time, complete, granularity) =>
     {
         logger.Info("{0}: {1} percent complete, {2} ops completed, {3} ops/sec", preamble, complete,value, granularity / time.TotalSeconds);
     };
 }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceControl"/> class.
        /// </summary>
        internal ServiceControl()
        {
            _logger = LogManager.GetCurrentClassLogger();
            _monitoringTask = new MonitoringTask(MonitoringConfig.ReadFromAppSettings());

            _logger.Info(Const.Messages.ServiceInitialized);
        }
Пример #17
0
        public QueueProcessor(Logger log, IDataStore dataStore, IHubContext<IMatchmakingClient> hub, ITracker tracker, IMatchEvaluator matchBuilder, CircularBuffer<TimeSpan> timeToMatch)
        {
            _log = log;
            _dataStore = dataStore;
            _hub = hub;
            _tracker = tracker;
            _matchBuilder = matchBuilder;
            _timeToMatch = timeToMatch;

            _queueSleepMin = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepMin") );
            _queueSleepMax = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepMax") );
            _queueSleepLength = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepLength") );

            Task.Run( async () =>
            {
                _log.Info("Running QueueProcessor...");

                while( true )
                {
                    var sleepTime = _queueSleepMax;

                    try
                    {
                        await processQueue();
                        sleepTime = _queueSleepMax - (_dataStore.DocumentDbPopulation * (_queueSleepMax/_queueSleepLength));
                    }
                    catch(Exception ex)
                    {
                        _log.Error(ex);
                    }

                    Thread.Sleep(sleepTime < _queueSleepMin ? _queueSleepMin : sleepTime);
                }
            });
        }
        static void Main(string[] args)
        {
            Log = LogManager.GetCurrentClassLogger();

            Log.Info(
                String.Format("Version: {0} ({1} bit)\r\n ", RocksmithToolkitLib.ToolkitVersion.version, Environment.Is64BitProcess ? "64" : "32") +
                String.Format("OS: {0} ({1} bit)\r\n ", Environment.OSVersion, Environment.Is64BitOperatingSystem ? "64" : "32") +
                String.Format("Runtime: v{0}\r\n ", Environment.Version) +
                String.Format("JIT: {0}", JitVersionInfo.GetJitVersion())
            );

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                var exception = (Exception)e.ExceptionObject;
                MessageBox.Show(String.Format("Application.ThreadException\n{0}\n{1}\nPlease send us \"_RSToolkit_{2}.log\", you can find it in Toolkit folder.",
                    exception.ToString(), exception.Message.ToString(), DateTime.Now.ToString("yyyy-MM-dd")), "Unhandled Exception catched!");
                Log.ErrorException(String.Format("\n{0}\n{1}\nException catched:\n{2}\n", exception.Source, exception.TargetSite, exception.InnerException), exception);
            };

            // UI thread exceptions handling.
            Application.ThreadException += (s, e) =>
            {
                var exception = (Exception)e.Exception;
                MessageBox.Show(String.Format("Application.ThreadException\n{0}\n{1}\nPlease send us \"_RSToolkit_{2}.log\", you can find it in Toolkit folder.",
                    exception.ToString(), exception.Message.ToString(), DateTime.Now.ToString("yyyy-MM-dd")), "Thread Exception catched!");
                Log.ErrorException(String.Format("\n{0}\n{1}\nException catched:\n{2}\n", exception.Source, exception.TargetSite, exception.InnerException), exception);
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm(args));
        }
Пример #19
0
        // GET: Movies
        public ActionResult Index(string movieGenre, string searchString)
        {
            var GenreLst = new List<string>();

            var GenreQry = from d in db.Movies
                           orderby d.Genre
                           select d.Genre;

            GenreLst.AddRange(GenreQry.Distinct());
            ViewBag.movieGenre = new SelectList(GenreLst);

            var movies = from m in db.Movies
                         select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                movies = movies.Where(s => s.Title.Contains(searchString));
            }

            if (!string.IsNullOrEmpty(movieGenre))
            {
                movies = movies.Where(x => x.Genre == movieGenre);
            }

            var config = LogManager.Configuration;
            string basedirPath = AppDomain.CurrentDomain.BaseDirectory;
#if TRACE
            logger = NLog.LogManager.GetLogger("rule1");
            logger.Info("\n{0}", movies);
#endif
            return View(movies);
        }
Пример #20
0
        public async Task RunAsync(params string[] args)
        {
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            //create client
            Client = new ShardedDiscordClient(new DiscordSocketConfig
            {
                AudioMode = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize = 10,
                LogLevel = LogSeverity.Warning,
                TotalShards = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue
            });

            //initialize Services
            CommandService = new CommandService();
            Localizer = new Localization();
            Google = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats = new StatsService(Client, CommandHandler);

            //setup DI
            var depMap = new DependencyMap();
            depMap.Add<ILocalization>(Localizer);
            depMap.Add<ShardedDiscordClient>(Client);
            depMap.Add<CommandService>(CommandService);
            depMap.Add<IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader<PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader<Command>(new CommandTypeReader());
            CommandService.AddTypeReader<Module>(new ModuleTypeReader());
            CommandService.AddTypeReader<IGuild>(new GuildTypeReader());

            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);
            await Client.ConnectAsync().ConfigureAwait(false);
            await Client.DownloadAllUsersAsync().ConfigureAwait(false);

            _log.Info("Connected");

            //load commands and prefixes
            using (var uow = DbHandler.UnitOfWork())
            {
                ModulePrefixes = new ConcurrentDictionary<string, string>(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix));
            }
            // start handling messages received in commandhandler
            await CommandHandler.StartHandling().ConfigureAwait(false);

            await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false);
#if !GLOBAL_NADEKO
            await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
Пример #21
0
 private void Log(Logger logger, Object message)
 {
     try
     {
         logger.Info(message);
     }
     catch { }
 }
        public PeriodicalActionState(Action<DateTime> action, int interval, DateTime now, Logger logger)
        {
            logger.Info("Register periodical action: {0} ({1})", action.Method, action.Method.DeclaringType);

            if (interval < 1)
                throw new Exception(string.Format("Wrong interval: {0} min", interval));

            // offset
            int offset = random.Next(interval);
            logger.Info("Interval: {0} minutes, random offset: {1} minutes", interval, offset);

            // set fields
            this.interval = interval;
            this.action = action;
            this.logger = logger;

            lastRun = now.AddMinutes(offset - interval);
        }
        public static void LoadAndCacheStorage()
        {
            Paused = true;

            EmptyCacheCollectors();
            {
                Logger?.Info(string.Format("Clearing Cache... Success"));
                Logger?.Info(string.Format(""));
            }

            Logger?.Trace(string.Format("Loading Server Templates..."));

            LoadMaps();
            LoadSkillTemplates();
            LoadSpellTemplates();
            LoadItemTemplates();
            LoadMonsterTemplates();
            LoadMundaneTemplates();
            LoadWarpTemplates();
            LoadPopupTemplates();
            LoadWorldMapTemplates();
            CacheCommunityAssets();
            BindTemplates();
            LoadMetaDatabase();
            LoadExtensions();

            Paused = false;

            Logger?.Trace(string.Format("Server Ready!, Listening for Connections..."));

            ServerContext.Log("Loaded {0} Boards Loaded from Cache ({1})", GlobalBoardCache.Count, GlobalBoardCache.Dump());
            ServerContext.Log("Loaded {0} Monster Templates Loaded from Cache ({1})", GlobalMonsterTemplateCache.Count, GlobalMonsterTemplateCache.Dump());
            ServerContext.Log("Loaded {0} Item Templates Loaded from Cache ({1})", GlobalItemTemplateCache.Count, GlobalItemTemplateCache.Count);
            ServerContext.Log("Loaded {0} Mundane Templates Loaded from Cache ({1})", GlobalMundaneTemplateCache, GlobalMundaneTemplateCache.Dump());
            ServerContext.Log("Loaded {0} Warp Templates Loaded from Cache ({1})", GlobalWarpTemplateCache.Count, GlobalWarpTemplateCache.Dump());
            ServerContext.Log("Loaded {0} Area Templates Loaded from Cache ({1})", GlobalMapCache.Count, GlobalMapCache.Dump());
            ServerContext.Log("Loaded {0} Popup Templates Loaded from Cache ({1})", GlobalPopupCache.Count, GlobalPopupCache.Dump());
            ServerContext.Log("Loaded {0} Buff Templates Loaded from Cache ({1})", GlobalBuffCache.Count, GlobalBuffCache.Dump());
            ServerContext.Log("Loaded {0} DeBuff Templates Loaded from Cache ({1})", GlobalDeBuffCache.Count, GlobalDeBuffCache.Dump());
            ServerContext.Log("Loaded {0} Skill Templates Loaded from Cache ({1})", GlobalSkillTemplateCache.Count, GlobalSkillTemplateCache.Dump());
            ServerContext.Log("Loaded {0} Spell Templates Loaded from Cache ({1})", GlobalSpellTemplateCache.Count, GlobalSpellTemplateCache.Dump());
            ServerContext.Log("Loaded {0} WorldMap Templates Loaded from Cache ({1})", GlobalWorldMapTemplateCache.Count, GlobalWorldMapTemplateCache.Dump());
            ServerContext.Log("Loaded {0} Reactor Templates Loaded from Cache ({1})", GlobalReactorCache.Count, GlobalReactorCache.Dump());
        }
Пример #24
0
        static void Main()
        {
            Application.CurrentCulture = new System.Globalization.CultureInfo("ru-Ru");
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);

            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(EventHandler_CurrentDomain_UnhandledException);
            Application.ThreadException +=
                new System.Threading.ThreadExceptionEventHandler(EventHandler_Application_ThreadException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Создаём объект для ведения логов приложения
            //_Logger = LogManager.GetCurrentClassLogger();
            _Logger = LogManager.GetLogger("CorrosionMonitoringSystemLogger");
            _Logger.Info("Приложение запущено");

            // Data base layer 
            _NetworkManager = NetworksManager.Instance;

            try
            {
                _NetworkManager.LoadConfig(Application.StartupPath + 
                    @"\newtorkconfig.bin.nwc");
            }
            catch
            {
                MessageBox.Show("Ошибка при конфигурировании системы. " + 
                    "Приложение будет закрыто", 
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }

            // Presentation layer
            CorrosionMonitoringSystemForm _PresentationForm = new CorrosionMonitoringSystemForm();

            // Business layer
            BLController controller = new BLController(_NetworkManager, _PresentationForm);

            Application.Run(_PresentationForm);
            
            _Logger.Info("Приложение остановлено");
        }
Пример #25
0
        public TopService(INancyBootstrapper ninjectNancyBootstrapper, ServiceSettings serviceSettings, Logger logger, IScheduler scheduler)
        {
            _serviceSettings = serviceSettings;
            _ninjectNancyBootstrapper = ninjectNancyBootstrapper;
            _scheduler = scheduler;
            _logger = logger;

            logger.Info("Service was created with base url {0}", serviceSettings.BaseUrl);
            Trace.WriteLine("Service was created with base url: "+serviceSettings.BaseUrl);
        }
Пример #26
0
 public ConsulAgent(string consulPath, ConsulConfig config, Process consulProcess)
 {
     _consulPath = consulPath;
     _config = config;
     _logger = LogManager.GetLogger(typeof(ConsulAgent).FullName + ":PID" + consulProcess.Id);
     _consulProcess = consulProcess;
     _consulProcess.Exited += (_, __) =>
     {
         _logger.Info("Shutdown");
     };
     _consulProcess.ErrorDataReceived += (s, a) =>
     {
         _logger.Error(a.Data);
     };
     _consulProcess.OutputDataReceived += (s2, a2) =>
     {
         _logger.Info(a2.Data);
     };
     _consulProcess.BeginErrorReadLine();
     _consulProcess.BeginOutputReadLine();
 }
Пример #27
0
        public Collector(MailBoxManager manager, MailQueueSettings settings)
        {
            _log = LogManager.GetLogger("Collector");
            _manager = manager;
            _settings = settings;
            _itemManger = new MailItemManager(_manager);
            _queue = new MailWorkerQueue(settings.ConcurrentThreadCount, settings.CheckInterval, this);

            _log.Info("MailWorkerQueue: ConcurrentThreadCount = {0} and CheckInterval = {1}", 
                settings.ConcurrentThreadCount, settings.CheckInterval);

            
        }
Пример #28
0
        static void Main(string[] args)
        {
            bool created;
            mutex = new Mutex(false, "HMAController_1AABE6DC-00C2-4C01-9FA3-C3426FD16F51", out created);
            if (!created)
            {
                Console.WriteLine("Another instance of HMAController is already running");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                return;
            }
            
            logger = LogManager.GetLogger("HMAController");

            Console.WriteLine("Starting HMA controller...");
            logger.Info("Starting HMA controller...");

            if (VerifyConfiguration())
            {
                while (true)
                {
                    Console.WriteLine("Triggered @ " + DateTime.Now.ToString());

                    string[] files = Directory.GetFiles(Settings.HMAControllerDirectory, "*.hma");

                    if (files.Count() == 1)
                    {
                        FileInfo file = new FileInfo(files[0]);

                        if (Path.GetFileNameWithoutExtension(file.FullName).ToLower() == "restart")
                        {
                            if (KickInAss())
                            {
                                file.Delete();
                            }
                        }
                    }

                    Thread.Sleep(Settings.IntervalMinutes * 60000);
                }
            }
            else
            {
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
Пример #29
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="transport">Message transport used as a backend for this message bus</param>
 public MessageBus(IMessageTransport transport, IMessageDispatcher dispatcher, ISerializeMessages serializer, IServiceResolver serviceResolver)
 {
     log = LogManager.GetLogger("BUS_" + transport.Endpoint);
     log.Info("Message Bus {0} created", transport.Endpoint);
     MessageSerializer = serializer;
     Dispatcher = dispatcher;
     ServiceLocator = serviceResolver;
     _transport = transport;
     _transport.OnMessageArrived += new MessageArrived(_transport_OnMessageArrived);
     _transport.OnMessageToUnknownDestination += new MessageArrived(_transport_OnMessageToUnknownDestination);
     SubscriptionService = new DummySubscriptionService();
     BatchOutgoingMessagesInTransaction = true;
     MessageHandlerTransactionScopeOption = TransactionScopeOption.Required;
     UseTransactionScope = true;
     DefaultSubscriptionLifetime = TimeSpan.FromHours(48);
     PublishLocalByDefault = true;
 }
Пример #30
0
        public AdminModule(IScheduler scheduler, LogsStore logsStore, CreativePackagesStore creativePackagesStore,Logger logger,OmniRecordManager omniRecordManager)
            : base("/admin")
        {
            Get["/hello"] = x => Response.AsText("OK");

            Get["/fire-task/{job}"] = x =>
                {
                    scheduler.TriggerTaskByClassName((string)x.job);
                    return Response.AsText("OK");
                };

            Get["/postfix-logs"] = x =>
                {
                    var logs = logsStore.GetAllLogs();
                    var lines = logs.Select(entry => string.Format("{0} {1}", entry.time.ToLongTimeString(), entry.msg)).ToList();
                    return Response.AsText(string.Join(Environment.NewLine, lines));
                };

            Get["/jobs"] = x =>
                {
                    var tasks = scheduler.GetCurrentJobs();
                    var data = tasks.Select(jobKey => new { Data = scheduler.GetJobDetail(jobKey).JobDataMap, Job = jobKey.Name }).ToList();

                    return Response.AsJson(data);
                };

            Post["/flush-unprocessed-packages"] = _ =>
                {
                    var packages = creativePackagesStore.GetAll();
                    packages.ToList().ForEach(x =>
                        {
                            x.Processed = true;
                            logger.Info("write false for: {0}",x.To);
                            creativePackagesStore.Save(x);
                        });

                    return Response.AsText("OK");
                };

            Get["/purge-blocking-rules"] = _ =>
                {
                    omniRecordManager.RemoveSingle<GroupsAndIndividualDomainsSendingPolicies>();
                    return "OK";
                };
        }
Пример #31
0
        public virtual void OpeningItem(IWebDriver wd, Logger logger)
        {
            var eventArgs = new DOMEventArgs(wd, logger);
            OnOpeningItem(this, eventArgs);

            if (eventArgs.ShouldCancelNavigation)
            {
                return;
            }

            var link = wd.FirstOrDefault(By.CssSelector(this.LocationCriteria));
            
            if (link == null || !link.IsDisplayed())
            {
                logger.Info("Couldn't find Element to Engage Alternate Activity for: {0}", Key);
                return;
            }

            link.Click();
        }
Пример #32
0
        public void Execute()
        {
            _logger = LogManager.GetLogger("log");
            #if DEBUG
            {
                _emailService = new EmailService(true);
            }
            #else
            {
                _emailService = new EmailService(false);
            }
            #endif

            try
            {

                InitializeLoggingConfiguration();

                Application.AddMessageFilter(KeyboardTracking.Instance);
                SdlTradosStudio.Application.Closing += Application_Closing;

                _service = new KeyboardTrackingService(_logger,_emailService);
                _editorController = SdlTradosStudio.Application.GetController<EditorController>();
                _editorController.Opened += _editorController_Opened;
                _editorController.ActiveDocumentChanged += _editorController_ActiveDocumentChanged;
                _editorController.Closing += _editorController_Closing;

                var twitterPersistenceService = new TwitterPersistenceService(_logger);
                if (twitterPersistenceService.HasAccountConfigured) return;
                using (var tForm = new TwitterAccountSetup(twitterPersistenceService))
                {
                    tForm.ShowDialog();
                }
                _logger.Info(string.Format("Started productivity plugin version {0}",VersioningService.GetPluginVersion()));
            }
            catch (Exception ex)
            {
                _logger.Debug(ex,"Unexpected exception when intializing the app");
                _emailService.SendLogFile();
            }
        }
Пример #33
0
        /// <summary>
        ///     Login User to OneDrive.
        /// </summary>
        public async Task LoginAsync()
        {
            AuthenticationResult?  authResult = null;
            IEnumerable <IAccount> accounts   = await publicClientApplication.GetAccountsAsync();

            // let's see if we have a user in our belly already
            try
            {
                IAccount firstAccount = accounts.FirstOrDefault();
                authResult = await publicClientApplication.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync();

                GraphServiceClient = new GraphServiceClient(
                    new DelegateAuthenticationProvider(requestMessage =>
                {
                    requestMessage.Headers.Authorization =
                        new
                        AuthenticationHeaderValue("bearer",
                                                  authResult
                                                  .AccessToken);
                    return(Task.CompletedTask);
                }));
            }
            catch (MsalUiRequiredException ex)
            {
                logManager.Debug(ex);
                // pop the browser for the interactive experience
                authResult = await publicClientApplication.AcquireTokenInteractive(scopes)
                             .WithParentActivityOrWindow(ParentActivityWrapper
                                                         .ParentActivity)                                 // this is required for Android
                             .ExecuteAsync();
            }
            catch (MsalClientException ex)
            {
                if (ex.ErrorCode == ERROR_CODE_CANCELED)
                {
                    logManager.Info(ex);
                    throw new BackupOperationCanceledException();
                }

                logManager.Error(ex);
                throw;
            }
        }
Пример #34
0
 public void Info(string msg)
 {
     logger.Info(msg);
 }
Пример #35
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            string userChoice = "";

            try
            {
                do
                {
                    Console.WriteLine("1) Display your list of Blogs");
                    Console.WriteLine("2) Make a Blog");
                    Console.WriteLine("3) Make a Post");
                    Console.WriteLine("4) Display your Posts");
                    Console.WriteLine("Press any key to quit");

                    userChoice = Console.ReadLine();
                    logger.Info("User choice: ", userChoice);


                    if (userChoice == "1")
                    {
                        // Display all Blogs from the database
                        var database = new BloggingContext();
                        var sqlQuery = database.Blogs.OrderBy(b => b.Name);

                        Console.WriteLine($"{sqlQuery.Count()} Blogs");
                        foreach (var item in sqlQuery)
                        {
                            Console.WriteLine(item.Name);
                        }
                    }

                    else if (userChoice == "2")
                    {
                        // Create and save a new Blog
                        Console.Write("Enter a name for a new Blog: ");
                        var name = Console.ReadLine();
                        if (name.Length == 0)
                        {
                            logger.Error("Please enter a name for your Blog, it can't be blank.");
                        }
                        else
                        {
                            var blog = new Blog {
                                Name = name
                            };

                            var database = new BloggingContext();
                            database.AddBlog(blog);
                            logger.Info("Blog added - {name}", name);
                        }
                    }


                    else if (userChoice == "3")
                    {
                        var database = new BloggingContext();
                        var sqlQuery = database.Blogs.OrderBy(b => b.BlogId);

                        Console.WriteLine("Which blog do you want to post to? : ");
                        foreach (var item in sqlQuery)
                        {
                            Console.WriteLine($"{item.BlogId}) {item.Name}");
                        }

                        if (int.TryParse(Console.ReadLine(), out int BlogID))
                        {
                            if (database.Blogs.Any(b => b.BlogId == BlogID))
                            {
                                Post post = new Post();
                                post.BlogId = BlogID;
                                Console.WriteLine("Name the title of your Post:");
                                post.Title = Console.ReadLine();
                                logger.Info("Post added - {postTitle}", post.Title);
                                if (post.Title.Length == 0)
                                {
                                    logger.Info("Sorry partner, your title can't be blank");
                                }
                                else
                                {
                                    Console.WriteLine("Wanna add some content to your post?");
                                    post.Content = Console.ReadLine();
                                    database.AddPost(post);
                                    logger.Info("Content added - {Content}", post.Content);
                                }
                            }
                            else
                            {
                                logger.Error("Hmmm, seems there aren't any blogs with that ID Number");
                            }
                        }
                        else
                        {
                            logger.Error("Invalid Blog ID Number");
                        }
                    }

                    else if (userChoice == "4")
                    {
                        var database = new BloggingContext();
                        var sqlQuery = database.Blogs.OrderBy(b => b.BlogId);
                        Console.WriteLine("Which Blog do you want to see posts from?");

                        foreach (var item in sqlQuery)
                        {
                            Console.WriteLine($"{item.BlogId}) {item.Name}");
                        }
                        if (int.TryParse(Console.ReadLine(), out int BlogId))
                        {
                            IEnumerable <Post> Posts;
                            if (BlogId != 0 && database.Blogs.Count(b => b.BlogId == BlogId) == 0)
                            {
                                logger.Error("Hmmm, there aren't any blogs saved with that ID Number");
                            }
                            else
                            {
                                Posts = database.Posts.OrderBy(p => p.Title);
                                if (BlogId == 0)
                                {
                                    Posts = database.Posts.OrderBy(p => p.Title);
                                }
                                else
                                {
                                    Posts = database.Posts.Where(p => p.BlogId == BlogId).OrderBy(p => p.Title);
                                }
                                Console.WriteLine($"{Posts.Count()} post/s returned");
                                foreach (var item in Posts)
                                {
                                    Console.WriteLine($"Blog: {item.Blog.Name}\nTitle: {item.Title}\nContent: {item.Content}\n");
                                }
                            }
                        }
                        else
                        {
                            logger.Error("Error! Blog ID Number nonexistent!");
                        }
                    }
                } while (userChoice == "1" || userChoice == "2" || userChoice == "3" || userChoice == "4");
                logger.Info("Program has ended");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }
Пример #36
0
        /// <summary>
        /// Login User to OneDrive.
        /// </summary>
        public async Task LoginAsync()
        {
            AuthenticationResult?  authResult = null;
            IEnumerable <IAccount> accounts   = await publicClientApplication.GetAccountsAsync();

            // let's see if we have a user in our belly already
            try
            {
                IAccount firstAccount = accounts.FirstOrDefault();
                authResult = await publicClientApplication.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync();

                GraphServiceClient = graphClientFactory.CreateClient(authResult);
            }
            catch (MsalUiRequiredException ex)
            {
                logManager.Debug(ex);
                // pop the browser for the interactive experience
                authResult = await publicClientApplication.AcquireTokenInteractive(scopes)
                             .WithParentActivityOrWindow(ParentActivityWrapper.ParentActivity)                              // this is required for Android
                             .ExecuteAsync();

                GraphServiceClient = graphClientFactory.CreateClient(authResult);
            }
            catch (MsalClientException ex)
            {
                if (ex.ErrorCode == ERROR_CODE_CANCELED)
                {
                    logManager.Info(ex);
                    throw new BackupOperationCanceledException();
                }

                logManager.Error(ex);
                throw;
            }
        }
Пример #37
0
 public SecureFileDownloadPage(DriverContext driverContext)
     : base(driverContext)
 {
     Logger.Info("Waiting for File Download page to open");
     this.Driver.IsElementPresent(this.downloadPageHeader, BaseConfiguration.ShortTimeout);
 }
 public void LogInfo(string logMessage)
 {
     _NLog.Info(logMessage);
 }
Пример #39
0
 void ILogger.Info(string message)
 {
     _logger.Info(message);
 }
Пример #40
0
        private static string CURRENCY  = "TBTC";  //user BTC for production

        public Hpo()
        {
            var config     = new NLog.Config.LoggingConfiguration();
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            NLog.LogManager.Configuration = config;

            Api api = new Api();

            //get server time
            string     timeResponse     = api.get("/api/v2/time");
            ServerTime serverTimeObject = Newtonsoft.Json.JsonConvert.DeserializeObject <ServerTime>(timeResponse);
            string     time             = serverTimeObject.serverTime;

            Logger.Info("server time: {}", time);

            //get algo settings
            string    algosResponse = api.get("/main/api/v2/mining/algorithms");
            DataSet   algoObject    = Newtonsoft.Json.JsonConvert.DeserializeObject <DataSet>(algosResponse);
            DataTable algoTable     = algoObject.Tables["miningAlgorithms"];

            DataRow mySettings = null;

            foreach (DataRow algo in algoTable.Rows)
            {
                if (algo["algorithm"].Equals(ALGORITHM))
                {
                    mySettings = algo;
                }
            }
            Logger.Info("algo settings: {}", mySettings["algorithm"]);

            //get balance
            string     accountsResponse = api.get("/main/api/v2/accounting/accounts2", true, time);
            Currencies currenciesObj    = Newtonsoft.Json.JsonConvert.DeserializeObject <Currencies>(accountsResponse);
            double     myBalace         = 0;

            foreach (Currency c in currenciesObj.currencies)
            {
                if (c.currency.Equals(CURRENCY))
                {
                    myBalace = c.available;
                }
            }
            Logger.Info("balance: {} {}", myBalace, CURRENCY);

            //create pool
            Dictionary <string, string> pool = new Dictionary <string, string>
            {
                { "algorithm", ALGORITHM },
                { "name", "my pool " + Guid.NewGuid().ToString() },
                { "username", "pool_username" },         //your pool username
                { "password", "x" },                     //your pool password
                { "stratumHostname", "pool.host.name" }, //pool hostname
                { "stratumPort", "3456" } //pool port
            };

            string poolResponse = api.post("/main/api/v2/pool", Newtonsoft.Json.JsonConvert.SerializeObject(pool), time, false);
            Pool   poolObject   = Newtonsoft.Json.JsonConvert.DeserializeObject <Pool>(poolResponse);
            string myPoolId     = poolObject.id;

            Logger.Info("new pool id: {}", myPoolId);

            //create order
            Dictionary <string, string> order = new Dictionary <string, string> {
                { "algorithm", ALGORITHM },
                { "amount", (string)mySettings["minimalOrderAmount"] },
                { "displayMarketFactor", (string)mySettings["displayMarketFactor"] },
                { "limit", (string)mySettings["minSpeedLimit"] }, // GH [minSpeedLimit-maxSpeedLimit] || 0 - unlimited speed
                { "market", "EU" },
                { "marketFactor", (string)mySettings["marketFactor"] },
                { "poolId", myPoolId },
                { "price", "0.0010" }, //per BTC/GH/day
                { "type", "STANDARD" }
            };

            string newOrderResponse = api.post("/main/api/v2/hashpower/order", Newtonsoft.Json.JsonConvert.SerializeObject(order), time, true);
            Order  orderObject      = Newtonsoft.Json.JsonConvert.DeserializeObject <Order>(newOrderResponse);
            string myOrderId        = orderObject.id;

            Logger.Info("new order id: {}", myOrderId);

            //update price and limit
            Dictionary <string, string> updateOrder = new Dictionary <string, string> {
                { "displayMarketFactor", (string)mySettings["displayMarketFactor"] },
                { "limit", "0.11" }, // GH [minSpeedLimit-maxSpeedLimit] || 0 - unlimited speed
                { "marketFactor", (string)mySettings["marketFactor"] },
                { "price", "0.00123" } //per BTC/GH/day
            };

            string updateOrderResponse = api.post("/main/api/v2/hashpower/order/" + myOrderId + "/updatePriceAndLimit", Newtonsoft.Json.JsonConvert.SerializeObject(updateOrder), time, true);

            Logger.Info("update order response: {}", updateOrderResponse);

            //delete order
            string deleteOrderResponse = api.delete("/main/api/v2/hashpower/order/" + myOrderId, time, true);

            Logger.Info("delete order response: {}", deleteOrderResponse);

            //delete pool
            string deletePoolResponse = api.delete("/main/api/v2/pool/" + myPoolId, time, true);

            Logger.Info("update pool response: {}", deletePoolResponse);
        }
Пример #41
0
 /// <inheritdoc cref="NLog.Logger.Info(string)"/>
 public void Info(string message)
 {
     _internalLogger.Info(message);
 }
Пример #42
0
 public BasicAuthPage(DriverContext driverContext)
     : base(driverContext)
 {
     Logger.Info("Waiting for page to open");
     this.Driver.IsElementPresent(this.pageHeader, BaseConfiguration.ShortTimeout);
 }
Пример #43
0
 public static void LogInfo(string message)
 {
     Initialize();
     logger.Info(message);
 }
Пример #44
0
        public void ConfigureServices(IServiceCollection services)
        {
            ConfigureLoggingService();
            logger.Info("Configure Logging Service");

            ConfigureAppsettings(services);
            logger.Info("Configure Appsettings");

            ConfigureDatabaseServices.Configure(services, Environment.EnvironmentName,
                                                Configuration["AppSettings:DatabaseType"], Configuration["AppSettings:ConnectionString"]);
            logger.Info("Configure Database");

            //services.AddHealthChecks();
            //logger.Info("AddHealthChecks");

            ConfigureAuthentication(services);
            logger.Info("Configure Authentication");

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            logger.Info("Clear JWT ClaimTypeMap");

            ConfigureIdentity(services);
            logger.Info("Configure Identity");

            ConfigureAuthorization(services);
            logger.Info("Add Authorization");

            services.AddControllersWithViews();
            logger.Info("Add services for Web API, MVC & Razor Views");

            //services.AddOpenApiDocument();
            services.AddSwaggerDocument(settings =>
            {
                settings.PostProcess = document =>
                {
                    document.Info.Version     = "v1";
                    document.Info.Title       = "WebApp API";
                    document.Info.Description = "REST API for WebApp.";
                };
            });
            logger.Info("Add services for Swagger Document");

            services.AddRazorPages();
            logger.Info("Add services for Razor Pages");

            services.Configure <RazorViewEngineOptions>(options => options.ViewLocationExpanders.Add(new FeatureLocationExpander()));
            logger.Info("Enable Feature Folders");
            // https://scottsauber.com/2016/04/25/feature-folder-structure-in-asp-net-core/

            // Angular files will be served from this directory in production.
            services.AddSpaStaticFiles(configuration => configuration.RootPath = "clientapp/dist");
            logger.Info("AddSpaStaticFiles");

            // get the current user for auditing
            services.AddScoped <ICurrentUserService, CurrentUserService>();

            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            services.AddCQR(executingAssembly);
            logger.Info("Configure CQR Services");

            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();
            logger.Info("Add email and sms");

            services.AddScoped <ValidateReCaptchaAttribute>();
            logger.Info("Add ValidateReCaptchaAttribute");

            services.AddTransient <ISeedDatabase, SeedDatabase>();

            services.AddTransient <IViewMeetingRepository, ViewMeetingRepository>();
            services.AddTransient <IEditMeetingRepository, EditMeetingRepository>();
        }
Пример #45
0
 public void Info(string message)
 {
     _log.Info(message);
 }
Пример #46
0
 /// <summary>
 /// Information the specified message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="args">The arguments.</param>
 public void Info(string message, params object[] args)
 {
     Logger.Info(CultureInfo.CurrentCulture, message, args);
 }
Пример #47
0
 public void Info(string info)
 {
     _logger.Info($"{_typeName} {info}");
 }
Пример #48
0
        public async Task UpdateUsers(int page = 1)
        {
            while (true)
            {
                _logger.Info($"Page: {page}");
                var list = await _usersParser.LoadUsersByPage(page);

                if (list is null || list.Count == 0)
                {
                    return;
                }
                _logger.Info($"Users loaded: {list.Count}");
                using (var pixelContext = new PixelContext(_dbContextOptions))
                {
                    foreach (var item in list)
                    {
                        var entity = await pixelContext.PixelUser.SingleOrDefaultAsync(x => x.NickName == item.nickName);

                        if (entity == null)
                        {
                            await pixelContext.PixelUser.AddAsync(new PixelUser()
                            {
                                NickName    = item.nickName,
                                PixelUserId = Guid.NewGuid(),
                                UserName    = item.userName
                            });
                        }
                        else
                        {
                            entity.UserName = entity.UserName;
                            pixelContext.PixelUser.Update(entity);
                        }
                    }

                    await pixelContext.SaveChangesAsync();
                }

                page++;
            }
        }
Пример #49
0
        private void handleResponseMessage(BaseMessage msg)
        {
            switch (msg.getMessageType())
            {
            case MessageType.DETECTOR_STATUS_MESSAGE:
            {
                DetectorStatus detectorStatus = msg as DetectorStatus;
                this.mState         = detectorStatus.getState();
                this.mOperationMode = detectorStatus.getOperationMode();
                this.mFPS           = detectorStatus.getFPS();
                this.mNOF           = detectorStatus.getNOF();
                this.mBMPRate       = detectorStatus.getBMPRate();

                this.Dispatcher.Invoke((MethodInvoker) delegate
                    {
                        switch (this.mState)
                        {
                        case DetectorState.DISCONNECTED:
                            {
                                lbDetectorState.Content      = "Chưa kết nối";
                                lbDetectorBMPRate.Content    = "";
                                lbDetectorFPS.Content        = "";
                                lbDetectorNumOfFrame.Content = "";
                                break;
                            }

                        case DetectorState.CONNECTED:
                            {
                                lbDetectorState.Content  = "Đã kết nối";
                                circleDetectorState.Fill = Brushes.Green;
                                //lbDetectorBMPRate.Content = "BMPRate ( " + this.mBMPRate.ToString() + " % )";
                                lbDetectorFPS.Content        = "FPS (" + this.mFPS.ToString() + ")";
                                lbDetectorNumOfFrame.Content = "Số ảnh chụp(" + this.mNOF.ToString() + ")";
                                break;
                            }

                        case DetectorState.CALIBARATING:
                            {
                                lbDetectorState.Content  = "Đang hiệu chỉnh";
                                circleDetectorState.Fill = Brushes.Green;
                                //lbDetectorBMPRate.Content = "BMPRate ( " + this.mBMPRate.ToString() + " % )";
                                lbDetectorFPS.Content        = "FPS (" + this.mFPS.ToString() + ")";
                                lbDetectorNumOfFrame.Content = "Số ảnh chụp(" + this.mNOF.ToString() + ")";
                                break;
                            }

                        case DetectorState.CALIBRATE_DARK_DONE:
                            {
                                lbDetectorState.Content  = "Hiệu chỉnh tối xong";
                                circleDetectorState.Fill = Brushes.Green;
                                //lbDetectorBMPRate.Content = "BMPRate ( " + this.mBMPRate.ToString() + " % )";
                                lbDetectorFPS.Content        = "FPS ( " + this.mFPS.ToString() + " )";
                                lbDetectorNumOfFrame.Content = "Số ảnh chụp(" + this.mNOF.ToString() + ")";
                                break;
                            }

                        case DetectorState.CALIBRATE_BRIGHT_DONE:
                            {
                                lbDetectorState.Content      = "Hiệu chỉnh sáng xong";
                                circleDetectorState.Fill     = Brushes.Green;
                                lbDetectorBMPRate.Content    = "BMPRate ( " + this.mBMPRate.ToString() + " % )";
                                lbDetectorFPS.Content        = "FPS ( " + this.mFPS.ToString() + " )";
                                lbDetectorNumOfFrame.Content = "Số ảnh chụp(" + this.mNOF.ToString() + ")";
                                break;
                            }

                        case DetectorState.READY_GET_IMAGE:
                            {
                                lbDetectorState.Content      = "Sẵn sàng chụp ảnh";
                                circleDetectorState.Fill     = Brushes.Green;
                                lbDetectorBMPRate.Content    = "BMPRate (" + this.mBMPRate.ToString() + " %)";
                                lbDetectorFPS.Content        = "FPS ( " + this.mFPS.ToString() + " )";
                                lbDetectorNumOfFrame.Content = "Số ảnh chụp(" + this.mNOF.ToString() + ")";
                                break;
                            }
                        }
                    });

                //Logger.Info("DETECTOR_STATUS_MESSAGE: state = {0}, mode = {1}, FPS = {2}, NOF = {3}, BMP = {4}",
                //    detectorStatus.getState(), detectorStatus.getOperationMode(), detectorStatus.getFPS(), detectorStatus.getNOF(), detectorStatus.getBMPRate());
                break;
            }

            case MessageType.DETECTOR_GET_IMAGE_DONE:
            {
                DetectorGetImageDone res = msg as DetectorGetImageDone;
                this.mCurResImage = res.getIndex();
                Logger.Info("DETECTOR_GET_IMAGE_DONE: index = {0}", res.getIndex());
                break;
            }

            case MessageType.DETECTOR_ERROR_MESSAGE:
            {
                DetectorError res = msg as DetectorError;
                Logger.Info("DETECTOR_ERROR_MESSAGE: error code = {0}", res.getErrorCode());
                break;
            }

            default:
            {
                //Logger.Info("DetectorCodec key = {0} does NOT match any key", BitConverter.ToString(BitConverter.GetBytes((ushort)_key)));
                break;
            }
            }
        }
Пример #50
0
 public void LoggerTest()
 {
     Logger.Configure();
     NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
     logger.Info("hello world");
 }
Пример #51
0
 public void Info(string msg)
 {
     System.Diagnostics.Debug.WriteLine(msg);
     _log.Info(msg);
 }
Пример #52
0
        public void ShouldGenerateInt()
        {
            var i = faker.Create <int>();

            if (i != 0)
            {
                logger.Info("ObjectFieldTest compled succesfully: objects are't zero");
            }
            else
            {
                logger.Info("ObjectFieldTest compled not succesfully: objects are zero");
            }
            Assert.NotZero(i);
        }
Пример #53
0
 public void Info(string msg)
 {
     _log?.Info(msg);
     System.Diagnostics.Trace.TraceInformation($"{ProjectName} : {msg}");
 }
Пример #54
0
 public static void Info([Localizable(false)] string message, params object[] args)
 {
     Log.Info(message, args);
 }
Пример #55
0
        public bool goToPosition(double _rotX, double _detY, double _rotC, double _detZ, double _xrayZ)
        {
            Logger.Info("Move to position: {0}, {1}, {2}, {3}, {4}", _rotX, _detY, _rotC, _detZ, _xrayZ);
//            if (!this.ReadyMotion) return false;

            double deltaRotX = _rotX - this.mRotXPos;
            double deltaDetZ = _detZ - this.mDetZPos;
            //if ((_rotX < 98) && (_detZ > 0))
            //{
            //    deltaRotX = 0;
            //    deltaDetZ = 0;
            //    Logger.Warn("Require to move restrict region RotX = {0} and DetZ = {1}", _rotX, _detZ);
            //}
            double deltaDetY = _detY - this.mDetYPos;
            double deltaRotC = _rotC - this.mRotCPos;

            double deltaXRayPos = _xrayZ - this.mXRayPos;

            this.moveToPositionByValue(deltaRotX, deltaDetY, deltaRotC, deltaDetZ, deltaXRayPos);
            return(true);
        }
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    Console.WriteLine("Enter your selection:");
                    Console.WriteLine("1) Display all blogs");
                    Console.WriteLine("2) Add Blog");
                    Console.WriteLine("3) Create Post");
                    Console.WriteLine("Enter q to quit");
                    choice = Console.ReadLine();
                    Console.Clear();
                    logger.Info("Option {choice} selected", choice);

                    if (choice == "1")
                    {
                        // display blogs
                        var db    = new BloggingContext();
                        var query = db.Blogs.OrderBy(b => b.Name);

                        Console.WriteLine($"{query.Count()} Blogs returned");
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.Name);
                        }
                    }
                    else if (choice == "2")
                    {
                        // Add blog
                        Console.Write("Enter a name for a new Blog: ");
                        var blog = new Blog {
                            Name = Console.ReadLine()
                        };

                        ValidationContext       context = new ValidationContext(blog, null, null);
                        List <ValidationResult> results = new List <ValidationResult>();

                        var isValid = Validator.TryValidateObject(blog, context, results, true);
                        if (isValid)
                        {
                            var db = new BloggingContext();
                            // check for unique name
                            if (db.Blogs.Any(b => b.Name == blog.Name))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Blog name exists", new string[] { "Name" }));
                            }
                            else
                            {
                                logger.Info("Validation passed");
                                // save blog to db
                                db.AddBlog(blog);
                                logger.Info("Blog added - {name}", blog.Name);
                            }
                        }
                        if (!isValid)
                        {
                            foreach (var result in results)
                            {
                                logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                            }
                        }
                    }
                    else if (choice == "3")
                    {
                        // Create Post
                        var db    = new BloggingContext();
                        var query = db.Blogs.OrderBy(b => b.BlogId);

                        Console.WriteLine("Select the blog you would to post to:");
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.BlogId}) {item.Name}");
                        }
                        if (int.TryParse(Console.ReadLine(), out int BlogId))
                        {
                            if (db.Blogs.Any(b => b.BlogId == BlogId))
                            {
                                Post post = InputPost(db);
                                if (post != null)
                                {
                                    post.BlogId = BlogId;
                                    db.AddPost(post);
                                    logger.Info("Post added - {title}", post.Title);
                                }
                            }
                            else
                            {
                                logger.Error("There are no Blogs saved with that Id");
                            }
                        }
                        else
                        {
                            logger.Error("Invalid Blog Id");
                        }
                    }
                    Console.WriteLine();
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }
Пример #57
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice = "";
                do
                {
                    Console.WriteLine("Enter Selection: ");
                    Console.WriteLine("1) Display all blogs");
                    Console.WriteLine("2) Add blog");
                    Console.WriteLine("3) Create Post");
                    Console.WriteLine("4) Display Posts");
                    Console.WriteLine("Enter q to quit");
                    choice = Console.ReadLine();
                    logger.Info("User choice: {Choice}", choice);
                    var db = new BloggingContext();
                    if (choice == "1")
                    {
                        var query = db.Blogs.OrderBy(b => b.Name);
                        int c     = db.Blogs.Count();

                        Console.WriteLine("{0} Blogs returned", c);
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.Name);
                        }
                    }
                    else if (choice == "2")
                    {
                        // Create and save a new Blog
                        Console.Write("Enter a name for a new Blog: ");
                        var name = Console.ReadLine();
                        if (name == "")
                        {
                            logger.Error("Blog Name cannot be null");
                        }
                        else
                        {
                            var blog = new Blog {
                                Name = name
                            };


                            db.AddBlog(blog);
                            logger.Info("Blog added - {name}", name);
                        }
                    }
                    else if (choice == "3")
                    {
                        Console.WriteLine("Select the blog you want to post to: ");
                        var query = db.Blogs.OrderBy(b => b.Name);
                        int bln;
                        // As of right now i can not test this as the blog ID is broken
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.BlogId + ") " + item.Name);
                        }

                        if (!int.TryParse(Console.ReadLine(), out bln))
                        {
                            logger.Error("Invalid Blog Id");
                        }
                        else
                        {
                            if (db.Blogs.Any(b => b.BlogId == bln))
                            {
                                Blog bl = db.RealBlog(bln);
                                Console.WriteLine("Enter Post Title: ");
                                string blpt = Console.ReadLine();
                                if (blpt == "")
                                {
                                    logger.Error("Post title cannot be null");
                                }
                                else
                                {
                                    Console.WriteLine("Enter Post Content: ");
                                    string blpc = Console.ReadLine();
                                    var    post = new Post {
                                        Title = blpt, Content = blpc, BlogId = bln
                                    };
                                    db.MakePost(post);
                                    logger.Info("Post added - \"{blpt}\"", blpt);
                                }
                            }
                            else
                            {
                                logger.Error("There are no Blogs saved with that Id");
                            }
                        }

                        //Console.Write("Enter blog name: ");
                        //bln = Console.ReadLine();
                        //Blog bl = db.RealBlog(bln);
                        //Console.Write("Enter Post Title: ");
                        //string blpt = Console.ReadLine();
                        //Console.Write("Enter Post Content: ");
                        //string blpc = Console.ReadLine();
                        //var post = new Post { Title = blpt, Content = blpc, Blog = bl };
                        //db.MakePost(post);
                        //logger.Info("Post made");
                    }
                    else if (choice == "4")
                    {
                        Console.WriteLine("Select the blog's post(s) to display: ");
                        Console.WriteLine("0) Posts from all blogs");
                        var query = db.Blogs.OrderBy(b => b.Name);
                        int bln;
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.BlogId + ") Posts from " + item.Name);
                        }

                        if (!int.TryParse(Console.ReadLine(), out bln))
                        {
                            logger.Error("Invalid Blog Id");
                        }
                        else
                        {
                            if (bln != 0 && db.Blogs.Count(b => b.BlogId == bln) == 0)
                            {
                                logger.Error("There are no Blogs saved with that Id");
                            }
                            else
                            {
                                var qu = db.Posts.OrderBy(p => p.Title);
                                if (bln == 0)
                                {
                                    qu = db.Posts.OrderBy(p => p.Title);
                                }
                                else
                                {
                                    qu = db.Posts.Where(p => p.BlogId == bln).OrderBy(p => p.Title);
                                }
                                Console.WriteLine($"{qu.Count()} post(s) returned");
                                foreach (var item in qu)
                                {
                                    Console.WriteLine("Blog: " + item.Blog.Name);
                                    Console.WriteLine("Title: " + item.Title);
                                    Console.WriteLine("Content: " + item.Content);
                                }
                            }
                        }
                    }
                    Console.WriteLine();
                } while ((choice != "q" && choice != "Q") && (choice == "1" || choice == "2" || choice == "3" || choice == "4"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }

            logger.Info("Program ended");
        }
Пример #58
0
 public void Info(string message)
 {
     NLogger.Info(message);
 }
Пример #59
0
 public void Info(string msg, params object[] args)
 {
     logger.Info(msg, args);
 }
Пример #60
0
 public void Save(string fileName)
 {
     new TableWriter(this).WriteTable(fileName);
     Logger.Info("File successfully saved to {0}.", fileName);
 }