public void ProcessRequest(IDictionary <string, object> environment, ResponseCallBack responseCallBack, Action <Exception> errorCallback) { Dictionary <string, dynamic> nrackEnvironment = GetNrackEnvironment(environment); var config = ConfigResolver.GetRackConfigInstance(); var builder = new Builder(config.ExecuteStart); var response = new OwinResponseAdapter(builder.Call(nrackEnvironment)); responseCallBack(response.Status, response.Headers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString()), (next, error, complete) => { try { next(response.GetBody(), null); complete(); } catch (Exception ex) { error(ex); } return(() => { }); }); }
/// <summary> /// 返回指定接口类型的实例(代理类,不需要实现) /// </summary> /// <param name="type">返回的代理类型</param> /// <param name="resolver">配置类解析方法</param> /// <returns></returns> public static object GetProxy(Type type, ConfigResolver resolver = null) { return(_feigns.GetOrAdd(type, typeInner => { if (!type.IsInterface) { throw new Exception("必须是接口类型"); } var atts = TypeHelper.GetCustomAttributes <FeignClientAttribute>(type); if (atts.Count <= 0) { throw new Exception("未找到FeignClient特性配置"); } if (atts[0].Url == null || (atts[0].Url = atts[0].Url.Trim()).Length == 0) { throw new Exception("FeignClient特性配置Url不能为空"); } var feignAtt = atts[0]; var wrapper = new ProxyInvokeWrapper(); var ret = (FeignProcess)_factory.CreateProxy(typeof(FeignProcess), wrapper, type); resolver = resolver ?? Resolver ?? ResolveConfig; ret.Config = resolver(feignAtt.Configuration); ret.Url = feignAtt.Url; return ret; })); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); IConfigResolver configResolver = new ConfigResolver(Configuration); services.AddSingleton(configResolver); services.AddSecurity(configResolver); AddSwagger(services); services.AddSingleton <TokenGenerator>(); }
public static void log(string message) { if (ConfigResolver.GetInstance().IsDebug()) { FileInfo fileIofo = new FileInfo(Assembly.GetExecutingAssembly().Location); string path = fileIofo.Directory.FullName + "\\log.txt"; StreamWriter writer = new StreamWriter(path, true, Encoding.UTF8); writer.WriteLine(message); writer.Close(); } }
public IDocumentHandler dispatch(IDocumentHandler previous) { if (DateTime.Now >= DateTime.Parse("2013-10-15")) { return(new DummyHandler(previous)); } ConfigResolver resolver = ConfigResolver.GetInstance(); UrlMatcher matcher = new UrlMatcher(this.url); if (matcher.matches(resolver.GetPopupPatterns())) { if (null != previous) { previous.destroy(); } if (matcher.matches(resolver.GetTmsPatterns())) { LogUtil.log("Match tms patterns"); return(new PopupHandler(new TMSFiller(this.document))); } else if (matcher.matches(resolver.GetPmsPatterns())) { LogUtil.log("Match pms patterns"); return(new PopupHandler(new PMSFiller(this.document))); } else if (matcher.matches(resolver.GetDmsPatterns())) { LogUtil.log("Match dms patterns"); return(new PopupHandler(new DMSFiller(this.document))); } else { return(new PopupHandler(new DummyFiller(this.document))); } } else if (matcher.matches(resolver.GetRewritePatterns())) { if (null != previous) { previous.destroy(); } return(new RewriteHandler(this.document)); } else if (matcher.matches(resolver.GetWrapPatterns())) { return(new WrapHandler()); } return(new DummyHandler(previous)); }
public StudentModel obtainData() { DataWindow window = new DataWindow(); DialogResult result = window.ShowDialog(); if (DialogResult.OK == result) { StudentModel model = window.SelectedModel; if (ConfigResolver.GetInstance().IsShowDetail()) { MessageBox.Show(model.ToString()); } return(model); } return(null); }
public ConfigModel FetchConfig(bool hasRunOnce) { var commandLineArgs = ArgumentParser.ParseCommandLine(); _logger.SetDebug(commandLineArgs.Verbose); var defaultArgs = CreateConfig(hasRunOnce); var config = ConfigResolver.ResolveConfig ( defaultArgs, commandLineArgs, _logger ); _logger.SetDebug(config.Verbose); return(config); }
public static ShopViewModel GetShopViewModel(NetworkInstanceId clientId) { var player = PlayerCharacterMasterController.instances.First(x => x.master.netId == clientId); var allItems = AugmentResolver.AllAvailableAugments; var activeForPlayer = AugmentResolver.GetActiveAugmentsForPlayer(clientId); var viewModels = new List <ShopItemViewModel>(); foreach (var item in allItems) { if (!activeForPlayer.Augments.TryGetValue(item.Key, out var existingAugments)) { existingAugments = new ConcurrentDictionary <AugmentId, AugmentBase>(); } var itemCount = player.master.inventory.GetItemCount(item.Key); var itemTier = ItemCatalog.GetItemDef(item.Key).tier; var itemCost = ConfigResolver.ItemCount(itemTier); var pointsToSpend = itemCount / (itemCost * (existingAugments.Count + 1)); var augmentViewModels = new List <AugmentViewModel>(); foreach (var augment in item.Value) { var active = existingAugments.ContainsKey(augment.Key); var level = augment.Value.GetLevel(clientId); var purchasable = pointsToSpend > 0 && level < augment.Value.MaxLevel; var viewModel = new AugmentViewModel(augment.Value, active, purchasable, level); augmentViewModels.Add(viewModel); } viewModels.Add(new ShopItemViewModel(item.Key, augmentViewModels, pointsToSpend)); } return(new ShopViewModel(viewModels)); }
private void update(SearchModel searcher) { searcher.name = nameText.Text.Trim(); searcher.code = codeText.Text.Trim(); Pagination pagination = ConfigResolver.GetInstance().GetDataProvider().Provide(searcher); ModelBindingSource.Clear(); for (int i = 0; i < pagination.Records.Count; i++) { ModelBindingSource.Add(pagination.Records[i]); } if (pagination.PageNo <= 1) { ForwardFirstLabel.Enabled = false; ForwardPrevLabel.Enabled = false; } else { ForwardFirstLabel.Enabled = true; ForwardPrevLabel.Enabled = true; } if (searcher.pageNo >= pagination.getTotalPage()) { ForwardNextLabel.Enabled = false; ForwardLastLabel.Enabled = false; } else { ForwardNextLabel.Enabled = true; ForwardLastLabel.Enabled = true; } StatisticLabel.Text = String.Format("页次:{0}/{1} 共{2}条数据", pagination.PageNo, pagination.getTotalPage(), pagination.TotalCount); PagingPanel.Tag = pagination; ForwardPageText.Text = pagination.PageNo.ToString(); StudentTable.ClearSelection(); }
public Pagination Provide(SearchModel searcher) { ConfigResolver resolver = ConfigResolver.GetInstance(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/xml;charset=UTF-8"; Encoding encoding = Encoding.GetEncoding("utf-8"); byte[] postdata = encoding.GetBytes(GetRequestParameters(searcher)); request.ContentLength = postdata.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postdata, 0, postdata.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); DataResolver dataResolver = new DataResolver(); Pagination result = dataResolver.resolve(reader); reader.Close(); return(result); }
public ConfigResolverTests() { _configResolver = new ConfigResolver(new FakeConfigFileReader()); }
public static Func <IMicroservice> CreateEventProcessor( string uniqueName, IEventStoreConfig eventStoreConfig = null, IPollerConfig pollerConfig = null, PersistencePlugin persistencePlugin = PersistencePlugin.SqlServer, bool persistIncomingPayloads = false, bool persistSnapshots = true, Func <InMemoryEventStore <TStream>, InMemoryEventStore <TStream> > setupInMemoryPersistence = null, Func <string, ITextSerializer, string, bool> consumerFilter = null, bool isSubscriptor = true, Func <IBus, ILogger, IEventStore <TStream>, THandler> processorFactory = null, Func <string, IEventStore, IBus, ILogger, int, TimeSpan, IPollableEventSource> publisherFactory = null) { return(() => { var streamFullName = EnsureStreamCategoryNameIsValid(uniqueName); var container = EventSystem.ResolveNewChildContainerAndRegisterInMemorySubscriptions(uniqueName); var inMemoryPublisher = container.Resolve <IInMemoryEventPublisher>(); eventStoreConfig = ConfigResolver.ResolveConfig(eventStoreConfig); var connectionString = eventStoreConfig.ConnectionString; AuthorizationFactory.SetToken(eventStoreConfig); PersistencePluginResolver <TStream> .ResolvePersistence( container, persistencePlugin, streamFullName, connectionString, persistIncomingPayloads, persistSnapshots, setupInMemoryPersistence, consumerFilter); var log = container.Resolve <ILogger>(); var eventStore = container.Resolve <IEventStore <TStream> >(); var bus = new Bus(); container.RegisterInstance <IBus>(bus); IPollableEventSource publisher; if (publisherFactory == null) { publisher = new Publisher(streamFullName, eventStore, bus, log, eventStoreConfig.PushMaxCount, TimeSpan.FromMilliseconds(eventStoreConfig.LongPollingTimeout)); container.RegisterInstance <IPollableEventSource>(publisher); } else { publisher = publisherFactory.Invoke(streamFullName, eventStore, bus, log, eventStoreConfig.PushMaxCount, TimeSpan.FromMilliseconds(eventStoreConfig.LongPollingTimeout)); } var fsm = new MicroserviceHost(streamFullName, bus, log, isSubscriptor); container.RegisterInstance <IMicroservice>(fsm); // Processor factory THandler processor; if (processorFactory == null) { var constructor = typeof(THandler).GetConstructor(new[] { typeof(IBus), typeof(ILogger), typeof(IEventStore <TStream>) }); Ensure.CastIsValid(constructor, "Type TProcessor must have a valid constructor with the following signature: .ctor(IBus, ILogger, IEventStore<T>)"); processor = (THandler)constructor.Invoke(new object[] { bus, log, eventStore }); } else { processor = processorFactory.Invoke(bus, log, eventStore); } container.RegisterInstance <IProcessor <TStream> >(processor); // For nodes that polls events from subscribed sources if (isSubscriptor) { pollerConfig = ConfigResolver.ResolveConfig(pollerConfig); var receiver = new LongPoller(bus, log, TimeSpan.FromMilliseconds(pollerConfig.Timeout), streamFullName, inMemoryPublisher); var poller = new Poller(bus, log, inMemoryPublisher, container.Resolve <ISubscriptionRepository>(), receiver, container.Resolve <ITextSerializer>(), pollerConfig.BufferQueueMaxCount, pollerConfig.EventsToFlushMaxCount); container.RegisterInstance <IMonitoredSubscriber>(poller); //var heartbeatEmitter = new HeartbeatEmitter(fsm, log, poller); var heartbeatEmitter = new HeartbeatEmitter(streamFullName); container.RegisterInstance <HeartbeatEmitter>(heartbeatEmitter); } inMemoryPublisher.Register(publisher); return fsm; }); }
public static Func <IMicroservice> CreateDenormalizer <TDbContext>( string uniqueName, IEventStoreConfig eventStoreConfig = null, IPollerConfig pollerConfig = null, bool persistIncomingPayloads = true, Func <IBus, ILogger, IEventStore <TStream>, THandler> processorFactory = null) where TDbContext : DbContext, IEventStoreDbContext { return(() => { var streamFullName = EnsureStreamCategoryNameIsValid(uniqueName); var container = EventSystem.ResolveNewChildContainerAndRegisterInMemorySubscriptions(streamFullName); System.Data.Entity.Database.SetInitializer <TDbContext>(null); pollerConfig = ConfigResolver.ResolveConfig(pollerConfig); eventStoreConfig = ConfigResolver.ResolveConfig(eventStoreConfig); var connectionString = eventStoreConfig.ConnectionString; AuthorizationFactory.SetToken(eventStoreConfig); Func <bool, EventStoreDbContext> storeContextFactory = isReadOnly => new EventStoreDbContext(isReadOnly, connectionString); Func <bool, EventQueueDbContext> queueContextFactory = isReadOnly => new EventQueueDbContext(isReadOnly, connectionString); var log = container.Resolve <ILogger>(); var serializer = container.Resolve <ITextSerializer>(); var time = container.Resolve <IUtcTimeProvider>(); var guid = container.Resolve <IGuidProvider>(); // Do not know why an EventStore will need a denormalizer... and a Publisher! // The only events that can (and sould) be queries is 'ReadModelUpdated'. var dbContextConstructor = typeof(TDbContext).GetConstructor(new[] { typeof(bool), typeof(string) }); Ensure.CastIsValid(dbContextConstructor, "Type TDbContext must have a constructor with the following signature: ctor(bool, string)"); Func <bool, IEventStoreDbContext> dbContextFactory = isReadOnly => (TDbContext)dbContextConstructor.Invoke(new object[] { isReadOnly, connectionString }); var eventStore = new OrmEventStore <TStream>(streamFullName, serializer, dbContextFactory, time, guid, log, persistIncomingPayloads, null); container.RegisterInstance <IEventStore <TStream> >(eventStore); var bus = new Bus(); container.RegisterInstance <IBus>(bus); var receiver = new LongPoller(bus, log, TimeSpan.FromMilliseconds(pollerConfig.Timeout), streamFullName, container.Resolve <IInMemoryEventPublisher>()); var poller = new Poller(bus, log, container.Resolve <IInMemoryEventPublisher>(), eventStore, receiver, serializer, pollerConfig.BufferQueueMaxCount, pollerConfig.EventsToFlushMaxCount); container.RegisterInstance <IMonitoredSubscriber>(poller); var publisher = new Publisher(streamFullName, eventStore, bus, log, eventStoreConfig.PushMaxCount, TimeSpan.FromMilliseconds(eventStoreConfig.LongPollingTimeout)); container.RegisterInstance <IPollableEventSource>(publisher); var fsm = new MicroserviceHost(streamFullName, bus, log, true); container.RegisterInstance <IMicroservice>(fsm); if (processorFactory == null) { var processorConstructor = typeof(THandler).GetConstructor(new[] { typeof(IBus), typeof(ILogger), typeof(IEventStore <TStream>) }); Ensure.CastIsValid(processorConstructor, "Type THandler must have a valid constructor with the following signature: .ctor(IBus, ILogger, IEventStore<T>)"); var processor = (THandler)processorConstructor.Invoke(new object[] { bus, log, eventStore }); } else { var processor = processorFactory.Invoke(bus, log, eventStore); } //var heartbeatEmitter = new HeartbeatEmitter(fsm, log, poller); var heartbeatEmitter = new HeartbeatEmitter(streamFullName); return fsm; }); }
/// <summary> /// 返回指定接口类型的实例(代理类,不需要实现) /// </summary> /// <typeparam name="TInterface">返回的代理类型</typeparam> /// <param name="resolver">配置类解析方法</param> /// <returns></returns> public static TInterface GetProxy <TInterface>(ConfigResolver resolver = null) { return((TInterface)GetProxy(typeof(TInterface), resolver)); }
public void ProcessRequest(HttpContext context) { if (_config == null) { _config = ConfigResolver.GetRackConfigInstance(); _getBuilderInContext = () => new Builder(_config.ExecuteStart); } var rawEnvironment = context.Request.ServerVariables; Dictionary <string, dynamic> environment = rawEnvironment.AllKeys.ToDictionary(key => key, key => (object)rawEnvironment[key]); environment["SCRIPT_NAME"] = string.Empty; //if ((string)environment["SCRIPT_NAME"] == string.Empty) //{ // environment["SCRIPT_NAME"] = "/"; //} var rackEnvs = new Dictionary <string, dynamic> { { "rack.version", RackVersion.Version }, { "rack.input", context.Request.InputStream }, { "rack.errors", Console.OpenStandardError() }, { "rack.multithread", true }, { "rack.multiprocess", false }, { "rack.run_once", false }, { "rack.url_scheme", context.Request.IsSecureConnection ? "https" : "http" } }; environment = environment.Union(rackEnvs).ToDictionary(key => key.Key, val => val.Value); //if (!environment.ContainsKey("SCRIPT_NAME")) //{ // environment["SCRIPT_NAME"] = string.Empty; //} var builder = _getBuilderInContext(); var responseArray = builder.Call(environment); var response = AspNetResponse.Create(responseArray); context.Response.StatusCode = response.StatusCode; //context.Response.Headers.Add(response.Headers); if (response.Headers != null) { foreach (var key in response.Headers.AllKeys) { context.Response.AddHeader(key, response.Headers[key]); } } response.Body.Each((Action <dynamic>)(body => { if (body is string) { context.Response.Write(body); } else if (body is byte[]) { context.Response.BinaryWrite(body); } })); var methodInfos = (IEnumerable <MethodInfo>)response.Body.GetType().GetMethods(); var closeMethods = Enumerable.Where(methodInfos, method => method.Name == "Close"); foreach (var method in closeMethods) { if (method.GetParameters().Length == 0 && method.ReturnType.Equals(typeof(void))) { method.Invoke(response.Body, null); break; } } }
private void InitializeMenu() { ContextMenu contextMenu = new ContextMenu(); output = new MenuItem(Resources.Resources.GetString("OutputText")); foreach (var plugin in PluginResolver.GetPlugins()) { MenuItem item = new MenuItem(); item.Text = plugin.GetOutputName(); item.Click += delegate { foreach (var it in output.MenuItems) { if (it != item) { MenuItem i = (MenuItem)it; i.Checked = false; } } item.Checked = true; ConfigResolver.ChangeOutput(plugin.GetHashCode().ToString()); label1.Text = plugin.GetOutputName(); }; output.MenuItems.Add(item); } contextMenu.MenuItems.Add(output); contextMenu.MenuItems.Add(Resources.Resources.GetString("OptionsText")); contextMenu.MenuItems.Add(Resources.Resources.GetString("BrowseText")); contextMenu.MenuItems.Add("-"); contextMenu.MenuItems.Add(Resources.Resources.GetString("HideText")); contextMenu.MenuItems.Add("-"); contextMenu.MenuItems.Add(Resources.Resources.GetString("ExitText")); contextMenu.MenuItems[1].Click += delegate { var OptionsForm = new Configures(); if (OptionsForm.ShowDialog() == DialogResult.OK) { this.Refresh(); f2.Refresh(); f2.TopMost = true; this.TopMost = true; f2.TopMost = false; this.TopMost = false; } }; contextMenu.MenuItems[2].Click += delegate { string windir = Environment.GetEnvironmentVariable("WINDIR"); System.Diagnostics.Process prc = new System.Diagnostics.Process(); prc.StartInfo.FileName = windir + @"\explorer.exe"; prc.StartInfo.Arguments = ConfigurationManager.AppSettings["Destination"]; prc.Start(); }; contextMenu.MenuItems[4].Click += delegate { this.WindowState = FormWindowState.Minimized; }; contextMenu.MenuItems[6].Click += delegate { Application.Exit(); }; this.ContextMenu = contextMenu; icon.ContextMenu = contextMenu; }