Beispiel #1
0
        private static void Main(string[] args)
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.xml"));

            try
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
                Console.WriteLine("Press <Enter> to start emulation...");
                Console.ReadLine();

                //int threads;
                //int iothreads;

                //ThreadPool.GetMaxThreads(out threads, out iothreads);
                //ThreadPool.SetMaxThreads(threads, 4000);

                //ThreadPool.GetMinThreads(out threads, out iothreads);
                //ThreadPool.SetMinThreads(4000, 4000);

                //DedicatedThreadPool threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount));
                DedicatedThreadPool threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(4000));

                Emulator emulator = new Emulator {
                    Running = true
                };
                Stopwatch watch = new Stopwatch();
                watch.Start();

                long start = DateTime.UtcNow.Ticks;

                //IPEndPoint endPoint = new IPEndPoint(Dns.GetHostEntry("yodamine.com").AddressList[0], 19132);
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 19132);

                var sw = Stopwatch.StartNew();
                for (int j = 0; j < NumberOfBots; j++)
                {
                    string playerName = $"TheGrey{j + 1:D3}";

                    ClientEmulator client = new ClientEmulator(threadPool, emulator, DurationOfConnection,
                                                               playerName, (int)(DateTime.UtcNow.Ticks - start), endPoint,
                                                               RanSleepMin, RanSleepMax, RequestChunkRadius);

                    new Thread(o => { client.EmulateClient(); })
                    {
                        IsBackground = true
                    }.Start();

                    if (ConcurrentSpawn)
                    {
                        emulator.ConcurrentSpawnWaitHandle.Set();
                    }

                    emulator.ConcurrentSpawnWaitHandle.WaitOne();

                    long elapsed = sw.ElapsedMilliseconds;
                    if (elapsed < TimeBetweenSpawns)
                    {
                        Thread.Sleep((int)(TimeBetweenSpawns - elapsed));
                    }

                    sw.Restart();
                }

                Console.WriteLine("Press <enter> to stop all clients.");
                Console.ReadLine();
                emulator.Running = false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Emulation complete. Press <enter> to exit.");
            Console.ReadLine();
        }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AppTraceHelper"/> class.
 /// </summary>
 public AppTraceHelper()
 {
     XmlConfigurator.Configure();
 }
 /// <summary>
 /// Controller constructor.
 /// Initialize repository.
 /// </summary>
 /// <param name="Repository">Repository object</param>
 public ProfileController(IRepository Repository)
 {
     XmlConfigurator.Configure();
     repository = Repository;
 }
 public void InitLogger()
 {
     XmlConfigurator.Configure();
 }
 public static void Initialize(TestContext context)
 {
     XmlConfigurator.Configure(new FileInfo("log4net.config"));
 }
Beispiel #6
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 = "Mission Planner";

            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 + " " + 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
            {
            }
        }
Beispiel #7
0
        public MainWindow()
        {
#if !DEBUG
            //     try
            {
#endif
            InitializeComponent();
            MainDescription.MainFrm = this;
            Application.Current.Resources["ThemeDictionary"] = new ResourceDictionary();
            //   this.SetCurrentTheme("ShinyBlue");
            ;
            if (ConfigurationManager.AppSettings["PluginLocationRelative"] == "true")
            {
                pluginPosition = MainStartUpLocation
                                 + ConfigurationManager.AppSettings["MainPluginLocation"];
            }
            else
            {
                pluginPosition = ConfigurationManager.AppSettings["MainPluginLocation"];
            }

            XmlConfigurator.Configure(new FileInfo("log4net.config"));


            string icon = ConfigurationManager.AppSettings["Icon"];
            try
            {
                Icon = new BitmapImage(new Uri(pluginPosition + icon, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                XLogSys.Print.Error(Core.Properties.Resources.IconNotExist);
            }

            PluginManager = new PluginManager();
//#if !DEBUG
            //Dispatcher.UnhandledException += (s, e) =>
            //{
            //    MessageBox.Show("系统出现异常" + e.Exception);
            //    XLogSys.Print.Fatal(e.Exception);
            //};
//#endif
            ViewDictionary = new List <ViewItem>();
            Title          = ConfigurationManager.AppSettings["Title"];

            //    this.myDebugSystemUI.MainFrmUI = this;
            PluginManager.MainFrmUI = this;

            //  this.myDebugSystemUI.Init();

            PluginManager.Init(new[] { MainStartUpLocation });
            PluginManager.LoadPlugins();
            PluginManager.LoadView();

            DataContext = this;
            foreach (ICommand action in CommandCollection.Concat(Commands))
            {
                SetCommandKeyBinding(action);
            }
            XLogSys.Print.Info(Title + Core.Properties.Resources.Start);


            Closing += (s, e) =>
            {
                if (MessageBox.Show(Core.Properties.Resources.Closing, Core.Properties.Resources.Tips, MessageBoxButton.OKCancel) == MessageBoxResult.OK)

                {
                    PluginManager.Close();
                    PluginManager.SaveConfigFile();
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    e.Cancel = true;
                }
            };
            //  TestCode();
#if !DEBUG
        }

        // catch (Exception ex)
        {
            //   MessageBox.Show(ex.ToString());
        }
#endif
        }
Beispiel #8
0
        public static void AddNcfServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment env, CompatibilityVersion compatibilityVersion)
        {
            //如果运行在IIS中,需要添加IIS配置
            //https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-2.1&tabs=aspnetcore2x#supported-operating-systems
            //services.Configure<IISOptions>(options =>
            //{
            //    options.ForwardClientCertificate = false;
            //});

            //启用以下代码强制使用 https 访问
            //services.AddHttpsRedirection(options =>
            //{
            //    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            //    options.HttpsPort = 443;
            //});

            //读取Log配置文件
            var repository = LogManager.CreateRepository("NETCoreRepository");

            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

            //提供网站根目录
            if (env.ContentRootPath != null)
            {
                SiteConfig.ApplicationPath = env.ContentRootPath;
                SiteConfig.WebRootPath     = env.WebRootPath;
            }

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //services.AddMvc(options =>
            //{
            //    //options.Filters.Add<HttpGlobalExceptionFilter>();
            //})
            //.SetCompatibilityVersion(compatibilityVersion)
            //.AddRazorPagesOptions(options =>
            //{
            //    //options.AllowAreas = true;//支持 Area
            //    //options.AllowMappingHeadRequestsToGetHandler = false;//https://www.learnrazorpages.com/razor-pages/handler-methods
            //})


            services.AddMultiTenant();                                        //注册多租户(按需)
            EntitySetKeys.TryLoadSetInfo(typeof(SenparcEntitiesMultiTenant)); //注册多租户数据库的对象(按需)
            services.AddScoped(typeof(ITenantInfoDbData), typeof(TenantInfoDbData));
            services.AddScoped <TenantInfoRepository>();
            services.AddScoped(typeof(IClientRepositoryBase <TenantInfo>), typeof(TenantInfoRepository));

            services.AddSenparcGlobalServices(configuration);//注册 CO2NET 基础引擎所需服务

            var builder = services.AddRazorPages(opt =>
            {
                //opt.RootDirectory = "/";
            })
                          .AddNcfAreas(env)//注册所有 Ncf 的 Area 模块(必须)
                          .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var values = actionContext.ModelState.Where(_ => _.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid).Select(_ => new { _.Key, Errors = _.Value.Errors.Select(__ => __.ErrorMessage) });
                    AjaxReturnModel commonReturnModel = new AjaxReturnModel <object>(values);
                    commonReturnModel.Success         = false;
                    commonReturnModel.Msg             = "参数校验未通过";
                    //commonReturnModel.StatusCode = Core.App.CommonReturnStatusCode.参数校验不通过;
                    return(new BadRequestObjectResult(commonReturnModel));
                };
            })
                          .AddXmlSerializerFormatters()
                          .AddJsonOptions(options =>
            {
                //忽略循环引用
                //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
                          //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x
                          //.AddSessionStateTempDataProvider()
                          //忽略JSON序列化过程中的循环引用:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                          .AddRazorPagesOptions(options =>
            {
                //自动注册  防止跨站请求伪造(XSRF/CSRF)攻击
                options.Conventions.Add(new Core.Conventions.AutoValidateAntiForgeryTokenModelConvention());
            });

#if DEBUG
            //Razor启用运行时编译,多个项目不需要手动编译。
            if (env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    //自动索引所有需要使用 RazorRuntimeCompilation 的模块
                    foreach (var razorRegister in XncfRegisterManager.RegisterList.Where(z => z is IXncfRazorRuntimeCompilation))
                    {
                        try
                        {
                            var libraryPath = ((IXncfRazorRuntimeCompilation)razorRegister).LibraryPath;
                            options.FileProviders.Add(new PhysicalFileProvider(libraryPath));
                        }
                        catch (Exception ex)
                        {
                            SenparcTrace.BaseExceptionLog(ex);
                        }
                    }
                });
            }
#endif

            //TODO:在模块中注册
            services.AddScoped <Ncf.AreaBase.Admin.Filters.AuthenticationResultFilterAttribute>();

            //支持 Session
            services.AddSession();
            //解决中文进行编码问题
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
            //使用内存缓存
            services.AddMemoryCache();

            //注册 SignalR
            services.AddSignalR();
            //注册 Lazy<T>
            services.AddTransient(typeof(Lazy <>));

            services.Configure <SenparcCoreSetting>(configuration.GetSection("SenparcCoreSetting"));
            services.Configure <SenparcSmsSetting>(configuration.GetSection("SenparcSmsSetting"));

            //自动依赖注入扫描
            services.ScanAssamblesForAutoDI();
            //已经添加完所有程序集自动扫描的委托,立即执行扫描(必须)
            AssembleScanHelper.RunScan();
            //services.AddSingleton<Core.Cache.RedisProvider.IRedisProvider, Core.Cache.RedisProvider.StackExchangeRedisProvider>();

            ////添加多租户
            //services.AddMultiTenant();

            //注册 User 登录策略
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserAnonymous", policy =>
                {
                    policy.RequireClaim("UserMember");
                });
            });
            services.AddHttpContextAccessor();

            //Repository & Service
            services.AddScoped(typeof(ISysButtonRespository), typeof(SysButtonRespository));

            //Other
            services.AddScoped(typeof(Ncf.Core.WorkContext.Provider.IAdminWorkContextProvider), typeof(Ncf.Core.WorkContext.Provider.AdminWorkContextProvider));
            services.AddTransient <Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor, Microsoft.AspNetCore.Mvc.Infrastructure.ActionContextAccessor>();

            //激活 Xncf 扩展引擎(必须)
            services.StartEngine(configuration);
        }
 protected void Application_Start(object sender, EventArgs e)
 {
     //应用程序启动时,自动加载配置log4Net
     XmlConfigurator.Configure();
 }
 // ----------------------------------------------------------------------
 public LoggerFactoryLog4net()
 {
     XmlConfigurator.Configure();
 }         // LoggerFactoryLog4net
Beispiel #11
0
 static SpyingFixture()
 {
     XmlConfigurator.Configure();
 }
 public void RunBeforeAllTests()
 {
     XmlConfigurator.Configure();
     ServiceLocatorInitializer.Init();
 }
        public static void InitLogger()
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
        }
Beispiel #14
0
 static LogUtil()
 {
     XmlConfigurator.Configure();
 }
Beispiel #15
0
 public void FixtureSetup()
 {
     XmlConfigurator.Configure();
 }
Beispiel #16
0
 /// <summary>
 /// Constructor por default
 /// </summary>
 public ClienteTimbradoNtlink()
 {
     XmlConfigurator.Configure();
 }
        static Log4NetProvider()
        {
            var logRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
        }
Beispiel #18
0
 public TestHelper()
 {
     XmlConfigurator.Configure();
 }
Beispiel #19
0
        static LogHelper()
        {
            var fileInfo = new FileInfo($"{AppDomain.CurrentDomain.BaseDirectory}\\log4net.config");

            XmlConfigurator.Configure(fileInfo);
        }
Beispiel #20
0
 public TestHelper(IApplicationContext applicationContext)
 {
     SpringHelper.ApplicationContext = applicationContext;
     XmlConfigurator.Configure();
 }
Beispiel #21
0
        public PersonTrackerAPI()
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
        }
Beispiel #22
0
 static Logger()
 {
     XmlConfigurator.Configure();
 }
Beispiel #23
0
 public Node()
 {
     XmlConfigurator.Configure(logRepository, fileInfo);
     log.Info($"New Empty Node was created at {DateTime.Now}");
 }
Beispiel #24
0
        //Старт программы
        static void Main(string[] args)
        {
            //конфигурация логгера
            XmlConfigurator.Configure();

            //настройка ограничений по потокам
            int workerThreads         = 0;
            int completionPortThreads = 0;

            ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
            ThreadPool.SetMinThreads(MIN_THREAD_COUNT, completionPortThreads);

            HandlerManager.Instance.Register(new SignalHandler());

            #region API - соединение с Api
            var connector = UnityManager.Instance.Resolve <IConnector>();
            while (!connector.Relogin())
            {
                logger.Warn(string.Format("не удалось соединиться с сервером, повтор через 5 сек."));
                Thread.Sleep(5000);
            }
            connector.Subscribe();
            var autoEvent = new AutoResetEvent(false);
            ApiConnector.Instance.Initial();
            //Timer timer = new Timer(Calc.Instance.Calculate, autoEvent, 0, 1000 * 60 * 60 * 1);

            #endregion
            #region RabbitMQ - соединение с шиной
            var bus = new Bus();
            bus.OnMessageReceived += (se, ea) =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        if (ea.Message.head.what.StartsWith("signaling"))
                        {
                            if (ea.Message.body.what == "scheduler")
                            {
                                logger.Debug(string.Format("пришел пинг от scheduler", ea.Message.head.what));
                                countSchedulerCheck = 0;
                            }
                            if (ea.Message.body.what == "poll")
                            {
                                logger.Debug(string.Format("пришел пинг от poll", ea.Message.head.what));
                                countPollCheck = 0;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, "ВНИМАНИЕ ПРОБЛЕМА ПРИ ПРИЕМЕ ЗАЯВОК");
                    }
                });
            };
            bus.Start();
            #endregion

            //2. запуск веб-сервера
            var binding = ConfigurationManager.AppSettings["binding"];
            var root    = ConfigurationManager.AppSettings["root-folder"];

            try
            {
                WebApp.Start(url: binding, startup: b =>
                {
                    Newtonsoft.Json.JsonConvert.DefaultSettings = () =>
                                                                  new JsonSerializerSettings()
                    {
                        DateTimeZoneHandling = DateTimeZoneHandling.Local
                    };

                    b.UseFileServer(new FileServerOptions
                    {
                        EnableDirectoryBrowsing = false,
                        FileSystem = new PhysicalFileSystem(root)
                    });

                    var config = new HttpConfiguration();
                    config.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional }
                        );
                    var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
                    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

                    b.UseWebApi(config);
                });

                logger.Debug("сервер запущен (привязка {0}, корневая папка {1})", binding, root);
            }
            catch (Exception e)
            {
                logger.Error("Не удалось запустить сервер (привязка {0}, корневая папка {1})! {2}", binding, root, e);
            }

            #region Команды console, ожидание exit
            var cmd = "";
            while (!(cmd = Console.ReadLine()).Contains("exit"))
            {
                switch (cmd)
                {
                case "status":
                {
                    break;
                }

                case "info":
                {
                    break;
                }

                case "dump":
                {
                    string fileName = string.Format("dump_{0:dd.HH-mm-ss}.txt", DateTime.Now);
                    break;
                }

                case "sys":
                {
                    var sys = "";
                    foreach (ProcessThread thread in Process.GetCurrentProcess().Threads)
                    {
                        sys += string.Format("{0} {1}\n", thread.StartTime, thread.TotalProcessorTime);
                    }
                    string fileName = string.Format("sys_{0:dd.HH-mm-ss}.txt", DateTime.Now);
                    File.WriteAllText(fileName, sys);
                    break;
                }

                case "cancel":
                {
                    break;
                }

                case "connect":
                {
                    connector.Subscribe();
                    break;
                }
                }
            }
            #endregion
            #region освобождение ресурсов
            bus.Stop();
            connector.Dispose();
            #endregion
        }
Beispiel #25
0
 public static void Init(string configFileName)
 {
     XmlConfigurator.Configure(new FileInfo(configFileName));
 }
Beispiel #26
0
        public MainForm()
        {
            InitializeComponent();

            XmlConfigurator.Configure();
        }
Beispiel #27
0
 public LRITDataCenterWebService()
 {
     XmlConfigurator.Configure();
     DataCenterDataAccess.Config.ConnectionString = mBasicConfiguration.ConnectionString;
     QueueManager.Instance().SetIn(mBasicConfiguration.CoreInQueue);
 }
Beispiel #28
0
        static void Main(string[] args)
        {
            // set up a simple logging configuration
            XmlConfigurator.Configure();
            if (!LogManager.GetRepository().Configured)
            {
                Debug.Fail("Logging not configured!\n Press ignore to continue");
            }

            //
            MessageFilter oFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(
                (IMessageFilter)oFilter);

            // note: arguments are handled within FormMain constructor
            // using Environment.GetCommandLineArgs()
            // force CultureToUse culture if specified in config file
            string specifiedCulture = treeDiM.StackBuilder.Desktop.Properties.Settings.Default.CultureToUse;

            if (!string.IsNullOrEmpty(specifiedCulture))
            {
                try
                {
                    Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo(specifiedCulture);
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(specifiedCulture);
                }
                catch (Exception ex)
                {
                    _log.Error(string.Format("Specified culture in config file ({0}) appears to be invalid: {1}", specifiedCulture, ex.Message));
                }
            }

            // get current culture
            _log.Info(string.Format("Starting {0} with user culture {1}", Application.ProductName, Thread.CurrentThread.CurrentUICulture));

            // set unit system
            UnitsManager.CurrentUnitSystem = (UnitsManager.UnitSystem)Properties.Settings.Default.UnitSystem;

            // file association
            RegisterFileType();

            // initialize database with containing folder
            PalletSolutionDatabase.Directory = Settings.Default.PalletSolutionsPath;

            // *** crash reporting
            Application.ThreadException += (sender, threadargs) => SendCrashReport(threadargs.Exception);
            AppDomain.CurrentDomain.UnhandledException += (sender, threadargs) =>
            {
                SendCrashReport((Exception)threadargs.ExceptionObject);
                Environment.Exit(0);
            };
            // *** crash reporting

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



            // show main form
            Application.Run(new FormMain());

            _log.Info("Closing " + Application.ProductName);
        }
Beispiel #29
0
 public static void Configure()
 {
     XmlConfigurator.Configure();
 }
Beispiel #30
0
 DDPSimulator()
 {
     XmlConfigurator.Configure(new FileInfo(ConfigurationManager.AppSettings["Log4NetConfigFile"]));
 }