Пример #1
0
        protected void applyAttributesAndConfigureMethods(GenerationRules rules, IContainer container)
        {
            var handlers         = HandlerCalls();
            var configureMethods = handlers.Select(x => x.HandlerType).Distinct()
                                   .SelectMany(x => x.GetTypeInfo().GetMethods())
                                   .Where(isConfigureMethod);

            foreach (var method in configureMethods)
            {
                method?.Invoke(null, new object[] { this });
            }

            var handlerAtts = handlers.SelectMany(x => x.HandlerType.GetTypeInfo()
                                                  .GetCustomAttributes <TModifyAttribute>());

            var methodAtts = handlers.SelectMany(x => x.Method.GetCustomAttributes <TModifyAttribute>());

            foreach (var attribute in handlerAtts.Concat(methodAtts))
            {
                attribute.Modify(this.As <TChain>(), rules);
            }

            var genericHandlerAtts = handlers.SelectMany(x => x.HandlerType.GetTypeInfo()
                                                         .GetCustomAttributes <ModifyChainAttribute>());

            var genericMethodAtts = handlers.SelectMany(x => x.Method.GetCustomAttributes <ModifyChainAttribute>());

            foreach (var attribute in genericHandlerAtts.Concat(genericMethodAtts))
            {
                attribute.Modify(this, rules, container);
            }
        }
Пример #2
0
 public void ApplyPolicies(GenerationRules rules)
 {
     foreach (var policy in _policies)
     {
         policy.Apply(Routes, rules);
     }
 }
Пример #3
0
 public void Apply(HandlerGraph graph, GenerationRules rules, IContainer container)
 {
     foreach (var chain in graph.Chains)
     {
         applyToChain(chain);
     }
 }
Пример #4
0
        public void write_method()
        {
            // SAMPLE: write-new-method
            // Configures the code generation rules
            // and policies
            var rules = new GenerationRules("GeneratedNamespace");

            // Adds the "now : DateTime" variable rule to
            // our generated code
            rules.Sources.Add(new NowTimeVariableSource());

            // Start the definition for a new generated assembly
            var assembly = new GeneratedAssembly(rules);

            // Add a new generated type called "WhatTimeIsIt" that will
            // implement the
            var type = assembly.AddType("WhatTimeIsIt", typeof(ISaySomething));

            // Getting the definition for the method named "Speak"
            var method = type.MethodFor(nameof(ISaySomething.Speak));

            // Adding a frame that calls the NowSpeaker.Speak() method and
            // adding it to the generated method
            var @call = new MethodCall(typeof(NowSpeaker), nameof(NowSpeaker.Speak));

            method.Frames.Add(@call);

            // Compile the new code!
            assembly.CompileAll();
            // ENDSAMPLE


            // Write the generated code to the console here
            _output.WriteLine(type.SourceCode);
        }
Пример #5
0
 /// <summary>
 ///     The currently known strategy for code generating transaction middleware
 /// </summary>
 public static void SetTransactionsIfNone(this GenerationRules rules, ITransactionFrameProvider value)
 {
     if (!rules.Properties.ContainsKey(TRANSACTIONS))
     {
         rules.Properties.Add(TRANSACTIONS, value);
     }
 }
 public void Apply(HandlerGraph graph, GenerationRules rules, IContainer container)
 {
     foreach (var chain in graph.Chains)
     {
         chain.Middleware.Add(new SimpleWrapper());
     }
 }
Пример #7
0
        public void should_not_be_using_service_provider()
        {
            var container = new Container(x => {
                x.AddDbContext <InputDbContext>(builder =>
                {
                    builder.UseSqlServer("some connection string");
                }, optionsLifetime: ServiceLifetime.Singleton);
            });

            var rules    = new GenerationRules();
            var source   = container.CreateServiceVariableSource();
            var assembly = new GeneratedAssembly(rules);

            var handler = assembly.AddType("SpecialHandler", typeof(Handler));

            var handleMethod = handler.MethodFor(nameof(Handler.Handle));

            var save = MethodCall.For <InputDbContext>(x => x.Add <Input>(null));

            handleMethod.Frames.Add(save);

            var code = assembly.GenerateCode(source);


            code.ShouldNotContain("ServiceProvider");
        }
        public Task AttachPreBuiltTypes(GenerationRules rules, Assembly assembly, IServiceProvider services)
        {
            foreach (var mapping in Storage.AllDocumentMappings)
            {
                var builder = typeof(ProviderBuilder <>).CloseAndBuildAs <IProviderBuilder>(mapping.DocumentType);
                builder.BuildAndStore(assembly, mapping, this);
            }

            if (_compiledQueryTypes.Any())
            {
                using var session = new LightweightSession(this);
                foreach (var compiledQueryType in _compiledQueryTypes)
                {
                    var plan    = QueryCompiler.BuildPlan(session, compiledQueryType, this);
                    var builder = new CompiledQuerySourceBuilder(plan, this);
                    var source  = builder.CreateFromPreBuiltType(assembly);

                    if (source == null)
                    {
                        Console.WriteLine("Could not find a pre-built compiled query source type for compiled query type " + compiledQueryType.FullNameInCode());
                    }
                    else
                    {
                        _querySources = _querySources.AddOrUpdate(compiledQueryType, source);
                    }
                }
            }

            return(Task.CompletedTask);
        }
Пример #9
0
        public JasperRegistry()
        {
            Features.Include <ConnegDiscoveryFeature>();

            _bus = Features.For <ServiceBusFeature>();

            Http = Features.For <AspNetCoreFeature>();

            Publish = new PublishingExpression(_bus);

            _applicationServices = new ServiceRegistry();
            ExtensionServices    = new ExtensionServiceRegistry();

            Services = _applicationServices;

            ApplicationAssembly = CallingAssembly.DetermineApplicationAssembly(this);

            deriveServiceName();

            var name = ApplicationAssembly?.GetName().Name ?? "JasperApplication";

            Generation = new GenerationRules($"{name}.Generated");

            Logging  = new Logging(this);
            Settings = new JasperSettings(this);

            Settings.Replace(_bus.Settings);

            if (JasperEnvironment.Name.IsNotEmpty())
            {
                EnvironmentName = JasperEnvironment.Name;
            }
        }
Пример #10
0
        public DocumentStore(StoreOptions options)
        {
            options.ApplyConfiguration();
            options.Validate();

            Options    = options;
            _logger    = options.Logger();
            Serializer = options.Serializer();

            if (options.CreateDatabases != null)
            {
                IDatabaseGenerator databaseGenerator = new DatabaseGenerator();
                databaseGenerator.CreateDatabases(Tenancy, options.CreateDatabases);
            }

            Schema = Tenancy.Default.Database;

            Storage.PostProcessConfiguration();
            Events.AssertValidity(this);
            Options.Projections.AssertValidity(this);

            Advanced = new AdvancedOperations(this);

            Diagnostics = new Diagnostics(this);

            if (Options.GeneratedCodeMode == TypeLoadMode.LoadFromPreBuiltAssembly)
            {
                var rules = new GenerationRules(SchemaConstants.MartenGeneratedNamespace);
                Events.As <IGeneratesCode>().AttachPreBuiltTypes(rules, Assembly.GetEntryAssembly(), null);

                Options.As <IGeneratesCode>().AttachPreBuiltTypes(rules, Assembly.GetEntryAssembly(), null);
            }

            options.InitialData.Each(x => x.Populate(this).GetAwaiter().GetResult());
        }
Пример #11
0
        public void generate_dynamic_types_with_no_fields()
        {
            var rules    = new GenerationRules("Lamar.Compilation");
            var assembly = new GeneratedAssembly(rules);



            var adder = assembly.AddType("Adder", typeof(INumberGenerator));

            adder.MethodFor("Generate").Frames.Append <AddFrame>();

            var multiplier = assembly.AddType("Multiplier", typeof(INumberGenerator));

            multiplier.MethodFor(nameof(INumberGenerator.Generate))
            .Frames.Append <MultiplyFrame>();

            assembly.CompileAll();

            Activator.CreateInstance(adder.CompiledType)
            .As <INumberGenerator>()
            .Generate(3, 4).ShouldBe(7);

            Activator.CreateInstance(multiplier.CompiledType)
            .As <INumberGenerator>()
            .Generate(3, 4).ShouldBe(12);

            adder.SourceCode.ShouldContain("public class Adder");
            multiplier.SourceCode.ShouldContain("public class Multiplier");
        }
Пример #12
0
        public GeneratedClass ToClass(GenerationRules rules)
        {
            try
            {
                var @class = new GeneratedClass(rules, TypeName)
                {
                    BaseType = typeof(RouteHandler)
                };

                var frames = DetermineFrames();
                var method = new GeneratedMethod(nameof(RouteHandler.Handle),
                                                 new Argument[] { Argument.For <HttpContext>(RouteGraph.Context) }, frames)
                {
                    Overrides = true
                };

                method.Sources.Add(new ContextVariableSource());
                method.DerivedVariables.AddRange(HttpContextVariables);

                @class.AddMethod(method);

                return(@class);
            }
            catch (Exception e)
            {
                throw new CodeGenerationException(this, e);
            }
        }
Пример #13
0
        /// <summary>
        /// Used internally to create the initial list of ordered Frames
        /// that will be used to generate the MessageHandler
        /// </summary>
        /// <param name="rules"></param>
        /// <param name="container"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public List <Frame> DetermineFrames(GenerationRules rules, IContainer container)
        {
            if (!Handlers.Any())
            {
                throw new InvalidOperationException("No method handlers configured for message type " +
                                                    MessageType.FullName);
            }

            if (!hasConfiguredFrames)
            {
                hasConfiguredFrames = true;

                applyAttributesAndConfigureMethods(rules, container);

                foreach (var attribute in MessageType.GetTypeInfo()
                         .GetCustomAttributes(typeof(ModifyHandlerChainAttribute))
                         .OfType <ModifyHandlerChainAttribute>())
                {
                    attribute.Modify(this, rules);
                }

                foreach (var attribute in MessageType.GetTypeInfo().GetCustomAttributes(typeof(ModifyChainAttribute))
                         .OfType <ModifyChainAttribute>())
                {
                    attribute.Modify(this, rules, container);
                }
            }

            var cascadingHandlers = determineCascadingMessages().ToArray();

            // The Enqueue cascading needs to happen before the post processors because of the
            // transactional & outbox support
            return(Middleware.Concat(Handlers).Concat(cascadingHandlers).Concat(Postprocessors).ToList());
        }
Пример #14
0
 public void Apply(HandlerGraph graph, GenerationRules rules, IContainer container)
 {
     foreach (var chain in graph.Chains.Where(IsSagaRelated))
     {
         Apply(chain, rules.GetSagaPersistence(), container);
     }
 }
Пример #15
0
        public override void Modify(HandlerChain chain, GenerationRules rules)
        {
            var timeSpans = _seconds.Select(x => x.Seconds()).ToArray();

            chain.OnExceptionOfType(_exceptionType)
            .RetryLater(timeSpans);
        }
Пример #16
0
        public JasperRegistry()
        {
            Logging = new Logging(this);

            Publish = new PublishingExpression(Bus);

            ExtensionServices = new ExtensionServiceRegistry();

            Services = _applicationServices;

            establishApplicationAssembly();

            _baseServices = new JasperServiceRegistry(this);


            deriveServiceName();

            var name = ApplicationAssembly?.GetName().Name ?? "JasperApplication";

            Generation = new GenerationRules($"{name}.Generated");


            Settings = new JasperSettings(this);

            Settings.Replace(Bus.Settings);


            if (JasperEnvironment.Name.IsNotEmpty())
            {
                EnvironmentName = JasperEnvironment.Name;
            }

            EnvironmentChecks = new EnvironmentCheckExpression(this);
        }
Пример #17
0
        public bool AttachTypesSynchronously(GenerationRules rules, Assembly assembly, IServiceProvider services,
                                             string containingNamespace)
        {
            var typeName = $"{containingNamespace}.{TypeName}";
            var type     = assembly.GetExportedTypes().FirstOrDefault(x => x.FullName == typeName);

            return(type != null);
        }
Пример #18
0
        IServiceVariableSource IGeneratesCode.AssemblyTypes(GenerationRules rules, GeneratedAssembly assembly)
        {
            foreach (var chain in Chains)
            {
                chain.AssembleType(rules, assembly, Container);
            }

            return(Container.CreateServiceVariableSource());
        }
Пример #19
0
        public ICompiledQuerySource Build(GenerationRules generationRules)
        {
            if (_builder == null)
            {
                AssembleTypes(new GeneratedAssembly(generationRules));
            }

            return(_builder.Build(_sourceType));
        }
Пример #20
0
        /// <summary>
        ///     The currently known strategy for code generating transaction middleware
        /// </summary>
        public static ITransactionFrameProvider GetTransactions(this GenerationRules rules)
        {
            if (rules.Properties.TryGetValue(TRANSACTIONS, out var transactions))
            {
                return((ITransactionFrameProvider)transactions);
            }

            return(_transactions);
        }
Пример #21
0
        /// <summary>
        ///     The currently known strategy for persisting saga state
        /// </summary>
        public static ISagaPersistenceFrameProvider GetSagaPersistence(this GenerationRules rules)
        {
            if (rules.Properties.TryGetValue(SAGA_PERSISTENCE, out var persistence))
            {
                return((ISagaPersistenceFrameProvider)persistence);
            }

            return(_nulloSagas);
        }
Пример #22
0
 public void Apply(HandlerGraph graph, GenerationRules rules, IContainer container)
 {
     // We're adding the StopwatchFrame to all message types,
     // but we *could* filter the application
     foreach (var chain in graph.Chains)
     {
         chain.Middleware.Add(new StopwatchFrame(chain));
     }
 }
Пример #23
0
 public void Apply(HandlerGraph graph, GenerationRules rules, IContainer container)
 {
     // Important! Create a brand new TransactionalFrame
     // for each chain
     graph
     .Chains
     .Where(x => x.MessageType.Name.EndsWith("Command"))
     .Each(x => x.Middleware.Add(new TransactionalFrame()));
 }
Пример #24
0
 public void Apply(RouteGraph graph, GenerationRules rules)
 {
     // Put this middleware on any route that
     // has the HTTP method POST, PUT, or DELETE
     foreach (var chain in graph.Commands)
     {
         chain.Middleware.Add(new StopwatchFrame(chain));
     }
 }
Пример #25
0
        Task IGeneratesCode.AttachGeneratedTypes(GenerationRules rules, IServiceProvider services)
        {
            foreach (var chain in Chains)
            {
                var handler = chain.CreateHandler((IContainer)services);
                _handlers = _handlers.Update(chain.MessageType, handler);
            }

            return(Task.CompletedTask);
        }
Пример #26
0
        Task IFeature.Activate(JasperRuntime runtime, GenerationRules generation)
        {
            var settings = runtime.Get <DiagnosticsSettings>();

            return(Task.Factory.StartNew(() =>
            {
                _server = new DiagnosticsServer();
                _server.Start(settings, runtime.Container);
            }));
        }
Пример #27
0
        internal void Compile(GenerationRules generation, JasperRuntime runtime, PerfTimer timer)
        {
            if (!_hasGrouped)
            {
                Group();
            }

            _generation = generation;
            _container  = runtime.Container;
        }
Пример #28
0
 public void Apply(RouteGraph graph, GenerationRules rules)
 {
     graph
     .Where(x => x.Action.HandlerType.CanBeCastTo <ControllerBase>())
     .Each(x =>
     {
         x.Middleware.Add(new BuildOutControllerContextFrame());
         x.Middleware.Add(new SetControllerContextFrame(x.Action.HandlerType));
     });
 }
Пример #29
0
        public AdvancedSettings(Assembly applicationAssembly)
        {
            var name = applicationAssembly?.GetName().Name ?? "JasperApplication";

            CodeGeneration = new GenerationRules($"{name.Replace(".", "_")}_Generated");
            CodeGeneration.Sources.Add(new NowTimeVariableSource());

            CodeGeneration.Assemblies.Add(GetType().GetTypeInfo().Assembly);
            CodeGeneration.Assemblies.Add(applicationAssembly);
        }
Пример #30
0
        public void BuildRoutingTree(ConnegRules rules, GenerationRules generation, JasperRuntime runtime)
        {
            Router.HandlerBuilder = new RouteHandlerBuilder(runtime.Container, rules, generation);
            assertNoDuplicateRoutes();

            foreach (var route in _chains.Select(x => x.Route))
            {
                Router.Add(route);
            }
        }