public void SetDefaultValuesOnCreation()
        {
            var options = new CorrelationOptions();

            Assert.Equal(CorrelationHeaders.IdHeaderKey, options.IdHeaderKey);
            Assert.Equal(CorrelationHeaders.SourceHeaderKey, options.SourceHeaderKey);
        }
Beispiel #2
0
        public void AddMiddlewareWithProvidedOptions()
        {
            // Arrange
            var app     = MockApplicationBuilder.MockUpWithRequiredServices(out _, out _, out _);
            var options = new CorrelationOptions();

            RequestDelegate next = new RequestDelegate((HttpContext _) => Task.CompletedTask);

            var middlewareWasCalled = false;
            Func <RequestDelegate, RequestDelegate> middlewareSupplied = null;

            app.OnUseCalled = (Func <RequestDelegate, RequestDelegate> middleware) =>
            {
                middlewareSupplied  = middleware;
                middlewareWasCalled = true;
            };

            // Act
            IApplicationBuilder returned = app.UseCorrelationId(options);

            // Assert
            returned.Should().Be(app, "the extension method should return the application builder to allow for chaining");
            middlewareWasCalled.Should().Be(true, "the correlation id middleware should have been added to the pipeline");

            // Arrange
            if (middlewareSupplied != null)
            {
                RequestDelegate result = middlewareSupplied.Invoke(next);
                result.Target.Should().BeAssignableTo(typeof(CorrelationMiddleware), "the build delegate target should be an instance of CorrelationIdMiddleware");
                CorrelationMiddleware middlewareInstance = result.Target as CorrelationMiddleware;
                middlewareInstance.Options.Should().Be(options, "the middleware should be initialized with the supplied CorrelationIdOptions");
            }
        }
        public void AddsCorrelationHeaderWithContext()
        {
            var client             = new HttpClient();
            var options            = new CorrelationOptions();
            var correlationContext = new CorrelationContext(Utilities.Options.Create(options));

            var id           = Guid.NewGuid().ToString();
            var sourceId     = Guid.NewGuid().ToString();
            var sourceName   = "testSource";
            var instanceId   = Guid.NewGuid().ToString();
            var instanceName = "testSource-instanceName";
            var userId       = "userId";
            var ipAddress    = "194.25.76.122";

            correlationContext.TrySetValues(id, sourceId, sourceName, instanceId, instanceName, userId, ipAddress);

            client.SetCorrelationValues(CreateServiceProvider(correlationContext, options));

            var result = client.DefaultRequestHeaders.Single(h => h.Key == CorrelationHeaders.HeaderKey);

            Assert.NotEqual(default(KeyValuePair <string, IEnumerable <string> >), result);
            byte[] data = Convert.FromBase64String(result.Value.Single());
            string json = Encoding.UTF8.GetString(data);

            dynamic parsedHeader  = JObject.Parse(json);
            string  correlationId = (string)parsedHeader.id;

            Assert.Equal(id, (string)parsedHeader.id);
            Assert.Equal(sourceId, (string)parsedHeader.sourceId);
            Assert.Equal(sourceName, (string)parsedHeader.sourceName);
            Assert.Equal(instanceId, (string)parsedHeader.instanceId);
            Assert.Equal(instanceName, (string)parsedHeader.instanceName);
            Assert.Equal(userId, (string)parsedHeader.userId);
            Assert.Equal(ipAddress, (string)parsedHeader.ipAddress);
        }
        public void SetValuesFirstTime()
        {
            var options      = new CorrelationOptions();
            var context      = new CorrelationContext(Options.Create(options));
            var id           = Guid.NewGuid().ToString();
            var sourceId     = Guid.NewGuid().ToString();
            var sourceName   = "appName";
            var instanceId   = Guid.NewGuid().ToString();
            var instanceName = "appName-instanceName";
            var userId       = "userId";
            var ipAddress    = "194.25.76.122";

            var result = context.TrySetValues(id, sourceId, sourceName, instanceId, instanceName, userId, ipAddress);

            Assert.True(result);
            Assert.Equal(id, context.Id);
            Assert.Equal(sourceId, context.SourceId);
            Assert.Equal(sourceName, context.SourceName);
            Assert.Equal(instanceId, context.InstanceId);
            Assert.Equal(instanceName, context.InstanceName);
            Assert.Equal(userId, context.UserId);
            Assert.Equal(ipAddress, context.IpAddress);

            byte[]  data         = Convert.FromBase64String(context.DgpHeader);
            string  json         = Encoding.UTF8.GetString(data);
            dynamic parsedHeader = JObject.Parse(json);

            Assert.Equal(id, (string)parsedHeader.id);
            Assert.Equal(sourceId, (string)parsedHeader.sourceId);
            Assert.Equal(sourceName, (string)parsedHeader.sourceName);
            Assert.Equal(instanceId, (string)parsedHeader.instanceId);
            Assert.Equal(instanceName, (string)parsedHeader.instanceName);
            Assert.Equal(userId, (string)parsedHeader.userId);
            Assert.Equal(ipAddress, (string)parsedHeader.ipAddress);
        }
Beispiel #5
0
        private void SetHeaderKeysFromOptions()
        {
            var options = new CorrelationOptions();

            var context = new CorrelationContext(Options.Create(options));

            Assert.Equal(options.IdHeaderKey, context.IdHeaderKey);
            Assert.Equal(options.SourceHeaderKey, context.SourceHeaderKey);
        }
        private void SetHeaderKeysFromOptions()
        {
            var options = new CorrelationOptions()
            {
                CorrelationHeaderRequired = true
            };

            var context = new CorrelationContext(Options.Create(options));

            Assert.True(options.CorrelationHeaderRequired);
        }
        private IServiceProvider CreateServiceProvider(ICorrelationContext context, CorrelationOptions options = null)
        {
            var serviceProviderMock = new Mock <IServiceProvider>();

            serviceProviderMock.Setup(p => p.GetService(typeof(ICorrelationContext))).Returns(context);

            if (options != null)
            {
                serviceProviderMock.Setup(p => p.GetService(typeof(IOptions <CorrelationOptions>))).Returns(Utilities.Options.Create(options));
            }

            return(serviceProviderMock.Object);
        }
Beispiel #8
0
        public void GenerateDifferentCorrelationIdsForEachRequest()
        {
            // Act
            var options  = new CorrelationOptions();
            var previous = new HashSet <string>(StringComparer.OrdinalIgnoreCase); // Guids are case-insensitive
            var context  = new DefaultHttpContext();

            // Assert
            while (previous.Count < 10000)
            {
                string generated = options.CorrelationIdGenerator(context);

                // .Add returns false if the element is already present.
                previous.Add(generated).Should().BeTrue("each generated value should be unique");
            }
        }
Beispiel #9
0
        public void HaveCorrectDefaults()
        {
            // Act
            var options = new CorrelationOptions();

            // Assert
            options.Header.Should().Be(Constants.XCorrelationID, "the default correlation id header should be used.");
            options.IncludeInResponse.Should().Be(true, "the correlation id should be included in the response by default.");
            options.UseTraceIdentifier.Should().Be(false, "the default trace identifier is machine and connection specific - it is not a very good cross machine correlation id by default.");
            options.UpdateTraceIdentifier.Should().Be(true, "the internal logging of ASP.NET uses the trace identifier thus it is easier if it is updated to match any incoming correlation id.");
            options.CorrelationIdGenerator.Should().NotBeNull("the options should have a non-null correlation id generator by default");

            string generated = options.CorrelationIdGenerator(new DefaultHttpContext());

            generated.Should().NotBeNullOrWhiteSpace();
            Guid.TryParse(generated, out _).Should().Be(true, "the default generator should create guid strings");
        }
Beispiel #10
0
        public void SetValuesFirstTime()
        {
            var options      = new CorrelationOptions();
            var context      = new CorrelationContext(Options.Create(options));
            var id           = Guid.NewGuid().ToString();
            var sourceId     = Guid.NewGuid().ToString();
            var sourceName   = "appName";
            var instanceId   = Guid.NewGuid().ToString();
            var instanceName = "appName-instanceName";
            var userId       = "userId";
            var ipAddress    = "194.25.76.122";

            var result = context.TrySetValues(id, sourceId, sourceName, instanceId, instanceName, userId, ipAddress);

            Assert.True(result);
            Assert.Equal(id, context.Id);
            Assert.Equal(sourceId, context.SourceId);
            Assert.Equal(sourceName, context.SourceName);
            Assert.Equal(instanceId, context.InstanceId);
            Assert.Equal(instanceName, context.InstanceName);
            Assert.Equal(userId, context.UserId);
            Assert.Equal(ipAddress, context.IpAddress);
        }
Beispiel #11
0
        public void AddHeadersToClientWithServiceProvider()
        {
            var client             = new HttpClient();
            var options            = new CorrelationOptions();
            var correlationContext = new CorrelationContext(Utilities.Options.Create(options));

            var id           = Guid.NewGuid().ToString();
            var sourceId     = Guid.NewGuid().ToString();
            var sourceName   = "testSource";
            var instanceId   = Guid.NewGuid().ToString();
            var instanceName = "testSource-instanceName";
            var userId       = "userId";
            var ipAddress    = "194.25.76.122";

            correlationContext.TrySetValues(id, sourceId, sourceName, instanceId, instanceName, userId, ipAddress);

            client.SetCorrelationValues(CreateServiceProvider(correlationContext, options));

            Assert.NotNull(client.DefaultRequestHeaders.Single(h => h.Key == options.IdHeaderKey));
            Assert.Equal(correlationContext.Id.ToString(), client.DefaultRequestHeaders.Single(h => h.Key == options.IdHeaderKey).Value.Single());

            Assert.NotNull(client.DefaultRequestHeaders.Single(h => h.Key == options.SourceHeaderKey));
            Assert.Equal(correlationContext.SourceId.ToString(), client.DefaultRequestHeaders.Single(h => h.Key == options.SourceHeaderKey).Value.Single());
        }
Beispiel #12
0
        public void SetDefaultValuesOnCreation()
        {
            var options = new CorrelationOptions();

            Assert.False(options.CorrelationHeaderRequired);
        }
Beispiel #13
0
        public static IServiceCollection AddCorrelation(this IServiceCollection services, CorrelationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            services?.AddSingleton(Options.Create(options));
            return(services?.AddSingleton <CorrelationMIddleware>()
                   ?? throw new ArgumentNullException(nameof(services)));
        }
 public CorrelationMIddleware(IOptions <CorrelationOptions> options, ILogger <CorrelationMIddleware> logger)
 {
     this.options = options?.Value
                    ?? throw new ArgumentNullException(nameof(options));
     this.logger = logger;
 }