Beispiel #1
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            if (_inner.Any())
            {
                writer.Write($"BLOCK:switch ({_event.Usage})");
                foreach (var frame in _inner)
                {
                    frame.GenerateCode(method, writer);
                }
                writer.FinishBlock();
            }

            Next?.GenerateCode(method, writer);
        }
Beispiel #2
0
        public sealed override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            if (_inner.Length > 1)
            {
                for (int i = 1; i < _inner.Length; i++)
                {
                    _inner[i - 1].Next = _inner[i];
                }
            }

            generateCode(method, writer, _inner[0]);

            Next?.GenerateCode(method, writer);
        }
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            if (_aggregate == null)
            {
                writer.WriteLine($"return new {_slot.ReturnType.FullNameInCode()}({_arg.Usage});");
            }
            else
            {
                writer.WriteLine($"{_aggregate.Usage} ??= new {_slot.ReturnType.FullNameInCode()}({_arg.Usage});");
            }


            Next?.GenerateCode(method, writer);
        }
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var alias = RoutingFrames.TypeOutputs[Variable.VariableType];

            writer.WriteLine($"{alias} {Variable.Usage};");
            writer.Write($"BLOCK:if (!{alias}.TryParse({_segments.Usage}[{Position}], out {Variable.Usage}))");
            writer.WriteLine(
                $"{RouteGraph.Context}.{nameof(HttpContext.Response)}.{nameof(HttpResponse.StatusCode)} = 400;");
            writer.WriteLine(method.ToExitStatement());
            writer.FinishBlock();

            writer.BlankLine();
            Next?.GenerateCode(method, writer);
        }
Beispiel #5
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.Write($"var {Persistor.Usage} = new {typeof(InMemoryEnvelopeTransaction).FullNameInCode()}();");
            writer.Write($"await {_context.Usage}.{nameof(IMessageContext.EnlistInTransaction)}({Persistor.Usage});");


            if (_existence == SagaStateExistence.Existing)
            {
                writer.Write(
                    $"var {Document.Usage} = {_persistor.Usage}.{nameof(InMemorySagaPersistor.Load)}<{Document.VariableType.FullNameInCode()}>({_sagaId.Usage});");
            }

            Next?.GenerateCode(method, writer);
        }
Beispiel #6
0
        private void writeDeclaration(ISourceWriter writer)
        {
            var implemented = implements().ToArray();

            if (implemented.Any())
            {
                writer.Write(
                    $"BLOCK:public class {TypeName} : {implemented.Select(x => x.FullNameInCode()).Join(", ")}");
            }
            else
            {
                writer.Write($"BLOCK:public class {TypeName}");
            }
        }
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var creation = $"var {_output.Usage} = new {_output.VariableType.FullName.Replace("+", ".")}()";

            if (_output.VariableType.CanBeCastTo <IDisposable>())
            {
                writer.UsingBlock(creation, w => Next?.GenerateCode(method, w));
            }
            else
            {
                writer.WriteLine(creation + ";");
                Next?.GenerateCode(method, writer);
            }
        }
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var typeFullName = Service.VariableType.FullName.Replace("+", ".");
            var declaration  = $"var {Service.Usage} = ({typeFullName}){_provider.Usage}.{nameof(IServiceProvider.GetService)}(typeof({typeFullName}))";

            if (Service.VariableType.CanBeCastTo <IDisposable>())
            {
                writer.UsingBlock(declaration, w => Next?.GenerateCode(method, w));
            }
            else
            {
                writer.Write(declaration + ";");
                Next?.GenerateCode(method, writer);
            }
        }
        public static void Write(IGenerationModel generationModel, ISourceWriter writer)
        {
            writeClassDeclaration(generationModel, writer);
            writeFields(generationModel, writer);

            writer.BlankLine();

            writeConstructor(generationModel, writer);

            writer.BlankLine();

            writeHandleMethod(generationModel, writer);

            writer.FinishBlock();
        }
Beispiel #10
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.WriteComment("Check if the saga has been completed");
            writer.Write($"BLOCK:if ({_handler.Usage}.{nameof(StatefulSagaOf<string>.IsCompleted)})");
            writer.WriteComment("Delete the saga state entity");
            writer.Write($"{_context.Usage}.{nameof(DbContext.Remove)}({_state.Usage});");
            writer.FinishBlock();
//            writer.Write("BLOCK:else");
//            writer.WriteComment("Persist the saga state entity");
//            writer.Write($"{_context.Usage}.{nameof(DbContext.Add)}({_state.Usage});");
//            writer.FinishBlock();

            writer.BlankLine();

            Next?.GenerateCode(method, writer);
        }
Beispiel #11
0
        protected void LoopAttributes(IMethodVariables variables, ISourceWriter writer, string methodCall)
        {
            var resultsVariable = variables.FindVariable(typeof(ValidationFailures));
            var attributeType   = typeof(T).FullNameInCode();
            var awaitMethod     = this.IsAsync ? "await" : string.Empty;

            writer.Comment($"{this._property.PropertyInfoVariable} == {this._property.PropertyInfoVariable.Property.DeclaringType.Name}.{this._property.PropertyInfoVariable.Property.Name}");
            writer.Block($"foreach (var attribute in {this._property.PropertyAttributesVariable})");
            writer.Block($"if (attribute is {attributeType} x)");
            writer.WriteLine($"var result = {awaitMethod} x.{methodCall};");
            writer.Block($"if (result != {Variable.StaticFrom<ValidationResult>(nameof(ValidationResult.Success))})");
            writer.WriteLine($"{resultsVariable}.{nameof(ValidationFailures.AddFailure)}(result);");
            writer.FinishBlock();
            writer.FinishBlock();
            writer.FinishBlock();
        }
Beispiel #12
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            if (SagaId.VariableType == typeof(string))
            {
                writer.Write($"var {SagaId.Usage} = {_envelope.Usage}.{nameof(Envelope.SagaId)};");
                writer.Write($"if (string.{nameof(string.IsNullOrEmpty)}({SagaFramePolicy.SagaIdVariableName})) throw new {typeof(IndeterminateSagaStateIdException).FullName}({_envelope.Usage});");
            }
            else
            {
                var typeNameInCode = SagaId.VariableType == typeof(Guid) ? typeof(Guid).FullName : SagaId.VariableType.NameInCode();

                writer.Write($"if (!{typeNameInCode}.TryParse({_envelope.Usage}.{nameof(Envelope.SagaId)}, out {typeNameInCode} sagaId)) throw new {typeof(IndeterminateSagaStateIdException).FullName}({_envelope.Usage});");
            }

            Next?.GenerateCode(method, writer);
        }
Beispiel #13
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var declaration = $"{typeof(List<>).Namespace}.List<{ElementType.FullNameInCode()}>";

            var elements = Elements.Select(x => x.Usage).Join(", ");

            if (ReturnCreated)
            {
                writer.Write($"return new {declaration}{{{elements}}};");
            }
            else
            {
                writer.Write($"var {Variable.Usage} = new {declaration}{{{elements}}};");
            }
            Next?.GenerateCode(method, writer);
        }
Beispiel #14
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.Write($"case {SpecificEvent.VariableType.FullNameInCode()} {SpecificEvent.Usage}:");
            // TODO -- fix this with LamarCodeGeneration
            writer.As <SourceWriter>().IndentionLevel++;

            foreach (var frame in _inner)
            {
                frame.GenerateCode(method, writer);
            }

            writer.Write("break;");
            writer.As <SourceWriter>().IndentionLevel--;

            Next?.GenerateCode(method, writer);
        }
Beispiel #15
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.Write($"var stopwatch = new {typeof(Stopwatch).FullNameInCode()}();");
            writer.Write($"stopwatch.Start();");

            writer.Write("BLOCK:try");
            Next?.GenerateCode(method, writer);
            writer.FinishBlock();

            // Write a finally block where you record the stopwatch
            writer.Write("BLOCK:finally");

            writer.Write($"stopwatch.Stop();");
            writer.Write($"{_logger.Usage}.Log(Microsoft.Extensions.Logging.LogLevel.Information, \"{_chain.Description} ran in \" + {_stopwatch.Usage}.{nameof(Stopwatch.ElapsedMilliseconds)});)");

            writer.FinishBlock();
        }
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.WriteLine($"{_aggregateType.FullNameInCode()} {Aggregate.Usage} = default({_aggregateType.FullNameInCode()});");
            writer.Write($"BLOCK:if ({_slice.Usage}.{nameof(StreamAction.ActionType)} == {Constant.ForEnum(StreamActionType.Start).Usage})");

            _create.Action = CreateAggregateAction.Assign;
            _create.GenerateCode(method, writer);

            writer.FinishBlock();

            writer.Write("BLOCK:else");
            _loadMethod.GenerateCode(method, writer);
            _create.Action = CreateAggregateAction.NullCoalesce;
            _create.GenerateCode(method, writer);
            writer.FinishBlock();

            Next?.GenerateCode(method, writer);
        }
Beispiel #17
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var elements = Elements.Select(x => x.Usage).Join(", ");

            var arrayType = ElementType.MustBeBuiltWithFunc() ? "object" : ElementType.FullNameInCode();

            if (ReturnCreated)
            {
                writer.Write($"return new {arrayType}[]{{{elements}}};");
            }
            else
            {
                writer.Write($"var {Variable.Usage} = new {arrayType}[]{{{elements}}};");
            }


            Next?.GenerateCode(method, writer);
        }
Beispiel #18
0
        // You have to override this method
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var creation = $"var {Output.Usage} = new {Output.VariableType.FullNameInCode()}()";

            if (Output.VariableType.CanBeCastTo <IDisposable>())
            {
                // there is an ISourceWriter shortcut for this, but this makes
                // a better code demo;)
                writer.Write($"BLOCK:using ({creation})");
                Next?.GenerateCode(method, writer);
                writer.FinishBlock();
            }
            else
            {
                writer.WriteLine(creation + ";");
                Next?.GenerateCode(method, writer);
            }
        }
Beispiel #19
0
        public virtual void WriteSelectCode(ISourceWriter writer)
        {
            foreach (var route in ComplexArgRoutes)
            {
                writer.WriteComment("Look for odd shaped routes with complex parameter structures");
                writer.Write($"if (Matches{route.VariableName}(segments)) return {route.VariableName};");
            }


            if (_children.Any())
            {
                writer.Write($"BLOCK:if (segments.Length > {LeafDepth})");
                foreach (var node in _children)
                {
                    writer.IfCurrentSegmentEquals(Depth, node.Segment, node.WriteSelectCode);
                }

                if (SpreadRoute != null)
                {
                    writer.Return(SpreadRoute);
                }

                writer.ReturnNull();

                writer.FinishBlock();
            }

            foreach (var leaf in Leaves.OrderBy(x => x.LastSegment))
            {
                writer.IfCurrentSegmentEquals(Depth, leaf.LastSegment, w => w.Return(leaf));
            }

            if (TryFindLeafArgRoute(out var leafArg))
            {
                writer.Return(leafArg);
            }

            if (SpreadRoute != null)
            {
                writer.Return(SpreadRoute);
            }

            writer.ReturnNull();
        }
Beispiel #20
0
        private void writeConstructorMethod(ISourceWriter writer, IList <InjectedField> args)
        {
            var ctorArgs    = args.Select(x => x.CtorArgDeclaration).Join(", ");
            var declaration = $"BLOCK:public {TypeName}({ctorArgs})";

            if (BaseConstructorArguments.Any())
            {
                declaration = $"{declaration} : base({BaseConstructorArguments.Select(x => x.Usage).Join(", ")})";
            }

            writer.Write(declaration);

            foreach (var field in args)
            {
                field.WriteAssignment(writer);
            }

            writer.FinishBlock();
        }
Beispiel #21
0
 public ApplicationGenerator(
     ILogProvider logProvider,
     IDslModel dslModel,
     IPluginsContainer <IGenerator> generatorsContainer,
     RhetosBuildEnvironment buildEnvironment,
     FilesUtility filesUtility,
     ISourceWriter sourceWriter,
     BuildOptions buildOptions)
 {
     _logProvider         = logProvider;
     _logger              = logProvider.GetLogger(GetType().Name);
     _performanceLogger   = logProvider.GetLogger("Performance." + GetType().Name);
     _dslModel            = dslModel;
     _generatorsContainer = generatorsContainer;
     _buildEnvironment    = buildEnvironment;
     _filesUtility        = filesUtility;
     _sourceWriter        = sourceWriter;
     _buildOptions        = buildOptions;
 }
Beispiel #22
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var invokeMethod = invocationCode();

            var returnValue = "";

            if (IsAsync)
            {
                returnValue = method.AsyncMode == AsyncMode.ReturnFromLastNode ? "return " : "await ";
            }

            if (ReturnVariable != null)
            {
                returnValue = $"var {ReturnVariable.Usage} = {returnValue}";
            }

            writer.Write($"{returnValue}{invokeMethod};");

            Next?.GenerateCode(method, writer);
        }
Beispiel #23
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            if (CommentText.IsNotEmpty())
            {
                writer.WriteComment(CommentText);
            }

            var invokeMethod = invocationCode();

            var returnValue = "";

            if (IsAsync)
            {
                returnValue = method.AsyncMode == AsyncMode.ReturnFromLastNode ? "return " : "await ";
            }

            var isDisposable = false;

            if (shouldAssignVariableToReturnValue(method))
            {
#if !NET4x
                returnValue = ReturnVariable.VariableType.IsValueTuple() ? $"{ReturnVariable.Usage} = {returnValue}" : $"var {ReturnVariable.Usage} = {returnValue}";
                #else
                returnValue = $"var {ReturnVariable.Usage} = {returnValue}";
#endif


                isDisposable = ReturnVariable.VariableType.CanBeCastTo <IDisposable>();
            }

            if (isDisposable && DisposalMode == DisposalMode.UsingBlock)
            {
                writer.UsingBlock($"{returnValue}{invokeMethod}", w => Next?.GenerateCode(method, writer));
            }
            else
            {
                writer.Write($"{returnValue}{invokeMethod};");

                Next?.GenerateCode(method, writer);
            }
        }
Beispiel #24
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            var arguments = _arguments.Select(x => x.Usage).Join(", ");
            var implementationTypeName = _implementationType.FullNameInCode();

            if (ReturnCreated)
            {
                writer.Write($"return new {implementationTypeName}({arguments});");
                Next?.GenerateCode(method, writer);
                return;
            }

            var declaration = $"var {Variable.Usage} = new {implementationTypeName}({arguments})";

            switch (Disposal)
            {
            case DisposeTracking.None:
                writer.Write(declaration + ";");
                Next?.GenerateCode(method, writer);
                break;

            case DisposeTracking.WithUsing:
                if (Next is ConstructorFrame && Next.As <ConstructorFrame>().Disposal == DisposeTracking.WithUsing)
                {
                    writer.Write($"using ({declaration})");
                    Next?.GenerateCode(method, writer);
                }
                else
                {
                    writer.UsingBlock(declaration, w => Next?.GenerateCode(method, w));
                }

                break;

            case DisposeTracking.RegisterWithScope:
                writer.Write(declaration + ";");
                writer.Write($"{_scope.Usage}.{nameof(Scope.TryAddDisposable)}({Variable.Usage});");
                Next?.GenerateCode(method, writer);
                break;
            }
        }
Beispiel #25
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            IfStyle.Open(writer, null);

            if (_constructor == null)
            {
                writer.WriteLine($"throw new {typeof(InvalidOperationException).FullNameInCode()}(\"There is no default constructor for {_returnType.FullNameInCode()}\");");
            }
            else if (_setter != null)
            {
                writer.WriteLine("return AggregateBuilder();");
            }
            else
            {
                writer.WriteLine($"return new {_returnType.FullNameInCode()}();");
            }

            IfStyle.Close(writer);

            Next?.GenerateCode(method, writer);
        }
        private void WriteConstructorMethod(ISourceWriter writer, HashSet <InjectedField> args)
        {
            var tempQualifier = args.Select(x => x.CtorArgDeclaration);
            var ctorArgs      = string.Join(", ", tempQualifier);
            var declaration   = $"public {this.TypeName}({ctorArgs})";

            if (this.BaseConstructorArguments.Any())
            {
                var tempQualifier1 = this.BaseConstructorArguments.Select(x => x.ArgumentName);
                declaration = $"{declaration} : base({string.Join(", ", tempQualifier1)})";
            }

            writer.Block(declaration);

            foreach (var field in args)
            {
                field.WriteAssignment(writer);
            }

            writer.FinishBlock();
        }
Beispiel #27
0
        public void Write(ISourceWriter writer)
        {
            writeDeclaration(writer);

            if (AllInjectedFields.Any())
            {
                writeFieldDeclarations(writer, AllInjectedFields);
                writeConstructorMethod(writer, AllInjectedFields);
            }

            writeSetters(writer);


            foreach (var method in _methods.Where(x => x.WillGenerate()))
            {
                writer.BlankLine();
                method.WriteMethod(writer);
            }

            writer.FinishBlock();
        }
Beispiel #28
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            writer.Write(
                $"await {typeof(JasperEnvelopeEntityFrameworkCoreExtensions).FullName}.{nameof(JasperEnvelopeEntityFrameworkCoreExtensions.EnlistInTransaction)}({_context.Usage}, {Context.Usage});");

            foreach (var loaded in _loadedDocs)
            {
                loaded.Write(writer, Context);
            }

            Next?.GenerateCode(method, writer);


            foreach (var saved in _saved)
            {
                writer.Write($"{Context.Usage}.{nameof(DbContext.Add)}({saved.Usage});");
            }

            writer.BlankLine();
            writer.WriteComment("Commit the unit of work");
            writer.Write($"await {Context.Usage}.{nameof(DbContext.SaveChangesAsync)}();");
        }
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            if (_createsSession)
            {
                writer.BlankLine();
                writer.WriteComment("Open a new document session");
                writer.Write(
                    $"BLOCK:using (var {Session.Usage} = {_store.Usage}.{nameof(IDocumentStore.LightweightSession)}())");
            }

            if (_context != null && _isUsingPersistence)
            {
                writer.Write(
                    $"await {typeof(MessageContextExtensions).FullName}.{nameof(MessageContextExtensions.EnlistInTransaction)}({_context.Usage}, {Session.Usage});");
            }

            foreach (var loaded in _loadedDocs)
            {
                loaded.Write(writer, Session);
            }

            Next?.GenerateCode(method, writer);


            foreach (var saved in _saved)
            {
                writer.Write($"{Session.Usage}.{nameof(IDocumentSession.Store)}({saved.Usage});");
            }

            writer.BlankLine();
            writer.WriteComment("Commit the unit of work");
            writer.Write($"await {Session.Usage}.{nameof(IDocumentSession.SaveChangesAsync)}();");

            if (_createsSession)
            {
                writer.FinishBlock();
            }
        }
Beispiel #30
0
        public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
        {
            switch (Mode)
            {
            case ConstructorCallMode.Variable:
                writer.Write(Declaration() + ";");
                ActivatorFrames.Write(method, writer);

                Next?.GenerateCode(method, writer);
                break;

            case ConstructorCallMode.ReturnValue:
                if (ActivatorFrames.Any())
                {
                    writer.Write(Declaration() + ";");
                    ActivatorFrames.Write(method, writer);

                    writer.Write($"return {Variable.Usage};");
                    Next?.GenerateCode(method, writer);
                }
                else
                {
                    writer.Write($"return {Invocation()};");
                    Next?.GenerateCode(method, writer);
                }


                break;

            case ConstructorCallMode.UsingNestedVariable:
                writer.UsingBlock(Declaration(), w =>
                {
                    ActivatorFrames.Write(method, writer);
                    Next?.GenerateCode(method, w);
                });
                break;
            }
        }