示例#1
0
        public static void AddKnownExtensions(this EventSourcePrototype eventSource, EventSourceEventCustomArgument customArgument, string templateCLRType)
        {
            if (customArgument.Assignment.Contains("$this.AsJson()"))
            {
                eventSource.AddKnownExtension("AsJson", templateCLRType);
                return;
            }

            if (customArgument.Assignment.Contains("$this.GetReplicaOrInstanceId()"))
            {
                eventSource.AddKnownExtension("GetReplicaOrInstanceId", templateCLRType);
                return;
            }

            if (customArgument.Assignment.Contains("$this.GetContentDigest("))
            {
                eventSource.AddKnownExtension("GetContentDigest", templateCLRType);
                eventSource.AddKnownExtension("GetMD5Hash", templateCLRType);
                return;
            }
            if (customArgument.Assignment.Contains("$this.GetMD5Hash("))
            {
                eventSource.AddKnownExtension("GetMD5Hash", templateCLRType);
                return;
            }
        }
        // ReSharper restore InconsistentNaming



        public virtual void SetCLRType(EventSourcePrototype eventSource)
        {
            var type = this.Type;

            if (this.IsComplexType())
            {
                var template = eventSource.TypeTemplates.FirstOrDefault(t =>
                                                                        t.Name.Equals(this.Type, StringComparison.InvariantCultureIgnoreCase) ||
                                                                        t.CLRType.Equals(this.Type, StringComparison.InvariantCultureIgnoreCase));
                if (template != null)
                {
                    var parsedType   = ParseType(template.CLRType);
                    var renderedType = RenderCLRType(parsedType);
                    if (renderedType == "string" && (parsedType != typeof(string)))
                    {
                        type = template.CLRType;
                    }
                    else
                    {
                        type = renderedType;
                    }
                }
            }
            this.CLRType = type;
        }
示例#3
0
        public string RenderPartial(EventSourcePrototype eventSource, int index, string fileName)
        {
            var output = Template.Template_LOGGER_PARTIAL_CLASS_DELCARATION;

            output = output.Replace(Template.Variable_EVENTSOURCE_CLASS_NAME, eventSource.ClassName);
            output = output.Replace(Template.Variable_NAMESPACE_DECLARATION, eventSource.Namespace);
            output = output.Replace(Template.Variable_EVENTSOURCE_PARTIAL_FILE_NAME, fileName);
            output = output.Replace(Template.Variable_LOGGER_SOURCE_FILE_NAME, this.Name);


            var logger = new StringBuilder();
            var next   = index;

            var renderer = new EventRenderer();

            foreach (var loggerEvent in this.Events)
            {
                if (ImplicitArguments != null && ImplicitArguments.Length > 0)
                {
                    loggerEvent.InsertImplicitArguments(ImplicitArguments);
                }
                if (OverrideArguments != null && OverrideArguments.Length > 0)
                {
                    loggerEvent.OverrideArguments(OverrideArguments);
                }
                loggerEvent.Keywords = new string[] { this.GetKeyword() };
                logger.AppendLine(renderer.Render(loggerEvent, next, eventSource));
                next += 1;
            }

            output = output.Replace(Template.Variable_LOGGER_EVENTS_DECLARATION, logger.ToString());

            return(output);
        }
示例#4
0
 public static void AddKnownExtension(this EventSourcePrototype eventSource, string extensionName, string clrType)
 {
     if (!eventSource.Extensions.Any(ext => ext.CLRType == clrType && ext.Type == extensionName))
     {
         eventSource.Extensions.Add(new EventSourceExtensionsMethod()
         {
             CLRType = clrType, Type = extensionName
         });
     }
 }
        public string Render(EventModel model, int index, EventSourcePrototype eventSource)
        {
            var output = Template.Template_LOGGER_METHOD;

            output = output.Replace(Template.Variable_LOGGER_METHOD_NAME, model.Name);
            output = output.Replace(Template.Variable_EVENTSOURCE_CLASS_NAME, eventSource.ClassName);

            var next = 0;

            var methodArguments         = new StringBuilder();
            var methodArgumentDelimiter = "";

            var callArguments         = new StringBuilder();
            var callArgumentDelimiter = "";

            foreach (var argument in model?.ImplicitArguments ?? new EventArgumentModel[0])
            {
                callArguments.Append($"{callArgumentDelimiter}{argument.RenderWriteEventMethodCallArgument(isPrivateMember: true)}");
                callArgumentDelimiter = Template.Template_LOGGER_CALL_ARGUMENTS_DELIMITER;

                next += 1;
            }

            foreach (var argument in model.Arguments)
            {
                var type = argument.Type;
                if (argument.IsComplexType())
                {
                    var typeTemplate = eventSource.TypeTemplates.FirstOrDefault(t =>
                                                                                t.Name.Equals(argument.Type, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                t.CLRType.Equals(argument.Type, StringComparison.InvariantCultureIgnoreCase));
                    if (typeTemplate != null)
                    {
                        type = typeTemplate.CLRType;
                    }
                }

                methodArguments.Append($"{methodArgumentDelimiter}{argument.RenderMethodArgument()}");
                methodArgumentDelimiter = Template.Template_LOGGER_METHOD_ARGUMENTS_DELIMITER;

                callArguments.Append($"{callArgumentDelimiter}{argument.RenderWriteEventMethodCallArgument(isPrivateMember: false)}");
                callArgumentDelimiter = Template.Template_LOGGER_CALL_ARGUMENTS_DELIMITER;

                next += 1;
            }
            output = output.Replace(Template.Variable_LOGGER_METHOD_ARGUMENTS, methodArguments.ToString());
            output = output.Replace(Template.Variable_LOGGER_CALL_ARGUMENTS, callArguments.ToString());

            foreach (var builderExtension in eventSource.BuilderExtensions)
            {
                //builderExtension.OnEventRendered()
            }

            return(output);
        }
        private IEnumerable <ProjectItem> GenerateEventSourceCode(string projectBasePath, ProjectItem projectItem, EventSourcePrototype eventSourcePrototype, LoggerTemplateModel[] loggers, ILoggerBuilderExtension[] extensions)
        {
            eventSourcePrototype.AvailableLoggers  = loggers;
            eventSourcePrototype.BuilderExtensions = extensions;
            var outputs = eventSourcePrototype.Render(projectBasePath);

            var eventSourceProjectItems = new List <ProjectItem>();

            foreach (var output in outputs)
            {
                output.DependentUpon = projectItem;
                eventSourceProjectItems.Add(output);
            }
            return(eventSourceProjectItems);
        }
        private IEnumerable <ProjectItem> AddDefaultEventSource(string projectBasePath, LoggerTemplateModel[] loggers, ILoggerBuilderExtension[] extensions, IEnumerable <ProjectItem> projectFiles)
        {
            var defaultEventSourceFile = projectFiles.GetDefaultEventSourceProjectItem();

            if (defaultEventSourceFile != null)
            {
                var defaultEventSource = new EventSourcePrototype()
                {
                    Namespace     = defaultEventSourceFile.RootNamespace,
                    Name          = "DefaultEventSource",
                    ClassName     = "DefaultEventSource",
                    TypeTemplates = new EventSourceTypeTemplate[]
                    {
                        new EventSourceTypeTemplate()
                        {
                            Name    = "Exception",
                            CLRType = "System.Exception" +
                                      "",
                            Arguments = new EventSourceEventCustomArgument[]
                            {
                                new EventSourceEventCustomArgument("message", "string", "$this.Message"),
                                new EventSourceEventCustomArgument("source", "string", "$this.Source"),
                                new EventSourceEventCustomArgument("exceptionTypeName", "string", "$this.GetType().FullName"),
                                new EventSourceEventCustomArgument("exception", "string", "$this.AsJson()"),
                            }
                        }
                    }
                };
                var eventSourceLoggers = new List <EventSourceLogger>();
                var startId            = 1000;
                foreach (var logger in loggers)
                {
                    eventSourceLoggers.Add(new EventSourceLogger()
                    {
                        Name              = logger.Name,
                        StartId           = startId,
                        ImplicitArguments = new EventSourceEventArgument[]
                        {
                            new EventSourceEventArgument()
                            {
                                Name = "autogenerated", Type = "bool"
                            }
                        }
                    });
                    startId += 1000;
                }
                defaultEventSource.Loggers = eventSourceLoggers.ToArray();

                var sourceFileName         = System.IO.Path.GetFileName(defaultEventSourceFile.Name);
                var implementationFileName = $"{System.IO.Path.GetFileNameWithoutExtension(defaultEventSourceFile.Name)}.cs";
                var fileRelativePath       = defaultEventSourceFile.Name.RemoveFromStart(projectBasePath + System.IO.Path.DirectorySeparatorChar).Replace(sourceFileName, implementationFileName);

                defaultEventSource.Include        = fileRelativePath;
                defaultEventSource.SourceFilePath = defaultEventSourceFile.Include;

                var jsonFile = Newtonsoft.Json.JsonConvert.SerializeObject(defaultEventSource, Newtonsoft.Json.Formatting.Indented);
                yield return
                    (new ProjectItem(ProjectItemType.DefaultGeneratedEventSource, name: defaultEventSourceFile.Name, content: jsonFile)
                {
                    Include = defaultEventSourceFile.Include,
                    RootNamespace = defaultEventSourceFile.RootNamespace
                });

                var outputs = GenerateEventSourceCode(projectBasePath, defaultEventSourceFile, defaultEventSource, loggers, extensions);
                foreach (var output in outputs)
                {
                    yield return(output);
                }
            }
        }
        public string Render(EventModel model, int index, EventSourcePrototype eventSource)
        {
            var outputEventMethod = Template.Template_EVENT_METHOD;

            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_NAME, model.Name);
            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_ID, index.ToString());
            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_LEVEL, model.Level.ToString());

            var outputNonEventMethod = Template.Template_NON_EVENT_METHOD;

            outputNonEventMethod = outputNonEventMethod.Replace(Template.Variable_EVENT_NAME, model.Name);

            var keywords = new ListBuilder("", " | ", "");

            foreach (var keyword in model.Keywords ?? new KeywordModel[] { })
            {
                keywords.Append($"Keywords.{keyword.Name}");
            }
            var keywordsDeclaration = (keywords.Length > 0) ? $", Keywords = {keywords}" : "";

            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_KEYWORDS_DECLARATION, keywordsDeclaration);

            var next = 0;

            var messageFormatBuilder = new ListBuilder($"{model.Name.GetHumanReadable()}", " ", " ");
            var eventMethodArgumentsDeclarationBuilder    = new EventArgumentsListBuilder((arg) => arg.RenderMethodArgument(), Template.Template_EVENT_METHOD_ARGUMENT_DELIMITER);
            var nonEventMethodArgumentsDeclarationBuilder = new EventArgumentsListBuilder((arg) => arg.RenderMethodArgument(), Template.Template_NONEVENT_METHOD_ARGUMENT_DELIMITER);
            var callArgumentsBuilder       = new EventArgumentsListBuilder((arg) => arg.RenderWriteEventMethodCallArgument(), Template.Template_EVENT_METHOD_CALL_ARGUMENT_DELIMITER);
            var assignmentArgumentsBuilder = new EventArgumentsListBuilder((arg) => (arg as EventSourceEventCustomArgument)?.Assignment.Replace(@"$this", arg.Name) ?? arg.Name, Template.Template_NON_EVENT_ASSIGNMENT_ARGUMENT_DELIMITER);

            var hasComplexArguments = false;

            var allArguments          = new List <EventArgumentModel>();
            var messageArgumentsStart = 0;
            var messageArgumentsCount = 0;

            if (model.ImplicitArguments != null && model.ImplicitArguments.Length > 0)
            {
                allArguments.AddRange(model.ImplicitArguments);
                messageArgumentsStart += model.ImplicitArguments.Length;
            }
            allArguments.AddRange(model.Arguments);

            var messageArgument      = allArguments.FirstOrDefault(arg => model.Name.Equals("message", StringComparison.InvariantCultureIgnoreCase));
            var messageArgumentIndex = messageArgument != null?allArguments.IndexOf(messageArgument) : -1;


            var flatIndex = 0;

            foreach (var argument in allArguments)
            {
                argument.SetCLRType(eventSource);

                var methodArgument = "";

                if (argument is EventSourceEventCustomArgument)
                {
                    methodArgument = argument.RenderMethodArgument();
                    if (flatIndex >= messageArgumentsStart)
                    {
                        messageFormatBuilder.Append($"{{{next}}}");
                    }
                    var customArgument = argument as EventSourceEventCustomArgument;

                    assignmentArgumentsBuilder.Append(customArgument);
                    eventSource.AddKnownExtensions(customArgument, customArgument.CLRType);

                    var originalCLRType = customArgument.CLRType;
                    customArgument.CLRType = customArgument.AssignedCLRType ?? customArgument.CLRType;

                    eventMethodArgumentsDeclarationBuilder.Append(customArgument);
                    callArgumentsBuilder.Append(customArgument);
                    customArgument.CLRType = originalCLRType;

                    next += 1;
                }
                else if (!argument.IsComplexType())
                {
                    // Just render the argument as it is
                    methodArgument = argument.RenderMethodArgument();
                    if (flatIndex >= messageArgumentsStart)
                    {
                        messageFormatBuilder.Append($"{{{next}}}");
                    }

                    assignmentArgumentsBuilder.Append(argument);
                    eventMethodArgumentsDeclarationBuilder.Append(argument);
                    callArgumentsBuilder.Append(argument);

                    next += 1;
                }
                else
                {
                    // Split the argument according to a template
                    hasComplexArguments = true;
                    var template = eventSource.TypeTemplates.GeTypeTemplate(argument.Type);
                    if (template != null)
                    {
                        methodArgument = argument.RenderMethodArgument();

                        foreach (var customArgument in template.Arguments)
                        {
                            if (flatIndex >= messageArgumentsStart)
                            {
                                messageFormatBuilder.Append($"{{{next}}}");
                            }
                            customArgument.SetCLRType(eventSource);

                            assignmentArgumentsBuilder.Append(customArgument);
                            eventMethodArgumentsDeclarationBuilder.Append(customArgument);
                            callArgumentsBuilder.Append(customArgument);

                            next += 1;
                        }
                    }
                    else
                    {
                        // Render it as ToString()
                        methodArgument = argument.RenderMethodPureArgument();
                        if (flatIndex >= messageArgumentsStart)
                        {
                            messageFormatBuilder.Append($"{{{next}}}");
                        }

                        assignmentArgumentsBuilder.Append($"{argument.Name}.ToString()");
                        eventMethodArgumentsDeclarationBuilder.Append(argument.RenderMethodArgument(useSimpleTypesOnly: true));
                        callArgumentsBuilder.Append(argument);

                        next += 1;
                    }
                }

                nonEventMethodArgumentsDeclarationBuilder.Append(methodArgument);

                flatIndex++;
            }
            outputNonEventMethod = outputNonEventMethod.Replace(Template.Variable_NON_EVENT_METHOD_ARGUMENTS, nonEventMethodArgumentsDeclarationBuilder.ToString());
            outputNonEventMethod = outputNonEventMethod.Replace(Template.Variable_NON_EVENT_ASSIGNMENT_ARGUMENTS, assignmentArgumentsBuilder.ToString());

            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_METHOD_ACCESS, hasComplexArguments ? "private" : "public");
            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_METHOD_ARGUMENTS, eventMethodArgumentsDeclarationBuilder.ToString());
            outputEventMethod = outputEventMethod.Replace(Template.Variable_WRITEEVENT_CALL_ARGUMENTS, callArgumentsBuilder.ToString());

            var nonEventMethodDeclaration = hasComplexArguments ? outputNonEventMethod : "";

            outputEventMethod = outputEventMethod.Replace(Template.Variable_NON_EVENT_METHOD_DECLARATION, nonEventMethodDeclaration);

            var formatter = $"{{{next - 1}}}";

            if (model.MessageFormatter != null)
            {
                formatter = model.MessageFormatter;
            }
            else if (messageArgumentIndex >= 0)
            {
                formatter = $"{{{messageArgumentIndex}}}";
            }
            else
            {
                formatter = messageFormatBuilder.ToString();
            }
            outputEventMethod = outputEventMethod.Replace(Template.Variable_EVENT_MESSAGE_FORMATTER, formatter);

            //var formatter = messageFormatBuilder.ToString();
            //output = output.Replace(Template_EVENT_METHOD_ARGUMENTS, MessageFormatter ?? "{7}");

            return(outputEventMethod);
        }
示例#9
0
        public string RenderImplementation(EventSourcePrototype eventSource, int index)
        {
            var className = GetImplementationName();

            var output = Template.Template_LOGGER_CLASS_DECLARATION;

            output = output.Replace(Template.Variable_LOGGER_SOURCE_FILE_NAME, this.SourceFileName);
            output = output.Replace(Template.Variable_NAMESPACE_DECLARATION, this.LoggerNamespace);

            output = output.Replace(Template.Variable_LOGGER_NAME, this.Name);
            output = output.Replace(Template.Variable_LOGGER_NAMESPACE, this.LoggerNamespace);
            output = output.Replace(Template.Variable_LOGGER_CLASS_NAME, className);

            var memberDeclarations          = new StringBuilder();
            var memberDeclarationsDelimiter = "";

            var memberAssignments          = new StringBuilder();
            var memberAssignmentsDelimiter = "";

            var methodArguments          = new StringBuilder();
            var methodArgumentsDelimiter = "";

            var next = 0;

            foreach (var argument in this?.ImplicitArguments ?? new EventSourceEventArgument[0])
            {
                argument.SetCLRType(eventSource);

                var methodArgument = argument.RenderMethodArgument();
                methodArguments.Append($"{methodArgumentsDelimiter}{methodArgument}");
                methodArgumentsDelimiter = Template.Template_LOGGER_IMPLICIT_ARGUMENTS_METHOD_DECLARATION_DELIMITER;

                var memberDeclaration = argument.RenderPrivateDeclaration();
                memberDeclarations.Append($"{memberDeclarationsDelimiter}{memberDeclaration}");
                memberDeclarationsDelimiter = Template.Template_LOGGER_IMPLICIT_ARGUMENTS_MEMBER_DECLARATION_DELIMITER;

                var memberAssignment = argument.RenderPrivateAssignment();
                memberAssignments.Append($"{memberAssignmentsDelimiter}{memberAssignment}");
                memberAssignmentsDelimiter = Template.Template_LOGGER_IMPLICIT_ARGUMENTS_MEMBER_ASSIGNMENT_DELIMITER;

                next++;
            }
            output = output.Replace(Template.Variable_LOGGER_IMPLICIT_ARGUMENTS_METHOD_DECLARATION, methodArguments.ToString());
            output = output.Replace(Template.Variable_LOGGER_IMPLICIT_ARGUMENTS_MEMBER_DECLARATION, memberDeclarations.ToString());
            output = output.Replace(Template.Variable_LOGGER_IMPLICIT_ARGUMENTS_MEMBER_ASSIGNMENT, memberAssignments.ToString());

            var implementation = new StringBuilder();

            next = index;

            var renderer = new LoggerEventRenderer();

            foreach (var loggerEvent in this.Events)
            {
                if (ImplicitArguments != null && ImplicitArguments.Length > 0)
                {
                    loggerEvent.InsertImplicitArguments(ImplicitArguments);
                }
                if (OverrideArguments != null && OverrideArguments.Length > 0)
                {
                    loggerEvent.OverrideArguments(OverrideArguments);
                }
                loggerEvent.Keywords = new string[] { this.GetKeyword() };
                implementation.AppendLine(renderer.Render(loggerEvent, next, eventSource));
                next += 1;
            }

            output = output.Replace(Template.Variable_LOGGER_IMPLEMENTATION, implementation.ToString());

            return(output);
        }