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

public Trace ( string message ) : void
message string
Результат void
Пример #1
0
        static void Main()
        {
            Config = new ServiceConfig().Load();
            Logger = LogManager.GetCurrentClassLogger();

            try
            {
                Host = new WebHost();
                Host.Start();

                Logger.Trace("Сервис запущен");

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

                Application.Run(new FormService());

                Logger.Trace("Сервис остановлен");
            }
            catch (Exception ex)
            {
                Program.Logger.Error(ex.Message);
                Application.Exit();
            }
        }
Пример #2
0
 public void OnDataReceived(MocapFrame mocapFrame)
 {
     if (this._enabled)
     {
         // logging the mocapFrame into JsonFile.
         _logger?.Trace("mocapFrame {MocapFrame}", mocapFrame);
     }
 }
        public FileProvider()
        {
            _logger = LogManager.GetCurrentClassLogger();

            var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            _logger.Trace("AppData: " + appData);
            _settingsFolderPath = Path.Combine(appData, "MergeToolSelector");
            _logger.Trace("Settings folder path: " + _settingsFolderPath);
        }
Пример #4
0
        private int Run()
        {
            Bootstrap();
            _logger = _container.Resolve<Logger>();

            var exitCode = HostFactory.Run(host =>
            {
                host.Service<RefreshService>(svc =>
                {
                    svc.ConstructUsing(() =>
                    {
                        var agent = new RefreshService(RefreshInterval, () => _container.Resolve<RabbitMonitorRepository>() as RabbitMonitorRepository);

                        agent.OnReport += (s, e) => _logger.Trace(e.Data);
                        agent.OnError += (s, e) => _logger.Fatal(e.Data);

                        return agent;
                    });

                    svc.WhenStarted(a => a.Start());
                    svc.WhenStopped(a => a.Stop());
                });

                host.SetDescription("Refresh Service Agent for RabbitMQ");
                host.SetDisplayName("RabbitMQ Refresh Agent");
                host.SetServiceName("RabbitMQRefreshAgent");
                host.RunAsNetworkService();
            });

            return (int)exitCode;
        }
Пример #5
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();
        }
Пример #6
0
        static void Main(string[] args)
        {
            Database.SetInitializer<AwpContext>(null);
            Database.SetInitializer<OenContext>(null);
            Database.SetInitializer<HeatContext>(null);

            try
            {
                Container = Bootstrap();

                Runner = Container.Resolve<IJobsRunner>() as JobsRunner;
                Runner.Title = "Automated Warming Process - Warmer Agent";
                Runner.StartTime = DateTime.Now;

                Log = Container.Resolve<Logger>();

                Console.WriteLine("**************************************************************************");
                Console.WriteLine("*");
                Console.WriteLine("* {0} ", Runner.Title);
                Console.WriteLine("* Date: {0} ", Runner.StartTime);
                Console.WriteLine("*");
                Console.WriteLine("* Usage:");
                Console.WriteLine("*");
                Console.WriteLine("*    Warmer [-options] where options are:");

                JobsRunner.CommandLineOptions.ToList().ForEach(x => Console.WriteLine("*         {0}", x));

                Console.WriteLine("*");
                Console.WriteLine("**************************************************************************");
                Console.WriteLine("\n\n\n");

                Log.Trace("Starting the Process with Command Line: {0}", args.Dump());

                PrepareRunner();
                Runner.ParseCommandLine(args);
                Runner.SetDefaultValuesForSettings();
                Runner.BuildJobs();
                Runner.ApplySettings();

                Run();
            }
            catch (Exception e)
            {
                Log.Fatal(e.Message);
            }

            Console.WriteLine("\n\n\n");
            Console.WriteLine("**************************************************************************");
            Console.WriteLine("*");
            Console.WriteLine("* Duration: {0} ", Runner.Duration);
            Console.WriteLine("*");
            Console.WriteLine("**************************************************************************");
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.ReadLine();   
            }
#endif
        }
Пример #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Scheduler"/> class.
 /// </summary>
 /// <param name="tasks">The tasks.</param>
 /// <param name="internalCheckInterval">The internal check interval (in seconds).</param>
 public Scheduler(SchedulerTask[] tasks, int internalCheckInterval = 120)
 {
     _tasks = tasks;
     _internalCheckInterval = internalCheckInterval;
     _cache = HttpRuntime.Cache;
     _logger = LogManager.GetLogger("SchedulerTask");
     _logger.Trace("Scheduler created.");
 }
 protected DockableToolwindowPresenter(VBE vbe, AddIn addin, IDockableUserControl view)
 {
     _vbe = vbe;
     _addin = addin;
     _logger = LogManager.GetCurrentClassLogger();
     _logger.Trace(string.Format("Initializing Dockable Panel ({0})", GetType().Name));
     UserControl = view as UserControl;
     _window = CreateToolWindow(view);
 }
        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());
        }
Пример #10
0
        static void Main(string[] args)
        {
            logger = LogManager.GetCurrentClassLogger();
            DependencyFactory.RegisterDependency<IMathSolver, MathSolver>();
            logger.Trace("Logger Created");

            IMathSolver solver = DependencyFactory.Resolve<IMathSolver>();
            solver.DoComplexTimeTakingCalculation();
            Console.ReadLine();
        }
Пример #11
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
            }
        }
Пример #12
0
        public SuppressionFilesController
        (
            ISuppressionFilesRequestValidator validator,

            SettingsProvider settings,
            Logger logger
        )
        {
            Logger = logger;
            Logger.Trace("Initializing WebAPI Service...");

            _validator = validator;

            _settings = settings;
            _powerUser = new NetworkCredential(_settings.PowerUserName, _settings.PowerUserPassword, _settings.PowerUserDomain);
        }
Пример #13
0
        public TCPTransportFactory(ClientConfig configuration, ISerializer serializer, IRequestBalancer reqBalancer)
        {
            logger = LogManager.GetLogger("TCPTransportFactory");
            this.config = configuration;
            serverIP = IPAddress.Parse(config.ServerIP);
            serverPort = Convert.ToInt16(config.ServerPort);
            balancer = reqBalancer;
            CreateAndPreparePool(configuration.GetServerList());
            this.serializer = serializer;

            if (logger.IsTraceEnabled)
            {
                foreach (IPEndPoint ep in configuration.GetServerList())
                    logger.Trace("server list : " + ep.Address.ToString() + ":" + ep.Port);
            }
        }
        protected void Application_Start()
        {
            try
            {
                log = LogManager.GetCurrentClassLogger();

                AreaRegistration.RegisterAllAreas();

                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);

                log.Trace("Application was started");

            }
            catch (Exception e)
            {
                log.ErrorException("Exeption during start application: " + e.Message, e);
            }
        }
Пример #15
0
        public void InitWebSocket()
        {
            disposed = false;

            socket = new WebSocket("wss://ws-feed.gdax.com");

            socket.SslConfiguration.EnabledSslProtocols = SupportedProtocols;

            socket.OnOpen += (sender, e) =>
                             logger.Trace("Gdax WebSocket Connected");



            socket.OnError += (sender, e) =>
                              logger.Trace(JsonConvert.SerializeObject(e, Formatting.Indented));

            socket.OnClose += (sender, e) =>
                              logger.Trace("GDax WebSocket Disconnected");
        }
Пример #16
0
        public void Trace(string message, object obj)
        {
            string msg = string.Empty;

            if (obj != null)
            {
                msg = $"{message} 資料:{JsonConvert.SerializeObject(obj)}";
            }
            else
            {
                msg = $"{message}";
            }

            msg += System.Environment.NewLine;
            msg += "--------------------------------------------";
            msg += System.Environment.NewLine;

            log.Trace(msg);

            System.Diagnostics.Debug.WriteLine(msg);
        }
        /// <summary>
        /// Log application messages to app logger with different logging levels.
        /// </summary>
        /// <param name="logMessageType">The levlel of the message to log.</param>
        /// <param name="message">The message to log.</param>
        public static void LogMessage(LogMessageType logMessageType, string message)
        {
            try
            {
                switch (logMessageType)
                {
                case LogMessageType.Debug:
                    Logger.Debug(message);
                    break;

                case LogMessageType.Info:
                    Logger.Info(message);
                    break;

                case LogMessageType.Warn:
                    Logger.Warn(message);
                    break;

                case LogMessageType.Error:
                    Logger.Error(message);
                    break;

                case LogMessageType.Fatal:
                    Logger.Fatal(message);
                    break;

                case LogMessageType.Trace:
                    Logger.Trace(message);
                    break;

                default:
                    Logger.Info(message);
                    break;
                }
            }
            catch
            {
                // There's nothing can be done if logging fails. At the very least, the sytem should not bubble it up to the user.
            }
        }
Пример #18
0
 public TCPTransport(IPAddress server, int serverPort)
 {
     this.serverIP = server;
     this.serverPort = serverPort;
     logger = LogManager.GetLogger("TCPTransport");
     try
     {
         tcpClient = new TcpClient();
         tcpClient.Connect(server, serverPort);
         this.buff = new BufferedStream(tcpClient.GetStream());
         this.bWriter = new BinaryWriter(buff);
         this.bReader = new BinaryReader(tcpClient.GetStream());
         String message = string.Format("Connected to server :" + server.ToString() + " : " + serverPort);
         logger.Trace(message);
     }
     catch (Exception e)
     {
         String message = string.Format("Could not connect to server :" + server.ToString() + " : " + serverPort);
         logger.Warn("Infinispan.DotNetClient", message);
         throw new TransportException(message, e);
     }
 }
        static void Main(string[] args)
        {            
            ConfigurationItemFactory.Default.Targets.RegisterDefinition("SignalTarget", typeof(SignalTarget));
            Logger = LogManager.GetCurrentClassLogger(typeof(SignalTarget));
            var rnd = new Random((int)DateTime.Now.Ticks);

            for (int i = 0; i < 100; i++) {
                Logger.Trace("Sample trace message from NLog");
                Logger.Debug("Sample debug message from NLog");
                Logger.Info("Sample informational message from NLog");
                Logger.Warn("Sample warning message from NLog");
                Logger.Error("Sample error message from NLog", new Exception("Something bad happened!"));
                Logger.Fatal("Sample fatal error message from NLog");

                var sleep = rnd.Next(20, 250);
                Console.WriteLine(string.Concat("Sleeping...:", sleep, "ms"));
                Thread.Sleep(sleep);
            }

            Console.WriteLine("Logging Complete. Press enter to continue...");
            Console.ReadLine();
        }
Пример #20
0
        private static void NativeLogHandle(int severity, string msg)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("native:: ");
            builder.Append(msg);

            msg = builder.ToString();

            LogSeverity logSeverity = (LogSeverity)severity;

            switch ((LogSeverity)severity)
            {
            case LogSeverity.Trace:
                s_logger.Trace(msg);
                break;

            case LogSeverity.Debug:
                s_logger.Debug(msg);
                break;

            case LogSeverity.Info:
                s_logger.Info(msg);
                break;

            case LogSeverity.Warn:
                s_logger.Warn(msg);
                break;

            case LogSeverity.Error:
                s_logger.Error(msg);
                break;

            case LogSeverity.Critical:
                s_logger.Fatal(msg);
                break;
            }
        }
Пример #21
0
        protected void btnAddCustomer_Click(object sender, EventArgs e)
        {
            sw.Start();
            NLog.Logger logger          = LogManager.GetCurrentClassLogger();
            string      currentUsername = "******";
            string      pcname          = Dns.GetHostName();
            Guid        currentUserGuid = new Guid("{c7d8acdc-fdb0-4ee7-87ce-cfc88dc3882e}");


            for (int i = 0; i < 1; i++)
            {
                Customer customer = new Customer()
                {
                    CustomerID  = 13,
                    Name        = "dwefızfzzzg " + i.ToString(),
                    Address     = "blkıjrrdhk.",
                    MobilePhone = "1277328",
                    StartDate   = new DateTime(2004, 1, 25)
                };



                logger.Trace(customer);

                //  customer.Address = "dfdfrfdfnnujhtyjhscgfg";
                // customer.Address = "sfffffrfdg";
                // customer.Fax = "1235689135";

                //logger.Info(string.Empty, customer, new OHAuditInfo() { UserName = currentUsername, Guid = currentUserGuid, PcName = pcname });

                string        strItems  = "items1, item2, item3";
                string[]      items     = strItems.Split(',');
                List <string> ItemsList = new List <string>(items);
                TimeSpan      x;
                x           = sw.Elapsed;
                Label1.Text = x.ToString();
            }
        }
Пример #22
0
        public void ResetPwd(int userID, string newPWD)
        {
            string connString = "SERVER=xxxx.mysql.database.azure.com" + ";" +
                                "DATABASE=HW_5;" +
                                "UID=xxxxx;" +
                                "PASSWORD=xxxxx;";

            MySqlConnection cnMySQL = new MySqlConnection(connString);

            cnMySQL.Open();
            MySqlCommand cmdMySQL = cnMySQL.CreateCommand();

            cmdMySQL.CommandText = "update users set pwd = @newPWD where users.userID = @userID;";
            cmdMySQL.Parameters.Add("@newPWD", MySqlDbType.VarChar).Value = newPWD;
            cmdMySQL.Parameters.Add("@userID", MySqlDbType.Int64).Value   = userID;
            cmdMySQL.ExecuteNonQuery();
            logger.Trace("user create - Trace"); //Won't log
            logger.Debug("user create - Debug"); //Won't log
            logger.Info("user create - Info");   //Won't log
            logger.Warn("user create - Warn");   //Won't log
            logger.Error("user create - Error"); //Will log
            logger.Fatal("user create - Fatal");
        }
Пример #23
0
        public TCPTransport(IPEndPoint endPoint)
        {
            ipEndPoint = endPoint;
            logger = LogManager.GetLogger("TCPTransport");
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(ipEndPoint.Address, ipEndPoint.Port);
                // tcpClient.Connect(IPAddress.Loopback, 11222);
                this.buff = new BufferedStream(tcpClient.GetStream());
                this.bWriter = new BinaryWriter(buff);
                this.bReader = new BinaryReader(tcpClient.GetStream());
                String message = string.Format("Connected to server :" + ipEndPoint.Address.ToString() + " : " + ipEndPoint.Port);

                logger.Trace(message);
            }
            catch (Exception e)
            {
                String message = string.Format("Could not connect to server :" + ipEndPoint.Address.ToString() + " : " + ipEndPoint.Port);
                logger.Warn("Infinispan.DotNetClient", message);
                throw new TransportException(message, e);
            }
        }
Пример #24
0
        public static void MyMethod1()
        {
            //各ログレベルの出力サンプル
            logger.Trace("Sample trace message");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");

            // Exseption情報を出力する例
            try
            {
                //またはLog()メソッドにログレベルとメッセージを渡すことで出力することが可能
                logger.Log(LogLevel.Info, "Sample informational message");
            }
            catch (Exception ex)
            {
                logger.Error(ex, "ow noos!"); // render the exception with ${exception}
                throw;
            }
            return;
        }
 public void Log(LogType logType, string errorMessage)
 {
     switch (logType)
     {
         case LogType.Trace:
             _logger.Trace(errorMessage);
             break;
         case LogType.Debug:
             _logger.Debug(errorMessage);
             break;
         case LogType.Info:
             _logger.Info(errorMessage);
             break;
         case LogType.Warn:
             _logger.Warn(errorMessage);
             break;
         case LogType.Error:
             _logger.Error(errorMessage);
             break;
         case LogType.Fatal:
             _logger.Fatal(errorMessage);
             break;
     }
 }
Пример #26
0
        private void _kpuRegisterer_PropertyChanged(object sender, KpuStateEventArg e)
        {
            logger.Trace($"_kpuRegisterer_PropertyChanged Commando:{e.Commando}, KpuId:{e.KpuId}");

            if (e.Commando.CompareTo("restart") == 0)
            {
                RestartKpu(e.KpuId);
                //_engine.Stop();

                //_engine.Run();
            }
            else if (e.Commando.CompareTo("start") == 0)
            {
                logger.Debug($"In Run:{e.Commando}, KpuId:{e.KpuId}");
                //_engine.Run();
                StartKpu(e.KpuId);
            }
            else if (e.Commando.CompareTo("stop") == 0)
            {
                logger.Debug($"In Stop:{e.Commando}, KpuId:{e.KpuId}");
                StopKpu(e.KpuId);
                //_engine.Stop();
            }
        }
Пример #27
0
        public void MyMethod1()
        {
            logger.Trace("Sample trace message");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");

            // alternatively you can call the Log() method
            // and pass log level as the parameter.
            logger.Log(LogLevel.Info, "Sample informational message");


            // Example of logging an exception
            try
            {
            }
            catch (Exception ex)
            {
                logger.Error(ex, "ow noos!"); // render the exception with ${exception}
                throw;
            }
        }
Пример #28
0
        private bool ApplicationInit()
        {
            Logger.Trace("=== Application loader start ===");
            var config = ApplicationSection.Get();

            RestartInterval = new TimeSpan(config.Timer / 60, config.Timer % 60, 0);
            Logger.Debug("Restart interval is set on {0} minutes", RestartInterval.TotalMinutes);

            Emails = config.Email.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            if (Directory.Exists(config.Path))
            {
                ExtensionPath = new Uri(config.Path);
                Logger.Debug("Extension path found on {0}", ExtensionPath.AbsolutePath);
            }
            else
            {
                ExtensionPath = new Uri(Directory.GetCurrentDirectory());
                Logger.Error("Extension path not found on {0}", config.Path);
                return(false);
            }
            Logger.Debug("=== Application loader end ===");
            return(true);
        }
Пример #29
0
        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connectionString);
            Form1 form1 = new Form1();

            NLog.Logger logger = LogManager.GetCurrentClassLogger();



            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    sb.UserID         = textBox1.Text;
                    sb.Password       = textBox2.Text;
                    conn.StateChange += connection_StateChange;
                    conn.Open();
                    MessageBox.Show("Logined");
                    conn.Close();
                    MessageBox.Show("Connection closed");
                    this.Hide();
                    form1.ShowDialog();
                }
                catch
                {
                    logger.Trace("UserId" + sb.UserID);
                    logger.Debug("Passsword" + sb.Password);
                    logger.Info("DataSource" + sb.DataSource);
                    logger.Info("DataSource" + sb.InitialCatalog);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
Пример #30
0
 /// <summary>
 /// 创建由 numConnections 指定数目的数据库连接 , 并把这些连接 放入 m_Pooledconnections
 /// </summary>
 /// <param name="numConnections"></param>
 private void CreateConnections(int numConnections)
 {
     // 循环创建指定数目的数据库连接
     for (int x = 0; x < numConnections; x++)
     {
         if (this._maxConnections > 0 && this._mPooledconnections.Count >= this._maxConnections)
         {
             _logger.Trace($"连接数已经达到最大值无法追加.");
             break;
         }
         _logger.Trace($"追加了 1 个连接.");
         try
         {
             MySqlConnection tmpConnect = NewConnection();
             _mPooledconnections.Add(new PooledConnection(ref tmpConnect));
         }
         catch (Exception ex)
         {
             _logger.Error(ex, $"追加连接 {x + 1} 异常");
             throw ex;
         }
     }
 }
Пример #31
0
 private void ProcessRequest(object sender, TcpRequest req)
 {
     Logger.Trace("Begin ProcessRequest");
     Logger.Info("Requested command: {0}", req.PlayerRequest);
     if (!req.ResponseRequired)
     {
         _commandDictionary[(int)req.PlayerRequest].DynamicInvoke(req.Arguments);
         return;
     }
     try
     {
         var res = _commandDictionary[(int)req.PlayerRequest].DynamicInvoke(req.Arguments);
         _mbTcpHelper.SendResponse(req.PlayerRequest, res);
     }
     catch (Exception e)
     {
         Logger.Error(e, "Sending response failed");
     }
     Logger.Trace("End ProcessRequest");
 }
Пример #32
0
        public string MigrateVirtualMachine(MigrationVM virtualMachine)
        {
            MigrationVMDetail vmDetail = new MigrationVMDetail(virtualMachine, this);

            if (!vmDetail.Verified)
            {
                Logger.Error("{0}: Skipped: Verify Failed", virtualMachine.Name);
                return("skipped-verifyfailed");
            }

            try {
                VirtualMachineRelocateSpec vmRelocSpec = GetRelocationSpec(vmDetail);
                if (vmRelocSpec != null)
                {
                    Logger.Info("==========================================");
                    Logger.Info("Migrating {0} to {1}{2}", virtualMachine.Name, vmDetail.DestinationClusterComputeResource?.Name, vmDetail.DestinationHostSystem?.Name);
                    Logger.Info("Migrating {0} storage to {1}{2}", virtualMachine.Name, vmDetail.DestinationDatastore?.Name, vmDetail.DestinationStoragePod?.Name);
                    if (vmRelocSpec.DeviceChange?.Count() > 0)
                    {
                        foreach (var deviceChange in vmRelocSpec.DeviceChange)
                        {
                            Logger.Info("Migrating networking to {@0}", deviceChange);
                        }
                    }
                    Logger.Info("==========================================");

                    return(((VirtualMachine)GetViewByName <VirtualMachine>(virtualMachine.Name))
                           .RelocateVM_Task(vmRelocSpec, VirtualMachineMovePriority.highPriority).ToString());
                }
            }
            catch (Exception e)
            {
                Logger.Error("EXCEPTION: {0}", e.Message);
                Logger.Error("EXCEPTION: {0}", e.StackTrace);
                throw;
            }

            Logger.Trace("return null {@value}", vmDetail);
            return(null);
        }
Пример #33
0
        public override bool SupportedProtocol(string protocol)
        {
            logger.Trace("SupportedProtocol");
            OnSupportedProtocolEvent(protocol);

            protocol = protocol.ToLower();
            if (protocol == "http")
            {
                return(true);
            }

            return(false);
        }
Пример #34
0
 /// <summary>
 /// Raises the <see cref="E:Navigating" /> event.
 /// </summary>
 /// <param name="e">The <see cref="WebDriverNavigationEventArgs"/> instance containing the event data.</param>
 protected override void OnNavigating(WebDriverNavigationEventArgs e)
 {
     Logger.Trace(CultureInfo.CurrentCulture, "Navigating to: {0}", e.Url);
     base.OnNavigating(e);
 }
Пример #35
0
 /// <summary>
 /// Logs a message at the TRACE level.
 /// </summary>
 /// <param name="Message">The message to log</param>
 public void Trace(string Message)
 {
     LoggerImpl.Trace(Message);
 }
Пример #36
0
 public void Trace <T>(T value)
 {
     _logger.Trace(value);
 }
Пример #37
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="msg"></param>
 public static void Trace(string msg)
 {
     logger.Trace(msg);
 }
Пример #38
0
 public void Trace(string msg, params object[] args)
 {
     _logger.Trace(msg, args);
     //LogManager.Shutdown();
 }
Пример #39
0
        // Конструктор класса. Ему нужно передавать принятого клиента от TcpListener
        public Client(Logger log, TcpClient client)
        {
            _log = log;
            _log.Trace("Init client");

            // Объявим строку, в которой будет хранится запрос клиента
            string request = "";
            // Буфер для хранения принятых от клиента данных
            byte[] buffer = new byte[1024];
            // Переменная для хранения количества байт, принятых от клиента
            int count;

            _log.Trace("Read request");
            // Читаем из потока клиента до тех пор, пока от него поступают данные
            while ((count = client.GetStream().Read(buffer, 0, buffer.Length)) > 0)
            {
                // Преобразуем эти данные в строку и добавим ее к переменной Request
                request += Encoding.ASCII.GetString(buffer, 0, count);
                // Запрос должен обрываться последовательностью \r\n\r\n
                // Либо обрываем прием данных сами, если длина строки Request превышает 4 килобайта
                // Нам не нужно получать данные из POST-запроса (и т. п.), а обычный запрос
                // по идее не должен быть больше 4 килобайт
                if (request.IndexOf("\r\n\r\n", StringComparison.Ordinal) >= 0 || request.Length > 4096)
                {
                    break;
                }
            }

            _log.Trace("Request match");
            // Парсим строку запроса с использованием регулярных выражений
            // При этом отсекаем все переменные GET-запроса
            Match reqMatch = Regex.Match(request, @"^\w+\s+([^\s\?]+)[^\s]*\s+HTTP/.*|");

            // Если запрос не удался
            if (reqMatch == Match.Empty)
            {
                // Передаем клиенту ошибку 400 - неверный запрос
                _log.Warn(HttpStatusCode.BadRequest + ": " + request);
                SendError(client, HttpStatusCode.BadRequest);
                return;
            }

            _log.Trace("Get request Uri");
            // Получаем строку запроса
            string requestUri = reqMatch.Groups[1].Value;

            _log.Trace("Unescape request Uri");
            // Приводим ее к изначальному виду, преобразуя экранированные символы
            // Например, "%20" -> " "
            requestUri = Uri.UnescapeDataString(requestUri);

            // Если в строке содержится двоеточие, передадим ошибку 400
            // Это нужно для защиты от URL типа http://example.com/../../file.txt
            if (requestUri.IndexOf("..", StringComparison.Ordinal) >= 0)
            {
                _log.Warn(HttpStatusCode.BadRequest + ": " + request);
                SendError(client, HttpStatusCode.BadRequest);
                return;
            }

            if (string.IsNullOrEmpty(requestUri))
            {
                requestUri += "/";
            }

            // Если строка запроса оканчивается на "/", то добавим к ней index.html
            if (requestUri.EndsWith("/"))
            {
                requestUri += "index.html";
            }

            string filePath;
            if (Settings.IsSite)
            {
                filePath = Settings.Folder + requestUri;
            }
            else
            {
                string fileName;
                try
                {
                    fileName = Path.GetFileName(requestUri);
                }
                catch (Exception)
                {
                    _log.Warn(HttpStatusCode.BadRequest + ": " + request);
                    SendError(client, HttpStatusCode.BadRequest);
                    return;
                }

                if (!Settings.Files.TryGetValue(fileName, out filePath))
                {
                    log.Warn(HttpStatusCode.Forbidden + ": " + request);
                    SendError(client, HttpStatusCode.Forbidden);
                    return;
                }
            }

            // Если в папке www не существует данного файла, посылаем ошибку 404
            if (!File.Exists(filePath))
            {
                _log.Warn(HttpStatusCode.NotFound + ": " + request + " => " + filePath);
                SendError(client, HttpStatusCode.NotFound);
                return;
            }

            _log.Trace("Get Mime type");
            // Тип содержимого
            string contentType = MimeTypes.GetMimeType(requestUri);

            _log.Trace("Read file from drive");
            // Открываем файл, страхуясь на случай ошибки
            FileStream fs;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (Exception)
            {
                // Если случилась ошибка, посылаем клиенту ошибку 500
                _log.Warn(HttpStatusCode.InternalServerError + ": " + request + " => " + filePath);
                SendError(client, HttpStatusCode.InternalServerError);
                return;
            }

            _log.Trace("Create response");
            try
            {
                // Посылаем заголовкиy
                string headers = "HTTP/1.1 200 OK\nContent-Type: " + contentType + "\nContent-Length: " + fs.Length + "\n\n";
                byte[] headersBuffer = Encoding.ASCII.GetBytes(headers);
                client.GetStream().Write(headersBuffer, 0, headersBuffer.Length);

                // Пока не достигнут конец файла
                while (fs.Position < fs.Length)
                {
                    // Читаем данные из файла
                    count = fs.Read(buffer, 0, buffer.Length);
                    // И передаем их клиенту
                    client.GetStream().Write(buffer, 0, count);
                }

            }
            catch (Exception ex)
            {
                _log.Trace(ex, "Failed to create response");
            }
            finally
            {
                // Закроем файл и соединение
                fs.Close();
                try
                {
                    client.Close();
                }
                catch (Exception ignore)
                {
                }

            }

            _log.Info(HttpStatusCode.OK + ": " + request + " => " + filePath);
        }
Пример #40
0
 private static void DoWrite(Logger logger, LogLevel level, string message)
 {
     switch (level)
     {
         case LogLevel.Debug:
             logger.Debug(message);
             break;
         case LogLevel.Info:
             logger.Info(message);
             break;
         case LogLevel.Trace:
             logger.Trace(message);
             break;
         case LogLevel.Error:
         default:
             logger.Error(message);
             break;
     }
 }
        private void VerifyMessagesInMockChannel(Logger aiLogger, string instrumentationKey)
        {
            aiLogger.Trace("Sample trace message");
            aiLogger.Debug("Sample debug message");
            aiLogger.Info("Sample informational message");
            aiLogger.Warn("Sample warning message");
            aiLogger.Error("Sample error message");
            aiLogger.Fatal("Sample fatal error message");

            AdapterHelper.ValidateChannel(this.adapterHelper, instrumentationKey, 6);
        }
        /// <summary>
        ///     thực hienj việc load thông tin của Form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frm_quanlycacphongchucnang_Load(object sender, EventArgs e)
        {
            //SearchFormRadio();
            //RoleConfigUserRadio();
            InitData();

            ModifyCommand();
            log = LogManager.GetCurrentClassLogger();

            log.Trace("Form Load OK");
            TabInfo.SelectedTab = tabDanhsach;
            txtMaluotkham.Focus();
            txtMaluotkham.SelectAll();

            //  cmdSearchListRadio.PerformClick();
        }
Пример #43
0
        private void HandleEventSet(Event ev)
        {
            var type = ev.EventType;

            _engine.IsSuspended = true;

            logger.Trace($"HandleEventSet: {ev}");

            try
            {
                switch (type)
                {
                case EventType.AssemblyLoad:
                    HandleAssemblyLoad((AssemblyLoadEvent)ev);
                    break;

                case EventType.UserBreak:
                    if (!HandleUserBreak((UserBreakEvent)ev))
                    {
                        return;
                    }
                    break;

                case EventType.Breakpoint:
                    if (!HandleBreakPoint((BreakpointEvent)ev))
                    {
                        return;
                    }
                    break;

                case EventType.Step:
                    HandleStep((StepEvent)ev);
                    return;

                case EventType.TypeLoad:
                    var typeEvent = (TypeLoadEvent)ev;
                    RegisterType(typeEvent.Type);
                    TryBindBreakpoints();
                    break;

                case EventType.UserLog:
                    UserLogEvent e = (UserLogEvent)ev;
                    HostOutputWindowEx.WriteLaunchError(e.Message);
                    break;

                case EventType.VMDeath:
                case EventType.VMDisconnect:
                    Disconnect();
                    return;

                case EventType.VMStart:
                case EventType.ThreadStart:
                    var domain    = ev.Thread.Domain.FriendlyName;
                    var threadId  = ev.Thread.ThreadId;
                    var newThread = new AD7Thread(_engine, ev.Thread);
                    if (_threads.TryAdd(threadId, newThread))
                    {
                        _engine.Callback.ThreadStarted(newThread);
                    }
                    else
                    {
                        logger.Error($"Thread {threadId} already added!");
                    }
                    break;

                case EventType.ThreadDeath:
                    var       oldThreadId = ev.Thread.ThreadId;
                    AD7Thread oldThread   = null;
                    if (!_threads.TryRemove(oldThreadId, out oldThread))
                    {
                        _engine.Callback.ThreadDestroyed(oldThread, 0);
                    }
                    else
                    {
                        logger.Error($"Thread {oldThreadId} not found!");
                    }
                    break;

                case EventType.Exception:
                    var exEvent = ev as ExceptionEvent;
                    var exceptionObjectMirror = exEvent.Exception;
                    // TODO Reading properties from complex exceptions throws an exception. Why?
                    var filter = MonoProperty.EnumOnlyFieldsFilter;
                    IEnumDebugPropertyInfo2 propInfo;
                    var monoProperty = new MonoProperty(exEvent.Thread.GetFrames().FirstOrDefault(), exceptionObjectMirror);
                    var propInfo1    = new DEBUG_PROPERTY_INFO[1];
                    monoProperty.GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ALL, 0, 10000, null, 0, propInfo1);
                    monoProperty.EnumChildren(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ALL, 0, ref filter, enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_ACCESS_ALL, "", 10000, out propInfo);
                    var sbException = new StringBuilder();
                    sbException.AppendLine($"Excption thrown: {exceptionObjectMirror.Type.FullName}");
                    var propInfoCast = propInfo as AD7PropertyEnum;
                    foreach (var prop in propInfoCast.GetData())
                    {
                        if (prop.bstrName.StartsWith("_message") || prop.bstrName.StartsWith("_innerException"))
                        {
                            sbException.AppendLine($"{prop.bstrName} = {prop.bstrValue}");
                        }
                    }
                    logger.Error($"Exception thrown: {sbException.ToString()}");
                    HostOutputWindowEx.WriteLaunchError($"Exception thrown: {sbException.ToString()}");
                    break;

                default:
                    logger.Trace(ev);
                    break;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"Exception thrown in {nameof(HandleEventSet)}({ev})");
            }

            try
            {
                if (type != EventType.VMStart)
                {
                    logger.Trace($"HandleEventSet: ResumeVM ({ev})");
                    ResumeVM();
                }
            }
            catch (VMNotSuspendedException)
            {
                if (type != EventType.VMStart && _vm.Version.AtLeast(2, 2))
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Пример #44
0
        static void Main(string[] args)
        {
            DisplayMenu(true);
            string MSelection = Console.ReadLine().Trim();
            string LSelection = "";

            logger.Debug("Starting application");

            do
            {
                // User search removed to Notepad for easier look at Ticket
                if (MSelection == "1")
                {
                    Console.WriteLine("Thank you for participating");
                    Console.WriteLine();
                }
                else if (MSelection == "2") // Tickets
                {
                    logger.Debug("Ticket Records Accessed)");

                    TicketMenu();
                    LSelection = Console.ReadLine().Trim();
                    do
                    {
                        if (LSelection == "1") // Display Ticket Records
                        {
                            logger.Debug("Searching Ticket Records");

                            Console.WriteLine("You chose Display Tickets");
                            int tCount = 0;

                            Console.WriteLine("Enter ticket summary information to search");
                            string entry = Console.ReadLine();

                            using (var dbContext = new TicketContext())
                            {
                                var results = dbContext.Tickets
                                              .Include(x => x.WatchingUsers.Select(u => u.User))
                                              .Include(t => t.TicketType)
                                              .Where(d => d.Summary.Contains(entry))
                                              .ToList();

                                foreach (var record in results)
                                {
                                    tCount++;

                                    if (tCount % 20 == 0)
                                    {
                                        Console.WriteLine("Display more records? y/n");
                                        string continueDisp = Console.ReadLine();
                                        if (continueDisp.ToUpper() == "N")
                                        {
                                            break;
                                        }
                                    }
                                    record.DisplayTickets();
                                }
                            }
                            logger.Info("{0} was search, {1} returned", entry, tCount);
                            Console.WriteLine();
                            Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
                            Console.WriteLine();
                            break;
                        }
                        else if (LSelection == "2") // Add
                        {
                            logger.Debug("New Ticket Record");

                            Console.WriteLine("Enter a summary");
                            var    sum      = Console.ReadLine();
                            var    priority = "";
                            string stats;
                            var    valid = false;

                            // determine ticket priority
                            do
                            {
                                TicketPriority();
                                priority = Console.ReadLine();
                                if (priority.Trim() == "1")
                                {
                                    priority = "Low";
                                    logger.Debug("Priority Added");
                                    valid = true;
                                }
                                else if (priority.Trim() == "2")
                                {
                                    priority = "Medium";
                                    logger.Debug("Priority Added");
                                    valid = true;
                                }
                                else if (priority.Trim() == "3")
                                {
                                    priority = "High";
                                    logger.Debug("Priority Added");
                                    valid = true;
                                }
                                else
                                {
                                    Console.WriteLine("Bad Input");
                                    break;
                                }
                            } while (valid == false);

                            // determine ticket status
                            do
                            {
                                TicketStatus();
                                stats = Console.ReadLine();

                                if (stats.Trim() == "1")
                                {
                                    stats = "Open";
                                    logger.Debug("Status Added");
                                    valid = true;
                                }
                                else if (stats.Trim() == "2")
                                {
                                    stats = "Closed";
                                    logger.Debug("Status Added");
                                    valid = true;
                                }
                                else
                                {
                                    Console.WriteLine("Bad input");
                                    break;
                                }
                            } while (valid == false);

                            using (var dbContext = new TicketContext())
                            {
                                var record = new Ticket();

                                record.Summary  = sum;
                                record.Priority = priority;
                                record.Status   = stats;

                                TicketType typeCheck = null;

                                // determine ticket type
                                TicketTypeMenu();
                                var ttype = Console.ReadLine();
                                do
                                {
                                    if (ttype == "1")
                                    {
                                        ttype             = "Enhancement";
                                        typeCheck         = dbContext.TicketTypes.Where(t => t.Description == ttype).SingleOrDefault();
                                        record.TicketType = typeCheck;
                                        logger.Debug("Ticket Type Generated: {0}", ttype);
                                    }
                                    else if (ttype == "2")
                                    {
                                        ttype             = "Bug";
                                        typeCheck         = dbContext.TicketTypes.Where(t => t.Description == ttype).SingleOrDefault();
                                        record.TicketType = typeCheck;
                                        logger.Debug("Ticket Type Generated: {0}", ttype);
                                    }
                                    else if (ttype == "3")
                                    {
                                        ttype             = "Task";
                                        typeCheck         = dbContext.TicketTypes.Where(t => t.Description == ttype).SingleOrDefault();
                                        record.TicketType = typeCheck;
                                        logger.Debug("Ticket Type Generated: {0}", ttype);
                                    }
                                    else if (ttype == "4")
                                    {
                                        // ensure that ticket type is actually new
                                        do
                                        {
                                            Console.WriteLine("Enter name of new ticket type to create");
                                            ttype     = Console.ReadLine();
                                            typeCheck = dbContext.TicketTypes.Where(t => t.Description == ttype).SingleOrDefault();
                                        } while (typeCheck != null);
                                        var tt = new TicketType();
                                        tt.Description = ttype;

                                        // ensure that new ticket type was added to database
                                        var attempt = 0;
                                        while (attempt < 5)
                                        {
                                            do
                                            {
                                                typeCheck = dbContext.TicketTypes.Where(t => t.Description == ttype).SingleOrDefault();
                                            } while (typeCheck == null);
                                            attempt++;
                                        }
                                        if (typeCheck != null)
                                        {
                                            record.TicketType = typeCheck;
                                        }
                                        else
                                        {
                                            Console.WriteLine("Ticket Type could not be added to database, type defaulted to Task");
                                            ttype             = "Task";
                                            typeCheck         = dbContext.TicketTypes.Where(t => t.Description == ttype).SingleOrDefault();
                                            record.TicketType = typeCheck;
                                        }
                                    }
                                    else
                                    {
                                    }
                                } while (valid == false);

                                Console.WriteLine("Enter the user ID of the submitter");
                                var sUser = Console.ReadLine();

                                // validate userID
                                int subUser = 0;
                                while (!int.TryParse(sUser, out subUser))
                                {
                                    Console.WriteLine("Enter the numerical user ID");
                                    sUser = Console.ReadLine();
                                    logger.Debug("Invalid UserID");
                                }
                                var user = dbContext.Users.Where(u => u.UserID == subUser).FirstOrDefault();

                                // ensure user in database
                                while (user == null)
                                {
                                    Console.WriteLine("Enter a valid User ID");
                                    subUser = Convert.ToInt32(Console.ReadLine());
                                    user    = dbContext.Users.Where(u => u.UserID == subUser).FirstOrDefault();
                                }

                                if (user != null)
                                {
                                    User u = new User();
                                    u.UserID = subUser;

                                    // add an submitter and create WatchingUser item
                                    record.Submitter = u.UserID;
                                    record.WatchingUsers.Add(new WatchingUser {
                                        UserID = u.UserID
                                    });
                                }
                                string addUser = "";
                                do
                                {
                                    Console.WriteLine("Enter a user ID - when finished enter 'end'");
                                    addUser = Console.ReadLine();

                                    if (addUser != "end")
                                    {
                                        int aUser = 0;

                                        // validate userID
                                        while (!int.TryParse(addUser, out aUser))
                                        {
                                            Console.WriteLine("Enter the numerical user ID of the submitter");
                                            addUser = Console.ReadLine();
                                            logger.Debug("Invalid UserID");
                                        }

                                        user = dbContext.Users.Where(u => u.UserID == aUser).FirstOrDefault();

                                        // ensure user in database
                                        while (user == null)
                                        {
                                            Console.WriteLine("Enter valid User ID");
                                            aUser = Convert.ToInt32(Console.ReadLine());
                                            user  = dbContext.Users.Where(u => u.UserID == aUser).FirstOrDefault();
                                        }
                                        if (user != null)
                                        {
                                            User u = new User();
                                            u.UserID = aUser;

                                            // add an assigned user and create a new WatchingUser item
                                            record.Assigned = u.UserID;
                                            record.WatchingUsers.Add(new WatchingUser {
                                                UserID = u.UserID
                                            });
                                        }
                                    }
                                } while (addUser != "end");

                                dbContext.Tickets.Add(record);
                                dbContext.SaveChanges();
                                logger.Info("Ticket {0} was created", record.TicketID);
                            }

                            Console.WriteLine();
                            Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
                            Console.WriteLine();
                            break;
                        }
                        else if (LSelection == "3") // Update
                        {
                            logger.Debug("Updating Ticket Record");
                            Console.WriteLine("Enter search term for ticket to update");
                            var entry = Console.ReadLine();
                            using (var dbContext = new TicketContext())
                            {
                                var results = dbContext.Tickets
                                              .Include(x => x.WatchingUsers.Select(u => u.User))
                                              .Include(t => t.TicketType)
                                              .Where(d => d.Summary.Contains(entry))
                                              .ToList();

                                int tCount = 0;
                                foreach (var record in results)
                                {
                                    tCount++;

                                    if (tCount % 20 == 0)
                                    {
                                        Console.WriteLine("Display more records? y/n");
                                        string continueDisp = Console.ReadLine();
                                        if (continueDisp.ToUpper() == "N")
                                        {
                                            break;
                                        }
                                    }
                                    record.DisplayTickets();
                                }

                                //ensure TicketID in db
                                var valid = false;
                                Console.WriteLine("Enter the TicketID of the ticket to update");
                                string tID = Console.ReadLine();
                                int    tIDint;
                                do
                                {
                                    while (!int.TryParse(tID, out tIDint))
                                    {
                                        Console.WriteLine("Enter the numerical TicketID of the ticket to update");
                                        tID = Console.ReadLine();
                                        logger.Debug("Invalid data type TicketID");
                                    }
                                    var ticket = dbContext.Tickets.Where(t => t.TicketID == tIDint).FirstOrDefault();
                                    if (ticket != null)
                                    {
                                        valid           = true;
                                        ticket.TicketID = tIDint;
                                        logger.Debug("Updating Ticket Record {0}", tIDint);
                                        // New Priority
                                        do
                                        {
                                            TicketPriority();
                                            var newPrior = Console.ReadLine();

                                            if (newPrior.Trim() == "1")
                                            {
                                                newPrior        = "Low";
                                                ticket.Priority = newPrior;
                                                valid           = true;
                                                logger.Debug("Priority Updated");
                                            }
                                            else if (newPrior.Trim() == "2")
                                            {
                                                newPrior        = "Medium";
                                                ticket.Priority = newPrior;
                                                valid           = true;
                                                logger.Debug("Priority Updated");
                                            }
                                            else if (newPrior.Trim() == "3")
                                            {
                                                newPrior        = "High";
                                                ticket.Priority = newPrior;
                                                valid           = true;
                                                logger.Debug("Priority Updated");
                                            }
                                            else
                                            {
                                                Console.WriteLine("Bad input");
                                                Console.WriteLine();
                                                valid = false;
                                            }
                                        } while (valid == false);

                                        // New Status
                                        do
                                        {
                                            TicketStatus();
                                            var newStat = Console.ReadLine();

                                            if (newStat.Trim() == "1")
                                            {
                                                newStat       = "Open";
                                                ticket.Status = newStat;
                                                valid         = true;
                                                logger.Debug("Status Updated");
                                            }
                                            else if (newStat.Trim() == "2")
                                            {
                                                newStat       = "Closed";
                                                ticket.Status = newStat;
                                                valid         = true;
                                                logger.Debug("Status Updated");
                                            }
                                            else
                                            {
                                                Console.WriteLine("Bad input");
                                                Console.WriteLine();
                                                valid = false;
                                            }
                                        } while (valid == false);

                                        // Add new Assigned and WatchingUsers
                                        string addUser = "";
                                        do
                                        {
                                            Console.WriteLine("Enter a user ID - when finished enter 'end'");
                                            addUser = Console.ReadLine();

                                            if (addUser != "end")
                                            {
                                                int aUser = 0;

                                                // validate userID
                                                while (!int.TryParse(addUser, out aUser))
                                                {
                                                    Console.WriteLine("Enter the numerical user ID of the submitter");
                                                    addUser = Console.ReadLine();
                                                    logger.Debug("Invalid UserID");
                                                }

                                                var user = dbContext.Users.Where(u => u.UserID == aUser).FirstOrDefault();
                                                // ensure user in database
                                                while (user == null)
                                                {
                                                    Console.WriteLine("Enter a valid user ID");
                                                    aUser = Convert.ToInt32(Console.ReadLine());
                                                    user  = dbContext.Users.Where(u => u.UserID == aUser).FirstOrDefault();
                                                }

                                                if (user != null)
                                                {
                                                    User u = new User();
                                                    u.UserID = aUser;

                                                    // add an assigned user and create a new WatchingUser item
                                                    ticket.Assigned = u.UserID;
                                                    ticket.WatchingUsers.Add(new WatchingUser {
                                                        UserID = u.UserID
                                                    });
                                                }
                                            }
                                        } while (addUser != "end");

                                        // save changes
                                        dbContext.SaveChanges();
                                        Console.WriteLine("You updated {0}", tID);
                                        logger.Trace("Ticket {0} was updated", tID);
                                    }
                                    else
                                    {
                                        valid = false;
                                    }
                                } while (valid == false);
                            }

                            Console.WriteLine();
                            Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
                            Console.WriteLine();
                            break;
                        }

                        else if (LSelection == "4") // Exit
                        {
                            return;
                        }
                        else
                        {
                            Console.WriteLine("Bad Input");
                            Console.WriteLine();
                            break;
                        }
                    } while (LSelection != "4");
                }
                else if (MSelection == "3") // Exit
                {
                    return;
                }
                else
                {
                    Console.WriteLine("Bad Input");
                    Console.WriteLine();
                    break;
                }
                DisplayMenu(false);
                MSelection = Console.ReadLine().Trim();
            } while (MSelection != "3");
            return;
        }
Пример #45
0
 /// <summary>
 /// Simple Constructor
 /// </summary>
 public MathSolver()
 {
     logger = LogManager.GetCurrentClassLogger();
     logger.Trace("Constructor Called");
 }
Пример #46
0
 public LogWrapper(string str)
 {
     logger = LogManager.GetCurrentClassLogger();
     infoString = str;
     logger.Trace("Begin " + infoString);
 }
 public ActionResult InsertDataChiDinhKn(KnChidinhXn objChidinh, KnDangkyXn objLuotkham, KnChidinhChitiet[] arrAssignDetails)
 {
     try
     {
         using (var scope = new TransactionScope())
         {
             using (var sh = new SharedDbConnectionScope())
             {
                 if (objChidinh != null)
                 {
                     log.Trace("BEGIN INSERTING..........................................................");
                     if (objLuotkham == null)
                     {
                         log.Trace("Lieu co the vao day duoc khong..........................................................");
                         objLuotkham = new Select().From(KnDangkyXn.Schema)
                                       .Where(KnDangkyXn.Columns.MaDangky).IsEqualTo(objChidinh.MaDangky)
                                       .And(KnDangkyXn.Columns.IdKhachhang).IsEqualTo(
                             Utility.Int32Dbnull(objChidinh.IdKhachhang)).ExecuteSingle <KnDangkyXn>();
                     }
                     if (objLuotkham != null)
                     {
                         log.Trace("0.1. Bat dau sinh code");
                         objChidinh.MaChidinh = THU_VIEN_CHUNG.SinhMaChidinhKiemNghiem();
                         log.Trace("0.2. Bat dau them moi chi dinh CLS");
                         objChidinh.NgayTao  = globalVariables.SysDate;
                         objChidinh.NguoiTao = globalVariables.UserName;
                         objChidinh.IsNew    = true;
                         objChidinh.Save();
                         log.Trace("0.3 Da thuc hien xong cau SP");
                         log.Trace("1. Da them moi chi dinh CLS");
                         foreach (var knChidinhChitiet in arrAssignDetails)
                         {
                             if (knChidinhChitiet.IdChidinhChitiet <= 0)
                             {
                                 log.Info("1.2 Bat dau them moi Id_chidinh=" + objChidinh.IdChidinh + "timeprocess in : " + globalVariables.SysDate.ToString());
                                 var sp =
                                     SPs.KnThemmoiChitietChidinh(knChidinhChitiet.IdChidinhChitiet,
                                                                 objChidinh.IdChidinh, objChidinh.MaChidinh,
                                                                 knChidinhChitiet.IdDichvu
                                                                 , knChidinhChitiet.IdChitietdichvu, knChidinhChitiet.DonGia,
                                                                 knChidinhChitiet.PhuThu, knChidinhChitiet.SoLuong,
                                                                 knChidinhChitiet.Donvi, knChidinhChitiet.PpKiemnghiem,
                                                                 knChidinhChitiet.Qcvn,
                                                                 knChidinhChitiet.ThanhTien, knChidinhChitiet.NgayNhapmau,
                                                                 knChidinhChitiet.Ketqua, knChidinhChitiet.NgaynhapKetqua,
                                                                 knChidinhChitiet.NguoinhapKq, knChidinhChitiet.TrangthaiThanhtoan,
                                                                 Utility.ByteDbnull(knChidinhChitiet.TrangThai),
                                                                 knChidinhChitiet.ChitieuPhantich, knChidinhChitiet.MahoaMau,
                                                                 knChidinhChitiet.NguoiTao, knChidinhChitiet.NgayTao,
                                                                 knChidinhChitiet.NguoiSua, knChidinhChitiet.NgaySua,
                                                                 knChidinhChitiet.IpMaytao, knChidinhChitiet.IpMaysua);
                                 sp.Execute();
                                 knChidinhChitiet.IdChidinhChitiet = Utility.Int64Dbnull(sp.OutputValues[0]);
                                 knChidinhChitiet.MahoaMau         = Utility.sDbnull(sp.OutputValues[1]);
                                 log.Info("1.3 ket thuc them moi Id_chidinh=" + objChidinh.IdChidinh + "timeprocess out: " + globalVariables.SysDate.ToString());
                             }
                         }
                         log.Trace("2. Da them moi chi tiet chi dinh CLS");
                     }
                     else
                     {
                         return(ActionResult.Error);
                     }
                 }
             }
             scope.Complete();
             log.Trace("FINISH INSERTING..........................................................");
             return(ActionResult.Success);
         }
     }
     catch (Exception exception)
     {
         log.Error(string.Format("Loi khi them moi chi dinh dich vu CLS {0}", exception.Message));
         return(ActionResult.Error);
     }
     finally
     {
         GC.Collect();
     }
 }
Пример #48
0
 public void Trace(string msg, params object[] args)
 {
     _logger.Trace(msg, args);
 }
Пример #49
0
 public void Trace(string message)
 {
     logger.Trace(message);
 }
 public IEnumerable <User> Get()
 {
     logger.Trace("Get all users!");
     return(um.GetAll);
 }
 public void Trace <T>(T message)
 {
     Logger.Trace(message);
 }
 public MethodLogger(Logger logger, string methodName)
 {
     _logger = logger;
     _methodName = methodName;
     _logger.Trace(methodName + " - Entered");
     _sw = Stopwatch.StartNew();
 }