コード例 #1
0
        internal static string Format(IServiceConfig config)
        {
            string name        = config.Name;
            string displayName = config.DisplayName;

            return($"{(string.IsNullOrEmpty(displayName) ? name : displayName)} ({name})");
        }
コード例 #2
0
 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);
 }
コード例 #3
0
 public Storage(ICreds creds, ILogTracer log, IServiceConfig config)
 {
     _creds     = creds;
     _armClient = creds.ArmClient;
     _log       = log;
     _config    = config;
 }
コード例 #4
0
ファイル: Config.cs プロジェクト: ranweiler/onefuzz
 public Config(ILogTracer logTracer, IOnefuzzContext context)
 {
     _context       = context;
     _logTracer     = logTracer;
     _containers    = _context.Containers;
     _serviceConfig = _context.ServiceConfiguration;
     _queue         = _context.Queue;
 }
コード例 #5
0
ファイル: Creds.cs プロジェクト: ranweiler/onefuzz
 public Creds(IServiceConfig config, IHttpClientFactory httpClientFactory, IMemoryCache cache)
 {
     _config            = config;
     _httpClientFactory = httpClientFactory;
     _cache             = cache;
     _azureCredential   = new DefaultAzureCredential();
     _armClient         = new ArmClient(this.GetIdentity(), this.GetSubscription());
 }
コード例 #6
0
 public VmssOperations(ILogTracer log, IOnefuzzContext context, IMemoryCache cache)
 {
     _log           = log;
     _creds         = context.Creds;
     _imageOps      = context.ImageOperations;
     _serviceConfig = context.ServiceConfiguration;
     _cache         = cache;
 }
コード例 #7
0
 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();
 }
コード例 #8
0
ファイル: Extension.cs プロジェクト: nharper285/onefuzz
 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;
 }
コード例 #9
0
ファイル: TestHooks.cs プロジェクト: nharper285/onefuzz
 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;
 }
コード例 #10
0
 public Storage(ICreds creds, ILogTracer log, IServiceConfig config)
 {
     _creds     = creds;
     _armClient = creds.ArmClient;
     _log       = log;
     _config    = config;
     _cache     = new MemoryCache(new MemoryCacheOptions()
     {
     });
 }
コード例 #11
0
 /// <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()));                                 //再尝试全局配置
     }
 }
コード例 #12
0
        public static IServicePid Create(IServiceConfig config)
        {
            switch (config)
            {
            case ServiceConfig concreteConfig:
                var pid = Actor.Spawn(concreteConfig.Props);
                return(new ServicePid(pid));
            }

            return(null);
        }
コード例 #13
0
        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()));
        }
コード例 #14
0
        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());
        }
コード例 #15
0
        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);
        }
コード例 #16
0
ファイル: Bootstrap.cs プロジェクト: hakunamatata/wincreeper
        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);
            }
        }
コード例 #17
0
 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");
 }
コード例 #18
0
        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));
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        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);
        }
コード例 #21
0
        /// <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;
        }
コード例 #22
0
ファイル: ProxyFacade.cs プロジェクト: tiaanp/Framework
        /// <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()));
        }
コード例 #23
0
        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);
        }
コード例 #24
0
ファイル: RestService.cs プロジェクト: luukwullink/Wul.Link
        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);
        }
コード例 #25
0
        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();
        }
コード例 #26
0
ファイル: Containers.cs プロジェクト: ranweiler/onefuzz
    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);
    }
コード例 #27
0
        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);
        }
コード例 #28
0
        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);
            }
        }
コード例 #29
0
        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>();
        }
コード例 #30
0
        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);
        }
コード例 #31
0
ファイル: RestService.cs プロジェクト: luukwullink/Wul.Link
        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);
            }
        }
コード例 #32
0
ファイル: WinService.cs プロジェクト: Jammox/EsterService
        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));
        }
コード例 #33
0
        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
                );
        }
コード例 #34
0
 public RethinkGoalService(IWebServiceClient<ChildInfo> apiClient, IServiceConfig serviceConfig = null)
 {
     _apiClient = apiClient;
     ServiceConfig = (serviceConfig == null || string.IsNullOrWhiteSpace(serviceConfig.ApiKey)) ? SetServiceConfig() : serviceConfig;
     _apiClient.BaseUri = ServiceConfig.BaseUrl;
 }
コード例 #35
0
 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;
 }
コード例 #36
0
ファイル: TfsHelperClass.cs プロジェクト: iozag/Buildscreen
 public TfsHelperClass(IServiceConfig configurationTfsService)
 {
     _configurationTfsService = configurationTfsService;
 }