コード例 #1
0
ファイル: VHallConfig.cs プロジェクト: yjcrab777/Sheep.VHall
 public VHallConfig GetConfig()
 {
     ConfiguratorManager manager = new ConfiguratorManager();
     XmlConfigurator configurator = new XmlConfigurator(manager);
     Kernel.Configuration.XmlSerializer serializer = new Kernel.Configuration.XmlSerializer(manager);
     return manager.Get<VHallConfig>(configurator);
 }
コード例 #2
0
 public Startup(IConfiguration configuration)
 {
     Configuration    = configuration;
     loggerRepository = LogManager.CreateRepository(Log4NetConfig.RepositoryName);
     XmlConfigurator.ConfigureAndWatch(loggerRepository, new System.IO.FileInfo("Config/Log4net.config"));
 }
コード例 #3
0
ファイル: Logger.cs プロジェクト: fsjal/FFmpeg-Old
 static Logger()
 {
     XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetEntryAssembly()), new FileInfo(ConfigFile));
 }
コード例 #4
0
 protected override void Configure(Dictionary <string, string> defaultProperties)
 {
     XmlConfigurator.Configure();
     base.Configure(defaultProperties);
     defaultProperties.Add("priority", 2.ToString());
 }
コード例 #5
0
        public static void Main(string[] args)
        {
            var consoleTitle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.Title = consoleTitle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and assumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the ExecutingAssembly location
            var exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig            = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample     = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer   = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
            {
                File.Copy(log4netConfigContainer, log4netConfig, true);
            }

            var log4netFileInfo = new FileInfo("log4net.config");

            if (!log4netFileInfo.Exists)
            {
                log4netFileInfo = new FileInfo(log4netConfig);
            }

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }
                    }
                }
            }

            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
            {
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");
            }

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
            {
                log.Info("ACEmulator is running in a container...");
            }

            var configFile            = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
            {
                File.Copy(configConfigContainer, configFile, true);
            }

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                {
                    DoOutOfBoxSetup(configFile);
                }
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                    {
                        File.Copy(configConfigContainer, configFile);
                    }
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consoleTitle  = $"{ConfigManager.Config.Server.WorldName} | {consoleTitle}";
                Console.Title = consoleTitle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                {
                    AutoApplyWorldCustomizations();
                }
            }
            else
            {
                log.Info($"AutoUpdateWorldDatabase is disabled...");
            }

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
            {
                AutoApplyDatabaseUpdates();
            }
            else
            {
                log.Info($"AutoApplyDatabaseUpdates is disabled...");
            }

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
            {
                log.Info("Precaching World Database Disabled...");
            }

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0; i < 10; i++)
            {
                GC.Collect();
            }

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }
コード例 #6
0
        public JsonResult CreateMemo(HomeViewModel mod, string fileBase64)
        {
            XmlConfigurator.Configure();

            string bts; byte[] file;
            string fileType;

            if (fileBase64 == null || fileBase64 == "")
            {
                bts      = null;
                fileType = null;
            }
            else
            {
                if (fileBase64.Contains("application/msword"))
                {
                    bts = fileBase64.Remove(0, 31); fileType = fileBase64.Substring(0, 31);
                }
                else if (fileBase64.Contains("application/vnd"))
                {
                    bts = fileBase64.Remove(0, 84); fileType = fileBase64.Substring(0, 84);
                }
                else
                {
                    bts = fileBase64.Remove(0, 28); fileType = fileBase64.Substring(0, 28);
                }
                file = System.Convert.FromBase64String(bts);
            }

            CreateMemoModel mem  = new CreateMemoModel();
            CreateResponse  resp = new CreateResponse();

            mem.IRNumber         = mod.IRNo;
            mem.TransactionType  = mod.DebitCredit;
            mem.TransactionDate1 = mod.TransactionDate1;
            mem.TransactionDate2 = mod.TransactionDate2;
            mem.TransactionDate2 = mod.TransactionDate2;
            mem.Reason1          = (mod.WrongAmount).Equals(true) ? "WrongAmount" : null;
            mem.Reason2          = (mod.Erroneous).Equals(true) ? "Erroneous" : null;
            mem.Reason3          = (mod.SystemError).Equals(true) ? "SystemError" : null;
            mem.ReferenceNo1     = !String.IsNullOrEmpty(mod.refno1) ? mod.refno1 : null;
            mem.ReferenceNo2     = !String.IsNullOrEmpty(mod.refno2) ? mod.refno2 : null;
            mem.ReferenceNo3     = !String.IsNullOrEmpty(mod.refno3) ? mod.refno3 : null;
            mem.WalletUser       = mod.WalletUser;
            mem.WalletID         = mod.WalletID;
            mem.WrongAmount      = mod.IncorrectAmount;
            mem.CorrectAmount    = mod.CorrectAmount;
            mem.AdjustedAmount   = mod.AdjustAmount;
            mem.OperatorName     = Session["user"].ToString();
            mem.File             = bts;
            mem.FileType         = fileType;

            resp.data = mem;

            byte[] data       = UTF8Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(resp));
            var    source     = new System.Uri(service + "/CreateMemo");
            var    reqHandler = new RequestHandler("POST", source, "application/json", data);
            var    response   = reqHandler.HttpPostRequest();

            if (!response.Contains("200"))
            {
                log.Info(response.ToString());
                return(Json(new { status = "5000", msg = "System encountered an error. Please retry or contact admin." }));
            }
            else
            {
                resp = Newtonsoft.Json.JsonConvert.DeserializeObject <CreateResponse>(response);
                log.Info(JsonConvert.SerializeObject(resp, Formatting.None).ToString());
                return(Json(new { status = resp.ResponseCode, msg = resp.ResponsMessage }));
            }
        }
コード例 #7
0
ファイル: Logger.cs プロジェクト: belya0695/ElectronicCard
 static Logger()
 {
     log = LogManager.GetLogger("logger");
     XmlConfigurator.Configure();
 }
コード例 #8
0
 public static void Initialize(TestContext context)
 {
     XmlConfigurator.Configure(new FileInfo("log4net.config"));
 }
コード例 #9
0
 public void TestFixtureSetUp()
 {
     XmlConfigurator.Configure();
 }
コード例 #10
0
 public void XmlConfiguratorConfigureAndWatch(string configFile)
 {
     XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
 }
コード例 #11
0
 public void XmlConfiguratorConfigure()
 {
     XmlConfigurator.Configure();
 }
コード例 #12
0
        public static void Start(string[] args)
        {
            Program.args = args;
            Console.WriteLine(
                "If your error is about Microsoft.DirectX.DirectInput, please install the latest directx redist from here http://www.microsoft.com/en-us/download/details.aspx?id=35 \n\n");
            Console.WriteLine("Debug under mono    MONO_LOG_LEVEL=debug mono MissionPlanner.exe");
            Console.WriteLine("To fix any filename case issues under mono use    export MONO_IOMAP=drive:case");

            Console.WriteLine("Data Dir " + Settings.GetDataDirectory());
            Console.WriteLine("Log Dir " + Settings.GetDefaultLogDir());
            Console.WriteLine("Running Dir " + Settings.GetRunningDirectory());
            Console.WriteLine("User Data Dir " + Settings.GetUserDataDirectory());

            var t = Type.GetType("Mono.Runtime");

            MONO = (t != null);

            Thread = Thread.CurrentThread;

            System.Windows.Forms.Application.EnableVisualStyles();
            XmlConfigurator.Configure();
            log.Info("******************* Logging Configured *******************");

            ServicePointManager.DefaultConnectionLimit = 10;

            System.Windows.Forms.Application.ThreadException += Application_ThreadException;

            // fix ssl on mono
            ServicePointManager.ServerCertificateValidationCallback =
                new System.Net.Security.RemoteCertificateValidationCallback(
                    (sender, certificate, chain, policyErrors) => { return(true); });

            if (args.Length > 0 && args[0] == "/update")
            {
                Utilities.Update.DoUpdate();
                return;
            }

            name = "HMJ Technology";  //add yp HMJ Technology

            try
            {
                if (File.Exists(Settings.GetRunningDirectory() + "logo.txt"))
                {
                    name = File.ReadAllLines(Settings.GetRunningDirectory() + "logo.txt",
                                             Encoding.UTF8)[0];
                }
            }
            catch
            {
            }

            if (File.Exists(Settings.GetRunningDirectory() + "logo.png"))
            {
                Logo = new Bitmap(Settings.GetRunningDirectory() + "logo.png");
            }

            if (File.Exists(Settings.GetRunningDirectory() + "logo2.png"))
            {
                Logo2 = new Bitmap(Settings.GetRunningDirectory() + "logo2.png");
            }

            if (File.Exists(Settings.GetRunningDirectory() + "icon.png"))
            {
                // 128*128
                IconFile = new Bitmap(Settings.GetRunningDirectory() + "icon.png");
            }
            else
            {
                IconFile = MissionPlanner.Properties.Resources.mpdesktop.ToBitmap();
            }

            if (File.Exists(Settings.GetRunningDirectory() + "splashbg.png")) // 600*375
            {
                SplashBG = new Bitmap(Settings.GetRunningDirectory() + "splashbg.png");
            }

            try
            {
                var file = NativeLibrary.GetLibraryPathname("libSkiaSharp");
                var ptr  = NativeLibrary.LoadLibrary(file);
                if (ptr != IntPtr.Zero)
                {
                    log.Info("SkiaLoaded");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            Splash = new MissionPlanner.Splash();
            if (SplashBG != null)
            {
                Splash.BackgroundImage     = SplashBG;
                Splash.pictureBox1.Visible = false;
            }

            if (IconFile != null)
            {
                Splash.Icon = Icon.FromHandle(((Bitmap)IconFile).GetHicon());
            }

            string strVersion = File.Exists("version.txt")
                ? File.ReadAllText("version.txt")
                : System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Splash.Text = name + " V" + Application.ProductVersion;// + " build " + strVersion;
            Splash.Show();

            if (Debugger.IsAttached)
            {
                Splash.TopMost = false;
            }

            Application.DoEvents();
            Application.DoEvents();

            CustomMessageBox.ShowEvent += (text, caption, buttons, icon, yestext, notext) =>
            {
                return((CustomMessageBox.DialogResult)(int) MsgBox.CustomMessageBox.Show(text, caption,
                                                                                         (MessageBoxButtons)(int)buttons, (MessageBoxIcon)(int)icon, yestext, notext));
            };

            // setup theme provider
            MsgBox.CustomMessageBox.ApplyTheme                  += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            Controls.MainSwitcher.ApplyTheme                    += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            MissionPlanner.Controls.InputBox.ApplyTheme         += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            Controls.BackstageView.BackstageViewPage.ApplyTheme += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;

            Controls.MainSwitcher.Tracking += MissionPlanner.Utilities.Tracking.AddPage;
            Controls.BackstageView.BackstageView.Tracking += MissionPlanner.Utilities.Tracking.AddPage;

            // setup settings provider
            MissionPlanner.Comms.CommsBase.Settings       += CommsBase_Settings;
            MissionPlanner.Comms.CommsBase.InputBoxShow   += CommsBaseOnInputBoxShow;
            MissionPlanner.Comms.CommsBase.ApplyTheme     += MissionPlanner.Utilities.ThemeManager.ApplyThemeTo;
            MissionPlanner.Comms.SerialPort.GetDeviceName += SerialPort_GetDeviceName;

            // set the cache provider to my custom version
            GMap.NET.GMaps.Instance.PrimaryCache = new Maps.MyImageCache();
            // add my custom map providers
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.WMSProvider.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Custom.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Earthbuilder.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Statkart_Topo2.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Eniro_Topo.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.MapBox.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.MapboxNoFly.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.MapboxUser.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_Lake.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_1974.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_1979.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_1984.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_1988.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_Relief.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_Slopezone.Instance);
            GMap.NET.MapProviders.GMapProviders.List.Add(Maps.Japan_Sea.Instance);

            GoogleMapProvider.APIKey = "AIzaSyA5nFp39fEHruCezXnG3r8rGyZtuAkmCug";

            Tracking.productName               = Application.ProductName;
            Tracking.productVersion            = Application.ProductVersion;
            Tracking.currentCultureName        = Application.CurrentCulture.Name;
            Tracking.primaryScreenBitsPerPixel = Screen.PrimaryScreen.BitsPerPixel;
            Tracking.boundsWidth               = Screen.PrimaryScreen.Bounds.Width;
            Tracking.boundsHeight              = Screen.PrimaryScreen.Bounds.Height;

            Settings.Instance.UserAgent = Application.ProductName + " " + Application.ProductVersion + " (" + Environment.OSVersion.VersionString + ")";

            // optionally add gdal support
            if (Directory.Exists(Application.StartupPath + Path.DirectorySeparatorChar + "gdal"))
            {
                GMap.NET.MapProviders.GMapProviders.List.Add(GDAL.GDALProvider.Instance);
            }

            // add proxy settings
            GMap.NET.MapProviders.GMapProvider.WebProxy             = WebRequest.GetSystemWebProxy();
            GMap.NET.MapProviders.GMapProvider.WebProxy.Credentials = CredentialCache.DefaultCredentials;

            // generic status report screen
            MAVLinkInterface.CreateIProgressReporterDialogue += title =>
                                                                new ProgressReporterDialogue()
            {
                StartPosition = FormStartPosition.CenterScreen, Text = title
            };

            WebRequest.DefaultWebProxy             = WebRequest.GetSystemWebProxy();
            WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

            if (name == "VVVVZ")
            {
                // set pw
                Settings.Instance["password"]         = "******";
                Settings.Instance["password_protect"] = "True";
                // prevent wizard
                Settings.Instance["newuser"] = "******";
                // invalidate update url
                System.Configuration.ConfigurationManager.AppSettings["UpdateLocationVersion"] = "";
            }

            CleanupFiles();

            log.InfoFormat("64bit os {0}, 64bit process {1}", System.Environment.Is64BitOperatingSystem,
                           System.Environment.Is64BitProcess);

            try
            {
                Thread.CurrentThread.Name = "Base Thread";
                Application.Run(new MainV2());
            }
            catch (Exception ex)
            {
                log.Fatal("Fatal app exception", ex);
                Console.WriteLine(ex.ToString());

                Console.WriteLine("\nPress any key to exit!");
                Console.ReadLine();
            }

            try
            {
                // kill sim background process if its still running
                if (GCSViews.SITL.simulator != null)
                {
                    GCSViews.SITL.simulator.Kill();
                }
            }
            catch
            {
            }
        }
コード例 #13
0
 public Log4NetLoggerProvider(string log4netConfig)
 {
     _loggerRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
     XmlConfigurator.Configure(_loggerRepository, new FileInfo(log4netConfig));
 }
コード例 #14
0
 public Sudoku()
 {
     XmlConfigurator.Configure();
 }
コード例 #15
0
ファイル: Log4netHelper.cs プロジェクト: xjxafj/wpf-demo
 /// <summary>
 /// 加载配置
 /// </summary>
 /// <param name="configPath"></param>
 public static void loadConfig(string configPath)
 {
     Log4netHelper.Repository = LogManager.CreateRepository("NETCoreRepository");
     XmlConfigurator.Configure(Log4netHelper.Repository, new FileInfo(configPath));
 }
コード例 #16
0
        static void Main(string[] args)
        {
            #region Display Header Info

            System.Console.ForegroundColor = ConsoleColor.DarkGreen;
            System.Console.WriteLine("---------------------------------------------------------------");
            System.Console.WriteLine("Welcome to NearMap Test ---------------------------------------");
            System.Console.WriteLine("------------------------ https://github.com/izevaka/nearmap-test");
            System.Console.WriteLine("Amir--Pour-----------------------------------------------------");
            System.Console.WriteLine("Mobile: 0414 888 931-------------------------------------------");
            System.Console.WriteLine("---------------------------------------------------------------");
            System.Console.ResetColor();

            #endregion

            #region Setting up log

            ILog log = LogManager.GetLogger(typeof(Program));

            FileInfo configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.xml"));

            XmlConfigurator.ConfigureAndWatch(configFile);

            #endregion

            #region Composition root- Any kind of Dependency injector can be used to set it up

            DatabaseStore databaseStore = new DatabaseStore(log);

            ApplicationInitialiser applicationInitialiser = new ApplicationInitialiser(databaseStore, log);

            applicationInitialiser.Initialise();

            //getting all configs required for application
            CacheConfiguration cacheConfiguration = new CacheConfiguration();

            ICacheStoreAccelerator cacheStoreAccelerator = new CacheStoreAccelerator(cacheConfiguration, log);

            //this class helps local cache work faster, it adds more functionality
            LocalCacheStoreAccelerator localCacheAccelerator = new LocalCacheStoreAccelerator(cacheStoreAccelerator, cacheConfiguration, log);

            //this is the distributed cache
            DistributedCacheStore distributedCacheStore = new DistributedCacheStore(cacheConfiguration, log);

            //this class combines the localcache and distributed cache together  to provide a faster caching mechanism after a while
            //for more demanded objects, this class is the cache layer of the application
            SmartCacheStore fastCacheInterceptor = new SmartCacheStore(distributedCacheStore, localCacheAccelerator, log);

            //this class is responsible to retrieve the data either from cache layer or from database
            Repository repository = new Repository(fastCacheInterceptor, databaseStore, log);

            //this is the service that is going to expose to all consumers
            MyService myService = new MyService(repository);

            #endregion

            System.Console.WriteLine("Start up finished");
            System.Console.WriteLine("---------------------------------------------------------------");

            for (int i = 0; i < 10; i++)
            {
                new Thread(() =>
                {
                    //Sets the resolution of the timer. This has to be done per thread to ensure that 5ms sleep is actually 5 ms.
                    //http://stackoverflow.com/a/522681
                    timeBeginPeriod(5);

                    for (int j = 0; j < 50; j++)
                    {
                        string key = string.Format("key_{0}", random.Next(0, 9));

                        Stopwatch myStopwatch = new Stopwatch();

                        myStopwatch.Reset();
                        myStopwatch.Start();

                        var value = myService.GetItem(key);

                        myStopwatch.Stop();

                        var duration = myStopwatch.ElapsedMilliseconds;

                        System.Console.WriteLine("[{0}] Request '{1}', response '{2}', time: {3}",
                                                 Thread.CurrentThread.ManagedThreadId,
                                                 key,
                                                 value,
                                                 duration.ToString("F2"));

                        System.Console.ResetColor();
                    }

                    timeEndPeriod(5);
                }).Start();
            }

            System.Console.WriteLine("----E--N--D---");

            System.Console.Read();
        }
コード例 #17
0
 static Log4netTestingContext()
 {
     XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
 }
コード例 #18
0
 private static void _ConfigureLogging()
 {
     XmlConfigurator.Configure();//Note
     Logging.Logger.Current = new Log4netLogger();
     //Logger.Logger.Current = new ConsoleLogger();
 }
コード例 #19
0
 public Logger(FileInfo log4NetConfigFile)
     : this()
 {
     XmlConfigurator.Configure(log4NetConfigFile);
 }
コード例 #20
0
        static void Main(string[] args)
        {
            // get connected
            string url = ConfigurationManager.AppSettings["url"];

            if ((!url.EndsWith("/")) && (!url.EndsWith("\\")))
            {
                url += "/";
            }
            Console.Out.WriteLine($"Connecting to URL {url}");
            client = new WindwardClient(new Uri(url));
            VersionInfo version = client.GetVersion().Result;

            Console.Out.WriteLine($"REST server version = {version}");

            // if no arguments, then we list out the usage.
            if (args.Length < 2)
            {
                DisplayUsage();
                return;
            }

            // the try here is so we can print out an exception if it is thrown. This code does minimal error checking and no other
            // exception handling to keep it simple & clear.
            try
            {
                Console.Out.WriteLine("Running in {0}-bit mode", IntPtr.Size * 8);

                // parse the arguments passed in. This method makes no calls to Windward, it merely organizes the passed in arguments.
                CommandLine cmdLine = CommandLine.Factory(args);

                // This turns on log4net logging. You can also call log4net.Config.XmlConfigurator.Configure(); directly.
                // If you do not make this call, then there will be no logging (which you may want off).
                var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
                XmlConfigurator.Configure(logRepository, new FileInfo("RunReport.config"));
                logWriter.Info($"Starting RunReport ({string.Join(", ", args)})");

                DateTime startTime = DateTime.Now;

                // run one report
                if (!cmdLine.IsPerformance)
                {
                    PerfCounters perfCounters = RunOneReport(cmdLine, args.Length == 2);
                    PrintPerformanceCounter(startTime, perfCounters, false);
                }
                else
                {
                    string dirReports = Path.GetDirectoryName(Path.GetFullPath(cmdLine.ReportFilename)) ?? "";
                    if (!Directory.Exists(dirReports))
                    {
                        Console.Error.WriteLine($"The directory {dirReports} does not exist");
                        return;
                    }

                    // drop out threads - twice the number of cores.
                    int numThreads = cmdLine.NumThreads;
                    numReportsRemaining = cmdLine.NumReports;
                    ReportWorker[] workers = new ReportWorker[numThreads];
                    for (int ind = 0; ind < numThreads; ind++)
                    {
                        workers[ind] = new ReportWorker(ind, new CommandLine(cmdLine));
                    }
                    System.Threading.Thread[] threads = new System.Threading.Thread[numThreads];
                    for (int ind = 0; ind < numThreads; ind++)
                    {
                        threads[ind] = new System.Threading.Thread(workers[ind].DoWork);
                    }
                    for (int ind = 0; ind < numThreads; ind++)
                    {
                        threads[ind].Name = "Report Worker " + ind;
                    }

                    Console.Out.WriteLine($"Start time: {startTime.ToLongTimeString()}, {numThreads} threads, {cmdLine.NumReports} reports");
                    Console.Out.WriteLine();
                    for (int ind = 0; ind < numThreads; ind++)
                    {
                        threads[ind].Start();
                    }

                    // we wait
                    for (int ind = 0; ind < numThreads; ind++)
                    {
                        threads[ind].Join();
                    }

                    PerfCounters perfCounters = new PerfCounters();
                    for (int ind = 0; ind < numThreads; ind++)
                    {
                        perfCounters.Add(workers[ind].perfCounters);
                    }

                    Console.Out.WriteLine();
                    PrintPerformanceCounter(startTime, perfCounters, true);
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("RunReport", ex);
                string indent = "  ";
                Console.Error.WriteLine();
                Console.Error.WriteLine("Error(s) running the report");
                while (ex != null)
                {
                    Console.Error.WriteLine($"{indent}Error: {ex.Message} ({ex.GetType().FullName})\n{indent}     stack: {ex.StackTrace}\n");
                    ex      = ex.InnerException;
                    indent += "  ";
                }
                throw;
            }
        }
コード例 #21
0
        public ActionResult ViewMemoDetails(string memoseries, int status)
        {
            XmlConfigurator.Configure();

            LoginController    ctr     = new LoginController();
            CreateResponse     resp    = new CreateResponse();
            CreateResponse     details = new CreateResponse();
            HomeViewModel      sss     = new HomeViewModel();
            List <Signatories> sign;

            //get signatories
            CreateResponse signatories = ctr.getSignatoryList();

            sign = signatories.SignatoryList;

            var source     = new System.Uri(service + "/CurrentStatusMemoDetails/?memoSeries=" + memoseries + "&status=" + status);
            var reqHandler = new RequestHandler("GET", source, "application/json", null);
            var response   = reqHandler.HttpGetRequest();

            resp = Newtonsoft.Json.JsonConvert.DeserializeObject <CreateResponse>(response);
            log.Info(JsonConvert.SerializeObject(resp, Formatting.None).ToString());

            if (resp.ResponseCode == 200)
            {
                details.status       = Convert.ToInt32(status);
                sss.OperatorName     = resp.MemoRequestDetails.OperatorName;
                sss.DebtCredNo       = resp.MemoRequestDetails.MemoSeries;
                sss.IRNo             = resp.MemoRequestDetails.IRNumber;
                sss.DebitCredit      = resp.MemoRequestDetails.TransactionType;
                sss.WrongAmount      = String.IsNullOrEmpty(resp.MemoRequestDetails.Reason1) ? false : true;
                sss.Erroneous        = String.IsNullOrEmpty(resp.MemoRequestDetails.Reason2) ? false : true;
                sss.SystemError      = String.IsNullOrEmpty(resp.MemoRequestDetails.Reason3) ? false : true;
                sss.TransactionDate1 = resp.MemoRequestDetails.TransactionDate1;
                sss.TransactionDate2 = resp.MemoRequestDetails.TransactionDate2;
                sss.TransactionDate3 = resp.MemoRequestDetails.TransactionDate3;
                sss.refno1           = resp.MemoRequestDetails.ReferenceNo1;
                sss.refno2           = resp.MemoRequestDetails.ReferenceNo2;
                sss.refno3           = resp.MemoRequestDetails.ReferenceNo3;
                sss.WalletUser       = resp.MemoRequestDetails.WalletUser;
                sss.WalletID         = resp.MemoRequestDetails.WalletID;
                sss.AdjustAmount     = Convert.ToDecimal(resp.MemoRequestDetails.AdjustedAmount);
                sss.CorrectAmount    = Convert.ToDecimal(resp.MemoRequestDetails.CorrectAmount);
                sss.IncorrectAmount  = Convert.ToDecimal(resp.MemoRequestDetails.WrongAmount);
                sss.File             = !String.IsNullOrEmpty(resp.MemoRequestDetails.File) ? resp.MemoRequestDetails.MemoSeries + "_Attachment" : "No file attached.";
                sss.FileValue        = !String.IsNullOrEmpty(resp.MemoRequestDetails.File) ? resp.MemoRequestDetails.File : "";
                sss.FileType         = resp.MemoRequestDetails.FileType;
                sss.Created_at       = resp.MemoRequestDetails.Created_at;
                sss.Noted_at         = resp.MemoRequestDetails.Noted_at;
                sss.Received_at      = resp.MemoRequestDetails.Received_at;
                sss.Audited_at       = resp.MemoRequestDetails.Audited_at;

                details.MemoRequestDetails = resp.MemoRequestDetails;
                details.SignatoryList      = sign;
                details.details            = sss;
                Session["RequestDetailsX"] = details;
                log.Info(JsonConvert.SerializeObject(details, Formatting.None).ToString());
                return(View());
            }
            else
            {
                return(RedirectToAction("ErrorPage"));
            }
        }
コード例 #22
0
 static LoggerHelper()
 {
     XmlConfigurator.Configure(Repository, new FileInfo("log4net.config"));
 }
コード例 #23
0
ファイル: TestCase.cs プロジェクト: v-kabanov/nhibernate-core
 static TestCase()
 {
     // Configure log4net here since configuration through an attribute doesn't always work.
     XmlConfigurator.Configure(LogManager.GetRepository(typeof(TestCase).Assembly));
 }
コード例 #24
0
 public static void Configure()
 {
     XmlConfigurator.Configure();
 }
コード例 #25
0
ファイル: MasterPage.master.cs プロジェクト: jehan2898/root
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = string.Format("Id: {0} Uri: {1}", Guid.NewGuid(), HttpContext.Current.Request.Url);

        using (Utils utility = new Utils())
        {
            utility.MethodStart(id, System.Reflection.MethodBase.GetCurrentMethod());
        }
        log.Debug("start Master Page Page_Load()");
        if (base.Application["Error"] != null)
        {
            base.Response.Write(base.Application["Error"].ToString());
        }
        try
        {
            this.objAppSettings = (ApplicationSettings_BO)base.Application["OBJECT_APP_SETTINGS"];
            if (this.objAppSettings == null)
            {
                this.objAppSettings = new ApplicationSettings_BO();
                base.Application["OBJECT_APP_SETTINGS"] = this.objAppSettings;
            }
            string str = this.objAppSettings.getParameterValue("site_logo").ParameterValue;
            this.ImageButton1.ImageUrl = str;
            XmlConfigurator.Configure();
            this.c_objUser = new DAO_User();
            string rawUrl = "";
            if (base.Request.RawUrl.IndexOf("?") > 0)
            {
                rawUrl = base.Request.RawUrl.Substring(0, base.Request.RawUrl.IndexOf("?"));
            }
            else
            {
                rawUrl = base.Request.RawUrl;
            }
            //  this.c_objUser.UserID=rawUrl.Substring(rawUrl.LastIndexOf("/") + 1, (rawUrl.LastIndexOf(".aspx") - rawUrl.LastIndexOf("/")) + 4);
            this.c_objUser.UserID = rawUrl.Substring(rawUrl.LastIndexOf("/") + 1, (rawUrl.LastIndexOf(".aspx") - rawUrl.LastIndexOf("/")) + 4);
            string[] strArray = base.Request.RawUrl.ToString().Split(new char[] { '?' });
            if ((strArray.Length > 1) && strArray[1].Equals("Menuflag=true"))
            {
                if (strArray[0].Contains("/AJAX Pages/Bill_Sys_OutScheduleReport.aspx"))
                {
                    this.c_objUser.UserID = "Bill_Sys_OutScheduleReport.aspx?Menuflag=true";
                }
                else
                {
                    this.c_objUser.UserID = "Bill_Sys_VerificationSent_PrintPOM.aspx";
                }
            }
            if (this.c_objUser.UserID == "Bill_Sys_ReferralBillTransaction.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_BillTransaction.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_ReferringDoctor.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_Doctor.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_ChangePasswordMaster.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_UserMaster.aspx";
            }
            if ((this.c_objUser.UserID == "Bill_Sys_BillSearch.aspx") && (base.Request.QueryString["fromCase"] != null))
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_BillTransaction.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if ((this.c_objUser.UserID == "Bill_Sys_NewPaymentReport.aspx") && (base.Request.QueryString["fromCase"] != null))
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_PaymentTransactions.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID.Contains("Bill_Sys_IM_"))
            {
                this.c_objUser.UserID = "Bill_Sys_IM_HistoryOfPresentIillness.aspx";
            }
            if (this.c_objUser.UserID.Contains("Bill_Sys_FUIM_"))
            {
                this.c_objUser.UserID = "Bill_Sys_FUIM_StartExamination.aspx";
            }
            if (this.c_objUser.UserID.Contains("Bill_Sys_AC_"))
            {
                this.c_objUser.UserID = "Bill_Sys_AC_AccuReEval.aspx";
            }
            if ((this.c_objUser.UserID == "Bill_Sys_MiscPaymentReport.aspx") && (base.Request.QueryString["fromCase"] != null))
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_Misc_Payment.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_Invoice.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_PatientBillingSummary.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
            }
            if (this.c_objUser.UserID == "Bill_Sys_Invoice_Report.aspx")
            {
                if (base.Request.QueryString["fromCase"] != "False")
                {
                    this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
                }
                else
                {
                    this.c_objUser.UserID = "Bill_Sys_BillSearch.aspx";
                }
            }
            if (this.c_objUser.UserID == "TemplateManager.aspx")
            {
                if (base.Request.QueryString["fromCase"] == "true")
                {
                    this.c_objUser.UserID = "Bill_Sys_CheckOut.aspx";
                }
                else
                {
                    this.c_objUser.UserID = "Bill_Sys_Notes.aspx";
                }
            }
            if (this.c_objUser.UserID == "Bill_Sys_PatientSearch.aspx")
            {
                this.c_objUser.UserID = "Bill_Sys_CheckOut.aspx";
            }
            SpecialityPDFDAO ypdfdao = new SpecialityPDFDAO();
            if (base.Session["SPECIALITY_PDF_OBJECT"] != null)
            {
                ypdfdao = (SpecialityPDFDAO)base.Session["SPECIALITY_PDF_OBJECT"];
            }
            else
            {
                ypdfdao = null;
            }
            this.c_objUser.UserRoleID = ((Bill_Sys_UserObject)base.Session["USER_OBJECT"]).SZ_USER_ROLE;
            ArrayList list = new ArrayList();
            list.Add(rawUrl);
            new OptionMenu(this.c_objUser).Initialize(this.problue, (Bill_Sys_BillingCompanyObject)base.Session["BILLING_COMPANY_OBJECT"], (Bill_Sys_UserObject)base.Session["USER_OBJECT"], (Bill_Sys_SystemObject)base.Session["SYSTEM_OBJECT"], this.c_objUser, ypdfdao, list);
            this.problue.AllExpanded  = true;
            this.problue.AutoPostBack = false;
            if (((Bill_Sys_BillingCompanyObject)base.Session["BILLING_COMPANY_OBJECT"]).BT_REFERRING_FACILITY)
            {
                //this.lnkCalendar.HRef = "AJAX Pages/Bill_Sys_AppointPatientEntry.aspx";
            }
            else
            {
                //this.lnkCalendar.HRef = "Bill_Sys_ScheduleEvent.aspx?TOp=true";
            }
            this.ShowAssignedLinks(this.c_objUser.UserRoleID);
            log.Debug("End Master Page_Load()");
            DataSet set = new DataSet();
            set = new Bill_Sys_ProcedureCode_BO().Get_Sys_Key("SS00040", ((Bill_Sys_BillingCompanyObject)base.Session["BILLING_COMPANY_OBJECT"]).SZ_COMPANY_ID);
            if (((set.Tables.Count > 0) && (set.Tables[0].Rows.Count > 0)) && (set.Tables[0].Rows[0][0].ToString() == "0"))
            {
                this.lnkshedulevisits.Visible = false;
            }
        }
        catch (Exception exception)
        {
            log.Debug("Shared_MasterPage. Method - Page_Load : " + exception.Message.ToString());
            log.Debug("Shared_MasterPage. Method - Page_Load : " + exception.StackTrace.ToString());
            if (exception.InnerException != null)
            {
                log.Debug("Shared_MasterPage. Method - Page_Load : " + exception.InnerException.Message.ToString());
                log.Debug("Shared_MasterPage. Method - Page_Load : " + exception.InnerException.StackTrace.ToString());
            }
            Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
            using (Utils utility = new Utils())
            {
                utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod());
            }
            string str2 = "Error Request=" + id + ".Please share with Technical support.";
            base.Response.Redirect("Bill_Sys_ErrorPage.aspx?ErrMsg=" + str2);
        }
        //Method End
        using (Utils utility = new Utils())
        {
            utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod());
        }
    }
コード例 #26
0
 public static void InitConfiguration(string configFileName)
 {
     XmlConfigurator.Configure(new FileInfo(configFileName));
 }
コード例 #27
0
 static Log()
 {
     XmlConfigurator.Configure(log4net.LogManager.GetRepository(Assembly.GetCallingAssembly()));
 }
コード例 #28
0
        private static int Main(string[] args)
        {
            // enable the code below for debug; disable otherwise
            //if (Environment.UserInteractive)
            //{
            //    MessageBox.Show("Attach the .NET debugger to the 'SSH Debug' Myrtille.SSH.exe process now for debug. Click OK when ready...", "SSH Debug");
            //}
            //else
            //{
            //    Thread.Sleep(10000);
            //}

            // logger
            XmlConfigurator.Configure();

            string argKeyValueSeparator = ":";

            foreach (string arg in args)
            {
                var argParts = arg.Trim().Split(argKeyValueSeparator.ToCharArray(), 2);
                parseCommandLineArg(argParts[0].ToLower(), (argParts.Length > 1 ? argParts[1] : ""));
            }

            if (!ValidConfig)
            {
                return((int)RemoteSessionExitCode.InvalidConfiguration);
            }

            pipeMessaging = new PipeMessaging(RemoteSessionID);

            if (pipeMessaging.ConnectPipes())
            {
                pipeMessaging.OnMessageReceivedEvent += PipeMessaging_OnMessageReceivedEvent;

                try
                {
                    pipeMessaging.ReadInputsPipe();
                }
                catch (Exception e)
                {
                    if (ConsoleOutput)
                    {
                        Console.WriteLine(e.Message);
                    }

                    Trace.TraceError("SSH error, remote session {0} ({1})", RemoteSessionID, e);

                    if (e is SshAuthenticationException)
                    {
                        if (e.Message == "Missing Username")
                        {
                            return((int)RemoteSessionExitCode.MissingUserName);
                        }
                        else if (e.Message == "Missing Password")
                        {
                            return((int)RemoteSessionExitCode.MissingPassword);
                        }
                        else
                        {
                            return((int)RemoteSessionExitCode.InvalidCredentials);
                        }
                    }

                    return((int)RemoteSessionExitCode.Unknown);
                }
                finally
                {
                    pipeMessaging.ClosePipes();
                    DisconnectSSHClient();
                }
            }

            return((int)RemoteSessionExitCode.Success);
        }
コード例 #29
0
 protected void InitLog4net()
 {
     XmlConfigurator.Configure();
 }
コード例 #30
0
        static void ConfigureLogging()
        {
            ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
        }
コード例 #31
0
 /// <summary>
 /// 静态构造函数
 /// 初始化log4net
 /// </summary>
 static Log()
 {
     repository = LogManager.CreateRepository("NETCoreRepository");
     XmlConfigurator.Configure(repository, new FileInfo("logger.config"));
 }
コード例 #32
0
			public ConfigureAndWatchHandler(XmlConfigurator xmlConfigurator, ILoggerRepository repository, FileInfo configFile)
			{
				_xmlConfigurator = xmlConfigurator;
				m_repository = repository;
				m_configFile = configFile;

				// Create a new FileSystemWatcher and set its properties.
				m_watcher = new FileSystemWatcher();

				m_watcher.Path = m_configFile.DirectoryName;
				m_watcher.Filter = m_configFile.Name;

				// Set the notification filters
				m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;

				// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
				m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
				m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
				m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
				m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);

				// Begin watching.
				m_watcher.EnableRaisingEvents = true;

				// Create the timer that will be used to deliver events. Set as disabled
				m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
			}