public static void EnableTraceLog() { if (StartupConfig.GetValue("EnableNetworkTraceLog") == "true") { var d = new DebugLogTraceListener { logToConsole = StartupConfig.GetValue("NetworkTraceLogToConsole") == "true" }; Trace.Listeners.Add(d); Application.quitting += () => d.logStream.Dispose(); } }
public override void OnInitialized(StartupConfig startup) { base.OnInitialized(startup); Task.Run(() => { while (true) { ClearCache(Domain.CacheImagePath); Thread.Sleep(1000 * 60 * 30); } }); }
static void Main(string[] args) { StartupConfig.ConfigEventProcessors(); //register interface:concrete class SysRuntime.Container.Register <IOrderAppFacade, OrderApplication>(); SysRuntime.Container.Register <IOrderBusiness, OrderComponent>(); SysRuntime.Container.Register <IOrderRepository, FakeOrderRepository>(); IOrderAppFacade orderApp = SysRuntime.Container.Resolve <IOrderAppFacade>(); orderApp.AddOrder("test"); }
public FontManager(IIdGenerator idGenerator, IStartupPropertiesCache startUpPropertiesCache, IFontCollection fontCollection, IFontLoader fontLoader) { _idGenerator = idGenerator; _fontLoader = fontLoader; _userFontCollection = fontCollection; _startUpProperties = startUpPropertiesCache.User; LoadSystemFonts(); _fontsForDestruction = new List <Tuple <ulong, bool> >(); }
private void processStartupConfigFile() { string startupConfigDir = $"{ directoryHelper.GetRootProjectDirectory() }\\iCreator\\Configuration\\StartupConfig.json"; if (!File.Exists(startupConfigDir)) { createStartupConfigFile(startupConfigDir); } else { startupConfig = JsonConvert.DeserializeObject <StartupConfig>( File.ReadAllText(startupConfigDir)); } }
protected virtual void InsertPlugin(Type type, StartupConfig startupConfig) { try { PluginBase plugin = (PluginBase)Activator.CreateInstance(type); string pluginType, error = "", commands = ""; switch (plugin.PluginType) { case PluginType.Command: pluginType = "命令"; CommandPlugin cmdPlugin = (CommandPlugin)plugin; if (cmdPlugin.Commands != null && cmdPlugin.Commands.Length > 0) { foreach (var cmd in cmdPlugin.Commands) { TaggedPlugins.Add(new TaggedClass <PluginBase>(cmd, cmdPlugin)); CachedCommands.Add(new TaggedClass <Type>(cmd, type)); } commands = $"({string.Join(",", cmdPlugin.Commands)}) "; } else { error = "但此命令插件未设置命令。"; } break; case PluginType.Unknown: throw new NotSupportedException(); case PluginType.Application: case PluginType.Service: default: pluginType = plugin.PluginType == PluginType.Application ? "应用" : "服务"; TaggedPlugins.Add(new TaggedClass <PluginBase>(null, plugin)); break; } plugin.OnInitialized(startupConfig); AllPluginInitialized += plugin.AllPlugins_Initialized; Logger.Origin($"{pluginType} \"{plugin.Name}\" {commands}已经加载完毕。{error}"); } catch (Exception ex) { Logger.Exception(ex.InnerException ?? ex); Logger.Error($"加载插件{type.Name}失败。"); } }
private void Button_Save_Click(object sender, RoutedEventArgs e) { ComboBoxItem i = (ComboBoxItem)cboxCheckAPI.SelectedItem; StartupConfig.LastFolder = (string)lblFilesPath.Text; StartupConfig.cboxCheckedAPI = (string)i.Content; StartupConfig.isShowTime = Convert.ToBoolean(isShowTime.IsChecked); if ((bool)isStartWithSystem.IsChecked != StartupConfig.isStartWithSystem) { StartupConfig.SetAutoload((bool)isStartWithSystem.IsChecked); } StartupConfig.isStartWithSystem = Convert.ToBoolean(isStartWithSystem.IsChecked); StartupConfig.isSaveFile = Convert.ToBoolean(isSaveFiles.IsChecked); StartupConfig.WriteParams(); }
public static StartupConfig AddSagasServer(this StartupConfig startupConfig, Action <PoleSagasServerOption> config = null) { Action <PoleSagasServerOption> defaultConfig = option => { }; var finalConfig = config ?? defaultConfig; startupConfig.Services.AddGrpc(); startupConfig.Services.Configure(finalConfig); startupConfig.Services.AddSingleton <IProcessor, NotEndedSagasFetchProcessor>(); startupConfig.Services.AddSingleton <ISagasBuffer, SagasBuffer>(); startupConfig.Services.AddSingleton <IProcessor, ExpiredSagasCollectorProcessor>(); startupConfig.Services.AddHostedService <BackgroundServiceBasedProcessorServer>(); return(startupConfig); }
private static void RegisterActivities(StartupConfig startupOption) { var baseActivityType = typeof(IActivity <>); foreach (var assembly in AssemblyHelper.GetAssemblies()) { foreach (var type in assembly.GetTypes().Where(m => m.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == baseActivityType) && m.IsClass && !m.IsAbstract)) { if (!type.FullName.EndsWith("Activity")) { throw new ActivityNameIrregularException(type); } startupOption.Services.AddScoped(type); } } }
public override void OnInitialized(StartupConfig startup) { _triggerObjects = LoadSettings <List <TriggerObject> >("UserDictionary") ?? new List <TriggerObject> { new TriggerObject(new List <string> { "我" }, new List <string> { "me1.jpg" }, 0.5), new TriggerObject(new List <string> { "你" }, new List <string> { "you1.jpg", "you2.jpg" }, 2), new TriggerObject(new List <string> { "为啥", "为什么", "为毛", "为嘛", "why " }, new List <string> { "why1.jpg" }, 20), new TriggerObject(new List <string> { "看来", "原来" }, new List <string> { "kanlai1.jpg", "kanlai2.jpg" }, 30), new TriggerObject(new List <string> { "黄花菜" }, new List <string> { "sb1.jpg", "sb2.jpg", "sb3.jpg", "sb4.jpg", "sb5.jpg", "sb6.jpg", "sb7.jpg", "sb8.jpg", "sb9.jpg" }, 50) }; // 概率从小到大排序,更科学 _triggerObjects.Sort(new TriggerComparer()); _triggerObjects.RemoveAll(p => p == null); SaveSettings(_triggerObjects, "UserDictionary"); }
public void ConfigureServices(IServiceCollection services) { var config = new StartupConfig(); Configuration.Bind("StartupConfiguration", config); services.AddTestCreationPersistence(Configuration.GetConnectionString("TestCreationDbContext")); services.AddTestCreationApplicationServices(); services.AddTestCreationInfrastructureServices(); services.AddUserManagementPersistence(Configuration.GetConnectionString("UserManagementDbContext")); services.AddUserManagementApplicationServices(); services.AddUserManagementInfrastructureServices(); services.AddMediatR(typeof(TestCreation.App.IServiceCollectionExtensionsFromTestCreationApp)); services.Configure <AuthenticationService.Config>(Configuration.GetSection("Jwt")); services.AddJWTAuthentication(Configuration, "Jwt"); services.AddControllers(); services.AddCORS(); services.AddOpenAPI(); services.AddResponseCaching(); services.AddHealthChecks(); services.Configure <PostManService.Config>(Configuration.GetSection("PostManService")); services.AddHostedService <PostManService>(); services.Configure <RabbitMQEventBus.Config>(Configuration.GetSection("RabbitMQ")); switch (config.EventBus) { case StartupConfig.EventBusType.InMemory: services.AddSingleton <IEventBus, InMemoryEventBus>(); break; case StartupConfig.EventBusType.RabbitMQ: services.AddSingleton <IEventBus, RabbitMQEventBus>(); break; default: throw new NotImplementedException(); } services.AddHttpContextAccessor(); services.AddPresentationAPIServices(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var fileData = File.ReadAllText("appsettings.Development.json"); StartConfiguration = JsonConvert.DeserializeObject <StartupConfig>(fileData); Config = StartConfiguration; 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.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder .AllowAnyMethod() .AllowAnyHeader(); })); System.Console.WriteLine(StartConfiguration.ConnectionStrings.RokonocontrolContext); services.AddEntityFrameworkSqlServer() .AddDbContext <RokonocontrolContext>((serviceProvider, options) => options.UseSqlServer(StartConfiguration.ConnectionStrings.RokonocontrolContext) .UseInternalServiceProvider(serviceProvider)); services.AddRazorPages(); services.AddSignalR(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(); services.AddScoped <IAutherizationManager, AutherizationManager>(); services.AddScoped <ICustomLogger, Logger>(); services.AddHttpContextAccessor(); services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); var projects = new List <Projects>(); using (var context = new RokonocontrolContext()) { projects = context.Projects.Include(x => x.Repository).ToList(); } Task.Run(() => RepositoryManager.InitRepositories(projects, Program.ServerOS)); }
public override void OnInitialized(StartupConfig startup) { base.OnInitialized(startup); int i = 0; //UpdateGroupList(i); Task.Run(() => { while (true) { Thread.Sleep(1000 * 60 * 30); UpdateGroupList(i); i++; } }); }
public FontLoader(IApplicationAssembly applicationAssembly, IFontsAssembly fontsAssembly, IFrameworkMessenger frameworkMessenger, IGpuSurfaceManager gpuSurfaceManager, IStartupPropertiesCache startUpPropertiesCache, ISubFontGenerator subFontGenerator, IFileSystem fileSystem) { _applicationAssembly = applicationAssembly; _fontsAssembly = fontsAssembly; _frameworkMessenger = frameworkMessenger; _gpuSurfaceManager = gpuSurfaceManager; _subFontGenerator = subFontGenerator; _fileSystem = fileSystem; _startUpProperties = startUpPropertiesCache.User; }
private void createStartupConfigFile(string startupConfigDir) { startupConfig = new StartupConfig() { StartupViewName = "iCreator" }; File.Create(startupConfigDir).Dispose(); using (StreamWriter writer = new StreamWriter( startupConfigDir)) { writer.Write(JsonConvert.SerializeObject(startupConfig, Formatting.Indented)); } string currentDirectoryStartupConfigDir = $"{ Directory.GetCurrentDirectory() }\\iCreator\\Configuration\\StartupConfig.json"; File.Copy(startupConfigDir, currentDirectoryStartupConfigDir, true); }
public override void OnInitialized(StartupConfig startup) { _apiTimes = LoadSettings <ConcurrentDictionary <string, int> >() ?? new ConcurrentDictionary <string, int>(TuLingSecret.ApiKeys.ToDictionary(k => k, k => 0)); foreach (var key in TuLingSecret.ApiKeys) { if (_apiTimes.ContainsKey(key)) { continue; } _apiTimes.TryAdd(key, 0); } Task.Factory.StartNew(() => { var now = DateTime.Now; var next = DateTime.Now.AddDays(1); var dateTime = new DateTime(next.Year, next.Month, next.Day); bool ok = false; while (true) { if (!ok) { Thread.Sleep(dateTime - now); ok = true; } else { Thread.Sleep(TimeSpan.FromDays(1)); } foreach (var apiTime in _apiTimes) { _apiTimes[apiTime.Key] = 0; } SaveConfig(); } }, TaskCreationOptions.LongRunning); SaveConfig(); }
public static StartupConfig AddEventBus(this StartupConfig startupOption, Action <PoleEventBusOption> config = null) { Action <PoleEventBusOption> defaultConfig = option => { }; var finalConfig = config ?? defaultConfig; startupOption.Services.Configure(finalConfig); startupOption.Services.AddSingleton <IEventBuffer, EventBuffer>(); startupOption.Services.AddScoped <IBus, Bus>(); startupOption.Services.AddTransient(typeof(IChannel <>), typeof(Channel <>)); startupOption.Services.AddSingleton <IObserverUnitContainer, ObserverUnitContainer>(); startupOption.Services.AddSingleton <IProcessor, PendingMessageRetryProcessor>(); startupOption.Services.AddSingleton <IProcessor, ExpiredEventsCollectorProcessor>(); startupOption.Services.AddSingleton <IProcessor, PrometheusFailedEventGaugeProcessor>(); startupOption.Services.AddHostedService <BackgroundServiceBasedProcessorServer>(); startupOption.Services.AddScoped <IUnitOfWork, Pole.EventBus.UnitOfWork.UnitOfWork>(); startupOption.Services.AddSingleton <IEventTypeFinder, EventTypeFinder>(); RegisterEventHandler(startupOption); return(startupOption); }
public override void OnInitialized(StartupConfig startup) { _imagePath = Path.Combine(SettingsPath, "image"); _content = Path.Combine(_imagePath, ".content"); SaveSettings(this); if (!File.Exists(_content)) { Logger.Info("正在建立目录……"); CreateContent(); } else { Logger.Info("目录已经建立。"); } LikeDic = LoadSettings <ConcurrentDictionary <string, List <string> > >() ?? new ConcurrentDictionary <string, List <string> >(); Logger.Info("已载入点赞情况。"); }
static void Initialize() { string requestedControllerType = StartupConfig.GetValue(STARTUP_CONFIG_CONTROLLER_TYPE_KEY); if (!string.IsNullOrEmpty(requestedControllerType)) { Type cfgControllerType = Type.GetType(requestedControllerType); cfgController = InitializeSpecifiedControllerType(cfgControllerType); } else { Debug.Log("No requested controller type specified, initializing with default (" + DEFAULT_CONTROLLER_TYPE.Name + ")"); cfgController = InitializeSpecifiedControllerType(DEFAULT_CONTROLLER_TYPE); } localConfig = GetController <IniConfigurationController>().GetConfiguration(LOCAL_CONFIG_PATH, DEFAULT_CONFIG_NAME); localConfig.ReadFile(); persistentConfig = GetController <IniConfigurationController>().GetConfiguration(PERSISTENT_CONFIG_PATH, DEFAULT_CONFIG_NAME); persistentConfig.ReadFile(); }
public static void AddSagasClient(this StartupConfig startupOption, Action <PoleSagasOption> configAction) { // 让客户端支持 没有TLS 的 grpc call AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); startupOption.Services.Configure(configAction); startupOption.Services.AddSingleton <IActivityFinder, ActivityFinder>(); startupOption.Services.AddSingleton <IEventSender, EventSender>(); startupOption.Services.AddSingleton <ISagaFactory, SagaFactory>(); startupOption.Services.AddHostedService <SagasCompensateRetryBackgroundService>(); PoleSagasOption sagasOption = null; using (var provider = startupOption.Services.BuildServiceProvider()) { sagasOption = provider.GetRequiredService <IOptions <PoleSagasOption> >().Value; startupOption.Services.AddGrpcClient <SagaClient>(o => { o.Address = new Uri(sagasOption.SagasServerHost); }); } RegisterActivities(startupOption); }
public static IServiceCollection AddPole(this IServiceCollection services, Action <StartupConfig> config) { StartupConfig startupOption = new StartupConfig(services); if (startupOption.PoleOptionsConfig == null) { services.Configure <PoleOptions>(option => { }); } services.AddSingleton <ISerializer, DefaultJsonSerializer>(); services.AddSingleton <IGeneratorIdSolver, InstanceIPV4_16IdGeneratorIdSolver>(); services.AddSingleton <IQueryRegister, QueryRegister>(); using (var serviceProvider = services.BuildServiceProvider()) { var generatorIdSolver = serviceProvider.GetService <IGeneratorIdSolver>(); services.AddSingleton(typeof(ISnowflakeIdGenerator), factory => new SnowflakeIdGenerator(new DateTime(2020, 1, 1), 16, generatorIdSolver.GetGeneratorId())); var queryRegister = serviceProvider.GetService <IQueryRegister>(); queryRegister.Register(services, ServiceLifetime.Scoped); } config(startupOption); return(services); }
public static void AddEventBusRabbitMQTransport( this StartupConfig startupOption, Action <RabbitOptions> rabbitConfigAction, Func <IRabbitEventBusContainer, Task> eventBusConfig = default) { startupOption.Services.Configure <RabbitOptions>(config => rabbitConfigAction(config)); startupOption.Services.AddSingleton <IRabbitMQClient, RabbitMQClient>(); startupOption.Services.AddSingleton <IRabbitEventBusContainer, EventBusContainer>(); startupOption.Services.AddSingleton <IProducer, RabbitProducer>(); startupOption.Services.AddSingleton(serviceProvider => serviceProvider.GetService <IRabbitEventBusContainer>() as IProducerInfoContainer); StartupBuilder.Register(async serviceProvider => { var container = serviceProvider.GetService <IRabbitEventBusContainer>(); var client = serviceProvider.GetService <IRabbitMQClient>(); var rabbitOptions = serviceProvider.GetService <IOptions <RabbitOptions> >().Value; if (eventBusConfig != default) { await eventBusConfig(container); } else { await container.AutoRegister(); } var consumers = container.GetConsumers(); foreach (var consumer in consumers) { if (consumer is RabbitConsumer value) { var queue = value.QueueInfo; var key = queue.Queue; var runner = new ConsumerRunner(client, serviceProvider, value, queue, rabbitOptions); ConsumerRunners.TryAdd(key, runner); await runner.Run(); } } }); }
static async Task Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Specify an input configuration file as an argument."); return; } var config = StartupConfig.FromJsonFile(args[0]); var manager = await(new UpdateManagerBuilder(config)).BuildAsync(); await manager.SynchronizeAsync(); manager.StartListening(); Console.CancelKeyPress += (_, __) => { Console.WriteLine("Terminating app..."); manager.StopListening(); }; while (true) { await Task.Delay(500); } }
public void SetUp() { StartupConfig.RegisterComponents(); }
public void RunBeforeAnyTests() { // NLog var config = new LoggingConfiguration(); var logconsole = new ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); LogManager.Configuration = config; // set config when nlog used from LogManager.GetCurrentClassLogger() NLogBuilder.ConfigureNLog(config); // set config when nlog used from asp net core // Database var factory = new DbContextFactory(); Dependencies.DbContext = factory.Build() as DbContext; // Backend api StartupConfig var startupConfig = new StartupConfig { IsTest = true, ConfigureTestServices = services => { services.AddScoped <IGraphQlDbContextFactory, DbContextFactory>(); } }; // Backend api service var basePathUrl = "https://*****:*****@NcRfUjXn2r4u7x!A%D*G-KaPdSgVkYp3s6v8y/B?E(H+MbQeThWmZq4t7w!z$C&F"; var jwtTokenService = new JwtTokenService(); var bearer = jwtTokenService.Generate(jwtToken, secretKey); var url = new UriBuilder(basePathUrl) { Path = "graphql/surveillance" }.ToString(); var client = new ApiClient(url, bearer, new HttpClientHandler { UseProxy = false }); Dependencies.ApiClient = client; }
public override void OnInitialized(StartupConfig startup) { base.OnInitialized(startup); CommandRate = LoadSettings <ConcurrentDictionary <string, int> >("CommandRate") ?? new ConcurrentDictionary <string, int>(); }
public void AddPlugin <T>(StartupConfig startupConfig) { Type type = typeof(T); InsertPlugin(type, startupConfig); }
public virtual void LoadPlugins(StartupConfig startupConfig) { Type[] supportedTypes = { typeof(CommandPlugin), typeof(ApplicationPlugin), typeof(ServicePlugin) }; foreach (var item in Directory.GetFiles(BackendDirectory, "*.dll")) { bool isValid = false; FileInfo fi = new FileInfo(item); try { Logger.Info("已发现" + fi.Name); //Assembly asm = Assembly.LoadFile(fi.FullName); Assembly asm = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(fi.FullName); //https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs#L250 //System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(asm).Unload(); Type[] t = asm.GetExportedTypes(); foreach (Type type in t) { string typeName = ""; try { if (supportedTypes.Any(supported => type.IsSubclassOf(supported))) { typeName = type.Name; InsertPlugin(type, startupConfig); isValid = true; } } catch (Exception ex) { Logger.Error(typeName + " 抛出了未处理的异常。"); Logger.Exception(ex); } } if (isValid) { Assemblies.Add(new TaggedClass <Assembly>(fi.Name, asm)); } } catch (Exception ex) { Logger.Error(ex.Message); } if (!isValid) { Logger.Warn($"\"{fi.Name}\" 不是合法的插件扩展。"); } } AllPluginInitialized?.Invoke(startupConfig); }
public virtual void OnInitialized(StartupConfig startup) { }
public virtual void AllPlugins_Initialized(StartupConfig startup) { }