internal static ProxyProviderBase CreateProvider (ProxyConfiguration proxyConfiguration) { switch (proxyConfiguration.ProxyType) { case ProxyType.Remote: { return new RemoteDomainProxyProvider(proxyConfiguration); } default: { return new DefaultProxyProvider(proxyConfiguration); } } }
/// <summary> /// Initializes a new instance of the <see cref="DefaultProxy"/> class. /// </summary> /// <param name="proxyConfiguration">The proxy configuration to use.</param> /// <param name="logger">The logging interface.</param> public DefaultProxy(ProxyConfiguration proxyConfiguration, ILogger logger) { if (proxyConfiguration == null) { throw new ArgumentNullException(nameof(proxyConfiguration)); } if (!string.IsNullOrEmpty(proxyConfiguration.Username) || !string.IsNullOrEmpty(proxyConfiguration.Password)) { logger.LogInformation("Using supplied proxy credentials"); _credentials = new NetworkCredential(proxyConfiguration.Username, proxyConfiguration.Password); } var host = proxyConfiguration.Host; if (!host.Contains(":")) { var port = proxyConfiguration?.Port ?? 8080; host = $"{host}:{port}"; } logger.LogInformation($"Using proxy host {host}"); _proxyUri = new Uri(host, UriKind.Absolute); }
private void RestWebApiRefresh() { ProxyConfiguration config = new ProxyConfiguration("http://localhost:59876/api"); IFooRest fooSvc = SimpleProxy.Proxy.For<IFooRest>(config); IEnumerable<Foo> foos = fooSvc.FindAll(); lstRestWebApi.Items.Clear(); foreach (Foo foo in foos) { lstRestWebApi.Items.Add(foo.ToListViewItem()); } }
private void RestWebApiAdd() { string bar = BarDialog.ShowDialog(string.Empty); ProxyConfiguration config = new ProxyConfiguration("http://localhost:59876/api"); IFooRest fooSvc = SimpleProxy.Proxy.For<IFooRest>(config); fooSvc.Add(new Foo { Bar = bar }); RestWebApiRefresh(); }
private void PageMethodsWebFormsRefresh() { ProxyConfiguration config = new ProxyConfiguration("http://localhost:59878"); IFooPageMethods fooSvc = SimpleProxy.Proxy.For<IFooPageMethods>(config); GetAllFoosResponse result = fooSvc.FindAll(); IEnumerable<Foo> foos = result.D; lstPageMethodsWebForms.Items.Clear(); foreach (Foo foo in foos) { lstPageMethodsWebForms.Items.Add(foo.ToListViewItem()); } }
private void PageMethodsWebFormsAdd() { string bar = BarDialog.ShowDialog(string.Empty); ProxyConfiguration config = new ProxyConfiguration("http://localhost:59878"); IFooPageMethods fooSvc = SimpleProxy.Proxy.For<IFooPageMethods>(config); fooSvc.Add(new AddParameters { foo = new Foo { Bar = bar } }); //fooSvc.Add(new Foo { Bar = bar }); PageMethodsWebFormsRefresh(); }
public CustomProxyController(ProxyConfiguration configuration) { Configuration = configuration; }
public void DistributorApi_ProcessAsyncOperationsFromProxy() { const int proxyServer = 22213; const int distrServer1 = 22214; const int distrServer12 = 22215; const int storageServer = 22216; #region hell var writer = new HashWriter(new HashMapConfiguration("TestClientDistributor", HashMapCreationMode.CreateNew, 1, 1, HashFileType.Distributor)); writer.CreateMap(); writer.SetServer(0, "localhost", storageServer, 157); writer.Save(); var netconfig = new NetConfiguration("localhost", proxyServer, "testService", 10); var toconfig = new ProxyConfiguration(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); var common = new CommonConfiguration(1, 100); var proxy = new TestGate(netconfig, toconfig, common); var distrNet = new DistributorNetConfiguration("localhost", distrServer1, distrServer12, "testService", 10); var distrConf = new DistributorConfiguration(1, "TestClientDistributor", TimeSpan.FromMilliseconds(100000), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), TimeSpan.FromMilliseconds(10000)); var distr = new DistributorApi(distrNet, distrConf, common); var storageNet = new StorageNetConfiguration("localhost", storageServer, 157, "testService", 10); var storageConfig = new StorageConfiguration("TestClientDistributor", 1, 10, TimeSpan.FromHours(1), TimeSpan.FromHours(1), TimeSpan.FromHours(1), TimeSpan.FromHours(1), false); var storage = new WriterApi(storageNet, storageConfig, common); #endregion proxy.Build(); proxy.Start(); distr.Build(); distr.Start(); proxy.Int.SayIAmHere("localhost", distrServer1); storage.Build(); storage.AddDbModule(new TestInMemoryDbFactory()); storage.Start(); const int count = 50; for (int i = 0; i < count; i++) { var state = proxy.Int.CreateSync(i, i); Assert.AreEqual(RequestState.Complete, state.State); } for (int i = 0; i < count; i++) { RequestDescription description; var read = proxy.Int.Read(i, out description); Assert.AreEqual(i, read); Assert.AreEqual(RequestState.Complete, description.State); } for (int i = 0; i < count; i++) { var state = proxy.Int.DeleteSync(i); Assert.AreEqual(RequestState.Complete, state.State); } for (int i = 0; i < count; i++) { RequestDescription description; proxy.Int.Read(i, out description); Assert.AreEqual(RequestState.DataNotFound, description.State); } proxy.Dispose(); distr.Dispose(); storage.Dispose(); }
public RedisGate(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration, CommonConfiguration commonConfiguration, TimeoutConfiguration timeoutConfiguration) : base(netConfiguration, proxyConfiguration, commonConfiguration, timeoutConfiguration) { }
public Startup(IConfiguration configuration, IWebHostEnvironment environment) { Configuration = configuration; Environment = environment; ProxyConfiguration = ProxyConfiguration.FromConfiguration(configuration); }
public ProxyFactory(IServiceProvider serviceProvider, IProxyGenerator proxyGenerator, ProxyConfiguration configuration) { _serviceProvider = serviceProvider; _proxyGenerator = proxyGenerator; _configuration = configuration; }
// user arbitrary thread ProxyPeer IEngine.NewProxyPeer(ProxyConfiguration config, VcallSubsystem core) { var timeout = TimeSpan.FromMilliseconds(_self.vconfig.Timeouts.ProxyOpening); int addressInUseRetries = 0; for (;;) { var proxy = new ProxyPeer(config, core); string uri = make_dynamic_uri(proxy.Tag, config.ProxyRole); try { proxy.Start(uri, timeout); return proxy; } catch (Exception ex) { if (ex.IsConsequenceOf<AddressAlreadyInUseException>()) { addressInUseRetries++; if (addressInUseRetries <= _self.vconfig.AddressInUseRetries) { warn("Dynamic URI '{0}' is in use; trying other one (retries={1})", uri, addressInUseRetries); continue; } lock (_self.mutex) _self.counters.Vcall_Error_AddressInUse++; throw Helpers.MakeNew<VcallException>(ex, _log, "proxy.{0}: Failed to listen on '{1}'; probably the TCP port is constantly in use (retries={2})", proxy.Tag, uri, addressInUseRetries); } lock (_self.mutex) _self.counters.Vcall_Error_NewProxyFailed++; throw; } } }
public static IApplicationBuilder UseProxySupportIfNecessary(this IApplicationBuilder app, ProxyConfiguration proxyConfiguration) { var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger("Acheve"); switch (proxyConfiguration.ProxyBehavior) { case ProxyBehavior.NoProxy when proxyConfiguration.IsDefaultPathBase: logger.LogInformation( "Proxy behavior: {proxyBehavior}. No proxy configuration required", proxyConfiguration.ProxyBehavior); break; case ProxyBehavior.NoProxy: logger.LogWarning( "Proxy behavior is {proxyBehavior} but a non default PathBase has been configured {PathBase}. Review your configuration", proxyConfiguration.ProxyBehavior, proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash); break; case ProxyBehavior.MaintainProxyPath when proxyConfiguration.IsDefaultPathBase: logger.LogWarning( "Proxy behavior is {proxyBehavior} but no PathBase has been configured. Review your configuration", proxyConfiguration.ProxyBehavior, proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash); break; case ProxyBehavior.MaintainProxyPath: logger.LogInformation( "Proxy behavior: {proxyBehavior}. Using PathBase middleware with path: {PathBase}", proxyConfiguration.ProxyBehavior, proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash); app.UsePathBase(new PathString(proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash)); break; case ProxyBehavior.RemoveProxyPath when proxyConfiguration.IsDefaultPathBase: logger.LogWarning( "Proxy behavior is {proxyBehavior} but no PathBase has been configured. Review your configuration", proxyConfiguration.ProxyBehavior, proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash); break; case ProxyBehavior.RemoveProxyPath: logger.LogInformation( "Proxy behavior: {proxyBehavior}. Set PathBase manually with path: {PathBase}", proxyConfiguration.ProxyBehavior, proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash); app.Use((context, next) => { context.Request.PathBase = proxyConfiguration.DefaultOrCurrentPathBaseWithoutTrailingSlash; return(next()); }); break; } return(app); }
// user arbitrary thread IProxy IVcallSubsystem.NewProxy(ProxyConfiguration config) { if (config == null) config = new ProxyConfiguration(); if (config.ProxyRole == null) config.ProxyRole = _self.vconfig.ProxyRole; if (config.HostingRole == null) config.HostingRole = _self.vconfig.HostingRole; if (config.NonRegisteredCall == NonRegisteredCallPolicy.Default) config.NonRegisteredCall = _self.vconfig.NonRegisteredCall; if (config.SubscribeToHosting_RetryTimeout == null) config.SubscribeToHosting_RetryTimeout = _self.vconfig.Timeouts.ProxyHostingSubscriptionRetry; ProxyPeer peer; using (Context.With(_countersDb)) { peer = _engine.NewProxyPeer(config, this); } string callbackUri = peer.ListeningUri; _self.resolver.Publish(callbackUri, config.ProxyRole, peer.Tag); _self.resolver.Subscribe(peer.HandlePublisher, peer.Tag); lock (_self.mutex) { _self.repo.Add(peer); _self.counters.Vcall_Event_NewProxy++; } trace("proxy.{0} is started", peer.Tag); var ibus = new InvocationBus(peer, this, config); peer.Subscribe(ibus.HandleNewHosting); return ibus; }
public void CollectorNet_ReadFromWriter() { const int proxyServer = 22337; const int distrServer1 = 22338; const int distrServer12 = 22339; const int st1 = 22335; const int st2 = 22336; #region hell var writer = new HashWriter(new HashMapConfiguration("TestCollectorNet", HashMapCreationMode.CreateNew, 1, 1, HashFileType.Distributor)); writer.CreateMap(); writer.SetServer(0, "localhost", st1, st2); writer.Save(); var common = new CommonConfiguration(1, 100); var netconfig = new NetConfiguration("localhost", proxyServer, "testService", 10); var toconfig = new ProxyConfiguration(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); var proxy = new TestGate(netconfig, toconfig, common); var distrNet = new DistributorNetConfiguration("localhost", distrServer1, distrServer12, "testService", 10); var distrConf = new DistributorConfiguration(1, "TestCollectorNet", TimeSpan.FromMilliseconds(100000), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), TimeSpan.FromMilliseconds(10000)); var distr = new DistributorApi(distrNet, distrConf, common); var storageNet = new StorageNetConfiguration("localhost", st1, st2, "testService", 10); var storageConfig = new StorageConfiguration("TestCollectorNet", 1, 10, TimeSpan.FromHours(1), TimeSpan.FromHours(1), TimeSpan.FromHours(1), TimeSpan.FromHours(1), false); var storage = new WriterApi(storageNet, storageConfig, common); var async = new AsyncTaskModule(new QueueConfiguration(4, 10)); var distributor = new DistributorModule(new CollectorModel(new DistributorHashConfiguration(1), new HashMapConfiguration("TestCollectorNet", HashMapCreationMode.ReadFromFile, 1, 1, HashFileType.Collector)), async, new AsyncTasksConfiguration(TimeSpan.FromMinutes(1))); var net = new CollectorNetModule(new ConnectionConfiguration("testService", 10), new ConnectionTimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout), distributor); distributor.SetNetModule(net); var back = new BackgroundModule(new QueueConfiguration(5, 10)); var loader = new DataLoader(net, 100, back); var parser = new TestIntParser(); parser.SetCommandsHandler( new UserCommandsHandler <TestCommand, Type, TestCommand, int, int, TestDbReader>( new TestUserCommandCreator(), new TestMetaDataCommandCreator())); var merge = new OrderMerge(loader, parser); var searchModule = new SearchTaskModule("Int", merge, loader, distributor, back, parser); storage.Build(); proxy.Build(); distr.Build(); storage.AddDbModule(new TestInMemoryDbFactory()); storage.Start(); proxy.Start(); distr.Start(); searchModule.Start(); distributor.Start(); merge.Start(); back.Start(); net.Start(); async.Start(); #endregion proxy.Int.SayIAmHere("localhost", distrServer1); const int count = 20; for (int i = 0; i < count; i++) { var request = proxy.Int.CreateSync(i, i); Assert.AreEqual(RequestState.Complete, request.State); } var reader = searchModule.CreateReader("asc", -1, 20); reader.Start(); for (int i = 0; i < count; i++) { Assert.IsTrue(reader.IsCanRead); reader.ReadNext(); Assert.AreEqual(i, reader.GetValue(0)); } reader.ReadNext(); Assert.IsFalse(reader.IsCanRead); reader.Dispose(); back.Dispose(); net.Dispose(); storage.Dispose(); proxy.Dispose(); distr.Dispose(); async.Dispose(); }
/// <summary> /// Gets an RPC proxy for the provided interface. /// </summary> /// <typeparam name="IT">The interface type.</typeparam> /// <param name="address">The service address.</param> /// <param name="configuration">The configuration.</param> /// <returns></returns> public IT Proxy <IT>(string address, ProxyConfiguration configuration) { return(Proxy <IT>(address, configuration)); }
/// <summary> /// Returns the invocation advices for specified method. /// </summary> /// <param name="method"></param> /// <returns></returns> public IEnumerable <ISolidProxyInvocationAdvice> GetInvocationAdvices(MethodInfo method) { var proxyInvocationConfiguration = ProxyConfiguration.GetProxyInvocationConfiguration(method); return(proxyInvocationConfiguration.GetSolidInvocationAdvices()); }
/// <summary> /// Gets an RPC proxy for the provided interface. /// </summary> /// <typeparam name="IT">The interface type.</typeparam> /// <param name="address">The service address.</param> /// <param name="configuration">The configuration.</param> /// <returns></returns> public IT Proxy <IT>(string address, ProxyConfiguration configuration) { return(Proxy <IT>(new ServiceAddress(address), configuration)); }
public CustomProxyController(ProxyConfiguration configuration, ManualProxyParameters manualProxyParameters) { ManualProxyParameters = manualProxyParameters; Configuration = configuration; }
public DashboardController(IOptionsSnapshot <ProxyConfiguration> appConfiguration) { ProxyConfiguration = appConfiguration.Value; }
internal static IEnumerable <InvocationContext> GetInterceptorMetadataForMethod( IInvocation invocation, IServiceProvider serviceProvider, ProxyConfiguration proxyConfiguration) { var interceptorList = new List <InvocationContext>(); var classAttributes = FilterInterceptionAttributes(invocation.InvocationTarget.GetType().GetCustomAttributes()); var methodAttributes = FilterInterceptionAttributes(invocation.MethodInvocationTarget.GetCustomAttributes()); var attribtutes = classAttributes.Concat(methodAttributes) .ToList(); var clearAttributeIndex = attribtutes.FindLastIndex(x => x is ClearInterceptorsAttribute); if (clearAttributeIndex != -1) { attribtutes = attribtutes .Skip(clearAttributeIndex + 1) .ToList(); } /* * If same attribute is applied to a class and a method, * we check if it allows multiple and either take both * or the one, applied to the method. Double reverse is * required to keep correct interceptors order. */ var finalInterceptors = attribtutes.AsEnumerable() .Cast <InterceptionAttribute>() .Reverse() .GroupBy(x => x.GetType()) .SelectMany( x => x.Key.GetCustomAttribute <AttributeUsageAttribute>() ?.AllowMultiple ?? false ? x.ToArray() : new[] { x.First() }) .Reverse() .ToList(); foreach (var interceptionAttribute in finalInterceptors) { var interceptorType = proxyConfiguration.ConfiguredInterceptors .FirstOrDefault(x => x.AttributeType == interceptionAttribute.GetType()) ?.InterceptorType; if (interceptorType == null) { throw new InvalidInterceptorException( $"The Interceptor Attribute '{interceptionAttribute}' is applied to the method, but there is no configured interceptor to handle it"); } var instance = (AspectBase)ActivatorUtilities.CreateInstance(serviceProvider, interceptorType); var context = new InvocationContext { Attribute = interceptionAttribute, Interceptor = instance, Invocation = invocation, ServiceProvider = serviceProvider }; interceptorList.Add(context); } return(interceptorList); }
public async Task ApplyProxyConfAsync(ProxyConfiguration proxyConfiguration, IProgress <ProgressReport> progress) { ProgressReport prgReport = new ProgressReport { ProgressMessage = "Applying Proxy Configuration", ProgressValue = 0 }; progress.Report(prgReport); await Task.Run(async() => { _registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); prgReport.ProgressMessage = "Applying Proxy IP address and port"; prgReport.ProgressValue = ((1 * 100 / 5)); progress.Report(prgReport); await Task.Delay(1000); _registry.SetValue("ProxyServer", string.Format("{0}:{1}", proxyConfiguration.ProxyAddress, proxyConfiguration.ProxyPort.ToString())); prgReport.ProgressMessage = "Clearing Advanced settings"; prgReport.ProgressValue = ((2 * 100 / 5)); progress.Report(prgReport); await Task.Delay(1000); _registry.SetValue("ProxyOverride", string.Empty); string proxyExceptions = proxyConfiguration.ProxyExceptions == null ? string.Empty : proxyConfiguration.ProxyExceptions; if (proxyConfiguration.UseProxyForLocalAddresses) { if (string.IsNullOrEmpty(proxyExceptions)) { proxyExceptions += "<local>"; } else { proxyExceptions += ";<local>"; } } prgReport.ProgressMessage = "Applying configuration advanced settings"; prgReport.ProgressValue = ((3 * 100 / 5)); progress.Report(prgReport); await Task.Delay(1000); _registry.SetValue("ProxyOverride", proxyExceptions); prgReport.ProgressMessage = "Enabling Proxy Server"; prgReport.ProgressValue = ((4 * 100 / 5)); progress.Report(prgReport); await Task.Delay(1000); _registry.SetValue("ProxyEnable", 1); _registry.Close(); _registry.Dispose(); await Task.Delay(1000); await Task.Run(() => { settingsReturn = SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); refreshReturn = SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); }); prgReport.ProgressMessage = "Proxy Configuration Applied"; prgReport.ProgressValue = ((5 * 100 / 5)); progress.Report(prgReport); }); }
private void PageMethodsWebFormsDelete() { if (lstPageMethodsWebForms.SelectedItems.Count != 1) { MessageBox.Show("Please select one item in the list.", "PageMethods WebForms - Delete"); return; } int theId = 0; if (int.TryParse((string)lstPageMethodsWebForms.SelectedItems[0].Tag, out theId)) { ProxyConfiguration config = new ProxyConfiguration("http://localhost:59878"); IFooPageMethods fooSvc = SimpleProxy.Proxy.For<IFooPageMethods>(config); fooSvc.Delete(new FooByIdParameters { id = theId }); } else { MessageBox.Show("Invalid Foo.", "PageMethods WebForms - Delete"); lstPageMethodsWebForms.SelectedItems.Clear(); } PageMethodsWebFormsRefresh(); }
public TestGate(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration, CommonConfiguration commonConfiguration) : base(netConfiguration, proxyConfiguration, commonConfiguration) { }
private void PageMethodsWebFormsUpdate() { if (lstPageMethodsWebForms.SelectedItems.Count != 1) { MessageBox.Show("Please select one item in the list.", "PageMethods WebForms - Update"); return; } int theId = 0; if (int.TryParse((string)lstPageMethodsWebForms.SelectedItems[0].Tag, out theId)) { ProxyConfiguration config = new ProxyConfiguration("http://localhost:59878"); IFooPageMethods fooSvc = SimpleProxy.Proxy.For<IFooPageMethods>(config); GetFooByIdResponse response = fooSvc.GetById(new FooByIdParameters { id = theId }); Foo foo = response.D; string theBar = BarDialog.ShowDialog(foo.Bar); if (null != theBar) { foo.Bar = theBar; fooSvc.Update(new UpdateParameters { id = foo.Id, value = foo }); } } else { MessageBox.Show("Invalid Foo.", "PageMethods WebForms - Update"); lstPageMethodsWebForms.SelectedItems.Clear(); } PageMethodsWebFormsRefresh(); }
protected ProxyApi(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration, CommonConfiguration commonConfiguration) : this(netConfiguration, proxyConfiguration, commonConfiguration, new TimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout)) { }
private void RestWebApiDelete() { if (lstRestWebApi.SelectedItems.Count != 1) { MessageBox.Show("Please select one item in the list.", "REST WebApi - Delete"); return; } int theId = 0; if (int.TryParse((string)lstRestWebApi.SelectedItems[0].Tag, out theId)) { ProxyConfiguration config = new ProxyConfiguration("http://localhost:59876/api"); IFooRest fooSvc = SimpleProxy.Proxy.For<IFooRest>(config); fooSvc.Delete(theId); } else { MessageBox.Show("Invalid Foo.", "REST WebApi - Delete"); lstRestWebApi.SelectedItems.Clear(); } RestWebApiRefresh(); }
public Startup(IConfiguration configuration) { Configuration = configuration; ProxyConfiguration = ProxyConfiguration .FromConfiguration(configuration); }
private void RestWebApiUpdate() { if (lstRestWebApi.SelectedItems.Count != 1) { MessageBox.Show("Please select one item in the list.", "REST WebApi - Update"); return; } int theId = 0; if (int.TryParse((string)lstRestWebApi.SelectedItems[0].Tag, out theId)) { ProxyConfiguration config = new ProxyConfiguration("http://localhost:59876/api"); IFooRest fooSvc = SimpleProxy.Proxy.For<IFooRest>(config); Foo foo = fooSvc.GetById(theId); string theBar = BarDialog.ShowDialog(foo.Bar); if (null != theBar) { foo.Bar = theBar; fooSvc.Update(foo.Id, foo); } } else { MessageBox.Show("Invalid Foo.", "REST WebApi - Update"); lstRestWebApi.SelectedItems.Clear(); } RestWebApiRefresh(); }
public RemoteDomainProxyProvider(ProxyConfiguration config) : base(config) { }
public ProxyController(ISharedHttpClient httpClient, ProxyConfiguration proxyConfiguration) { _httpClient = httpClient; _proxyConfiguration = proxyConfiguration; }
private static void ConfigureServices(HostBuilderContext context, IServiceCollection services) { services .AddAndConfigureMqtt("BlueRiiot2MQTT", configuration => { BlueRiiotHassConfiguration blueRiiotConfig = context.Configuration.GetSection("HASS").Get <BlueRiiotHassConfiguration>(); configuration.SendDiscoveryDocuments = blueRiiotConfig.EnableHASSDiscovery; }) .Configure <CommonMqttConfiguration>(x => x.ClientId = "blueriiot2mqtt") .Configure <CommonMqttConfiguration>(context.Configuration.GetSection("MQTT")); // Commands services .AddMqttCommandService() .AddMqttCommandHandler <ForceSyncCommand>() .AddMqttCommandHandler <ReleaseLastUnprocessedCommand>() .AddMqttCommandHandler <SetPumpScheduleCommand>(); services .Configure <BlueRiiotHassConfiguration>(context.Configuration.GetSection("HASS")) .Configure <HassConfiguration>(context.Configuration.GetSection("HASS")) .Configure <BlueRiiotConfiguration>(context.Configuration.GetSection("BlueRiiot")) .Configure <ProxyConfiguration>(context.Configuration.GetSection("Proxy")) .AddSingleton(x => new HassMqttTopicBuilder(x.GetOptions <HassConfiguration>())) .AddHttpClient("blueriiot") .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60) })) .ConfigurePrimaryHttpMessageHandler(provider => { ProxyConfiguration proxyConfig = provider.GetOptions <ProxyConfiguration>(); SocketsHttpHandler handler = new SocketsHttpHandler(); if (proxyConfig.Uri != null) { handler.Proxy = new WebProxy(proxyConfig.Uri); } return(handler); }) .Services .AddBlueRiiotClient((provider, builder) => { IHttpClientFactory httpFactory = provider.GetRequiredService <IHttpClientFactory>(); BlueRiiotConfiguration config = provider.GetOptions <BlueRiiotConfiguration>(); builder .UseUsernamePassword(config.Username, config.Password) .UseHttpClientFactory(httpFactory, "blueriiot", settings => { if (config.ServerUrl != null) { settings.ServerUri = config.ServerUrl; } }); }); services .AddAllFeatureUpdaters() .AddSingleton <FeatureUpdateManager>() .AddSingleton <SingleBlueRiiotPoolUpdaterFactory>() .AddSingleton <BlueRiiotMqttService>() .AddHostedService(x => x.GetRequiredService <BlueRiiotMqttService>()); }
/// <summary> /// Saves the specified filename. /// </summary> /// <param name="filename">The filename.</param> /// <param name="document">The document.</param> public static bool Save(List <NetworkProfile> profiles, string filename = "Profiles.xml") { XmlTextWriter writer = new XmlTextWriter(filename, null); writer.WriteStartDocument(); writer.Indentation = 1; writer.IndentChar = '\t'; writer.WriteStartElement("profiles"); foreach (NetworkProfile item in profiles) { writer.WriteStartElement("profile"); writer.WriteAttributeString("name", item.Name); writer.WriteAttributeString("id", item.Id.ToString()); writer.WriteAttributeString("imageName", item.ImageName); { WindowsNetworkCard nic = item.NetworkCardInfo; writer.WriteStartElement("networkcard"); if (nic.Id.Length > 0) { XmlUtility.WriteAttributeIfPresent(writer, "id", nic.Id); XmlUtility.WriteAttributeIfPresent(writer, "viewId", nic.ViewId); XmlUtility.WriteAttributeIfPresent(writer, "hardwareName", nic.HardwareName); XmlUtility.WriteAttributeIfPresent(writer, "name", nic.Name); XmlUtility.WriteAttributeIfPresent(writer, "dhcp", nic.Dhcp.ToString()); XmlUtility.WriteAttributeIfPresent(writer, "ipAddress", nic.IpAddress); XmlUtility.WriteAttributeIfPresent(writer, "subnetMask", nic.SubnetMask); XmlUtility.WriteAttributeIfPresent(writer, "defaultGateway", nic.GatewayAddress); XmlUtility.WriteAttributeIfPresent(writer, "macAddress", nic.MacAddress); XmlUtility.WriteAttributeIfPresent(writer, "dynamicDns", nic.DynamicDNS.ToString()); XmlUtility.WriteAttributeIfPresent(writer, "dns", nic.Dns); XmlUtility.WriteAttributeIfPresent(writer, "dns2", nic.Dns2); XmlUtility.WriteAttributeIfPresent(writer, "winsPrimaryServer", nic.WinsPrimaryServer); XmlUtility.WriteAttributeIfPresent(writer, "winsSecondaryServer", nic.WinsSecondaryServer); } writer.WriteEndElement(); } { ProxyConfiguration proxy = item.ProxyConfig; writer.WriteStartElement("proxy"); writer.WriteAttributeString("enabled", proxy.Enabled.ToString()); XmlUtility.WriteAttributeIfPresent(writer, "serverAddress", proxy.ServerAddress); XmlUtility.WriteAttributeIfPresent(writer, "port", proxy.Port.ToString()); writer.WriteAttributeString("overrideEnabled", proxy.ProxyOverrideEnabled.ToString()); XmlUtility.WriteAttributeIfPresent(writer, "proxyOverride", proxy.ProxyOverride.ToString()); writer.WriteEndElement(); } { writer.WriteStartElement("driveMaps"); List <DriveMap> listDriveMap = item.DriveMapList; foreach (DriveMap itemDriveMap in listDriveMap) { writer.WriteStartElement("driveMap"); writer.WriteAttributeString("name", itemDriveMap.Name); XmlUtility.WriteAttributeIfPresent(writer, "drive", itemDriveMap.Drive); XmlUtility.WriteAttributeIfPresent(writer, "description", itemDriveMap.Description); XmlUtility.WriteAttributeIfPresent(writer, "username", itemDriveMap.Username); XmlUtility.WriteAttributeIfPresent(writer, "password", itemDriveMap.Password); XmlUtility.WriteAttributeIfPresent(writer, "realPath", itemDriveMap.RealPath); XmlUtility.WriteAttributeIfPresent(writer, "type", itemDriveMap.Type.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); } { writer.WriteStartElement("applications"); List <WindowsExecutable> listExe = item.ExecList; foreach (WindowsExecutable itemExec in listExe) { writer.WriteStartElement("application"); writer.WriteAttributeString("name", itemExec.Name); XmlUtility.WriteAttributeIfPresent(writer, "description", itemExec.Description); XmlUtility.WriteAttributeIfPresent(writer, "directory", itemExec.Directory); XmlUtility.WriteAttributeIfPresent(writer, "fileName", itemExec.File); XmlUtility.WriteAttributeIfPresent(writer, "arguments", itemExec.Arguments); XmlUtility.WriteAttributeIfPresent(writer, "wait", itemExec.WaitForExit.ToString()); XmlUtility.WriteAttributeIfPresent(writer, "kill", itemExec.Kill.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); } { writer.WriteStartElement("services"); List <IWindowsServiceInfo> listService = item.ServiceList; foreach (IWindowsServiceInfo itemService in listService) { writer.WriteStartElement("service"); writer.WriteAttributeString("name", itemService.ServiceName); XmlUtility.WriteAttributeIfPresent(writer, "status", itemService.ForcedStatus.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); } // Printer { writer.WriteStartElement("printer"); XmlUtility.WriteAttributeIfPresent(writer, "defaultPrinter", item.DefaultPrinter); writer.WriteEndElement(); } // disabled nic { writer.WriteStartElement("forcedNics"); IList <WindowsNetworkCard> listDisabledNics = item.DisabledNetworkCards; foreach (WindowsNetworkCard itemNIC in listDisabledNics) { writer.WriteStartElement("forcedNic"); writer.WriteAttributeString("id", itemNIC.Id); writer.WriteAttributeString("hardwareName", itemNIC.HardwareName); writer.WriteEndElement(); } writer.WriteEndElement(); } // wifi { writer.WriteStartElement("wifi"); writer.WriteAttributeString("associatedSSID", item.AssociatedWifiSSID); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); return(true); }
public CoreInterceptor(IServiceProvider serviceProvider, ProxyConfiguration configuration) { _serviceProvider = serviceProvider; _configuration = configuration; }