public void Initialize()
        {
            this.settings = new FunctionGenerator.PhysicalAssemblySettings("Log", "dll", AppDomain.CurrentDomain.BaseDirectory);

            this.functionGenerator = new FunctionGenerator(this.settings);
            this.provider = new LogProvider(this.functionGenerator, Visibility.Debug | Visibility.Warning);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates an instance of <see cref="IBoilerplateContext"/>
        /// </summary>
        /// <param name="identity">The current identity being used (rights and roles contract requirements/restrictions will apply to this identity)</param>
        /// <param name="accessProvider">An access provider for specific types (available through IBoilerplateContext.Open&lt;T&gt;())</param>
        /// <param name="permissionsProvider">The provider that will be used for all permissions verification attempts</param>
        /// <param name="visibility">The visibility level that this context has. This will affect operations that rely on visibility (e.g. logging).</param>
        /// <returns>An instance of <see cref="IBoilerplateContext"/></returns>
        public static IBoilerplateContext New(IIdentity identity = null, 
                                              ITypeAccessProvider accessProvider = null, 
                                              IPermissionsProvider permissionsProvider = null,
                                              Visibility visibility = Visibility.None)
        {   
            var actualIdentity = identity ?? Identity.Default;
            var actualTypeAccessProvider = accessProvider ?? TypeAccessProvider.Empty;
            var actualPermissionsProvider = permissionsProvider ?? PermissionsProvider.Default;

            var functionGenerator = new FunctionGenerator();

            //Core providers
            var translationProvider = new TranslationProvider(functionGenerator);
            var validationProvider = new ValidationProvider(functionGenerator);
            var logProvider = new LogProvider(functionGenerator, visibility);

            //Set up error handling
            var tryCatchProvider = new TryCatchBlockProvider(functionGenerator);
            var exceptionHandlerProvider = new ExceptionHandlerProvider(logProvider);
            var errorContext = new ImmutableErrorContext(logProvider, tryCatchProvider, exceptionHandlerProvider);

            var bundle = new ContextBundle(permissionsProvider: actualPermissionsProvider,
                                           errorContext: errorContext,
                                           translationProvider: translationProvider,
                                           accessProvider: actualTypeAccessProvider,
                                           validationProvider: validationProvider,
                                           logProvider: logProvider,
                                           visibility: visibility);

            return new InitialBoilerplateContext<ContractContext>(bundle, actualIdentity);
        }
Ejemplo n.º 3
0
        public virtual void GetImpl_Invalid_setting(bool dllExists, string setting)
        {
            _moqChecker.Setup(s => s.CheckForDll(DllName)).Returns(dllExists);

            string.Format("Given dllAvailable = {0} and setting is [{1}]", dllExists, setting).Given(() =>
                _provider = new LogProvider
                {
                    DependencyChecker = _moqChecker.Object,
                    Settings = new NameValueCollection { { KeyName, setting } }
                });

            "Then an dependency exception should be thrown".Then(() =>
                Assert.Throws<DependencyException>(() => _provider.GetImpl())
                );
        }
Ejemplo n.º 4
0
        public virtual void GetImpl_NoSettings(bool dllExists, Type expected)
        {
            _moqChecker.Setup(s => s.CheckForDll(DllName)).Returns(dllExists);

            string.Format("Given dll available = {0} and NO Settings", dllExists).Given(() =>
                _provider = new LogProvider
                {
                    DependencyChecker = _moqChecker.Object,
                    Settings = null//<- no settings
                });

            WhenMsg.When(() =>
                _class = _provider.GetImpl());

            string.Format("Then a {0} should be returned", expected.Name).Then(() =>
                _class.GetType().Should().Be(expected));
        }
Ejemplo n.º 5
0
 public PacketRouter()
 {
     _logger = LogProvider.Logger <MhfLogger>(this);
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Sets the current log provider based on logger factory.
 /// </summary>
 /// <param name="loggerFactory">The logger factory.</param>
 public static void SetCurrentLogProvider(ILoggerFactory loggerFactory)
 {
     LogProvider.SetCurrentLogProvider(new MicrosoftLoggingProvider(loggerFactory));
 }
Ejemplo n.º 7
0
 protected SchedulerListenerSupport()
 {
     log = LogProvider.GetLogger(GetType());
 }
Ejemplo n.º 8
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider());

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();
            app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
            });

            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                Authority          = "https://localhost:44337/ids",
                ClientId           = "idmgr_client",
                RedirectUri        = "https://localhost:44337",
                ResponseType       = "id_token",
                UseTokenLifetime   = false,
                Scope = "openid idmgr",
                SignInAsAuthenticationType = "Cookies",
                Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = n =>
                    {
                        n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
                        {
                            var result = await n.OwinContext.Authentication.AuthenticateAsync("Cookies");
                            if (result != null)
                            {
                                var id_token = result.Identity.Claims.GetValue("id_token");
                                if (id_token != null)
                                {
                                    n.ProtocolMessage.IdTokenHint           = id_token;
                                    n.ProtocolMessage.PostLogoutRedirectUri = "https://localhost:44337/idm";
                                }
                            }
                        }
                    }
                }
            });

            app.Map("/idm", idm =>
            {
                var factory = new IdentityManagerServiceFactory();

                var rand  = new System.Random();
                var users = Users.Get(rand.Next(5000, 20000));
                var roles = Roles.Get(rand.Next(15));

                factory.Register(new Registration <ICollection <InMemoryUser> >(users));
                factory.Register(new Registration <ICollection <InMemoryRole> >(roles));
                factory.IdentityManagerService = new Registration <IIdentityManagerService, InMemoryIdentityManagerService>();

                idm.UseIdentityManager(new IdentityManagerOptions
                {
                    Factory = factory,
                    SecurityConfiguration = new HostSecurityConfiguration
                    {
                        HostAuthenticationType = "Cookies",
                        AdditionalSignOutType  = "oidc"
                    }
                });
            });

            // this configures an embedded IdentityServer to act as an external authentication provider
            // when using IdentityManager in Token security mode. normally you'd configure this elsewhere.
            app.Map("/ids", ids =>
            {
                IdSvrConfig.Configure(ids);
            });
        }
Ejemplo n.º 9
0
 public HazelcastCoreTopologyService(Config config, MemberId myself, JobScheduler jobScheduler, LogProvider logProvider, LogProvider userLogProvider, RemoteMembersResolver remoteMembersResolver, TopologyServiceRetryStrategy topologyServiceRetryStrategy, Monitors monitors) : base(config, myself, logProvider, userLogProvider)
 {
     this._localDBName                  = config.Get(CausalClusteringSettings.database);
     this._scheduler                    = new RobustJobSchedulerWrapper(jobScheduler, Log);
     this._refreshPeriod                = config.Get(CausalClusteringSettings.cluster_topology_refresh).toMillis();
     this._remoteMembersResolver        = remoteMembersResolver;
     this._topologyServiceRetryStrategy = topologyServiceRetryStrategy;
     this._monitor = monitors.NewMonitor(typeof(Monitor));
 }
Ejemplo n.º 10
0
 public ILogger Create(string name)
 {
     return(new LibLogLogger(LogProvider.GetLogger(name)));
 }
Ejemplo n.º 11
0
 public void FixtureSetUp()
 {
     // set Adapter to report problems
     oldProvider = (ILogProvider)typeof(LogProvider).GetField("s_currentLogProvider", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
     LogProvider.SetCurrentLogProvider(new FailFastLoggerFactoryAdapter());
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqsMessageProducer"/> class.
 /// </summary>
 public SqsMessageProducer()
     : this(LogProvider.GetCurrentClassLogger())
 {
 }
Ejemplo n.º 13
0
        public virtual void GetImpl_Valid_setting(bool dllExists, string setting, Type expected)
        {
            _moqChecker.Setup(s => s.CheckForDll(DllName)).Returns(dllExists);

            string.Format("Given dllAvailable = {0} and setting is [{1}]", dllExists, setting).Given(() =>
                _provider = new LogProvider
                {
                    DependencyChecker = _moqChecker.Object,
                    Settings = new NameValueCollection { { KeyName, setting } }
                });

            WhenMsg.When(() =>
                _class = _provider.GetImpl());

            string.Format("Then a {0} should be returned", expected.Name).Then(() =>
                _class.GetType().Should().Be(expected));
        }
Ejemplo n.º 14
0
 public static void Dispose()
 {
     LogProvider.Dispose();
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestHandler{TRequest}"/> class.
 /// </summary>
 protected RequestHandler()
     : this(LogProvider.GetCurrentClassLogger())
 {
 }
Ejemplo n.º 16
0
 protected internal AbstractCoreTopologyService(Config config, MemberId myself, LogProvider logProvider, LogProvider userLogProvider)
 {
     this.Config         = config;
     this.MyselfConflict = myself;
     this.Log            = logProvider.getLog(this.GetType());
     this.UserLog        = userLogProvider.getLog(this.GetType());
 }
Ejemplo n.º 17
0
 public ReplicatedIdRangeAcquirer(Replicator replicator, ReplicatedIdAllocationStateMachine idAllocationStateMachine, IDictionary <IdType, int> allocationSizes, MemberId me, LogProvider logProvider)
 {
     this._replicator = replicator;
     this._idAllocationStateMachine = idAllocationStateMachine;
     this._allocationSizes          = allocationSizes;
     this._me  = me;
     this._log = logProvider.getLog(this.GetType());
 }
Ejemplo n.º 18
0
        public virtual void GetImpl_No_setting_key(bool dllExists, Type expected)
        {
            _moqChecker.Setup(s => s.CheckForDll(DllName)).Returns(dllExists);

            string.Format("Given dll available = {0} and NO '{1}' setting", dllExists, KeyName).Given(() =>
                _provider = new LogProvider
                {
                    DependencyChecker = _moqChecker.Object,
                    Settings = new NameValueCollection()// <- don't contain the key
                });

            WhenMsg.When(() =>
                _class = _provider.GetImpl());

            string.Format("Then a {0} should be returned", expected.Name).Then(() =>
                _class.GetType().Should().Be(expected));
        }
 protected HostNameBasedIdGenerator()
 {
     logger = LogProvider.GetLogger(GetType());
 }
Ejemplo n.º 20
0
 public OutboundSocketTests()
 {
     LogProvider.SetCurrentLogProvider(new ColouredConsoleLogProvider());
 }
Ejemplo n.º 21
0
 public void FixtureTearDown()
 {
     // default back to old
     LogProvider.SetCurrentLogProvider(oldProvider);
 }
Ejemplo n.º 22
0
        public void Start()
        {
            LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());

            Run().GetAwaiter().GetResult();
        }
Ejemplo n.º 23
0
 public GetServersProcedureForSingleDC(TopologyService topologyService, LeaderLocator leaderLocator, Config config, LogProvider logProvider)
 {
     if (!InstanceFieldsInitialized)
     {
         InitializeInstanceFields();
         InstanceFieldsInitialized = true;
     }
     this._topologyService = topologyService;
     this._leaderLocator   = leaderLocator;
     this._config          = config;
     this._log             = logProvider.getLog(this.GetType());
 }
Ejemplo n.º 24
0
        private IndexProviderMap CreateIndexes(PageCache pageCache, FileSystemAbstraction fileSystem, File storeDir, Config config, JobScheduler scheduler, LogProvider logProvider, Monitors monitors)
        {
            LogService               logService   = new SimpleLogService(logProvider, logProvider);
            TokenHolders             tokenHolders = new TokenHolders(new DelegatingTokenHolder(new ReadOnlyTokenCreator(), Org.Neo4j.Kernel.impl.core.TokenHolder_Fields.TYPE_PROPERTY_KEY), new DelegatingTokenHolder(new ReadOnlyTokenCreator(), Org.Neo4j.Kernel.impl.core.TokenHolder_Fields.TYPE_LABEL), new DelegatingTokenHolder(new ReadOnlyTokenCreator(), Org.Neo4j.Kernel.impl.core.TokenHolder_Fields.TYPE_RELATIONSHIP_TYPE));
            DatabaseKernelExtensions extensions   = _life.add(instantiateKernelExtensions(storeDir, fileSystem, config, logService, pageCache, scheduler, RecoveryCleanupWorkCollector.ignore(), DatabaseInfo.COMMUNITY, monitors, tokenHolders));

            return(_life.add(new DefaultIndexProviderMap(extensions, config)));
        }
Ejemplo n.º 25
0
 public StreamTransformer([NotNull] StreamTransformerSettings settings, [CanBeNull] ILog log)
 {
     this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
     this.log      = (log ?? LogProvider.Get()).ForContext <StreamTransformer>();
 }
Ejemplo n.º 26
0
 public SpanProcessorTaskFactory(ILog logger, CancellationTokenSource cancellationTokenSource)
 {
     this.logger = logger ?? LogProvider.GetCurrentClassLogger();
     this.cancellationTokenSource = cancellationTokenSource ?? new CancellationTokenSource();
 }
 public DatabaseTranslateService(Func <IDatabaseStaticTextContext> dbContext, LocalizationConfiguration configuration)
     : base(LogProvider.GetCurrentClassLogger(), dbContext, configuration)
 {
     //Should be empty.
 }
Ejemplo n.º 28
0
 public SpanProcessorTaskFactory()
     : this(LogProvider.GetCurrentClassLogger(), new CancellationTokenSource())
 {
 }
Ejemplo n.º 29
0
 public TrimLogsJob(LogProvider logProvider)
 {
     _logProvider = logProvider;
 }
Ejemplo n.º 30
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(JobStateExample));

            log.Info("------- Initializing -------------------");

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = await sf.GetScheduler();

            log.Info("------- Initialization Complete --------");

            log.Info("------- Scheduling Jobs ----------------");

            // get a "nice round" time a few seconds in the future....
            DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 10);

            // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds
            IJobDetail job1 = JobBuilder.Create <ColorJob>()
                              .WithIdentity("job1", "group1")
                              .Build();

            ISimpleTrigger trigger1 = (ISimpleTrigger)TriggerBuilder.Create()
                                      .WithIdentity("trigger1", "group1")
                                      .StartAt(startTime)
                                      .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(4))
                                      .Build();

            // pass initialization parameters into the job
            job1.JobDataMap.Put(ColorJob.FavoriteColor, "Green");
            job1.JobDataMap.Put(ColorJob.ExecutionCount, 1);

            // schedule the job to run
            DateTimeOffset scheduleTime1 = await sched.ScheduleJob(job1, trigger1);

            log.Info($"{job1.Key} will run at: {scheduleTime1.ToString("r")} and repeat: {trigger1.RepeatCount} times, every {trigger1.RepeatInterval.TotalSeconds} seconds");

            // job2 will also run 5 times, every 10 seconds

            IJobDetail job2 = JobBuilder.Create <ColorJob>()
                              .WithIdentity("job2", "group1")
                              .Build();

            ISimpleTrigger trigger2 = (ISimpleTrigger)TriggerBuilder.Create()
                                      .WithIdentity("trigger2", "group1")
                                      .StartAt(startTime)
                                      .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(4))
                                      .Build();

            // pass initialization parameters into the job
            // this job has a different favorite color!
            job2.JobDataMap.Put(ColorJob.FavoriteColor, "Red");
            job2.JobDataMap.Put(ColorJob.ExecutionCount, 1);

            // schedule the job to run
            DateTimeOffset scheduleTime2 = await sched.ScheduleJob(job2, trigger2);

            log.Info($"{job2.Key} will run at: {scheduleTime2.ToString("r")} and repeat: {trigger2.RepeatCount} times, every {trigger2.RepeatInterval.TotalSeconds} seconds");

            log.Info("------- Starting Scheduler ----------------");

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            await sched.Start();

            log.Info("------- Started Scheduler -----------------");

            log.Info("------- Waiting 60 seconds... -------------");

            // wait five minutes to show jobs
            await Task.Delay(TimeSpan.FromMinutes(5));

            // executing...

            log.Info("------- Shutting Down ---------------------");

            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs.");
        }
Ejemplo n.º 31
0
 public FileReportOutputter(Func <string> loggerNameGenerator)
     : this(() => LogProvider.GetLogger(loggerNameGenerator()))
 {
 }
Ejemplo n.º 32
0
 public void Initialize()
 {
     this.generator = new FunctionGenerator();
     this.provider = new LogProvider(this.generator, Visibility.Debug);
 }
Ejemplo n.º 33
0
 public MhfSqlDb()
 {
     Logger = LogProvider.Logger <MhfLogger>(this);
 }
Ejemplo n.º 34
0
 public RmqMessageCreator()
     : this(LogProvider.For <RmqMessageCreator>())
 {
 }
Ejemplo n.º 35
0
 public CheckPointerImpl(TransactionIdStore transactionIdStore, CheckPointThreshold threshold, StorageEngine storageEngine, LogPruning logPruning, TransactionAppender appender, DatabaseHealth databaseHealth, LogProvider logProvider, CheckPointTracer tracer, IOLimiter ioLimiter, StoreCopyCheckPointMutex mutex)
 {
     this._appender           = appender;
     this._transactionIdStore = transactionIdStore;
     this._threshold          = threshold;
     this._storageEngine      = storageEngine;
     this._logPruning         = logPruning;
     this._databaseHealth     = databaseHealth;
     this._ioLimiter          = ioLimiter;
     this._msgLog             = logProvider.GetLog(typeof(CheckPointerImpl));
     this._tracer             = tracer;
     this._mutex = mutex;
 }
Ejemplo n.º 36
0
 public RabbitMQHealthCheck(string name, IConnectionFactory connectionFactory)
     : this(name, connectionFactory, LogProvider.For <IRunHealthChecks>())
 {
     _connectionFactory = connectionFactory;
 }
Ejemplo n.º 37
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(LoadExample));

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = await sf.GetScheduler();

            log.Info("------- Initialization Complete -----------");

            log.Info("------- Scheduling Jobs -------------------");

            Random r = new Random();

            // schedule 500 jobs to run
            for (int count = 1; count <= NumberOfJobs; count++)
            {
                IJobDetail job = JobBuilder
                                 .Create <SimpleJob>()
                                 .WithIdentity("job" + count, "group_1")
                                 .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                                 .Build();

                // tell the job to delay some small amount... to simulate work...
                long timeDelay = (long)(r.NextDouble() * 2500);
                job.JobDataMap.Put(SimpleJob.DelayTime, timeDelay);

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("trigger_" + count, "group_1")
                                   .StartAt(DateBuilder.FutureDate(10000 + count * 100, IntervalUnit.Millisecond)) // space fire times a small bit
                                   .Build();

                await sched.ScheduleJob(job, trigger);

                if (count % 25 == 0)
                {
                    log.Info("...scheduled " + count + " jobs");
                }
            }

            log.Info("------- Starting Scheduler ----------------");

            // start the schedule
            await sched.Start();

            log.Info("------- Started Scheduler -----------------");

            log.Info("------- Waiting five minutes... -----------");

            // wait five minutes to give our jobs a chance to run
            await Task.Delay(TimeSpan.FromMinutes(5));

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info("Executed " + metaData.NumberOfJobsExecuted + " jobs.");
        }
Ejemplo n.º 38
0
        private void ReadLogProvidersConfiguration()
        {
            XmlReaderSettings settings;
            XmlReader config;
            LogProvider logProvider;
            string key, value;

            settings = new XmlReaderSettings();
            settings.Schemas.Add(null, Constants.LOG_PROVIDERS_CONFIG_SCHEMA);
            settings.ValidationType = ValidationType.Schema;
            config = XmlReader.Create(Constants.LOG_PROVIDERS_CONFIG, settings);

            config.ReadStartElement("usmsgw");
            config.ReadStartElement("logProviders");
            while (config.ReadToFollowing("logProvider"))
            {
                config.Read();

                logProvider = new LogProvider
                {
                    Name = config.ReadElementString("name"),
                    AssemblyName = config.ReadElementString("assembly"),
                    ClassName = config.ReadElementString("class"),
                    Enabled = IsFeatureEnabled(config.GetAttribute("enabled"))
                };

                _logProviders.Add(logProvider.Name.Trim().ToLower(), logProvider);

                ///
                /// Configuration
                ///
                config.ReadToFollowing("configuration");
                config.ReadToFollowing("set");
                do
                {
                    key = config.GetAttribute("key");
                    value = config.GetAttribute("value");

                    if ((string.IsNullOrEmpty(key) == false) && (string.IsNullOrEmpty(value) == false))
                        logProvider.Configuration.Settings[key] = value;

                } while (config.ReadToNextSibling("set"));
            }
        }