internal static string Format(IServiceConfig config) { string name = config.Name; string displayName = config.DisplayName; return($"{(string.IsNullOrEmpty(displayName) ? name : displayName)} ({name})"); }
private static string CheckValidityOfConfig(IServiceConfig config) { try { Uri tempValue; if (!Uri.TryCreate(config.Uri, UriKind.Absolute, out tempValue)) { return("Uri is has a wrong format."); } if (!config.Uri.ToLower().Contains(ConfigurationManager.AppSettings[config.ServiceType + "Regex"])) { return("Url did not contain a valid domain or service"); } if (!CanLogIn(config.Username, config.Password, config.Uri, config.ServiceType).Result) { return("Could not authenticate, username and/or password are wrong."); } } catch (AggregateException e) { if (e.InnerException is Exception) { return(e.InnerException.Message); } return("DNS could not find server adress"); } catch (Exception e) { LogService.WriteError(e); throw; } return(null); }
public Storage(ICreds creds, ILogTracer log, IServiceConfig config) { _creds = creds; _armClient = creds.ArmClient; _log = log; _config = config; }
public Config(ILogTracer logTracer, IOnefuzzContext context) { _context = context; _logTracer = logTracer; _containers = _context.Containers; _serviceConfig = _context.ServiceConfiguration; _queue = _context.Queue; }
public Creds(IServiceConfig config, IHttpClientFactory httpClientFactory, IMemoryCache cache) { _config = config; _httpClientFactory = httpClientFactory; _cache = cache; _azureCredential = new DefaultAzureCredential(); _armClient = new ArmClient(this.GetIdentity(), this.GetSubscription()); }
public VmssOperations(ILogTracer log, IOnefuzzContext context, IMemoryCache cache) { _log = log; _creds = context.Creds; _imageOps = context.ImageOperations; _serviceConfig = context.ServiceConfiguration; _cache = cache; }
public void RethinkGoalServiceTest() { _serviceConfig= new ServiceConfig{ApiKey = "key",BaseUrl = "http://base.com",ServiceEndpoint = "service",TokenEndpoint = "token"}; ApiClientMock= new Mock<IWebServiceClient<ChildInfo>>(); ApiClientMock.Setup(x => x.GetAsync(null)).Returns(GetResponse); GoalService = new RethinkGoalService(ApiClientMock.Object, _serviceConfig); GoalService.ServiceConfig=new ServiceConfig(); }
public Extensions(IServiceConfig config, ICreds creds, IQueue queue, IContainers containers, IConfigOperations instanceConfigOps, ILogAnalytics logAnalytics) { _serviceConfig = config; _creds = creds; _queue = queue; _containers = containers; _instanceConfigOps = instanceConfigOps; _logAnalytics = logAnalytics; }
public TestHooks(ILogTracer log, IConfigOperations configOps, IEvents events, IServiceConfig config, ISecretsOperations secretOps, ILogAnalytics logAnalytics) { _log = log; _configOps = configOps; _events = events; _config = config; _secretOps = secretOps; _logAnalytics = logAnalytics; }
public Storage(ICreds creds, ILogTracer log, IServiceConfig config) { _creds = creds; _armClient = creds.ArmClient; _log = log; _config = config; _cache = new MemoryCache(new MemoryCacheOptions() { }); }
/// <summary> /// 读取指定服务配置 /// 先按照私有配置读取,如果失败,再按照共有配置读取 /// </summary> /// <typeparam name="T">返回配置内容类</typeparam> /// <param name="serviceConfig"></param> /// <param name="serviceName">共有服务</param> /// <param name="hostServiceName">私有子服务</param> /// <returns></returns> public static T GetServiceFromBuffer <T>(this IServiceConfig serviceConfig, ServiceName serviceName, ServiceName hostServiceName) where T : class { try { return(serviceConfig.GetServiceFromBuffer <T>(string.Format("{0}-{1}", serviceName, hostServiceName))); //先获取独立配置 } catch (MissConfigException) //如果没有取到 { return(serviceConfig.GetServiceFromBuffer <T>(serviceName.ToString())); //再尝试全局配置 } }
public static IServicePid Create(IServiceConfig config) { switch (config) { case ServiceConfig concreteConfig: var pid = Actor.Spawn(concreteConfig.Props); return(new ServicePid(pid)); } return(null); }
public static IContainerExtension UseRemoteServices(this IServiceConfig config, string gatewayBaseUrl) { config.RegisterServiceProvider(new ClientServiceProvider(gatewayBaseUrl)); //Configure isolated IocContainer for the client library return(ClientIocServiceProvider.Configure(sconfig => sconfig.AddServices(opt => { })) .GetServiceFactory() .Add <IServiceProxy>(() => new ClientServiceProxy()) .Add <IServiceClient>(() => new ServiceClient()) .Add <ISerializer>(() => new JsonSerializer())); }
public CoinMarketCapClient(HttpClient httpClient, IServiceConfig config, ILogger <CoinMarketCapClient> logger) { _logger = logger; _httpClient = httpClient; _config = config; _baseApiUrl = _config.GetCoinMarketCapApiUrl(); _httpClient.DefaultRequestHeaders.Clear(); _httpClient.DefaultRequestHeaders.Add("X-CMC_PRO_API_KEY", _config.GetCoinMarketCapApiKey()); }
public IServiceConfig GetConfig(IServiceConfig config) { NacosAPIEntity entity = GetNacosAPI("GetConfig"); item = new HttpItem { URL = $"{nacoshost}{entity.Url}?{String.Format(entity.Parms,query.NameSpaceId, config.dataId, config.group)}", Method = entity.Method }; config.configstr = HttpMethod.HttpWork(item).Html; return(config); }
private IService CreateService(IServiceConfig config) { Type o = Type.GetType(config.Type); try { return((IService)Activator.CreateInstance(o, config)); } catch (Exception ex) { Debug.Print("[Bootstrap] 创建服务失败: " + ex.Message); return(null); } }
public InvoiceController(ICompanyRepository CompanyRepository, IRequestService ServiceRequestImpl , IServiceConfig ConfigureService, IService ServiceImp, IInvoiceRepository InvoiceRepository , UserManager <CleaningUser> userManager, IDataProtectionProvider provider) { this.CompanyRepository = CompanyRepository; this.ServiceRequestImpl = ServiceRequestImpl; this.ConfigureService = ConfigureService; this.ServiceImp = ServiceImp; this.InvoiceRepository = InvoiceRepository; this.userManager = userManager; this.protector = provider.CreateProtector("protect_my_query_string"); }
public void ChangedStartMode() { string yaml = $@" id: service.exe name: Service description: The Service. executable: node.exe arguments: My Arguments startMode: manual"; this._extendedServiceDescriptor = YamlServiceConfig.FromYaml(yaml); Assert.That(this._extendedServiceDescriptor.StartMode, Is.EqualTo(ServiceStartMode.Manual)); }
public override void Configure(IServiceConfig descriptor, XmlNode node) { // We expect the upper logic to process any errors // TODO: a better parser API for types would be useful this.PidFile = XmlHelper.SingleElement(node, "pidfile", false) !; this.StopTimeout = TimeSpan.FromMilliseconds(int.Parse(XmlHelper.SingleElement(node, "stopTimeout", false) !)); this.StopParentProcessFirst = bool.Parse(XmlHelper.SingleElement(node, "stopParentFirst", false) !); this.ServiceId = descriptor.Name; // TODO: Consider making it documented string?checkWinSWEnvironmentVariable = XmlHelper.SingleElement(node, "checkWinSWEnvironmentVariable", true); this.CheckWinSWEnvironmentVariable = checkWinSWEnvironmentVariable is null ? true : bool.Parse(checkWinSWEnvironmentVariable); }
public void IncorrectStartMode() { string yaml = $@" id: service.exe name: Service description: The Service. executable: node.exe arguments: My Arguments startMode: roll"; this._extendedServiceDescriptor = YamlServiceConfig.FromYaml(yaml); Assert.That(() => this._extendedServiceDescriptor.StartMode, Throws.ArgumentException); }
/// <summary> /// Initializes a new instance of the <see cref="NotificationServiceControl" /> class. /// </summary> /// <param name="bus">The bus.</param> /// <param name="scheduler">The scheduler.</param> /// <param name="serviceConfig">The service configuration.</param> /// <param name="scheduleFactory">The schedule factory.</param> public NotificationServiceControl(IBusControl bus, IScheduler scheduler, IServiceConfig serviceConfig, IScheduleFactory scheduleFactory) : base(bus) { Contract.Requires(bus != null); Contract.Requires(scheduler != null); Contract.Requires(serviceConfig != null); Contract.Requires(scheduleFactory != null); _bus = bus; _scheduler = scheduler; _serviceConfig = serviceConfig; _scheduleFactory = scheduleFactory; }
/// <summary> /// /// </summary> /// <param name="serviceConfig"></param> public ProxyFacade(IServiceConfig serviceConfig) { this._ServiceConfig = serviceConfig; this._Binding = (Binding)Activator .CreateInstance( typeof(Binding) .Assembly .GetType( serviceConfig .BindingType .Description())); }
public void Add(IServiceConfig config) { if (config == null) { throw new ArgumentNullException(nameof(config)); } if (_configs.Any(x => x.Service.Equals(config.Service, StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException($"Service \"{config.Service}\" is already registered"); } _configs.Add(config); }
private void SetupEventQueueListener(IServiceConfig config, ILogger logger) { var factory = new ConnectionFactory { HostName = config.QueueHostName }; _connection = factory.CreateConnection(); _channel = _connection.CreateModel(); _channel.QueueDeclare(queue: config.QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(_channel); consumer.Received += async (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); if (message != null) { dynamic domainEventMessage = JObject.Parse(message); Type domainEventType = Type.GetType((string)domainEventMessage.DomainEventType, false); if (domainEventType == typeof(ShortlistCreated)) { var domainEvent = (domainEventMessage.DomainEvent as JObject).ToObject<ShortlistCreated>(); if (domainEvent != null) { await _shortlistQueryRepository.AddShortlistAsync(new ShortlistQueryModel { Date = domainEvent.Date }); } } else if (domainEventType == typeof(MovieAddedToShortlist)) { var domainEvent = (domainEventMessage.DomainEvent as JObject).ToObject<MovieAddedToShortlist>(); if (domainEvent != null) { var shortlist = await _shortlistQueryRepository.GetCurrentShortlistAsync(); shortlist.Selection.Add(new MovieQueryModel() { Name = domainEvent.MovieName, ReleaseYear = domainEvent.MovieReleaseYear }); } } } _channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; _channel.BasicConsume(queue: config.QueueName, noAck: false, consumer: consumer); }
protected BaseService(IServiceConfig config) { var factory = new ConnectionFactory { HostName = config.HostName, Port = config.Port, UserName = config.UserName, Password = config.Password, RequestedConnectionTimeout = config.Timeout, SocketReadTimeout = config.Timeout, SocketWriteTimeout = config.Timeout }; _connection = factory.CreateConnection(); }
public Containers(ILogTracer log, IStorage storage, ICreds creds, IServiceConfig config) { _log = log; _storage = storage; _creds = creds; _armClient = creds.ArmClient; _config = config; _getInstanceId = new Lazy <Async.Task <Guid> >(async() => { var blob = await GetBlob(new Container("base-config"), "instance_id", StorageType.Config); if (blob == null) { throw new Exception("Blob Not Found"); } return(Guid.Parse(blob.ToString())); }, LazyThreadSafetyMode.PublicationOnly); }
public void SetUp() { string seedXml = $@"<service> <id>SERVICE_NAME</id> <name>Jenkins Slave</name> <description>This service runs a slave for Jenkins continuous integration system.</description> <executable>C:\Program Files\Java\jre7\bin\java.exe</executable> <arguments>-Xrs -jar \""%BASE%\slave.jar\"" -jnlpUrl ...</arguments> <log mode=""roll""></log> <extensions> <extension enabled=""true"" className=""{this.testExtension}"" id=""killRunawayProcess""> <pidfile>foo/bar/pid.txt</pidfile> <stopTimeout>5000</stopTimeout> <stopParentFirst>true</stopParentFirst> </extension> </extensions> </service>"; this._testServiceDescriptor = XmlServiceConfig.FromXML(seedXml); string seedYaml = $@"--- id: jenkins name: Jenkins description: This service runs Jenkins automation server. env: - name: JENKINS_HOME value: '%LocalAppData%\Jenkins.jenkins' executable: java arguments: >- -Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar E:\Winsw Test\yml6\jenkins.war --httpPort=8081 extensions: - id: killRunawayProcess enabled: yes className: ""{this.testExtension}"" settings: pidFile: 'foo/bar/pid.txt' stopTimeout: 5000 stopParentFirst: true"; this._testServiceDescriptorYaml = YamlServiceConfig.FromYaml(seedYaml); }
public static string GetServiceProvider(string service, string provider) { IServiceConfig config = GetServiceConfig(service); if (config == null) { return(string.Empty); } NameValueConfigurationElement element = config.Providers[provider]; if (element == null) { return(string.Empty); } else { return(element.Value); } }
protected virtual void ConfigureHttpMessageHandlers(string serviceName, IServiceConfig serviceEndpoint, IHttpClientBuilder builder) { var retryPolicy = HttpPolicyExtensions .HandleTransientHttpError() .RetryAsync(TransientErrorRetryCount); var noOp = Policy.NoOpAsync().AsAsyncPolicy <HttpResponseMessage>(); // IMPORTANT: This component should be only dependent on SingleInstance() components. // Transient instances may cause difficulties with tracing side effects raised by their // state or other transient deps (for example, per-request auth). // https://github.com/aspnet/HttpClientFactory/issues/198 // https://github.com/aspnet/Docs/issues/9306 builder .AddHttpMessageHandler <CorrelationIdHandler>() .AddHttpMessageHandler(services => new BearerAccessTokenHandler(services.GetRequiredService <IBearerTokenStorage>(), serviceEndpoint.ExcludeAccessToken)) .AddPolicyHandler(request => request.Method == HttpMethod.Get || request.Method == HttpMethod.Head ? retryPolicy : noOp) .AddHttpMessageHandler <RequestResponseLoggingHandler>(); }
public void SetUp() { string yaml = $@" id: service.exe name: Service description: The Service. executable: node.exe arguments: My Arguments log: mode: roll logpath: c:\logs serviceAccount: domain: {Domain} user: {Username} password: {Password} allowServiceLogon: {AllowServiceAccountLogonRight} workingDirectory: {ExpectedWorkingDirectory}"; this._extendedServiceDescriptor = YamlServiceConfig.FromYaml(yaml); }
public RestService(INancyBootstrapper bootstrapper, IServiceConfig config, ILogger logger, ShortlistQueryRepository shortlistQueryRepository) { if (bootstrapper == null) { throw new ArgumentNullException(nameof(bootstrapper)); } if (config == null) { throw new ArgumentNullException(nameof(config)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (shortlistQueryRepository == null) { throw new ArgumentNullException(nameof(shortlistQueryRepository)); } _shortlistQueryRepository = shortlistQueryRepository; var nancyConfig = new HostConfiguration(); nancyConfig.UrlReservations.CreateAutomatically = true; _nancyService = new NancyHost(bootstrapper, nancyConfig, new Uri(config.RestUrl)); nancyConfig.UnhandledExceptionCallback = (exception) => { var message = String.Format("Uncaught exception: {0}", exception.Message); logger.WriteError(message); }; if (config.QueueConsumer) { SetupEventQueueListener(config, logger); } }
public WinService(IThreadScheduler threadScheduler, IProcessController processController, IServiceConfig serviceConfig, ISettings settings, ILog logger) { Log = logger ?? throw new ArgumentNullException(nameof(logger)); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location); Log.Info($"{fvi.ProductName} v{fvi.FileVersion}"); _threadScheduler = threadScheduler ?? throw new ArgumentNullException(nameof(threadScheduler)); _processController = processController ?? throw new ArgumentNullException(nameof(processController)); _serviceConfig = serviceConfig ?? throw new ArgumentNullException(nameof(serviceConfig)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); }
public HttpClientFactoryTests() { _serviceRegistry = A.Fake <IServiceRegistry>(); _config1 = A.Fake <IServiceConfig>(); A.CallTo(() => _serviceRegistry.Get(ServiceName)).Returns(_config1); A.CallTo(() => _serviceRegistry.GetAll()).Returns(new List <IServiceConfig> { _config1, A.Fake <IServiceConfig>() }); A.CallTo(() => _config1.AllowRedirect).Returns(true); A.CallTo(() => _config1.Timeout).Returns(TimeSpan.FromSeconds(222)); A.CallTo(() => _config1.BaseAddress).Returns("http://google.com"); A.CallTo(() => A.Fake <IServiceConfig>().AllowRedirect).Returns(false); A.CallTo(() => A.Fake <IServiceConfig>().Timeout).Returns(TimeSpan.FromSeconds(333)); A.CallTo(() => A.Fake <IServiceConfig>().BaseAddress).Returns("http://yandex.ru"); _underTest = new HttpClientFactory( _serviceRegistry ); }
public RethinkGoalService(IWebServiceClient<ChildInfo> apiClient, IServiceConfig serviceConfig = null) { _apiClient = apiClient; ServiceConfig = (serviceConfig == null || string.IsNullOrWhiteSpace(serviceConfig.ApiKey)) ? SetServiceConfig() : serviceConfig; _apiClient.BaseUri = ServiceConfig.BaseUrl; }
private static string CheckValidityOfConfig(IServiceConfig config) { try { Uri tempValue; if (!Uri.TryCreate(config.Uri, UriKind.Absolute, out tempValue)) { return "Uri is has a wrong format."; } if (!config.Uri.ToLower().Contains(ConfigurationManager.AppSettings[config.ServiceType + "Regex"])) { return "Url did not contain a valid domain or service"; } if (!CanLogIn(config.Username, config.Password, config.Uri, config.ServiceType).Result) { return "Could not authenticate, username and/or password are wrong."; } } catch (AggregateException e) { if (e.InnerException is Exception) { return e.InnerException.Message; } return "DNS could not find server adress"; } catch (Exception e) { LogService.WriteError(e); throw; } return null; }
public TfsHelperClass(IServiceConfig configurationTfsService) { _configurationTfsService = configurationTfsService; }