/// <summary> /// Creates session factory /// </summary> /// <param name="configurationReader">configuration reader</param> /// <returns></returns> private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader) { var configuration = new NHibernate.Cfg.Configuration(); configuration.SessionFactoryName("Jumblocks Blog"); configuration.DataBaseIntegration(db => { db.Dialect<MsSql2008FixedDialect>(); db.IsolationLevel = IsolationLevel.ReadCommitted; db.ConnectionString = configurationReader.ConnectionStrings["BlogDb"].ConnectionString; db.BatchSize = 100; //for testing db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); var mapper = new ModelMapper(); mapper.AddMapping<BlogPostMap>(); mapper.AddMapping<BlogUserMap>(); mapper.AddMapping<ImageReferenceMap>(); mapper.AddMapping<TagMap>(); mapper.AddMapping<SeriesMap>(); mapper.AddMapping<UserMap>(); mapper.AddMapping<RoleMap>(); mapper.AddMapping<OperationMap>(); configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities()); configuration.CurrentSessionContext<WebSessionContext>(); return configuration.BuildSessionFactory(); }
public FormsAuthenticationWrapper(IConfigurationReader configurationReader) { if (configurationReader == null) throw new ArgumentNullException(); ConfigurationReader = configurationReader; }
public CurrentApplicationInstanceRetriever(ISystemEnvironment environment, IConfigurationReader configurationReader, IApplicationInstanceRepository repository, IApplicationInstanceFactory factory) { _environment = environment; _configurationReader = configurationReader; _repository = repository; _factory = factory; }
/// <summary> /// Creates article controller /// </summary> /// <param name="blogPostRepository">blogpost repository to use, leave null to use default mocked implementation</param> /// <param name="shouldBlogPostRepositoryAlwayReturnPost">if using default blogpost repository, if set to true then repository will always return BlogPost regardless of input. If however it is false posts titles are 0 to 19 and published date is current day</param> /// <param name="lookupRepository">repository to look things up, leave null for default mocked implementation</param> /// <param name="configurationReader">configuration reader to use, leave null for default mocked implementation</param> /// <param name="waneTransform">wane transform, leave null for default mocked implementaion</param> /// <param name="logger">Logger, leave null for default implementation</param> /// <param name="principal">principal used for security, leave null for default implementation</param> /// <returns></returns> public static BlogPostController CreateBlogPostController(IBlogPostRepository blogPostRepository = null, bool shouldBlogPostRepositoryAlwayReturnPost = true, ILookupRepository lookupRepository = null, IConfigurationReader configurationReader = null, IWaneTransform waneTransform = null, IJumbleblocksLogger logger = null, IJumbleblocksPrincipal principal = null) { if (blogPostRepository == null) blogPostRepository = CreateMockedBlogPostRepository(shouldBlogPostRepositoryAlwayReturnPost).Object; if (lookupRepository == null) lookupRepository = CreateMockedLookupRepository().Object; if (configurationReader == null) configurationReader = CreateMockedConfigurationReader().Object; if (waneTransform == null) waneTransform = CreateMockedWaneTransform().Object; if (logger == null) logger = new Mock<IJumbleblocksLogger>().Object; if (principal == null) principal = CreateMockedPrincipalAndAddBlogUserToLookUp(Mock.Get<ILookupRepository>(lookupRepository)).Object; var controller = new BlogPostController(blogPostRepository, lookupRepository, configurationReader, waneTransform, logger); controller.SetMockedControllerContext(); controller.SetPrincipal(principal); return controller; }
public ConfigurationController( ILogger logger, IConfigurationReader configurationReader) { _logger = logger; _configurationReader = configurationReader; }
public HttpContextUserCache(IConfigurationReader configurationReader) { if (configurationReader == null) throw new ArgumentNullException(); ConfigurationReader = configurationReader; }
public FallbackConfiguration(string fileName) { var defaultPath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); var filePath = Path.Combine(defaultPath, fileName); if (System.IO.File.Exists(filePath)) _reader = new CustomConfigurationFileReader(filePath); else _reader = (IConfigurationReader) DefaultConfiguration.Instance; }
/// <summary> /// Initializes the feature configuration from specified configuration reader. /// </summary> /// <param name="reader">The reader.</param> /// <exception cref="ArgumentNullException">If <paramref name="reader"/> is <c>null</c>.</exception> public void FromSource(IConfigurationReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } IEnumerable<IFeatureToggle> items = reader.GetFeatures(); AddItems(items); }
public AuthenticationController(IWebAuthenticator webAuthenticator, IConfigurationReader configurationReader) { if (webAuthenticator == null) throw new ArgumentNullException("webAuthenticator"); if (configurationReader == null) throw new ArgumentNullException("configurationReader"); WebAuthenticator = webAuthenticator; ConfigurationReader = configurationReader; }
public RichEndpint( ILogger logger, IMessageBus messageBus, IConfigurationReader configurationReader, IRuntimeContext runtimeContext, IServiceContext serviceContext) { _logger = logger; _messageBus = messageBus; _configurationReader = configurationReader; _runtimeContext = runtimeContext; _serviceContext = serviceContext; }
public Orchestrator(IConfigurationReader configurationReader, IQueueClientFactory queueClientFactory, IMessageProcessorFactory messageProcessorFactory, IQueueProcessorFactory queueProcessorFactory, IConfigurationChangeManager configurationChangeManager) { IsProcessing = false; _configurationReader = configurationReader; _queueClientFactory = queueClientFactory; _messageProcessorFactory = messageProcessorFactory; _queueProcessorFactory = queueProcessorFactory; _configurationChangeManager = configurationChangeManager; }
public ConfigurationResourceLocator(string directory, string fileExtension, IConfigurationReader configurationReader, IIdConverter idConverter) { if (!Directory.Exists(directory)) throw new ArgumentException(string.Format("The path {0} does not exist.", directory ?? string.Empty)); _directory = directory; _fileExtension = !string.IsNullOrEmpty(fileExtension) ? "." + fileExtension : ""; _configurationReader = configurationReader; _idConverter = idConverter; }
public ImageManager( IConfigurationReader configurationReader, IUserIdManager userIdManager, IImageCapture imageCapture, IMessageTransmitter messageTransmitter, IOxfordClient oxfordClient) { _configurationReader = configurationReader; _userIdManager = userIdManager; _imageCapture = imageCapture; _messageTransmitter = messageTransmitter; _oxfordClient = oxfordClient; }
public AppState( IMachineLocator machineLocator, IConfigurationReader configurationReader, ConfigurationFactory configurationFactory ) { this.machineLocator = machineLocator ?? throw new ArgumentNullException(nameof(machineLocator)); this.configurationReader = configurationReader ?? throw new ArgumentNullException(nameof(configurationReader)); this.configurationFactory = configurationFactory ?? throw new ArgumentNullException(nameof(configurationFactory)); machines = Array.Empty <IMachineMetadata>(); Configuration = null; }
/// <summary> /// Turns a System.Diagnostic.StackFrame[] into a <see cref="CapturedStackFrame" /> list which can be reported to the APM /// Server /// </summary> /// <param name="frames">The stack frames to rewrite into APM stack traces</param> /// <param name="logger">The logger to emit exceptions on should one occur</param> /// <param name="dbgCapturingFor">Just for logging.</param> /// <param name="configurationReader"> /// Config reader - this controls the collection of stack traces (e.g. limit on frames, /// etc) /// </param> /// <returns>A prepared List that can be passed to the APM server</returns> internal static List <CapturedStackFrame> GenerateApmStackTrace(StackFrame[] frames, IApmLogger logger, IConfigurationReader configurationReader, string dbgCapturingFor ) { var stackTraceLimit = configurationReader.StackTraceLimit; if (stackTraceLimit == 0) { return(null); } if (stackTraceLimit > 0) { // new StackTrace(skipFrames: n) skips frames from the top of the stack (currently executing method is top) // the StackTraceLimit feature takes the top n frames, so unfortunately we currently capture the whole stack trace and just take // the top `configurationReader.StackTraceLimit` frames. - This could be optimized. frames = frames.Take(stackTraceLimit).ToArray(); } var retVal = new List <CapturedStackFrame>(frames.Length); logger.Trace()?.Log("transform stack frames"); try { foreach (var frame in frames) { var fileName = frame?.GetMethod() ?.DeclaringType?.FullName; //see: https://github.com/elastic/apm-agent-dotnet/pull/240#discussion_r289619196 var functionName = GetRealMethodName(frame?.GetMethod()); logger.Trace()?.Log("{MethodName}, {lineNo}", functionName, frame?.GetFileLineNumber()); retVal.Add(new CapturedStackFrame { Function = functionName ?? "N/A", FileName = string.IsNullOrWhiteSpace(fileName) ? "N/A" : fileName, Module = frame?.GetMethod()?.ReflectedType?.Assembly.FullName, LineNo = frame?.GetFileLineNumber() ?? 0, AbsPath = frame?.GetFileName() // optional property }); } } catch (Exception e) { logger?.Warning()?.LogException(e, "Failed capturing stacktrace for {ApmContext}", dbgCapturingFor); } return(retVal); }
public AgentComponents( AbstractLogger logger = null, IConfigurationReader configurationReader = null, Service service = null, IPayloadSender payloadSender = null ) { Logger = logger ?? ConsoleLogger.Instance; ConfigurationReader = configurationReader ?? new EnvironmentConfigurationReader(Logger); Service = service ?? Service.GetDefaultService(ConfigurationReader); PayloadSender = payloadSender ?? new PayloadSender(Logger, ConfigurationReader); TracerInternal = new Tracer(Logger, Service, PayloadSender); TransactionContainer = new TransactionContainer(); }
internal AgentComponents( IApmLogger logger, IConfigurationReader configurationReader, IPayloadSender payloadSender, IMetricsCollector metricsCollector, ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer, ICentralConfigFetcher centralConfigFetcher, IApmServerInfo apmServerInfo ) { try { var tempLogger = logger ?? ConsoleLogger.LoggerOrDefault(configurationReader?.LogLevel); ConfigurationReader = configurationReader ?? new EnvironmentConfigurationReader(tempLogger); Logger = logger ?? ConsoleLogger.LoggerOrDefault(ConfigurationReader.LogLevel); Service = Service.GetDefaultService(ConfigurationReader, Logger); var systemInfoHelper = new SystemInfoHelper(Logger); var system = systemInfoHelper.ParseSystemInfo(ConfigurationReader.HostName); ConfigStore = new ConfigStore(new ConfigSnapshotFromReader(ConfigurationReader, "local"), Logger); ApmServerInfo = apmServerInfo ?? new ApmServerInfo(); PayloadSender = payloadSender ?? new PayloadSenderV2(Logger, ConfigStore.CurrentSnapshot, Service, system, ApmServerInfo, isEnabled: ConfigurationReader.Enabled); HttpTraceConfiguration = new HttpTraceConfiguration(); if (ConfigurationReader.Enabled) { CentralConfigFetcher = centralConfigFetcher ?? new CentralConfigFetcher(Logger, ConfigStore, Service); MetricsCollector = metricsCollector ?? new MetricsCollector(Logger, PayloadSender, ConfigStore); MetricsCollector.StartCollecting(); } TracerInternal = new Tracer(Logger, Service, PayloadSender, ConfigStore, currentExecutionSegmentsContainer ?? new CurrentExecutionSegmentsContainer(), ApmServerInfo); if (!ConfigurationReader.Enabled) { Logger?.Info()?.Log("The Elastic APM .NET Agent is disabled - the agent won't capture traces and metrics."); } } catch (Exception e) { logger?.Error()?.LogException(e, "Failed initializing agent."); } }
/// <summary> /// Initializes the dependencies of the object /// </summary> public ConfigurationPropertyValueReader() { _valueReader = ServiceManager.GetService <IConfigurationReader>(); var fr = new StackFrame(1, false); _configurationSetType = fr.GetMethod().DeclaringType; // ReSharper disable once PossibleNullReferenceException var attrs = _configurationSetType.GetCustomAttributes(typeof(ConfigurationCategoryAttribute), false) as ConfigurationCategoryAttribute[]; _categoryName = attrs != null && attrs.Length > 0 ? attrs[0].Value : _configurationSetType.Name; }
public void DateTimeMappingTest(string input, Type expectedType, Type itemType, string expected) { DateTime expectedDate = DateTime.Parse(expected); XmlDocument xmlNode = new XmlDocument(); xmlNode.LoadXml(input); IConfigurationReader configurationParser = Substitute.For <IConfigurationReader>(); IMappingStrategy mappingStrategy = new DateTimeStrategy(); var actual = mappingStrategy.Map(xmlNode.FirstChild, expectedType, configurationParser); Assert.AreEqual(expectedType, actual.GetType()); Assert.AreEqual(expectedDate, ((DateTime)actual)); }
// Constructors public DefaultAudioSwitch(IDisplayManager displayManager, IAudioDeviceManager audioDeviceManager, IConfigurationReader configurationReader, IConfigurationWriter configurationWriter) { _displayManager = displayManager; _audioDeviceManager = audioDeviceManager; _configurationReader = configurationReader; _configurationWriter = configurationWriter; _configuration = CreateDefaultConfigurationIfNecessary(displayManager); _lastDisplayNode = _displayManager.GetCurrentDisplayMode(); _displayManager.DisplayModeChanged += DisplayModeChanged; _displayManager.StartPolling(1000); }
public FallbackConfiguration(string fileName) { var defaultPath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); var filePath = Path.Combine(defaultPath, fileName); if (System.IO.File.Exists(filePath)) { _reader = new CustomConfigurationFileReader(filePath); } else { _reader = (IConfigurationReader)DefaultConfiguration.Instance; } }
public Span( string name, string type, string parentId, string traceId, Transaction enclosingTransaction, IPayloadSender payloadSender, IApmLogger logger, IConfigurationReader configurationReader, ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer, Span parentSpan = null ) { Timestamp = TimeUtils.TimestampNow(); Id = RandomGenerator.GenerateRandomBytesAsString(new byte[8]); _logger = logger?.Scoped($"{nameof(Span)}.{Id}"); _payloadSender = payloadSender; _configurationReader = configurationReader; _currentExecutionSegmentsContainer = currentExecutionSegmentsContainer; _parentSpan = parentSpan; _enclosingTransaction = enclosingTransaction; Name = name; Type = type; ParentId = parentId; TraceId = traceId; if (IsSampled) { // Started and dropped spans should be counted only for sampled transactions if (enclosingTransaction.SpanCount.IncrementTotal() > _configurationReader.TransactionMaxSpans && _configurationReader.TransactionMaxSpans >= 0) { _isDropped = true; enclosingTransaction.SpanCount.IncrementDropped(); } else { enclosingTransaction.SpanCount.IncrementStarted(); } } _currentExecutionSegmentsContainer.CurrentSpan = this; _logger.Trace() ?.Log("New Span instance created: {Span}. Start time: {Time} (as timestamp: {Timestamp}). Parent span: {Span}", this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp, _parentSpan); }
internal static Service GetDefaultService(IConfigurationReader configurationReader, IApmLogger loggerArg) { IApmLogger logger = loggerArg.Scoped(nameof(Service)); return(new Service { Name = configurationReader.ServiceName, Agent = new AgentC { Name = Consts.AgentName, Version = typeof(Agent).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion }, Runtime = PlatformDetection.GetServiceRuntime(logger) }); }
public AgentComponents( IApmLogger logger = null, IConfigurationReader configurationReader = null, IPayloadSender payloadSender = null ) { Logger = logger ?? ConsoleLogger.LoggerOrDefault(configurationReader?.LogLevel); ConfigurationReader = configurationReader ?? new EnvironmentConfigurationReader(Logger); Service = Service.GetDefaultService(ConfigurationReader); PayloadSender = payloadSender ?? new PayloadSenderV2(Logger, ConfigurationReader, Service); TracerInternal = new Tracer(Logger, Service, PayloadSender, ConfigurationReader); TransactionContainer = new TransactionContainer(); }
static void Main(string[] args) { Arguments prms = new Arguments(); prms.Add("applicationName", "SERVICE - A"); prms.Add("refreshTimerIntervalInMs", 10000); prms.Add("connectionString", "Deneme"); IConfigurationReader configurationReader = IocHelper.Resolve <IConfigurationReader>(prms); var val = configurationReader.GetValue <int>("MaxItemCount"); Console.ReadKey(); }
public virtual ITestMethodBase UpdateConfigurationReader(string testMethod, IConfigurationReader configurationReader) { TestMethods.TryGetValue(testMethod, out var testMethodCore); if (testMethodCore == null) { throw new ApplicationException($"Test Method {testMethod} Doesn't Exist"); } testMethodCore.ConfigurationReader = configurationReader; TestMethods.AddOrUpdate(testMethod, testMethodCore, (key, oldValue) => testMethodCore); return(testMethodCore); }
/// <summary> /// Sets up service. /// </summary> private void SetUpService() { _configurationReader = TypeContainer.Resolve <IConfigurationReader>(); _defaultParser = TypeContainer.Resolve <IParser>(); _defaultBuilder = TypeContainer.Resolve <IBuilder>(); _dataService = TypeContainer.Resolve <IDataService>(); _messenger = TypeContainer.Resolve <IMessenger>(); _perfCounters = TypeContainer.Resolve <IPerfCounters>(); ExecutionResult.AttachPerfCounters(_perfCounters); ExecutionResult.AttachLogger(_logger); HostManager = TypeContainer.Resolve <IServiceHostManager>(); _messenger.Notify += MessengerNotification; _configFileMonitor.Changed += (s, e) => ReloadAndApplyConfigChanges(); Configure(); }
public Tracer( IApmLogger logger, Service service, IPayloadSender payloadSender, IConfigurationReader configurationReader, ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer ) { _logger = logger?.Scoped(nameof(Tracer)); _service = service; _sender = payloadSender.ThrowIfArgumentNull(nameof(payloadSender)); _configurationReader = configurationReader.ThrowIfArgumentNull(nameof(configurationReader)); Sampler = new Sampler(configurationReader.TransactionSampleRate); CurrentExecutionSegmentsContainer = currentExecutionSegmentsContainer.ThrowIfArgumentNull(nameof(currentExecutionSegmentsContainer)); }
public void Should_read_service_sleep_time() { MockRepository mocks = new MockRepository(); IConfigurationReader reader = mocks.CreateMock <IConfigurationReader>(); using (mocks.Record()) { Expect.Call(reader.GetRequiredIntegerSetting("ServiceSleepTime")).Return(7); } using (mocks.Playback()) { IApplicationSettings settings = new ApplicationSettings(reader); Assert.That(settings.GetServiceSleepTime(), Is.EqualTo(7)); } }
public void Should_read_show_sql() { MockRepository mocks = new MockRepository(); IConfigurationReader reader = mocks.CreateMock <IConfigurationReader>(); using (mocks.Record()) { Expect.Call(reader.GetOptionalBooleanSetting("ShowSql")).Return(true); } using (mocks.Playback()) { IApplicationSettings settings = new ApplicationSettings(reader); Assert.That(settings.GetShowSql(), Is.EqualTo(true)); } }
public void Should_read_smtp_password() { MockRepository mocks = new MockRepository(); IConfigurationReader reader = mocks.CreateMock <IConfigurationReader>(); using (mocks.Record()) { Expect.Call(reader.GetRequiredSetting("SmtpPassword")).Return("mypass"); } using (mocks.Playback()) { IApplicationSettings settings = new ApplicationSettings(reader); Assert.That(settings.GetSmtpPassword(), Is.EqualTo("mypass")); } }
public void Should_read_smtp_authentication_necessary() { MockRepository mocks = new MockRepository(); IConfigurationReader reader = mocks.CreateMock <IConfigurationReader>(); using (mocks.Record()) { Expect.Call(reader.GetRequiredBooleanSetting("SmtpAuthenticationNecessary")).Return(true); } using (mocks.Playback()) { IApplicationSettings settings = new ApplicationSettings(reader); Assert.That(settings.GetSmtpAuthenticationNecessary(), Is.EqualTo(true)); } }
public IActionResult Config() { Arguments prms = new Arguments(); prms.Add("applicationName", "SERVICE - A"); prms.Add("refreshTimerIntervalInMs", 10000); prms.Add("connectionString", "Deneme"); IConfigurationReader configurationReader = IocHelper.Resolve <IConfigurationReader>(prms); ConfigModel model = new ConfigModel(); model.Configs = IocHelper.Resolve <IConfigProvider>().GetByApplication("SERVICE - A"); return(View(model)); }
public ConfigurationReader(string applicationName, string connectionString, int refreshTimerIntervalInMs) { var settingsCacheManager = new SettingsCacheManager(); _advancedConfigurationReader = new AdvancedConfigurationReader( NullLogger <AdvancedConfigurationReader> .Instance, settingsCacheManager, new EmptyCacheMissHandler(), new PeriodicJobRunner(NullLogger <PeriodicJobRunner> .Instance, new ConfigurationUpdaterJob(settingsCacheManager, new ConfigurationStorageClient(NullLogger <ConfigurationStorageClient> .Instance, new HttpClient { BaseAddress = new Uri(connectionString) }), NullLogger <ConfigurationUpdaterJob> .Instance), applicationName, refreshTimerIntervalInMs)); }
public void InterfaceGenericCollectionMappingWithPrimitiveItemsTest(string input, Type expectedType, Type itemType, int collectionSize) { XmlDocument xmlNode = new XmlDocument(); xmlNode.LoadXml(input); IConfigurationReader configurationParser = Substitute.For <IConfigurationReader>(); IMappingStrategyFactory mappingStrategyFactory = Substitute.For <IMappingStrategyFactory>(); mappingStrategyFactory.CreatePrimitiveStrategy(itemType).Returns(new PrimitiveMappingStrategy()); IMappingStrategy mappingStrategy = new GenericCollectionMappingStrategy(mappingStrategyFactory); var actual = mappingStrategy.Map(xmlNode.FirstChild, expectedType, configurationParser); Assert.IsNotNull(actual.GetType().GetInterfaces().SingleOrDefault(x => x == expectedType)); Assert.AreEqual(collectionSize, ((ICollection)actual).Count); }
public ConfigurationService([NotNull] IAttributesReader attributesReader, [NotNull] IConfigurationReader configurationReader, [NotNull] IConfigurationTypeResolver configurationTypeResolver, [NotNull] IConfigurationItemsHelper configurationItemsHelper, [NotNull] ICanEditItemChecker canEditItemChecker) { if (attributesReader == null) throw new ArgumentNullException(nameof(attributesReader)); if (configurationReader == null) throw new ArgumentNullException(nameof(configurationReader)); if (configurationTypeResolver == null) throw new ArgumentNullException(nameof(configurationTypeResolver)); if (configurationItemsHelper == null) throw new ArgumentNullException(nameof(configurationItemsHelper)); if (canEditItemChecker == null) throw new ArgumentNullException(nameof(canEditItemChecker)); _attributesReader = attributesReader; _configurationReader = configurationReader; _configurationTypeResolver = configurationTypeResolver; _configurationItemsHelper = configurationItemsHelper; _canEditItemChecker = canEditItemChecker; }
public void ObjectMappingTest(string input, Type expectedType) { XmlDocument xmlNode = new XmlDocument(); xmlNode.LoadXml(input); IConfigurationReader configurationParser = Substitute.For <IConfigurationReader>(); configurationParser.ReadObject(expectedType, xmlNode).Returns(new TestClass { A = "test" }); IMappingStrategy mappingStrategy = new ObjectMappingStrategy(); var actual = mappingStrategy.Map(xmlNode, expectedType, configurationParser); Assert.AreEqual(expectedType, actual.GetType()); }
public void DictionaryMappingStrategyWithPrimitiveItemsTest(string input, Type expectedType, Type itemType, int collectionSize) { XmlDocument xmlNode = new XmlDocument(); xmlNode.LoadXml(input); IConfigurationReader configurationParser = Substitute.For <IConfigurationReader>(); IMappingStrategyFactory mappingStrategyFactory = Substitute.For <IMappingStrategyFactory>(); mappingStrategyFactory.CreatePrimitiveStrategy(itemType).Returns(new PrimitiveMappingStrategy()); IMappingStrategy mappingStrategy = new GenericDictionaryMappingStrategy(mappingStrategyFactory); var actual = mappingStrategy.Map(xmlNode.FirstChild, expectedType, configurationParser); Assert.AreEqual(expectedType, actual.GetType()); Assert.AreEqual(collectionSize, ((IDictionary)actual).Count); }
public void CreateFactoryFromConfig_can_derive_and_cache_options_correctly(IConfigurationReader configReader, IReadsEnvironmentVariables env, [NoAutoProperties] WebDriverFactoryConfigurationSection config, IDictionary <string, object> caps, IGetsBrowserFlags flagsProvider, string scenarioName) { // Arrange var envVars = new Dictionary <string, string>(); Mock.Get(configReader) .Setup(x => x.ReadSection <WebDriverFactoryConfigurationSection>()) .Returns(config); Mock.Get(env) .Setup(x => x.GetEnvironmentVariables()) .Returns(envVars); envVars.Add("Env_AnotherDummyNumber", "20"); envVars.Add("Env_DummyString", "Ohai"); envVars.Add("Invalid_DummyNumber", "8"); config.WebDriverFactoryAssemblyQualifiedType = typeof(DummyBrowserFactory).AssemblyQualifiedName; config.EnvironmentVariableSupportEnabled = true; config.EnvironmentVariablePrefix = "Env_"; config.FactoryOptions.Add(new FactoryOption { Name = "DummyString", Value = "Should be overridden" }); config.FactoryOptions.Add(new FactoryOption { Name = "DummyNumber", Value = "5" }); var sut = new WebDriverFactorySource(configurationReader: configReader, environmentReader: env); // Act var factory = sut.CreateFactoryFromConfig(); var result = GetProxiedFactory(factory); factory.CreateWebDriver(caps, flagsProvider, scenarioName); // Assert Assert.That(result.CapturedOptions.DummyString, Is.EqualTo("Ohai")); Assert.That(result.CapturedOptions.DummyNumber, Is.EqualTo(5)); Assert.That(result.CapturedOptions.AnotherDummyNumber, Is.EqualTo(20)); }
/// <summary> /// Registers the library helper. /// </summary> /// <param name="jarFile">The jar file.</param> /// <param name="config">The configuration.</param> /// <param name="registration">The registration.</param> /// <returns></returns> private ExecutionResult RegisterLibraryHelper(string jarFile, IConfigurationReader config, Dictionary <string, JniMetadata> registration) { var r = registration?.ToList(); var libraryId = Guid.NewGuid(); var retval = ExecutionResult.Empty; var c = (CustomConfigReader)config.Configuration; var assembly = Path.GetFileName(jarFile).Replace(".jar", ".dll"); var assemblyLocation = $@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\Proxies\{assembly}"; // If connection is closed then we'll open it if (_dataContext.Database.Connection.State == System.Data.ConnectionState.Closed) { _dataContext.Database.Connection.Open(); } using (var transaction = _dataContext.Database.Connection.BeginTransaction()) { // We first register our proxy assembly _dataContext.DynamicLibrary.Add(new DynamicLibrary() { AssemblyName = assembly, IsHostingEnabled = true, JarFileLocation = jarFile, AssemblyLocation = assemblyLocation, JarFileName = Path.GetFileName(jarFile), LibraryId = libraryId.ToString(), RegisteredDate = EpochTime }); try { r?.ForEach(_ => ProvisionTablesAtRegistration(_, jarFile, assembly, c, libraryId)); _dataContext.SaveChanges(); transaction.Commit(); retval.IsSuccess = true; } catch { transaction.Rollback(); retval.IsSuccess = false; } finally { _dataContext.Database.Connection.Close(); } } return(retval); }
public void Determines_that_url_is_internal_when_application_domain_names_match_except_for_casing() { MockRepository mocks = new MockRepository(); IWebContext context = mocks.CreateMock <IWebContext>(); IConfigurationReader configurationReader = mocks.CreateMock <IConfigurationReader>(); using (mocks.Record()) { Expect.Call(context.GetServerVariable("HTTP_HOST")).Return("www1.myapp.com"); Expect.Call(configurationReader.GetRequiredSetting("TarantinoWebManagementHttpHost")).Return("www.MyApp.com"); } using (mocks.Playback()) { IExternalUrlChecker urlChecker = new ExternalUrlChecker(context, configurationReader); Assert.That(urlChecker.CurrentUrlIsExternal(), Is.False); } }
public static T Deserialise <T>(this IConfigurationReader <T> reader, T defaultConfiguration, string serialised) where T : new() { var commandLine = new MyCommandLine(); if (String.IsNullOrWhiteSpace(serialised) || !commandLine.TryParse(serialised)) { Debug.Write(Debug.Level.Info, "No stored configuration."); return(defaultConfiguration); } var configuration = new T(); if (!reader.Read(configuration, commandLine.Items)) { Debug.Write(Debug.Level.Error, "Unable to read the stored configuration. Resetting to defaults."); return(defaultConfiguration); } return(configuration); }
public BlogPostController(IBlogPostRepository blogPostSummaryRepository, ILookupRepository lookupRepository, IConfigurationReader configurationReader, IWaneTransform waneTransformer, IJumbleblocksLogger logger) { if (blogPostSummaryRepository == null) throw new ArgumentNullException("blogPostSummaryRepository"); if (lookupRepository == null) throw new ArgumentNullException("lookupRepository"); if (configurationReader == null) throw new ArgumentNullException("configurationReader"); if (waneTransformer == null) throw new ArgumentNullException("waneTransformer"); if (logger == null) throw new ArgumentNullException("logger"); BlogPostRepository = blogPostSummaryRepository; LookupRepository = lookupRepository; ConfigurationReader = configurationReader; WaneTransformer = waneTransformer; Logger = logger; }
public UserIdManager(IConfigurationReader configurationReader) { _configurationReader = configurationReader; }
public AdministratorSecurityChecker(IWebContext context, IRoleManager manager, IConfigurationReader configurationReader) { _context = context; _manager = manager; _configurationReader = configurationReader; }
protected SettingsIncludeErrorDetailsResolver([NotNull] IConfigurationReader configurationReader) { if (configurationReader == null) throw new ArgumentNullException(nameof(configurationReader)); _configurationReader = configurationReader; }
public MessageTransmitter(IExceptionHandler exceptionHandler, IConfigurationReader configurationReader) { _exceptionHandler = exceptionHandler; _configurationReader = configurationReader; }
// TODO: put this on abstract class so it needs to be implemented in factory public ConfigurationSectionSwitchProvider(IConfigurationReader configurationReader, ConfigurationFeatureMapper mapper) { _configurationReader = configurationReader; _mapper = mapper; }
/// <summary> /// Sets up db registering session factory and repositories /// </summary> /// <param name="configurationReader">configuration reader</param> /// <param name="container">windsor container</param> public static void CreateSessionFactoryAndRegisterRepositories(IConfigurationReader configurationReader, IWindsorContainer container) { ISessionFactory sessionFactory = CreateSessionFactory(configurationReader); container.Register(Component.For<ISessionFactory>().Instance(sessionFactory).LifeStyle.Singleton); RegisterRepositories(container); }
public OxfordClient(IConfigurationReader configurationReader) { _configurationReader = configurationReader; }
public FileExtensionChecker(IConfigurationReader configurationReader, IWebContext context) { _configurationReader = configurationReader; _context = context; }
public ExternalUrlChecker(IWebContext context, IConfigurationReader configurationReader) { _context = context; _configurationReader = configurationReader; }
private void Setup() { _configurationReader = new SampleConfigurationReader(); _contentLocatorCreatorFilters = GetContentLocatorCreatorFilters(); }
public ServerAddressLoader(IConfigurationReader configurationReader) { Contract.Requires(configurationReader != null); this.configurationReader = configurationReader; }
public TasklingConfiguration(IConfigurationReader configurationReader) { _configurationReader = configurationReader; _taskConfigurations = new Dictionary<string, TaskConfiguration>(); }
public FacetReader(IConfigurationReader configurationReader) { _configurationReader = configurationReader; }
public Configuration(IConfigurationReader configurationReader) { this.configurationReader = configurationReader; }
/// <summary> /// Initializes a new instance of the <see cref="ConfigurationExpression" /> class. /// </summary> /// <param name="configuration">The configuration object to apply the initialization on.</param> /// <param name="applicationConfigurationReader">The application configuration reader.</param> internal ConfigurationExpression(IFeatureConfiguration configuration, IConfigurationReader applicationConfigurationReader) { this.configuration = configuration; this.applicationConfigurationReader = applicationConfigurationReader; }
public SqlServerConfiguration(IConfigurationReader configurationReader) { _connectionString = configurationReader.ValueOf("DbConnection"); if (_connectionString == null) _connectionString = @"Server=.\SQLEXPRESS;initial catalog=Godot;Integrated Security=SSPI"; }
public ConfigurationSectionSwitchProvider() { _configurationReader = new ConfigSectionReader(); }