Microsoft.Extensions.Options.Options.Create(TOptions)

Here are the examples of the csharp api Microsoft.Extensions.Options.Options.Create(TOptions) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

91 Examples 7

19 Source : KafkaTriggerAttributeBindingProviderTest.cs
with MIT License
from Azure

[Theory]
        [InlineData(nameof(SpecificAvro_Fn), typeof(Null))]
        [InlineData(nameof(RawSpecificAvro_Fn), typeof(Ignore))]
        [InlineData(nameof(SpecificAvroWithoutKey_Fn), typeof(Ignore))]
        public async Task When_Value_Type_Is_Specific_Record_Should_Create_SpecificRecord_Listener(string functionName, Type expectedKeyType)
        {
            var attribute = new KafkaTriggerAttribute("brokers:9092", "myTopic")
            {
            };

            var executor = new Mock<ITriggeredFunctionExecutor>();
            var listenerConfig = new KafkaListenerConfiguration()
            {
                BrokerList = attribute.BrokerList,
                Topic = attribute.Topic,
                ConsumerGroup = "group1",
            };

            var config = this.emptyConfiguration;

            var bindingProvider = new KafkaTriggerAttributeBindingProvider(
                config,
                Options.Create(new KafkaOptions()),
                new KafkaEventDataConvertManager(NullLogger.Instance),
                new DefaultNameResolver(config),
                NullLoggerFactory.Instance);

            var parameterInfo = new TriggerBindingProviderContext(this.GetParameterInfo(functionName), default);

            var triggerBinding = await bindingProvider.TryCreateAsync(parameterInfo);
            var listener = await triggerBinding.CreateListenerAsync(new ListenerFactoryContext(new FunctionDescriptor(), new Mock<ITriggeredFunctionExecutor>().Object, default));


            replacedert.NotNull(listener);
            replacedertIsCorrectKafkaListener(listener, expectedKeyType, typeof(MyAvroRecord), typeof(SyncOverAsyncDeserializer<MyAvroRecord>));
        }

19 Source : KafkaTriggerAttributeBindingProviderTest.cs
with MIT License
from Azure

[Theory]
        [InlineData(nameof(ByteArray_Fn), typeof(Null))]
        [InlineData(nameof(RawByteArray_Fn), typeof(Ignore))]
        [InlineData(nameof(ByteArrayWithoutKey_Fn), typeof(Ignore))]
        public async Task When_No_Type_Is_Set_Should_Create_ByteArray_Listener(string functionName, Type expectedKeyType)
        {
            var attribute = new KafkaTriggerAttribute("brokers:9092", "myTopic")
            {
            };

            var executor = new Mock<ITriggeredFunctionExecutor>();
            var listenerConfig = new KafkaListenerConfiguration()
            {
                BrokerList = attribute.BrokerList,
                Topic = attribute.Topic,
                ConsumerGroup = "group1",
            };

            var config = this.emptyConfiguration;

            var bindingProvider = new KafkaTriggerAttributeBindingProvider(
                config,
                Options.Create(new KafkaOptions()),
                new KafkaEventDataConvertManager(NullLogger.Instance),
                new DefaultNameResolver(config),                
                NullLoggerFactory.Instance);
            
            var parameterInfo = new TriggerBindingProviderContext(this.GetParameterInfo(functionName), default);

            var triggerBinding = await bindingProvider.TryCreateAsync(parameterInfo);
            var listener = await triggerBinding.CreateListenerAsync(new ListenerFactoryContext(new FunctionDescriptor(), new Mock<ITriggeredFunctionExecutor>().Object, default));

            replacedert.NotNull(listener);
            replacedertIsCorrectKafkaListener(listener, expectedKeyType, typeof(byte[]), null);
        }

19 Source : KafkaTriggerAttributeBindingProviderTest.cs
with MIT License
from Azure

[Theory]
        [InlineData(nameof(String_Fn), typeof(Null))]
        [InlineData(nameof(RawString_Fn), typeof(Ignore))]
        [InlineData(nameof(StringWithoutKey_Fn), typeof(Ignore))]
        public async Task When_String_Value_Type_Is_Set_Should_Create_String_Listener(string functionName, Type expectedKeyType)
        {
            var attribute = new KafkaTriggerAttribute("brokers:9092", "myTopic")
            {
            };

            var executor = new Mock<ITriggeredFunctionExecutor>();
            var listenerConfig = new KafkaListenerConfiguration()
            {
                BrokerList = attribute.BrokerList,
                Topic = attribute.Topic,
                ConsumerGroup = "group1",
            };

            var config = this.emptyConfiguration;

            var bindingProvider = new KafkaTriggerAttributeBindingProvider(
                config,
                Options.Create(new KafkaOptions()),
                new KafkaEventDataConvertManager(NullLogger.Instance),
                new DefaultNameResolver(config),
                NullLoggerFactory.Instance);

            var parameterInfo = new TriggerBindingProviderContext(this.GetParameterInfo(functionName), default);

            var triggerBinding = await bindingProvider.TryCreateAsync(parameterInfo);
            var listener = await triggerBinding.CreateListenerAsync(new ListenerFactoryContext(new FunctionDescriptor(), new Mock<ITriggeredFunctionExecutor>().Object, default));


            replacedert.NotNull(listener);
            replacedertIsCorrectKafkaListener(listener, expectedKeyType, typeof(string), null);
        }

19 Source : KafkaTriggerAttributeBindingProviderTest.cs
with MIT License
from Azure

[Theory]
        [InlineData(nameof(GenericAvro_Fn), typeof(Null))]
        [InlineData(nameof(GenericAvroWithoutKey_Fn), typeof(Ignore))]
        [InlineData(nameof(RawGenericAvro_Fn), typeof(Ignore))]
        public async Task When_Avro_Schema_Is_Provided_Should_Create_GenericRecord_Listener(string functionName, Type expectedKeyType)
        {
            var attribute = new KafkaTriggerAttribute("brokers:9092", "myTopic")
            {
            };

            var executor = new Mock<ITriggeredFunctionExecutor>();
            var listenerConfig = new KafkaListenerConfiguration()
            {
                BrokerList = attribute.BrokerList,
                Topic = attribute.Topic,
                ConsumerGroup = "group1",
            };

            var config = this.emptyConfiguration;

            var bindingProvider = new KafkaTriggerAttributeBindingProvider(
                config,
                Options.Create(new KafkaOptions()),
                new KafkaEventDataConvertManager(NullLogger.Instance),
                new DefaultNameResolver(config),
                NullLoggerFactory.Instance);

            var parameterInfo = new TriggerBindingProviderContext(this.GetParameterInfo(functionName), default);

            var triggerBinding = await bindingProvider.TryCreateAsync(parameterInfo);
            var listener = await triggerBinding.CreateListenerAsync(new ListenerFactoryContext(new FunctionDescriptor(), new Mock<ITriggeredFunctionExecutor>().Object, default));


            replacedert.NotNull(listener);
            replacedertIsCorrectKafkaListener(listener, expectedKeyType, typeof(GenericRecord), typeof(SyncOverAsyncDeserializer<GenericRecord>));            
        }

19 Source : KafkaTriggerAttributeBindingProviderTest.cs
with MIT License
from Azure

[Theory]
        [InlineData(nameof(Protobuf_Fn), typeof(Null))]
        [InlineData(nameof(RawProtobuf_Fn), typeof(Ignore))]
        [InlineData(nameof(ProtobufWithoutKey_Fn), typeof(Ignore))]
        public async Task When_Value_Type_Is_Protobuf_Should_Create_Protobuf_Listener(string functionName, Type expectedKeyType)
        {
            var attribute = new KafkaTriggerAttribute("brokers:9092", "myTopic")
            {
            };

            var executor = new Mock<ITriggeredFunctionExecutor>();
            var listenerConfig = new KafkaListenerConfiguration()
            {
                BrokerList = attribute.BrokerList,
                Topic = attribute.Topic,
                ConsumerGroup = "group1",
            };

            var config = this.emptyConfiguration;

            var bindingProvider = new KafkaTriggerAttributeBindingProvider(
                config,
                Options.Create(new KafkaOptions()),
                new KafkaEventDataConvertManager(NullLogger.Instance),
                new DefaultNameResolver(config),
                NullLoggerFactory.Instance);

            var parameterInfo = new TriggerBindingProviderContext(this.GetParameterInfo(functionName), default);

            var triggerBinding = await bindingProvider.TryCreateAsync(parameterInfo);
            var listener = await triggerBinding.CreateListenerAsync(new ListenerFactoryContext(new FunctionDescriptor(), new Mock<ITriggeredFunctionExecutor>().Object, default));


            replacedert.NotNull(listener);
            replacedertIsCorrectKafkaListener(listener, expectedKeyType, typeof(ProtoUser), typeof(ProtobufDeserializer<ProtoUser>));
        }

19 Source : KafkaTriggerAttributeBindingProviderTest.cs
with MIT License
from Azure

[Theory]
        [InlineData(nameof(String_With_LongKey_Fn), typeof(long), typeof(string))]
        [InlineData(nameof(String_With_StringKey_Fn), typeof(string), typeof(string))]

        [InlineData(nameof(GenericAvro_WithLongKey_Fn), typeof(long), typeof(GenericRecord))]
        [InlineData(nameof(GenericAvro_WithStringKey_Fn), typeof(string), typeof(GenericRecord))]

        [InlineData(nameof(ByteArrayWithLongKey_Fn), typeof(long), typeof(byte[]))]
        [InlineData(nameof(ByteArrayWithStringKey_Fn), typeof(string), typeof(byte[]))]

        [InlineData(nameof(SpecificAvro_WithLongKey_Fn), typeof(long), typeof(MyAvroRecord))]
        [InlineData(nameof(SpecificAvro_WithStringKey_Fn), typeof(string), typeof(MyAvroRecord))]

        [InlineData(nameof(Protobuf_WithLongKey_Fn), typeof(long), typeof(ProtoUser))]
        [InlineData(nameof(Protobuf_WithStringKey_Fn), typeof(string), typeof(ProtoUser))]
        public async Task When_Value_Is_KafkaEventData_With_Key_Should_Create_Listener_With_Key(string functionName, Type keyType, Type valueType)
        {
            var attribute = new KafkaTriggerAttribute("brokers:9092", "myTopic")
            {
            };

            var executor = new Mock<ITriggeredFunctionExecutor>();
            var listenerConfig = new KafkaListenerConfiguration()
            {
                BrokerList = attribute.BrokerList,
                Topic = attribute.Topic,
                ConsumerGroup = "group1",
            };

            var config = this.emptyConfiguration;

            var bindingProvider = new KafkaTriggerAttributeBindingProvider(
                config,
                Options.Create(new KafkaOptions()),
                new KafkaEventDataConvertManager(NullLogger.Instance),
                new DefaultNameResolver(config),
                NullLoggerFactory.Instance);

            var parameterInfo = new TriggerBindingProviderContext(this.GetParameterInfo(functionName), default);

            var triggerBinding = await bindingProvider.TryCreateAsync(parameterInfo);
            var listener = await triggerBinding.CreateListenerAsync(new ListenerFactoryContext(new FunctionDescriptor(), new Mock<ITriggeredFunctionExecutor>().Object, default));


            replacedert.NotNull(listener);
            replacedert.True(listener.GetType().IsGenericType);
            var genericTypes = listener.GetType().GetGenericArguments();
            replacedert.Equal(keyType, genericTypes[0]);
            replacedert.Equal(valueType, genericTypes[1]);
        }

19 Source : DispatcherHelper.cs
with MIT License
from Azure

internal static ServiceHubDispatcher PrepareAndGetDispatcher(IAppBuilder builder, HubConfiguration configuration, ServiceOptions options, string applicationName, ILoggerFactory loggerFactory)
        {
            // Ensure we have the conversions for MS.Owin so that
            // the app builder respects the OwinMiddleware base clreplaced
            SignatureConversions.AddConversions(builder);

            // ServiceEndpointManager needs the logger
            var hubs = GetAvailableHubNames(configuration);

            // Get the one from DI or new a default one
            var router = configuration.Resolver.Resolve<IEndpointRouter>() ?? new DefaultEndpointRouter();

            var serverNameProvider = configuration.Resolver.Resolve<IServerNameProvider>();
            if (serverNameProvider == null)
            {
                serverNameProvider = new DefaultServerNameProvider();
                configuration.Resolver.Register(typeof(IServerNameProvider), () => serverNameProvider);
            }

            var synchronizer = configuration.Resolver.Resolve<IAccessKeySynchronizer>();
            if (synchronizer == null)
            {
                synchronizer = new AccessKeySynchronizer(loggerFactory);
                configuration.Resolver.Register(typeof(IAccessKeySynchronizer), () => synchronizer);
            }

            var endpoint = new ServiceEndpointManager(synchronizer, options, loggerFactory);
            configuration.Resolver.Register(typeof(IServiceEndpointManager), () => endpoint);

            var requestIdProvider = configuration.Resolver.Resolve<IConnectionRequestIdProvider>();
            if (requestIdProvider == null)
            {
                requestIdProvider = new DefaultConnectionRequestIdProvider();
                configuration.Resolver.Register(typeof(IConnectionRequestIdProvider), () => requestIdProvider);
            }

            builder.Use<NegotiateMiddleware>(configuration, applicationName, endpoint, router, options, serverNameProvider, requestIdProvider, loggerFactory);

            builder.RunSignalR(configuration);

            // Fetch the trace manager from DI and add logger provider
            var traceManager = configuration.Resolver.Resolve<ITraceManager>();
            if (traceManager != null)
            {
                loggerFactory.AddProvider(new TraceManagerLoggerProvider(traceManager));
            }

            configuration.Resolver.Register(typeof(ILoggerFactory), () => loggerFactory);

            // TODO: Using IOptions looks wierd, thinking of a way removing it
            // share the same object all through
            var serviceOptions = Options.Create(options);

            // For safety, ALWAYS register abstract clreplacedes or interfaces
            // Some third-party DI frameworks such as Ninject, implicit self-binding concrete types:
            // https://github.com/ninject/ninject/wiki/dependency-injection-with-ninject#skipping-the-type-binding-bit--implicit-self-binding-of-concrete-types
            configuration.Resolver.Register(typeof(IOptions<ServiceOptions>), () => serviceOptions);

            var serviceProtocol = new ServiceProtocol();
            configuration.Resolver.Register(typeof(IServiceProtocol), () => serviceProtocol);

            // allow override from tests
            var scm = configuration.Resolver.Resolve<IServiceConnectionManager>();
            if (scm == null)
            {
                scm = new ServiceConnectionManager(applicationName, hubs);
                configuration.Resolver.Register(typeof(IServiceConnectionManager), () => scm);
            }

            var ccm = configuration.Resolver.Resolve<IClientConnectionManager>();
            if (ccm == null)
            {
                ccm = new ClientConnectionManager(configuration, loggerFactory);
                configuration.Resolver.Register(typeof(IClientConnectionManager), () => ccm);
            }

            var atm = new AzureTransportManager(configuration.Resolver);
            configuration.Resolver.Register(typeof(ITransportManager), () => atm);

            var parser = new SignalRMessageParser(hubs, configuration.Resolver, loggerFactory.CreateLogger<SignalRMessageParser>());
            configuration.Resolver.Register(typeof(IMessageParser), () => parser);

            var smb = new ServiceMessageBus(configuration.Resolver, loggerFactory.CreateLogger<ServiceMessageBus>());
            configuration.Resolver.Register(typeof(IMessageBus), () => smb);

            var serviceEventHandler = configuration.Resolver.Resolve<IServiceEventHandler>();
            if (serviceEventHandler == null)
            {
                serviceEventHandler = new DefaultServiceEventHandler(loggerFactory);
                configuration.Resolver.Register(typeof(IServiceEventHandler), () => serviceEventHandler);
            }

            var scf = configuration.Resolver.Resolve<IServiceConnectionFactory>();
            if (scf == null)
            {
                var connectionFactory = new ConnectionFactory(serverNameProvider, loggerFactory);
                scf = new ServiceConnectionFactory(serviceProtocol, ccm, connectionFactory, loggerFactory, serverNameProvider, serviceEventHandler);
                configuration.Resolver.Register(typeof(IServiceConnectionFactory), () => scf);
            }

            var sccf = new ServiceConnectionContainerFactory(scf, endpoint, router, options, loggerFactory);

            if (hubs?.Count > 0)
            {
                return new ServiceHubDispatcher(hubs, scm, sccf, serviceOptions, loggerFactory);
            }
            else
            {
                loggerFactory.CreateLogger<DispatcherHelper>().Log(LogLevel.Warning, "No hubs found.");
                return null;
            }
        }

19 Source : ServiceLifetimeManagerFacts.cs
with MIT License
from Azure

[Theory]
        [InlineData("SendAllAsync", typeof(BroadcastDataMessage))]
        [InlineData("SendAllExceptAsync", typeof(BroadcastDataMessage))]
        [InlineData("SendConnectionsAsync", typeof(MultiConnectionDataMessage))]
        [InlineData("SendGroupsAsync", typeof(MultiGroupBroadcastDataMessage))]
        [InlineData("SendUserAsync", typeof(UserDataMessage))]
        [InlineData("SendUsersAsync", typeof(MultiUserDataMessage))]
        public async void ServiceLifetimeManagerIgnoreBlazorHubProtocolTest(string functionName, Type type)
        {
            var blazorDetector = new DefaultBlazorDetector();
            var protocolResolver = new DefaultHubProtocolResolver(new IHubProtocol[]
                {
                    new JsonHubProtocol(),
                    new MessagePackHubProtocol(),
                    new CustomHubProtocol(),
                },
                NullLogger<DefaultHubProtocolResolver>.Instance);
            IOptions<HubOptions> globalHubOptions = Options.Create(new HubOptions() { SupportedProtocols = new List<string>() { "json", "messagepack", MockProtocol, "json" } });
            IOptions<HubOptions<TestHub>> localHubOptions = Options.Create(new HubOptions<TestHub>() { SupportedProtocols = new List<string>() { "json", "messagepack", MockProtocol } });
            var serviceConnectionManager = new TestServiceConnectionManager<TestHub>();
            var serviceLifetimeManager = new ServiceLifetimeManager<TestHub>(serviceConnectionManager,
                new ClientConnectionManager(), protocolResolver, Logger, Marker, globalHubOptions, localHubOptions, blazorDetector);

            await InvokeMethod(serviceLifetimeManager, functionName);

            replacedert.Equal(1, serviceConnectionManager.GetCallCount(type));
            VerifyServiceMessage(functionName, serviceConnectionManager.ServiceMessage);
            replacedert.Equal(2, (serviceConnectionManager.ServiceMessage as MulticastDataMessage).Payloads.Count);
            replacedert.True(blazorDetector.IsBlazor(nameof(TestHub)));
        }

19 Source : ServiceLifetimeManagerFacts.cs
with MIT License
from Azure

private HubLifetimeManager<TestHub> MockLifetimeManager(IServiceConnectionManager<TestHub> serviceConnectionManager, IClientConnectionManager clientConnectionManager = null, IBlazorDetector blazorDetector = null)
        {
            clientConnectionManager ??= new ClientConnectionManager();

            var protocolResolver = new DefaultHubProtocolResolver(new IHubProtocol[]
                {
                    new JsonHubProtocol(),
                    new MessagePackHubProtocol(),
                    new CustomHubProtocol(),
                },
                NullLogger<DefaultHubProtocolResolver>.Instance
            );
            IOptions<HubOptions> globalHubOptions = Options.Create(new HubOptions() { SupportedProtocols = new List<string>() { MockProtocol } });
            IOptions<HubOptions<TestHub>> localHubOptions = Options.Create(new HubOptions<TestHub>() { SupportedProtocols = new List<string>() { MockProtocol } });
            return new ServiceLifetimeManager<TestHub>(
                serviceConnectionManager,
                clientConnectionManager,
                protocolResolver,
                Logger,
                Marker,
                globalHubOptions,
                localHubOptions,
                blazorDetector
            );
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task GetSessionData()
        {
            DiagnosticsSink diagnosticsSink = new DiagnosticsSink();

            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            byte[] data = new byte[1] { 1 };

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                DiagnosticsHandler = diagnosticsSink.CaptureDiagnostics
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.SetAsync(sessionId, data, cacheOptions);

            replacedert.Equal(data, await cache.GetAsync(sessionId));

            replacedert.Equal(6, diagnosticsSink.CapturedDiagnostics.Count);
            foreach (CosmosDiagnostics diagnostics in diagnosticsSink.CapturedDiagnostics)
            {
                replacedert.NotNull(diagnostics?.ToString());
            }
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task SlidingAndAbsoluteExpiration()
        {
            const string sessionId = "sessionId";
            const int ttl = 10;
            const int absoluteTtl = 15;
            const int throughput = 400;

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            cacheOptions.AbsoluteExpiration = DateTimeOffset.UtcNow.AddSeconds(absoluteTtl);
            byte[] data = new byte[4] { 1, 2, 3, 4 };
            await cache.SetAsync(sessionId, data, cacheOptions);

            // Verify that container has been created

            CosmosCacheSession storedSession = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<CosmosCacheSession>(sessionId, new ParreplacedionKey(sessionId));
            replacedert.Equal(ttl, storedSession.TimeToLive);

            await Task.Delay(8000); // Wait

            await cache.GetAsync(sessionId);

            storedSession = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<CosmosCacheSession>(sessionId, new ParreplacedionKey(sessionId));

            // Since the absolute expiration is closer than the sliding value, the TTL should be lower
            replacedert.True(storedSession.TimeToLive < ttl);
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task StoreSessionData_CustomParreplacedionKey()
        {
            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            const string parreplacedionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                ContainerParreplacedionKeyAttribute = parreplacedionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            byte[] data = new byte[4] { 1, 2, 3, 4 };
            await cache.SetAsync(sessionId, data, cacheOptions);

            // Verify that container has been created

            CosmosCacheSession storedSession = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<CosmosCacheSession>(sessionId, new ParreplacedionKey(sessionId));
            replacedert.Equal(sessionId, storedSession.SessionKey);
            replacedert.Equal(data, storedSession.Content);

            ItemResponse<dynamic> dynamicSession = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<dynamic>(sessionId, new ParreplacedionKey(sessionId));
            replacedert.NotNull(dynamicSession.Resource.notTheId);
            replacedert.Equal(sessionId, (string)dynamicSession.Resource.notTheId);
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task GetSessionData_CustomParreplacedionKey()
        {
            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            byte[] data = new byte[1] { 1 };
            const string parreplacedionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                ContainerParreplacedionKeyAttribute = parreplacedionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.SetAsync(sessionId, data, cacheOptions);

            replacedert.Equal(data, await cache.GetAsync(sessionId));
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task RemoveSessionData_CustomParreplacedionKey()
        {
            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            byte[] data = new byte[1] { 1 };
            const string parreplacedionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                ContainerParreplacedionKeyAttribute = parreplacedionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.SetAsync(sessionId, data, cacheOptions);

            await cache.RemoveAsync(sessionId);

            CosmosException exception = await replacedert.ThrowsAsync<CosmosException>(() => this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<dynamic>(sessionId, new ParreplacedionKey(sessionId)));
            replacedert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task RemoveSessionData_WhenNotExists()
        {
            DiagnosticsSink diagnosticsSink = new DiagnosticsSink();

            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                DiagnosticsHandler = diagnosticsSink.CaptureDiagnostics
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.RemoveAsync(sessionId);

            replacedert.Equal(4, diagnosticsSink.CapturedDiagnostics.Count);
            foreach (CosmosDiagnostics diagnostics in diagnosticsSink.CapturedDiagnostics)
            {
                replacedert.NotNull(diagnostics?.ToString());
            }
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task GetSessionData_WhenNotExists()
        {
            DiagnosticsSink diagnosticsSink = new DiagnosticsSink();

            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                DiagnosticsHandler = diagnosticsSink.CaptureDiagnostics
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            replacedert.Null(await cache.GetAsync(sessionId));

            replacedert.Equal(4, diagnosticsSink.CapturedDiagnostics.Count);
            foreach (CosmosDiagnostics diagnostics in diagnosticsSink.CapturedDiagnostics)
            {
                replacedert.NotNull(diagnostics?.ToString());
            }
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task RemoveSessionData_WhenNotExists_CustomParreplacedionKey()
        {
            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            const string parreplacedionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                ContainerParreplacedionKeyAttribute = parreplacedionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.RemoveAsync(sessionId);
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task GetSessionData_WhenNotExists_CustomParreplacedionKey()
        {
            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            const string parreplacedionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                ContainerParreplacedionKeyAttribute = parreplacedionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            replacedert.Null(await cache.GetAsync(sessionId));
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task InitializeContainerIfNotExists()
        {
            DiagnosticsSink diagnosticsSink = new DiagnosticsSink();

            const string sessionId = "sessionId";
            const int ttl = 2000;
            const int ttlInSeconds = ttl / 1000;
            const int throughput = 2000;

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                DefaultTimeToLiveInMs = ttl,
                DiagnosticsHandler = diagnosticsSink.CaptureDiagnostics
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttlInSeconds);
            await cache.SetAsync(sessionId, new byte[0], cacheOptions);

            // Verify that container has been created

            ContainerResponse response = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadContainerAsync();
            replacedert.NotEqual(HttpStatusCode.NotFound, response.StatusCode);
            replacedert.Equal(ttlInSeconds, response.Resource.DefaultTimeToLive);
            replacedert.True(response.Resource.IndexingPolicy.ExcludedPaths.Any(e => e.Path.Equals("/*")));

            int? throughputContainer = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadThroughputAsync();

            replacedert.Equal(throughput, throughputContainer);

            replacedert.Equal(4, diagnosticsSink.CapturedDiagnostics.Count);
            foreach (CosmosDiagnostics diagnostics in diagnosticsSink.CapturedDiagnostics)
            {
                replacedert.NotNull(diagnostics?.ToString());
            }
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task InitializeContainerIfNotExists_CustomParreplacedionKey()
        {
            const string sessionId = "sessionId";
            const int ttl = 2000;
            const int ttlInSeconds = ttl / 1000;
            const int throughput = 2000;
            const string parreplacedionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                DefaultTimeToLiveInMs = ttl,
                ContainerParreplacedionKeyAttribute = parreplacedionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttlInSeconds);
            await cache.SetAsync(sessionId, new byte[0], cacheOptions);

            // Verify that container has been created

            ContainerResponse response = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadContainerAsync();
            replacedert.NotEqual(HttpStatusCode.NotFound, response.StatusCode);
            replacedert.Equal(ttlInSeconds, response.Resource.DefaultTimeToLive);
            replacedert.True(response.Resource.IndexingPolicy.ExcludedPaths.Any(e => e.Path.Equals("/*")));
            replacedert.Equal($"/{parreplacedionKeyAttribute}", response.Resource.ParreplacedionKeyPath);

            int? throughputContainer = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadThroughputAsync();

            replacedert.Equal(throughput, throughputContainer);
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task StoreSessionData()
        {
            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            byte[] data = new byte[4] { 1, 2, 3, 4 };
            await cache.SetAsync(sessionId, data, cacheOptions);

            // Verify that container has been created

            CosmosCacheSession storedSession = await this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<CosmosCacheSession>(sessionId, new ParreplacedionKey(sessionId));
            replacedert.Equal(sessionId, storedSession.SessionKey);
            replacedert.Equal(data, storedSession.Content);
        }

19 Source : CosmosCacheEmulatorTests.cs
with MIT License
from Azure

[Fact]
        public async Task RemoveSessionData()
        {
            DiagnosticsSink diagnosticsSink = new DiagnosticsSink();

            const string sessionId = "sessionId";
            const int ttl = 1400;
            const int throughput = 2000;
            byte[] data = new byte[1] { 1 };

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions<CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions(){
                ContainerName = "session",
                DatabaseName = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput = throughput,
                CreateIfNotExists = true,
                ClientBuilder = builder,
                DiagnosticsHandler = diagnosticsSink.CaptureDiagnostics
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();
            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.SetAsync(sessionId, data, cacheOptions);

            await cache.RemoveAsync(sessionId);

            CosmosException exception = await replacedert.ThrowsAsync<CosmosException>(() => this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync<dynamic>(sessionId, new ParreplacedionKey(sessionId)));
            replacedert.Equal(HttpStatusCode.NotFound, exception.StatusCode);

            replacedert.Equal(5, diagnosticsSink.CapturedDiagnostics.Count);
            foreach (CosmosDiagnostics diagnostics in diagnosticsSink.CapturedDiagnostics)
            {
                replacedert.NotNull(diagnostics?.ToString());
            }
        }

19 Source : Extensions.Register.cs
with Apache License 2.0
from cosmos-loops

private static void BuildAndActiveConfiguration(this AspectCoreServiceCollection services) {
            services.BuildConfiguration();
            services.ActiveSinkSettings();
            services.ActiveOriginConfiguration();

            services.AddDependency(s => s.TryAddSingleton(Options.Create((LoggingOptions) services.ExposeLogSettings())));
            services.AddDependency(s => s.TryAddSingleton(services.ExposeLoggingConfiguration()));
        }

19 Source : Extensions.Register.cs
with Apache License 2.0
from cosmos-loops

private static void BuildAndActiveConfiguration(this AutofacServiceCollection services) {
            services.BuildConfiguration();
            services.ActiveSinkSettings();
            services.ActiveOriginConfiguration();
            
            services.AddDependency(s => s.TryAddSingleton(Options.Create((LoggingOptions) services.ExposeLogSettings())));
            services.AddDependency(s => s.TryAddSingleton(services.ExposeLoggingConfiguration()));

        }

19 Source : Extensions.Register.cs
with Apache License 2.0
from cosmos-loops

private static void BuildAndActiveConfiguration(this StandardLogServiceCollection services) {
            services.BuildConfiguration();
            services.ActiveSinkSettings();
            services.ActiveOriginConfiguration();
            
            services.AddDependency(s => s.TryAddSingleton(Options.Options.Create((LoggingOptions) services.ExposeLogSettings())));
            services.AddDependency(s => s.TryAddSingleton(services.ExposeLoggingConfiguration()));
        }

19 Source : Extensions.EntityFrameworkEnricher.cs
with Apache License 2.0
from cosmos-loops

public static DatabaseIntegration UseEnreplacedyFramework(
            this DatabaseIntegration integration,
            Action<EfEnricherOptions> settingAct = null,
            Action<IConfiguration, EfEnricherConfiguration> configAction = null) {

            var settings = new EfEnricherOptions();
            settingAct?.Invoke(settings);

            void InternalAction(IConfiguration conf, EfEnricherConfiguration sink, LoggingConfiguration configuration) {
                configAction?.Invoke(conf, sink);
                if (configuration?.LogLevel != null) {
                    AddNamespace($"{typeof(DbContext).Namespace}.*", GetExpectLevelName());
                    AddNamespace($"{typeof(Database).FullName}", LogEventLevel.Debug.GetName());
                }

                void AddNamespace(string @namespace, string expectLevelName) {
                    if (string.IsNullOrWhiteSpace(@namespace)) return;
                    if (configuration.LogLevel.ContainsKey(@namespace)) {
                        configuration.LogLevel[@namespace] = expectLevelName;
                    } else {
                        configuration.LogLevel.Add(@namespace, expectLevelName);
                    }
                }

                string GetExpectLevelName() => settings.MinimumLevel.HasValue
                    ? settings.MinimumLevel.Value.GetName()
                    : LogEventLevel.Verbose.GetName();
            }

            return UseEnreplacedyFrameworkCore(integration, Options.Create(settings), InternalAction);
        }

19 Source : Extensions.EntityFrameworkCoreEnricher.cs
with Apache License 2.0
from cosmos-loops

public static DatabaseIntegration UseEnreplacedyFrameworkCore(
            this DatabaseIntegration integration,
            Action<EfCoreEnricherOptions> settingAct = null,
            Action<IConfiguration, EfCoreEnricherConfiguration> configAction = null) {
            var settings = new EfCoreEnricherOptions();
            settingAct?.Invoke(settings);

            void InternalAction(IConfiguration conf, EfCoreEnricherConfiguration sink, LoggingConfiguration configuration) {
                configAction?.Invoke(conf, sink);
                if (configuration?.LogLevel != null) {
                    AddNamespace($"{typeof(DbContext).Namespace}.*", GetExpectLevelName());
                    AddNamespace($"{typeof(DbContextOptionsBuilder).FullName}", GetExpectLevelName());
                    AddNamespace(DbLoggerCategory.Database.Command.Name, GetExpectLevelName());
                    AddNamespace(DbLoggerCategory.Query.Name, GetExpectLevelName());
                    AddNamespace(DbLoggerCategory.Update.Name, GetExpectLevelName());
                }

                void AddNamespace(string @namespace, string expectLevelName) {
                    if (string.IsNullOrWhiteSpace(@namespace)) return;
                    if (configuration.LogLevel.ContainsKey(@namespace)) {
                        configuration.LogLevel[@namespace] = expectLevelName;
                    } else {
                        configuration.LogLevel.Add(@namespace, expectLevelName);
                    }
                }

                string GetExpectLevelName() => settings.MinimumLevel.HasValue
                    ? settings.MinimumLevel.Value.GetName()
                    : LogEventLevel.Verbose.GetName();
            }

            return UseEnreplacedyFrameworkCoreInternal(integration, Options.Create(settings), InternalAction);
        }

19 Source : FreeSqlEnricherExtensions.cs
with Apache License 2.0
from cosmos-loops

public static DatabaseIntegration UseFreeSql(
            this DatabaseIntegration integration, Action<FreeSqlEnricherOptions> settingAct = null,
            Action<IConfiguration, FreeSqlEnricherConfiguration> configAction = null) {
            var settings = new FreeSqlEnricherOptions();
            settingAct?.Invoke(settings);

            void InternalAction(IConfiguration conf, FreeSqlEnricherConfiguration sink, LoggingConfiguration configuration) {
                configAction?.Invoke(conf, sink);
                if (configuration?.LogLevel != null) {
                    var @namespace = "FreeSql.*";
                    if (configuration.LogLevel.ContainsKey(@namespace)) {
                        configuration.LogLevel[@namespace] = GetExpectLevelName();
                    } else {
                        configuration.LogLevel.Add(@namespace, GetExpectLevelName());
                    }
                }
            }

            string GetExpectLevelName() => settings.MinimumLevel.HasValue ? settings.MinimumLevel.Value.GetName() : LogEventLevel.Verbose.GetName();

            return UseFreeSqlCore(integration, Options.Create(settings), InternalAction);
        }

19 Source : SqlSugarEnricherExtensions.cs
with Apache License 2.0
from cosmos-loops

public static DatabaseIntegration UseSqlSugar(
            this DatabaseIntegration integration,
            Action<SqlSugarEnricherOptions> settingAct = null,
            Action<IConfiguration, SqlSguarEnricherConfiguration> configAction = null) {

            var settings = new SqlSugarEnricherOptions();
            settingAct?.Invoke(settings);

            void InternalAction(IConfiguration conf, SqlSguarEnricherConfiguration sink, LoggingConfiguration configuration) {
                configAction?.Invoke(conf, sink);
                if (configuration?.LogLevel != null) {
                    var @namespace = $"{typeof(SqlSugarClient).Namespace}.*";
                    if (configuration.LogLevel.ContainsKey(@namespace)) {
                        configuration.LogLevel[@namespace] = GetExpectLevelName();
                    } else {
                        configuration.LogLevel.Add(@namespace, GetExpectLevelName());
                    }
                }
            }

            string GetExpectLevelName() => settings.MinimumLevel.HasValue ? settings.MinimumLevel.Value.GetName() : LogEventLevel.Verbose.GetName();

            return UseSqlSugarCore(integration, Options.Create(settings), InternalAction);
        }

19 Source : Extensions.Register.cs
with Apache License 2.0
from cosmos-loops

public static IContainer RegisterCosmosLogging(this IContainer ioc, Action<ILogServiceCollection> serviceConfigure) {

            var loggingServices = new ZkWebLogServiceCollection();

            loggingServices.RegisterCoreComponents(serviceConfigure);

            ioc.Register<ILoggingServiceProvider, ZKWebLoggingServiceProvider>(ReuseType.Singleton);
            ioc.Register<IPropertyFactoryAccessor, ShortcutPropertyFactoryAccessor>();

            ioc.RegisterFromServiceCollection(loggingServices.OriginalServices);
            ioc.RegisterTraceIdGenerator();
            ioc.RegisterInstance(Options.Create((LoggingOptions) loggingServices.ExposeLogSettings()), ReuseType.Singleton);
            ioc.RegisterInstance(loggingServices.ExposeLoggingConfiguration(), ReuseType.Singleton);

            StaticServiceResolver.SetResolver(ioc.Resolve<ILoggingServiceProvider>());

            loggingServices.ActiveLogEventEnrichers();

            return ioc;
        }

19 Source : AliyunSlsSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddAliyunSls(this ILogServiceCollection services, AliyunSlsSinkOptions sinkOptions,
            Action<IConfiguration, AliyunSlsSinkConfiguration> configAct = null) {
            return services.AddAliyunSls(Options.Create(sinkOptions), configAct);
        }

19 Source : ConsoleSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddConsole(this ILogServiceCollection services, ConsoleSinkOptions options,
            Action<IConfiguration, ConsoleSinkConfiguration> configAction = null) {
            return services.AddConsole(Options.Create(options), configAction);
        }

19 Source : ExceptionlessSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddExceptionless(this ILogServiceCollection services, ExceptionlessSinkOptions sinkOptions,
            Action<IConfiguration, ExceptionlessSinkConfiguration> configAct = null) {
            return services.AddExceptionless(Options.Create(sinkOptions), configAct);
        }

19 Source : LocalFileLogSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddFilelog(this ILogServiceCollection services, Action<FileSinkOptions> settingAct = null,
            Action<IConfiguration, FileSinkLogConfiguration> config = null) {
            var options = new FileSinkOptions();
            settingAct?.Invoke(options);
            return services.AddFilelog(Options.Create(options), config);
        }

19 Source : JdCloudLogSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddJdCloudLogService(this ILogServiceCollection services, JdCloudLogSinkOptions sinkOptions,
            Action<IConfiguration, JdCloudLogSinkConfiguration> configAct = null) {
            return services.AddJdCloudLogService(Options.Create(sinkOptions), configAct);
        }

19 Source : SampleLogSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddSampleLog(this ILogServiceCollection services, Action<SampleOptions> settingAct = null,
            Action<IConfiguration, SampleLogConfiguration> config = null) {
            var options = new SampleOptions();
            settingAct?.Invoke(options);
            return services.AddSampleLog(Options.Create(options), config);
        }

19 Source : SoloDependencyContainer.cs
with Apache License 2.0
from cosmos-loops

private static void BuildAndActiveConfiguration(this ConsoleLogServiceCollection services) {
            services.BuildConfiguration();
            services.ActiveSinkSettings();
            services.ActiveOriginConfiguration();

            services.AddDependency(s => s.TryAddSingleton(Options.Create((LoggingOptions) services.ExposeLogSettings())));
            services.AddDependency(s => s.TryAddSingleton(services.ExposeLoggingConfiguration()));

        }

19 Source : Log4NetSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddLog4Net(this ILogServiceCollection services, Log4NetSinkOptions sinkOptions,
            Action<IConfiguration, Log4NetSinkConfiguration> configAct = null) {
            return services.AddLog4Net(Options.Create(sinkOptions), configAct);
        }

19 Source : TencentCloudClsSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddTencentCloudCls(this ILogServiceCollection services, TencentCloudClsSinkOptions sinkOptions,
            Action<IConfiguration, TencentCloudClsSinkConfiguration> configAct = null) {
            return services.AddTencentCloudCls(Options.Create(sinkOptions), configAct);
        }

19 Source : TomatoLogSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddTomatoLog(this ILogServiceCollection services, TomatoLogSinkOptions sinkOptions,
            Action<IConfiguration, TomatoLogSinkConfiguration> configAct = null) {
            return services.AddTomatoLog(Options.Create(sinkOptions), configAct);
        }

19 Source : NhEnricherExtensions.cs
with Apache License 2.0
from cosmos-loops

public static DatabaseIntegration UseNHibernate(
            this DatabaseIntegration integration,
            Action<NhEnricherOptions> settingAct = null,
            Action<IConfiguration, NhEnricherConfiguration> configAction = null) {
            var settings = new NhEnricherOptions();
            settingAct?.Invoke(settings);

            void InternalAction(IConfiguration conf, NhEnricherConfiguration sink, LoggingConfiguration configuration) {
                configAction?.Invoke(conf, sink);
                if (configuration?.LogLevel != null) {
                    AddNamespace($"{typeof(ISessionFactory).Namespace}.*", GetExpectLevelName());
                }

                void AddNamespace(string @namespace, string expectLevelName) {
                    if (string.IsNullOrWhiteSpace(@namespace)) return;
                    if (configuration.LogLevel.ContainsKey(@namespace)) {
                        configuration.LogLevel[@namespace] = expectLevelName;
                    } else {
                        configuration.LogLevel.Add(@namespace, expectLevelName);
                    }
                }

                string GetExpectLevelName() => settings.MinimumLevel.HasValue
                    ? settings.MinimumLevel.Value.GetName()
                    : LogEventLevel.Verbose.GetName();
            }

            return UseNHibernateCore(integration, Options.Create(settings), InternalAction);
        }

19 Source : Extensions.PostgresEnricher.cs
with Apache License 2.0
from cosmos-loops

public static DatabaseIntegration UsePostgreSql(
            this DatabaseIntegration integration,
            Action<PostgresEnricherOptions> settingAct = null,
            Action<IConfiguration, PostgresEnricherConfiguration> configAction = null) {
            var settings = new PostgresEnricherOptions();
            settingAct?.Invoke(settings);

            void InternalAction(IConfiguration conf, PostgresEnricherConfiguration sink, LoggingConfiguration configuration) {
                configAction?.Invoke(conf, sink);
                if (configuration?.LogLevel != null) {
                    var @namespace = "Npgsql.*";
                    if (configuration.LogLevel.ContainsKey(@namespace)) {
                        configuration.LogLevel[@namespace] = GetExpectLevelName();
                    } else {
                        configuration.LogLevel.Add(@namespace, GetExpectLevelName());
                    }
                }
            }

            string GetExpectLevelName() => settings.MinimumLevel.HasValue ? settings.MinimumLevel.Value.GetName() : LogEventLevel.Verbose.GetName();

            return UsePostgreSqlCore(integration, Options.Create(settings), InternalAction);
        }

19 Source : NLogSinkExtensions.cs
with Apache License 2.0
from cosmos-loops

public static ILogServiceCollection AddNLog(this ILogServiceCollection services, NLogSinkOptions options,
            Action<IConfiguration, NLogSinkConfiguration> configAction = null) {
            return services.AddNLog(Options.Create(options), configAction);
        }

19 Source : BotAuthentication.cs
with MIT License
from CXuesong

public static IApplicationBuilder UseBotAuthentication(this IApplicationBuilder app, ICredentialProvider credentialProvider)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var options = new BotAuthenticationOptions
            {
                CredentialProvider = credentialProvider
            };
            
            return app.UseMiddleware<BotAuthenticationMiddleware>(Options.Create(options));
        }

19 Source : BotAuthentication.cs
with MIT License
from CXuesong

public static IApplicationBuilder UseBotAuthentication(this IApplicationBuilder app, BotAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<BotAuthenticationMiddleware>(Options.Create(options));
        }

19 Source : KustoClientProviderTests.cs
with MIT License
from dotnet

[Test]
        public async Task NoParameterQueryIsPreplacededPlainly()
        {
            var queryProvider = new Mock<ICslQueryProvider>();
            var dbNames = new List<string>();
            var queries = new List<string>();
            var properties = new List<ClientRequestProperties>();
            var reader = Mock.Of<IDataReader>();
            queryProvider.Setup(q =>
                    q.ExecuteQueryAsync(Capture.In(dbNames), Capture.In(queries), Capture.In(properties)))
                .Returns(Task.FromResult(reader));

            using (var client = new KustoClientProvider(Options.Create(new KustoClientProviderOptions
                    {QueryConnectionString = "IGNORED-CONNECTION-STRING", Database = "TEST-DATABASE",}),
                queryProvider.Object))
            {
                IDataReader result = await client.ExecuteKustoQueryAsync(new KustoQuery("basicQuery"));
                reader.Should().BeSameAs(result);
            }

            dbNames.Should().Equal(new[] {"TEST-DATABASE"});
            queries.Should().Equal(new[] {"basicQuery"});
            properties.Should().ContainSingle();
            properties[0].Parameters.Should().BeEmpty();
        }

19 Source : KustoClientProviderTests.cs
with MIT License
from dotnet

[Test]
        public async Task replacedignedToTextPropertyIsPreplacededPlainly()
        {
            var queryProvider = new Mock<ICslQueryProvider>();
            var dbNames = new List<string>();
            var queries = new List<string>();
            var properties = new List<ClientRequestProperties>();
            var reader = Mock.Of<IDataReader>();
            queryProvider.Setup(q =>
                    q.ExecuteQueryAsync(Capture.In(dbNames), Capture.In(queries), Capture.In(properties)))
                .Returns(Task.FromResult(reader));

            using (var client = new KustoClientProvider(Options.Create(new KustoClientProviderOptions
                    {QueryConnectionString = "IGNORED-CONNECTION-STRING", Database = "TEST-DATABASE",}),
                queryProvider.Object))
            {
                var query = new KustoQuery {Text = "basicQuery"};
                IDataReader result = await client.ExecuteKustoQueryAsync(query);
                reader.Should().BeSameAs(result);
            }

            dbNames.Should().Equal(new[] {"TEST-DATABASE"});
            queries.Should().Equal(new[] {"basicQuery"});
            properties.Should().ContainSingle();
            properties[0].Parameters.Should().BeEmpty();
        }

19 Source : KustoClientProviderTests.cs
with MIT License
from dotnet

[Test]
        public async Task ParameterizedQueryIncludesParameterInformation()
        {
            var queryProvider = new Mock<ICslQueryProvider>();
            var dbNames = new List<string>();
            var queries = new List<string>();
            var properties = new List<ClientRequestProperties>();
            var reader = Mock.Of<IDataReader>();
            queryProvider.Setup(q =>
                    q.ExecuteQueryAsync(Capture.In(dbNames), Capture.In(queries), Capture.In(properties)))
                .Returns(Task.FromResult(reader));

            using (var client = new KustoClientProvider(Options.Create(new KustoClientProviderOptions
                    {QueryConnectionString = "IGNORED-CONNECTION-STRING", Database = "TEST-DATABASE",}),
                queryProvider.Object))
            {
                var query = new KustoQuery("basicQuery | where Id = _id and Name = _name",
                    new KustoParameter("_id", 9274, KustoDataType.Int));
                query.AddParameter("_name", "TEST-NAME", KustoDataType.String);
                IDataReader result = await client.ExecuteKustoQueryAsync(
                    query);
                reader.Should().BeSameAs(result);
            }

            dbNames.Should().Equal(new[] {"TEST-DATABASE"});
            queries.Should().ContainSingle();
            queries[0].Should().EndWith("basicQuery | where Id = _id and Name = _name");
            var parameterDeclarationPattern = new Regex(@"declare\s*query_parameters\s*\(([^)]*)\)\s*;");
            queries[0].Should().MatchRegex(parameterDeclarationPattern);
            string parametersString = parameterDeclarationPattern.Match(queries[0]).Groups[1].Value;
            IReadOnlyDictionary<string, string> parameters = parametersString.Split(',')
                .Select(p => p.Split(':', 2))
                .ToDictionary(p => p[0], p => p[1]);
            parameters.Should().HaveCount(2);
            parameters.Should().ContainKey("_id");
            parameters["_id"].Should().Be(KustoDataType.Int.CslDataType);
            parameters.Should().ContainKey("_name");
            parameters["_name"].Should().Be(KustoDataType.String.CslDataType);
            properties.Should().ContainSingle();
            properties[0].Parameters.Should().HaveCount(2);
            properties[0].Parameters.Should().ContainKey("_id");
            properties[0].Parameters["_id"].Should().Be("9274");
            properties[0].Parameters.Should().ContainKey("_name");
            properties[0].Parameters["_name"].Should().Be("TEST-NAME");
        }

19 Source : KustoClientProviderTests.cs
with MIT License
from dotnet

[Test]
        public async Task SemanticExceptionReturnsNull()
        {
            var queryProvider = new Mock<ICslQueryProvider>();
            queryProvider.Setup(q =>
                    q.ExecuteQueryAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ClientRequestProperties>()))
                .Throws(new SemanticException());

            using (var client = new KustoClientProvider(Options.Create(new KustoClientProviderOptions
                    {QueryConnectionString = "IGNORED-CONNECTION-STRING", Database = "TEST-DATABASE",}),
                queryProvider.Object))
            {
                (await client.ExecuteKustoQueryAsync(new KustoQuery("basicQuery"))).Should().BeNull();
            }
        }

19 Source : EndpointUtilities.cs
with MIT License
from dotnet

public async Task<ServerSourceHolder> StartServerAsync(EndpointInfoSourceCallback sourceCallback = null, IDumpService dumpService = null,
            OperationTrackerService operationTrackerService = null)
        {
            DiagnosticPortHelper.Generate(DiagnosticPortConnectionMode.Listen, out _, out string transportName);
            _outputHelper.WriteLine("Starting server endpoint info source at '" + transportName + "'.");

            List<IEndpointInfoSourceCallbacks> callbacks = new();
            if (null != sourceCallback)
            {
                callbacks.Add(sourceCallback);
                if (null != dumpService)
                {
                    callbacks.Add(new OperationTrackerServiceEndpointInfoSourceCallback(operationTrackerService));
                }
            }

            IOptions<DiagnosticPortOptions> portOptions = Extensions.Options.Options.Create(
                new DiagnosticPortOptions()
                {
                    ConnectionMode = DiagnosticPortConnectionMode.Listen,
                    EndpointName = transportName
                });

            ServerEndpointInfoSource source = new(portOptions, callbacks, operationTrackerService);

            await source.StartAsync(CancellationToken.None);

            return new ServerSourceHolder(source, transportName);
        }

See More Examples