コード例 #1
0
    public override async Task Invoke(IIncomingPhysicalMessageContext context, Func <Task> next)
    {
        string messageTypeName;
        var    headers = context.MessageHeaders;

        if (headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageType))
        {
            messageTypeName = TypeNameConverter.GetName(messageType);
        }
        else
        {
            messageTypeName = "UnknownMessageType";
        }

        var logger = logBuilder.GetLogger(messageTypeName);
        List <PropertyEnricher> properties = new()
        {
            new("IncomingMessageId", context.MessageId),
            new("IncomingMessageType", messageTypeName)
        };


        if (headers.TryGetValue(Headers.CorrelationId, out var correlationId))
        {
            properties.Add(new PropertyEnricher("CorrelationId", correlationId));
        }

        if (headers.TryGetValue(Headers.ConversationId, out var conversationId))
        {
            properties.Add(new PropertyEnricher("ConversationId", conversationId));
        }

        ExceptionLogState exceptionLogState = new
                                              (
            processingEndpoint : endpoint,
            incomingHeaders : context.MessageHeaders,
            correlationId : correlationId,
            conversationId : conversationId
                                              );

        var loggerForContext = logger.ForContext(properties);

        context.Extensions.Set(exceptionLogState);
        context.Extensions.Set(loggerForContext);

        try
        {
            await next();
        }
        catch (Exception exception)
        {
            var data = exception.Data;
            if (!data.Contains("ExceptionLogState"))
            {
                data.Add("ExceptionLogState", exceptionLogState);
            }

            throw;
        }
    }
コード例 #2
0
 public override void WriteJson(
     JsonWriter writer, ConstructorInfo value,
     JsonSerializer serializer,
     IReadOnlyDictionary <string, object> context)
 {
     writer.WriteValue(TypeNameConverter.GetName(value));
 }
コード例 #3
0
ファイル: DelegateConverter.cs プロジェクト: wtf3505/Verify
    public override void WriteJson(JsonWriter writer, object?value, JsonSerializer serializer, IReadOnlyDictionary <string, object> context)
    {
        if (value is null)
        {
            return;
        }

        var @delegate = (Delegate)value;

        writer.WriteStartObject();
        writer.WritePropertyName("Type");
        writer.WriteValue(TypeNameConverter.GetName(@delegate.GetType()));
        var declaringType = @delegate.Method.DeclaringType;

        if (declaringType is not null)
        {
            writer.WritePropertyName("Target");
            writer.WriteValue(TypeNameConverter.GetName(declaringType));
        }

        writer.WritePropertyName("Method");
        var s = @delegate.Method.ToString() !;

        writer.WriteValue(CleanMethodName(s));
        writer.WriteEndObject();
    }
コード例 #4
0
    public Task GenericArguments()
    {
        var type = typeof(IEnumerable <>)
                   .GetGenericArguments()
                   .First();

        return(Verifier.Verify(TypeNameConverter.GetName(type)));
    }
コード例 #5
0
        public void ConvertFrom_TypeError()
        {
            TypeNameConverter cv = new TypeNameConverter();
            object            o;

            o = cv.ConvertFrom(null, null, 59);
            Assert.IsNull(o, "A1");
        }
コード例 #6
0
        public void ConvertFrom_TypeError()
        {
            TypeNameConverter cv = new TypeNameConverter();
            object            o  = null;

            Assert.Throws <InvalidCastException>(() => o = cv.ConvertFrom(null, null, 59));
            Assert.Null(o);
        }
コード例 #7
0
        public void CanConvertTo()
        {
            TypeNameConverter cv = new TypeNameConverter();

            Assert.IsTrue(cv.CanConvertTo(null, typeof(string)), "A1");
            Assert.IsFalse(cv.CanConvertTo(null, typeof(TimeSpan)), "A2");
            Assert.IsFalse(cv.CanConvertTo(null, typeof(int)), "A3");
            Assert.IsFalse(cv.CanConvertTo(null, typeof(object)), "A4");
        }
コード例 #8
0
        static LocalServiceElement()
        {
            TypeNameConverter typeNameConverter = new TypeNameConverter();

            LocalServiceElement._type       = new ConfigurationProperty("type", typeof(Type), null, typeNameConverter, null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
            LocalServiceElement._service    = new ConfigurationProperty("service", typeof(Type), null, typeNameConverter, null, ConfigurationPropertyOptions.IsRequired);
            LocalServiceElement._properties = new ConfigurationPropertyCollection();
            LocalServiceElement._properties.Add(LocalServiceElement._type);
            LocalServiceElement._properties.Add(LocalServiceElement._service);
        }
コード例 #9
0
ファイル: MethodInfoConverter.cs プロジェクト: wtf3505/Verify
    public override void WriteJson(JsonWriter writer, object?value, JsonSerializer serializer, IReadOnlyDictionary <string, object> context)
    {
        if (value == null)
        {
            return;
        }

        var method = (MethodInfo)value;

        writer.WriteValue(TypeNameConverter.GetName(method));
    }
コード例 #10
0
ファイル: TypeJsonConverter.cs プロジェクト: jawn/Verify
    public override void WriteJson(JsonWriter writer, object?value, JsonSerializer serializer)
    {
        if (value == null)
        {
            return;
        }

        var type = (Type)value;

        writer.WriteValue(TypeNameConverter.GetName(type));
    }
コード例 #11
0
        public void ConvertFrom()
        {
            TypeNameConverter cv = new TypeNameConverter();
            object            t;

            t = cv.ConvertFrom(null, null, typeof(object).AssemblyQualifiedName);
            Assert.IsTrue(t is Type, "A1");
            object o = Activator.CreateInstance((Type)t);

            Assert.AreEqual(typeof(object), o.GetType(), "A2");
        }
コード例 #12
0
ファイル: CustomContractResolver.cs プロジェクト: jawn/Verify
    protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
    {
        var contract = base.CreateDictionaryContract(objectType);

        contract.DictionaryKeyResolver = value =>
        {
            var keyType = contract.DictionaryKeyType;
            if (keyType == typeof(Guid))
            {
                if (scrubber.TryParseConvertGuid(value, out var result))
                {
                    return(result);
                }
            }

            if (keyType == typeof(DateTimeOffset))
            {
                if (scrubber.TryParseConvertDateTimeOffset(value, out var result))
                {
                    return(result);
                }
            }

            if (keyType == typeof(DateTime))
            {
                if (scrubber.TryParseConvertDateTime(value, out var result))
                {
                    return(result);
                }
            }

            if (keyType == typeof(Type))
            {
                var type = Type.GetType(value);
                if (type == null)
                {
                    throw new Exception($"Could not load type `{value}`.");
                }

                return(TypeNameConverter.GetName(type));
            }

            return(value);
        };

        return(contract);
    }
コード例 #13
0
    public override async Task Invoke(IOutgoingLogicalMessageContext context, Func <Task> next)
    {
        var headers = context.Headers;

        var bag = context.Extensions;

        var type            = context.Message.Instance.GetType();
        var messageTypeName = TypeNameConverter.GetName(type);

        if (!bag.TryGet <ILogger>(out var logger))
        {
            // if it a raw session send (ie no handler/saga, there will be no current logger)
            logger = logBuilder.GetLogger(messageTypeName);
        }

        List <PropertyEnricher> properties = new()
        {
            new("OutgoingMessageId", context.MessageId),
            new("OutgoingMessageType", messageTypeName)
        };

        if (headers.TryGetValue(Headers.CorrelationId, out var correlationId))
        {
            properties.Add(new PropertyEnricher("CorrelationId", correlationId));
        }

        if (headers.TryGetValue(Headers.ConversationId, out var conversationId))
        {
            properties.Add(new PropertyEnricher("ConversationId", conversationId));
        }

        var forContext = logger.ForContext(properties);

        try
        {
            bag.Set("SerilogOutgoingLogger", forContext);
            await next();
        }
        finally
        {
            bag.Remove("SerilogOutgoingLogger");
        }
    }
コード例 #14
0
    void AuditSaga(ActiveSagaInstance activeSagaInstance, IInvokeHandlerContext context, SagaUpdatedMessage sagaAudit)
    {
        var saga = activeSagaInstance.Instance;

        if (saga.Entity == null)
        {
            //this can happen if it is a timeout or for invoking "saga not found" logic
            return;
        }

        var headers = context.Headers;

        if (!headers.TryGetValue(Headers.MessageId, out var messageId))
        {
            return;
        }

        var intent = context.MessageIntent();

        sagaAudit.IsNew       = activeSagaInstance.IsNew;
        sagaAudit.IsCompleted = saga.Completed;
        sagaAudit.SagaId      = saga.Entity.Id;

        AssignSagaStateChangeCausedByMessage(context, sagaAudit);

        List <LogEventProperty> properties = new()
        {
            new("SagaType", new ScalarValue(sagaAudit.SagaType)),
            new("SagaId", new ScalarValue(sagaAudit.SagaId)),
            new("StartTime", new ScalarValue(sagaAudit.StartTime)),
            new("FinishTime", new ScalarValue(sagaAudit.FinishTime)),
            new("IsCompleted", new ScalarValue(sagaAudit.IsCompleted)),
            new("IsNew", new ScalarValue(sagaAudit.IsNew))
        };

        var logger      = context.Logger();
        var messageType = TypeNameConverter.GetName(context.MessageType());

        Dictionary <ScalarValue, LogEventPropertyValue> initiator = new()
        {
            { new("IsSagaTimeout"), new ScalarValue(context.IsTimeoutMessage()) },
            { new("MessageId"), new ScalarValue(messageId) },
コード例 #15
0
ファイル: DelegateConverter.cs プロジェクト: jawn/Verify
    public override void WriteJson(JsonWriter writer, object?value, JsonSerializer serializer)
    {
        if (value is null)
        {
            return;
        }

        var @delegate = (Delegate)value;

        writer.WriteStartObject();
        writer.WritePropertyName("Type");
        writer.WriteValue(TypeNameConverter.GetName(@delegate.GetType()));
        writer.WritePropertyName("Target");
        writer.WriteValue(TypeNameConverter.GetName(@delegate.Method.DeclaringType !));
        writer.WritePropertyName("Method");
        var s = @delegate.Method.ToString() !;

        writer.WriteValue(CleanMethodName(s));
        writer.WriteEndObject();
    }
コード例 #16
0
        public JsonSerializerAdapterFactory(TypeNameConverter typeNameConverter)
        {
            _jsonSettings = new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                NullValueHandling        = NullValueHandling.Ignore,
                ContractResolver         = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy
                    {
                        OverrideSpecifiedNames = true,
                        ProcessDictionaryKeys  = true,
                        //ProcessExtensionDataNames = true
                    }
                }
            };

            _jsonSettings.Converters.Add(typeNameConverter);
            _jsonSettings.Converters.Add(new ValueContainerConverter());
        }
コード例 #17
0
    string ResolveDictionaryKey(JsonDictionaryContract contract, string value)
    {
        var keyType = contract.DictionaryKeyType;

        if (keyType == typeof(Guid))
        {
            if (scrubber.TryParseConvertGuid(value, out var result))
            {
                return(result);
            }
        }

        if (keyType == typeof(DateTimeOffset))
        {
            if (scrubber.TryParseConvertDateTimeOffset(value, out var result))
            {
                return(result);
            }
        }

        if (keyType == typeof(DateTime))
        {
            if (scrubber.TryParseConvertDateTime(value, out var result))
            {
                return(result);
            }
        }

        if (keyType == typeof(Type))
        {
            var type = Type.GetType(value);
            if (type == null)
            {
                throw new($"Could not load type `{value}`.");
            }

            return(TypeNameConverter.GetName(type));
        }

        return(value);
    }
コード例 #18
0
                protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
                {
                    if (reader.Name != "properties")
                    {
                        return;
                    }

                    var attributeValue = reader.GetAttribute("Type");

                    if (string.IsNullOrWhiteSpace(attributeValue))
                    {
                        throw new InvalidOperationException("properties type undefined.");
                    }

                    var converter = new TypeNameConverter();

                    Type = converter.ConvertFromString(attributeValue) as Type;

                    var propertySettings = new Dictionary <string, object>();

                    reader.MoveToElement();
                    while (reader.Read())
                    {
                        if (reader.IsEmptyElement || string.IsNullOrWhiteSpace(reader.Name.Trim()))
                        {
                            continue;
                        }

                        if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "properties"))
                        {
                            reader.MoveToElement();
                            break;
                        }

                        propertySettings.Add(reader.Name, reader.ReadInnerXml());
                    }

                    PropertySettings = propertySettings;
                }
コード例 #19
0
 public Task RuntimeEnumerableDynamicWithInnerSelect()
 {
     return(Verify(TypeNameConverter.GetName(MethodWithYield().Select(x => new { X = x.ToString() }).GetType())));
 }
コード例 #20
0
 public void SetUpTests()
 {
     converter = new TypeNameConverter(new TypeNameParser());
 }
コード例 #21
0
 public void TestInit()
 {
     _typeNameConverter = new TypeNameConverter();
 }
コード例 #22
0
 public static IEnumerable <LogEventEx> LogsForType <T>(this IEnumerable <LogEventEx> logs)
 {
     return(LogsForName(logs, TypeNameConverter.GetName(typeof(T)))
            .OrderBy(x => x.MessageTemplate.Text));
 }
コード例 #23
0
    static async Task <IEnumerable <LogEventEx> > Send(object message, Action <SendOptions>?optionsAction = null)
    {
        logs.Clear();
        var suffix = TypeNameConverter.GetName(message.GetType())
                     .Replace("<", "_")
                     .Replace(">", "_");
        var configuration = ConfigBuilder.BuildDefaultConfig("SerilogTests" + suffix);

        configuration.PurgeOnStartup(true);

        var serilogTracing = configuration.EnableSerilogTracing();

        serilogTracing.EnableSagaTracing();
        serilogTracing.UseHeaderConversion((key, _) =>
        {
            if (key == "ConvertHeader")
            {
                return(new LogEventProperty("NewKey", new ScalarValue("newValue")));
            }

            return(null);
        });
        serilogTracing.EnableMessageTracing();
        ManualResetEvent resetEvent = new(false);

        configuration.RegisterComponents(components => components.RegisterSingleton(resetEvent));

        var recoverability = configuration.Recoverability();

        recoverability.Delayed(settings =>
        {
            settings.TimeIncrease(TimeSpan.FromMilliseconds(1));
            settings.NumberOfRetries(1);
        });
        recoverability.Immediate(settings => { settings.NumberOfRetries(1); });

        recoverability.Failed(settings => settings
                              .OnMessageSentToErrorQueue(_ =>
        {
            resetEvent.Set();
            return(Task.CompletedTask);
        }));

        var endpoint = await Endpoint.Start(configuration);

        SendOptions sendOptions = new();

        optionsAction?.Invoke(sendOptions);
        sendOptions.SetMessageId("00000000-0000-0000-0000-000000000001");
        sendOptions.RouteToThisEndpoint();
        await endpoint.Send(message, sendOptions);

        if (!resetEvent.WaitOne(TimeSpan.FromSeconds(10)))
        {
            throw new("No Set received.");
        }

        await endpoint.Stop();

        return(logs.Select(x =>
                           new LogEventEx
                           (
                               messageTemplate: x.MessageTemplate,
                               level: x.Level,
                               properties: x.Properties,
                               exception: x.Exception
                           )));
    }
コード例 #24
0
 public Task RuntimeEnumerableDynamicWithSelect()
 {
     return(Verify(TypeNameConverter.GetName(MethodWithYieldDynamic().Select(x => x != null).GetType())));
 }
コード例 #25
0
        public void ConvertTo_TypeError1()
        {
            TypeNameConverter cv = new TypeNameConverter();

            AssertExtensions.Throws <ArgumentException>(null, () => cv.ConvertTo(null, null, 59, typeof(string)));
        }
コード例 #26
0
        public void ConvertTo_NullError()
        {
            TypeNameConverter cv = new TypeNameConverter();

            Assert.AreEqual(null, cv.ConvertTo(null, null, null, typeof(string)), "A1");
        }
コード例 #27
0
        public void ConvertTo()
        {
            TypeNameConverter cv = new TypeNameConverter();

            Assert.AreEqual(typeof(string).AssemblyQualifiedName, cv.ConvertTo(null, null, typeof(string), typeof(string)), "A1");
        }
コード例 #28
0
 public Task EnumerableOfArray()
 {
     return(Verify(TypeNameConverter.GetName(typeof(IEnumerable <TargetWithNamespace[]>))));
 }
コード例 #29
0
ファイル: ShortNameBinder.cs プロジェクト: jawn/Verify
 public void BindToName(Type serializedType, out string?assemblyName, out string?typeName)
 {
     assemblyName = null;
     typeName     = TypeNameConverter.GetName(serializedType);
 }
コード例 #30
0
        public void ConvertTo_TypeError1()
        {
            TypeNameConverter cv = new TypeNameConverter();

            Assert.AreEqual("59", cv.ConvertTo(null, null, 59, typeof(string)), "A1");
        }