Exemple #1
0
        static async Task Main(string[] args)
        {
            using var context = new GeneratorContext();
            var startModule      = StageExtensions.FromResult("https://github.com/nota-game/nota.git", x => x, context);
            var generatorOptions = new GenerationOptions()
            {
                CompressCache = true,
                Refresh       = false
            };
            var s     = System.Diagnostics.Stopwatch.StartNew();
            var files = startModule
                        .GitModul()
                        .Where(x => x.Id == "origin/master")
                        .SingleEntry()
                        .GitRefToFiles()
                        .Sidecar()
                        .For <BookMetadata>(".metadata")
                        .Where(x => System.IO.Path.GetExtension(x.Id) == ".md")
                        .Select(x => x.Markdown().MarkdownToHtml().TextToStream());

            var razorProvider = files.FileProvider("Content").Concat().RazorProvider("Content");

            var rendered = files.Select(x => x.Razor(razorProvider).TextToStream());

            var g = rendered
                    .Transform(x => x.WithId(Path.ChangeExtension(x.Id, ".html")))
                    .Persist(new DirectoryInfo("out"), generatorOptions)
            ;

            await g.UpdateFiles().ConfigureAwait(false);
        }
Exemple #2
0
        public void GenerateTemplatesItems(GenerationOptions options)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            var generator = new LocalizableItemsGenerator(options.SourceDirectory, cultures);

            Console.WriteLine("\nGenerate catalog project types localization files");
            generator.GenerateCatalogProjectTypes();

            Console.WriteLine("\nEGenerate catalog frameworks localization files");
            generator.GenerateCatalogFramework();

            Console.WriteLine("\nGenerate pages localization files");
            generator.GeneratePages();

            Console.WriteLine("\nGenerate features localization files");
            generator.GenerateFeatures();

            Console.WriteLine("\nGenerate services localization files");
            generator.GenerateServices();

            Console.WriteLine("\nGenerate testing localization files");
            generator.GenerateTesting();

            Console.WriteLine("End");
            stopwatch.Stop();
            TimeSpan ts = stopwatch.Elapsed;

            Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));
        }
Exemple #3
0
        private HashSet <Type> GenerateMessages(GenerationOptions options, IEnumerable <Type> types)
        {
            string outputFilename = options.ProtoOutputFilename;

            CodeWriter codeWriter = new CodeWriter();

            codeWriter.Append("syntax = \"proto3\";").AppendLine(2);

            if (options.GenerateCode)
            {
                codeWriter.Append($"package {options.ServiceName};").AppendLine(2);
            }

            if (options.Imports != null)
            {
                foreach (var import in options.Imports)
                {
                    codeWriter.Append($"import \"{import}\";").AppendLine();
                }

                codeWriter.AppendLine();
            }

            var generated = new HashSet <Type>();

            foreach (var type in types)
            {
                if (generated.Contains(type))
                {
                    continue;
                }

                var attr = type.GetCustomAttribute <GenerateMessageAttribute>(true);
                if (attr == null)
                {
                    continue;
                }

                if (type.IsEnum)
                {
                    GenerateEnum(type, codeWriter, generated);
                }
                else if (type.IsClass && !type.IsAbstract)
                {
                    GenerateMessage(type, codeWriter, generated, new HashSet <Type>());
                }
            }

            var path = Path.GetDirectoryName(outputFilename);

            if (!string.IsNullOrEmpty(path) && path != "." && path != "..")
            {
                Directory.CreateDirectory(path);
            }

            GenerateServices(codeWriter, generated, options);

            File.WriteAllText(outputFilename, codeWriter.ToString());
            return(generated);
        }
Exemple #4
0
        public Room CreateRoom(CreateRoomInputModel input)
        {
            // Map input to new room
            var room = new Room
            {
                RoomName = input.RoomName,

                Users = new List <User>(),

                CreatedDateTime = DateTime.UtcNow,
                UpdatedDateTime = DateTime.UtcNow,
            };

            // Generate unique short id for the RoomId
            var shortIdGenerationOptions = new GenerationOptions {
                Length = 8
            };

            do
            {
                room.RoomId = ShortId.Generate(shortIdGenerationOptions);
            } while (DbContext.Rooms.Any(r => r.RoomId == room.RoomId));

            DbContext.Rooms.Add(room);
            DbContext.SaveChanges();
            return(room);
        }
Exemple #5
0
        public static string Execute(string[] commandArgs)
        {
            var options   = GenerationOptions.Parse(commandArgs);
            var processor = new GenerationProcessor(options);

            return(processor.Process());
        }
Exemple #6
0
 public PersistStage(StagePerformHandler <System.IO.Stream, TPreviousItemCache, TPreviousCache> inputList, DirectoryInfo output, GenerationOptions generatorOptions, GeneratorContext context)
 {
     this.generatorOptions = generatorOptions;
     this.inputList        = inputList;
     this.output           = output;
     this.context          = context;
 }
Exemple #7
0
        public void Generate(GenerationOptions opts)
        {
            using (var writer = this.GetWriter(opts))
            {
                // TODO: Validation if we have an userdata parameter we can use so we can write this code.
                // Otherwise, we need to generate code which uses a non-static callback.

                var returnType = this.GetReturnCSharpType(writer);
                var parameters = this.BuildParameters(opts, true);

                // Public API delegate which uses managed types.
                writer.WriteLine("[UnmanagedFunctionPointer (CallingConvention.Cdecl)]");
                writer.WriteLine($"public delegate {returnType} {Name} ({parameters.TypesAndNames})");
                writer.WriteLine();

                // Internal API delegate which uses unmanaged types.
                writer.WriteLine("[UnmanagedFunctionPointer (CallingConvention.Cdecl)]");
                // TODO: Use native marshal types.
                writer.WriteLine($"internal delegate {returnType} {Name}Native ({parameters.TypesAndNames})");
                writer.WriteLine();

                // Generate wrapper class - static if we can use gchandle, otherwise instance
                // Check callback convention - async, notify, call
                writer.WriteLine($"internal static class {Name}Wrapper");
                writer.WriteLine("{");
                using (writer.Indent()) {
                    writer.WriteLine($"public static void NativeCallback ({parameters.TypesAndNames})");
                    writer.WriteLine("{");
                    // TODO: marshal params, call, handle exceptions
                    writer.WriteLine("}");
                }
                writer.WriteLine("}");
            }
        }
 private void MutateGenerationOptionsADL(GenerationOptions options)
 {
     options.EmploymentRequired = true;
     options.LD.IncludeADL      = true;
     options.LD.IncludeHEFields = true;
     options.LD.IncludeSOF      = true;
 }
 public void MutateGenerationOptionsStandards(GenerationOptions options)
 {
     options.LD.OverrideLearnStartDate       = DateTime.Parse("2016-SEP-30");
     options.CreateDestinationAndProgression = true;
     options.LD.IncludeHHS = true;
     _options = options;
 }
Exemple #10
0
 private static void ExecuteReplaceInternal(GenerationOptions options, IExecutor exec)
 {
     foreach (var stm in CoreILSQLStatements)
     {
         exec.ExecuteSQL(stm.FileName);
     }
     foreach (var stm in ReplaceSQLStatements)
     {
         exec.ExecuteSQL(stm.FileName);
     }
     foreach (var stm in CoreBTSQLStatements)
     {
         exec.ExecuteSQL(stm.FileName);
     }
     if (options.GenerateSnowflake)
     {
         foreach (var stm in SnowflakeSQLStatements)
         {
             exec.ExecuteSQL(stm.FileName);
         }
     }
     else if (options.GenerateStar)
     {
         foreach (var stm in StarSQLStatements)
         {
             exec.ExecuteSQL(stm.FileName);
         }
     }
 }
Exemple #11
0
 private static void ExecuteUpdateInternal(GenerationOptions options, IExecutor exec)
 {
     foreach (var stm in CoreILSQLStatements)
     {
         exec.ExecuteSQL(stm.FileName);
     }
     exec.ExecuteSQL("BL_Drop_FKs.sql");
     foreach (var stm in UpdateSQLStatements)
     {
         exec.ExecuteSQL(stm.FileName);
     }
     if (options.GenerateConstraints)
     {
         exec.ExecuteSQL("BL_Create_FKs.sql");
     }
     foreach (var stm in CoreBTSQLStatements)
     {
         exec.ExecuteSQL(stm.FileName);
     }
     if (options.GenerateSnowflake)
     {
         foreach (var stm in SnowflakeSQLStatements)
         {
             exec.ExecuteSQL(stm.FileName);
         }
     }
     else if (options.GenerateStar)
     {
         foreach (var stm in StarSQLStatements)
         {
             exec.ExecuteSQL(stm.FileName);
         }
     }
 }
        public void GenerateProjectTemplatesAndCommandsHandler(GenerationOptions options)
        {
            if (CanOverwriteDirectory(options.DestinationDirectory))
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                Console.WriteLine("\nGenerate C# project templates.");
                var csProjectTemplateGenerator = new CSharpProjectTemplateGenerator(options.SourceDirectory, options.DestinationDirectory);
                csProjectTemplateGenerator.GenerateProjectTemplates(cultures);

                Console.WriteLine("\nGenerate VB project templates.");
                var vbProjectTemplateGenerator = new VisualBasicProjectTemplateGenerator(options.SourceDirectory, options.DestinationDirectory);
                vbProjectTemplateGenerator.GenerateProjectTemplates(cultures);

                Console.WriteLine("\nGenerate right click commands.");
                var rightClickCommandGenerator = new RightClickCommandGenerator(options.SourceDirectory, options.DestinationDirectory);
                rightClickCommandGenerator.GenerateRightClickCommands(cultures);

                Console.WriteLine("End");
                stopwatch.Stop();
                TimeSpan ts = stopwatch.Elapsed;
                Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));
            }
        }
Exemple #13
0
        static void ExecuteCompilation(string srcFile, GenerationOptions options)
        {
            string conStr = null;

            if (options != null)
            {
                conStr = options.DbConnectionString;
            }
            var data   = new ParsableData(System.IO.File.ReadAllText(srcFile), srcFile);
            var p      = new FileParser(data);
            var result = p.Parse();
            var model  = new CoreModel(result);

            var validationResult = CoreModelValidator.Validate(model);

            validationResult.Print();
            if (validationResult.ContainsErrors())
            {
                Console.WriteLine("ERROR: Compilation stopped by validation errors");
                throw new CeusdlCompilationException(validationResult);
            }

            // CeusDL generieren.
            ExecuteStep(new CeusDLGenerator(model), GENERATED_CEUSDL);

            // Code generieren
            if (options.GenerateMySql)
            {
                ExecuteGenerationMySql(options, conStr, model);
            }
            else
            {
                ExecuteGenerationMsSql(options, conStr, model);
            }
        }
        public SkyIslandMapImagesPhase(
            IStageIdentity stageIdentity,
            IStageBounds stageBounds,
            IAsyncFactory <ChunkOverheadKey, IDisposableValue <IReadOnlySkyIslandMapChunk> > chunkFactory,
            IKeyValueStore statsStore,
            SkyIslandMapImagesOptions imageOptions = null,
            GenerationOptions generationOptions    = null)
        {
            Contracts.Requires.That(stageIdentity != null);
            Contracts.Requires.That(stageBounds != null);
            Contracts.Requires.That(chunkFactory != null);
            Contracts.Requires.That(statsStore != null);

            var phaseIdentity = new GenerationPhaseIdentity(nameof(SkyIslandMapImagesPhase));
            var chunkKeys     = new ChunkOverheadKeyCollection(stageBounds);

            var chunkProcessor = new SkyIslandMapChunkImagesProcessor(stageBounds, statsStore, imageOptions);

            this.Phase = new ChunkedPhase <ChunkOverheadKey, IReadOnlySkyIslandMapChunk>(
                stageIdentity,
                phaseIdentity,
                chunkKeys,
                chunkFactory,
                chunkProcessor,
                generationOptions);
        }
Exemple #15
0
 public void MutateGenerationOptionsHEFCE(GenerationOptions options)
 {
     options.EmploymentRequired = true;
     options.LD.IncludeSOF      = true;
     options.LD.IncludeHEFields = true;
     options.LD.IncludeLDM      = true;
 }
Exemple #16
0
        public void ShouldAllowDefaultsToBeChanged()
        {
            const bool useNumbers = true;
            const bool useSpecial = false;
            const int  length     = 17;

            var options = new GenerationOptions
            {
                UseNumbers           = useNumbers,
                UseSpecialCharacters = useSpecial,
                Length = length
            };

            options
            .Length
            .Should()
            .Be(length);
            options
            .UseNumbers
            .Should()
            .Be(useNumbers);
            options
            .UseSpecialCharacters
            .Should()
            .Be(useSpecial);
        }
 private void MutateGenerationOptionsADL(GenerationOptions options)
 {
     options.EmploymentRequired = true;
     options.LD.IncludeADL      = true; // need this for the exception record
     options.LD.IncludeHEFields = true;
     options.LD.IncludeSOF      = true;
 }
Exemple #18
0
 public static AbstractConfigurationRunner Read(
     IWindsorContainer container, Stream stream,
     GenerationOptions generationOptions, string name,
     string environment, params string[] namespaces)
 {
     try
     {
         using (AbstractConfigurationRunner.UseLocalContainer(container))
         {
             AbstractConfigurationRunner conf = GetConfigurationInstanceFromStream(
                 name, environment, container, stream, generationOptions, namespaces);
             using (AbstractConfigurationRunner.CaptureRegistrations())
             {
                 conf.Run();
             }
             foreach (INeedSecondPassRegistration needSecondPassRegistration in NeedSecondPassRegistrations)
             {
                 needSecondPassRegistration.RegisterSecondPass();
             }
             return(conf);
         }
     }
     finally
     {
         NeedSecondPassRegistrations = null;
     }
 }
Exemple #19
0
 private void MutateGenerationOptionsSOFMLD(GenerationOptions options)
 {
     options.EmploymentRequired     = true;
     options.LD.IncludeSOF          = true;
     options.LD.GenerateMultipleLDs = 3;
     options.LD.IncludeHHS          = true;
 }
 private void MutateGenerationOptionsSolent(GenerationOptions options)
 {
     MutateStartDate(options);
     options.LD.IncludeLDM  = true;
     options.LD.OverrideLDM = (int)LearnDelFAMCode.LDM_SolentCity;
     _options = options;
 }
        protected static GenerationOptions GetOptions(Repository repo, bool compat = false)
        {
            var opts = new GenerationOptions("", repo.Namespace, compat, new MemoryStream());

            opts.SymbolTable.AddTypes(repo.GetSymbols());
            opts.SymbolTable.ProcessAliases();
            return(opts);
        }
 public GenerationOptionsViewModel(GenerationOptions model, IMarkDirty dirtyService, IMessageBoxService messageBoxService)
 {
     _model                      = model ?? throw new ArgumentNullException(nameof(model));
     _dirtyService               = dirtyService ?? throw new ArgumentNullException(nameof(dirtyService));
     _messageBoxService          = messageBoxService ?? throw new ArgumentNullException(nameof(messageBoxService));
     HeaderFilePathDialogCommand = new RelayCommand <string>(OpenHeaderFilePathDialog);
     CodeFilePathDialogCommand   = new RelayCommand <string>(OpenCodeFilePathDialog);
 }
Exemple #23
0
 private void MutateGenerationOptionsHE(GenerationOptions options)
 {
     options.LD.OverrideLearnStartDate       = DateTime.Parse(Helpers.ValueOrFunction("[AY-1|AUG|01]"));
     options.LD.IncludeHEFields              = true;
     options.LD.IncludeHHS                   = true;
     options.CreateDestinationAndProgression = true;
     _options = options;
 }
Exemple #24
0
        public void GenerateShouldSucceedWithLengthOptions()
        {
            var options  = new GenerationOptions(length: 22);
            var response = ShortId.Generate(options);

            response.Should().NotBeNullOrEmpty();
            response.Length.Should().Be(22);
        }
 private void MutateGenerationOptions(GenerationOptions options)
 {
     options.EmploymentRequired = true;
     options.LD.IncludeADL      = true;
     options.LD.IncludeLDM      = true;
     options.LD.IncludeSOF      = true;
     options.LD.OverrideLDM     = (int)LearnDelFAMCode.LDM_OLASS;
 }
 private void MutateGenerationOptions(GenerationOptions options)
 {
     options.LD.IncludeLDM                   = false;
     options.LD.IncludeHHS                   = true;
     options.LD.IncludeLDM                   = true;
     options.LD.OverrideLearnStartDate       = DateTime.Parse("2016-AUG-01");
     options.CreateDestinationAndProgression = true;
 }
Exemple #27
0
        public void CanConstruct()
        {
            var options = new GenerationOptions {
                FrameworkType = TestFrameworkTypes.NUnit3, MockingFrameworkType = MockingFrameworkType.NSubstitute, CreateProjectAutomatically = true, AddReferencesAutomatically = false, AllowGenerationWithoutTargetProject = false, TestProjectNaming = "TestValue460938778", TestFileNaming = "TestValue2008872683", TestTypeNaming = "TestValue1485974937"
            };
            var result = new InternalGenerationOptions(options);

            Assert.Fail("Create or modify test");
        }
Exemple #28
0
 public IdGenerator()
 {
     options = new GenerationOptions
     {
         UseNumbers           = true,
         UseSpecialCharacters = false,
         Length = 8
     };
 }
Exemple #29
0
        public static string Generate(int length)
        {
            var options = new GenerationOptions
            {
                Length = length
            };

            return(Generate(options));
        }
Exemple #30
0
        public string GetModifiers(IGeneratable parent, GenerationOptions opts)
        {
            if (parent is Class @class && @class.Abstract)
            {
                return("protected");
            }

            return("public");
        }
		/// <summary>
		/// </summary>
		public PersistentModel(){
			Classes = new Dictionary<string, PersistentClass>();
			DatabaseSqlObjects = new List<SqlObject>();
			Errors = new List<BSharpError>();
			ExtendedScripts = new List<SqlScript>();
			TablePrototype = "dbtable";
			TableAttribute = "persistent";
			FileGroupPrototype = "filegroup";
			ScriptPrototype = "dbscript";
			GenerationOptions = new GenerationOptions();
		}
         public WriteEventOverloadInfo(IMethodSymbol sourceMethod, GenerationOptions options, ParameterConverterCollection converters)
         {
            if (sourceMethod == null)
               throw new ArgumentNullException("sourceMethod", "sourceMethod is null.");

            if (options == null)
               throw new ArgumentNullException("options", "options is null.");

            if (converters == null)
               throw new ArgumentNullException("converters", "converters is null.");

            m_sourceMethod = sourceMethod;
            m_options = options;
            Parameters = m_sourceMethod.Parameters.Select(p => new EventParameterInfo(p, options, converters.TryGetConverter(p.Type))).ToImmutableArray();
         }
Exemple #33
0
 internal ScriptWriter(TextReader cmdletizationXmlReader, string moduleName, string defaultObjectModelWrapper, InvocationInfo invocationInfo, GenerationOptions generationOptions)
 {
     XmlReader xmlReader = XmlReader.Create(cmdletizationXmlReader, xmlReaderSettings);
     try
     {
         XmlSerializer serializer = new PowerShellMetadataSerializer();
         this.cmdletizationMetadata = (PowerShellMetadata) serializer.Deserialize(xmlReader);
     }
     catch (InvalidOperationException exception)
     {
         XmlSchemaException innerException = exception.InnerException as XmlSchemaException;
         if (innerException != null)
         {
             throw new XmlException(innerException.Message, innerException, innerException.LineNumber, innerException.LinePosition);
         }
         XmlException exception3 = exception.InnerException as XmlException;
         if (exception3 != null)
         {
             throw exception3;
         }
         if (exception.InnerException != null)
         {
             throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, CmdletizationCoreResources.ScriptWriter_ConcatenationOfDeserializationExceptions, new object[] { exception.Message, exception.InnerException.Message }), exception.InnerException);
         }
         throw;
     }
     string valueToConvert = this.cmdletizationMetadata.Class.CmdletAdapter ?? defaultObjectModelWrapper;
     this.objectModelWrapper = (Type) LanguagePrimitives.ConvertTo(valueToConvert, typeof(Type), CultureInfo.InvariantCulture);
     if (this.objectModelWrapper.IsGenericType)
     {
         throw new XmlException(string.Format(CultureInfo.CurrentCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperIsStillGeneric, new object[] { valueToConvert }));
     }
     Type objectModelWrapper = this.objectModelWrapper;
     while (!objectModelWrapper.IsGenericType || (objectModelWrapper.GetGenericTypeDefinition() != typeof(CmdletAdapter<>)))
     {
         objectModelWrapper = objectModelWrapper.BaseType;
         if (objectModelWrapper.Equals(typeof(object)))
         {
             throw new XmlException(string.Format(CultureInfo.CurrentCulture, CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperNotDerivedFromObjectModelWrapper, new object[] { valueToConvert, typeof(CmdletAdapter<>).FullName }));
         }
     }
     this.objectInstanceType = objectModelWrapper.GetGenericArguments()[0];
     this.moduleName = moduleName;
     this.invocationInfo = invocationInfo;
     this.generationOptions = generationOptions;
 }
Exemple #34
0
        public static AbstractConfigurationRunner Read(
			IWindsorContainer container, Stream stream,
			GenerationOptions generationOptions, string name,
			string environment, params string[] namespaces)
        {
            try
            {
                using (AbstractConfigurationRunner.UseLocalContainer(container))
                {
                    AbstractConfigurationRunner conf = GetConfigurationInstanceFromStream(
                        name, environment, container, stream, generationOptions, namespaces);
                    using (AbstractConfigurationRunner.CaptureRegistrations())
                    {
                        conf.Run();
                    }
                    foreach (INeedSecondPassRegistration needSecondPassRegistration in NeedSecondPassRegistrations)
                    {
                        needSecondPassRegistration.RegisterSecondPass();
                    }
                    return conf;
                }
            }
            finally
            {
                NeedSecondPassRegistrations = null;
            }
        }
Exemple #35
0
        public static AbstractConfigurationRunner Read(
			IWindsorContainer container, string fileName, string environment,
			GenerationOptions generationOptions, params string[] namespaces)
        {
            try
            {
                AbstractConfigurationRunner conf = GetConfigurationInstanceFromFile(
                    fileName, environment, container, generationOptions, namespaces);
                Execute(container, conf);
                return conf;
            }
            finally
            {
                NeedSecondPassRegistrations = null;
            }
        }
Exemple #36
0
        public static AbstractConfigurationRunner GetConfigurationInstanceFromStream(
			string name, string environment, IWindsorContainer container, Stream stream,
			GenerationOptions generationOptions, params string[] namespaces)
        {
            UrlResolverDelegate urlResolver = CreateWindorUrlResolver(container);
            using (StreamReader reader = new StreamReader(stream))
            {
                return GetConfigurationInstance(
                    name, environment, new ReaderInput(name, reader),
                    generationOptions, new AutoReferenceFilesCompilerStep(urlResolver),
                    namespaces);
            }
        }
Exemple #37
0
        public static AbstractConfigurationRunner GetConfigurationInstanceFromResource(
            string name, string environment, IWindsorContainer container, CustomUri uri,
			GenerationOptions generationOptions, params string[] namespaces)
        {
            IResourceSubSystem system =
                 (IResourceSubSystem)container.Kernel.GetSubSystem(SubSystemConstants.ResourceKey);
            IResource resource = system.CreateResource(uri);
            string baseDirectory = Path.GetDirectoryName(uri.Path);
            UrlResolverDelegate urlResolver = CreateWindorUrlResolver(container);
                return GetConfigurationInstance(
                    name, environment, new ReaderInput(name, resource.GetStreamReader()),
                    generationOptions, new AutoReferenceFilesCompilerStep(baseDirectory,urlResolver),
                    namespaces);
        }
      private IEnumerable<SyntaxNode> GenerateEventSourceMethods(INamedTypeSymbol sourceClass, EventSourceTypeInfo eventSourceTypeInfo, CollectedGenerationInfo overloads, GenerationOptions options)
      {
         var templateMethods = GetEventSourceTemplateMethods(sourceClass, eventSourceTypeInfo);
         foreach (var sourceMethodEntry in templateMethods.AsSmartEnumerable())
         {
            IMethodSymbol sourceMethod = sourceMethodEntry.Value;

            TemplateEventMethodInfo eventAttributeInfo = TranslateMethodAttributes(sourceMethod, eventSourceTypeInfo, overloads);

            WriteEventOverloadInfo overloadInfo = new WriteEventOverloadInfo(sourceMethodEntry.Value, options, m_parameterConverters);

            if (overloadInfo.Parameters.Any(p => p.IsSupported == false))
            {
               throw new CodeGeneratorException(sourceMethod, $"The parameter(s) {StringUtils.Join(overloadInfo.Parameters.Where(p => !p.IsSupported).Select(p => $"{p.Parameter.Name} ({p.Parameter.Type.Name})"), ", ", " and ")} are not supported.");
            }

            overloads.TryAdd(overloadInfo);

            // Check if this method has needs a wrapper method to perform parameter conversion into a natively supported parameter type.            
            if (overloadInfo.NeedsConverter)
            {
               // Create the wrapper method
               SyntaxNode wrapperMethod = m_generator.MethodDeclaration(sourceMethod);
               
               // This method should only have the [NonEvent] attribute.
               wrapperMethod = m_generator.AddAttributes(m_generator.RemoveAllAttributes(wrapperMethod), m_generator.Attribute(eventSourceTypeInfo.EventSourceNamespace.GetFullName() + ".NonEvent"));

               wrapperMethod = m_generator.WithAccessibility(wrapperMethod, sourceMethod.DeclaredAccessibility);
               wrapperMethod = m_generator.WithModifiers(wrapperMethod, DeclarationModifiers.Override);

               // And it should call the overload of the same method that is generated below (the actual event method)
               wrapperMethod = m_generator.WithStatements(wrapperMethod,
                  new[]
                  {
                     m_generator.IfStatement(
                        // Condition
                        m_generator.InvocationExpression(m_generator.IdentifierName("IsEnabled")),

                        // True-Statements
                        new[]
                        {
                           m_generator.ExpressionStatement(
                              m_generator.InvocationExpression(m_generator.IdentifierName(sourceMethod.Name),
                                 overloadInfo.Parameters.Select(parameter => m_generator.Argument(
                                          parameter.HasConverter ?
                                             parameter.Converter.GetConversionExpression(m_generator.IdentifierName(parameter.Parameter.Name)) :
                                             m_generator.IdentifierName(parameter.Parameter.Name)
                                    )
                                 )
                              )
                           )
                        }
                     )
                  }
               );

               // And let's add some warning comments about this being generated code.
               wrapperMethod = wrapperMethod.WithLeadingTrivia(wrapperMethod.GetLeadingTrivia().AddRange(CreateWarningComment()));

               yield return wrapperMethod;
            }

            // Generate the actual event method.
            SyntaxNode eventMethod = m_generator.MethodDeclaration(sourceMethod.Name);

            if (overloadInfo.NeedsConverter)
            {
               // If we have a wrapper method converting parameters, this will be a private method.
               eventMethod = m_generator.WithAccessibility(eventMethod, Accessibility.Private);
            }
            else
            {
               // Otherwise it has the same accessibility as the base class method, except this is an override of course.
               eventMethod = m_generator.WithAccessibility(eventMethod, sourceMethod.DeclaredAccessibility);
               eventMethod = m_generator.WithModifiers(eventMethod, DeclarationModifiers.Override);
            }

            // The parameter list may be modified from the source method to account for any conversions performed by the wrapper method.
            eventMethod = m_generator.AddParameters(eventMethod,
               overloadInfo.Parameters.Select(pi => m_generator.ParameterDeclaration(pi.Parameter.Name, m_generator.TypeExpression(pi.TargetType)))
            );

            // Statement to call the WriteEvent() method.
            SyntaxNode writeEventStatement = m_generator.ExpressionStatement(
                                       m_generator.InvocationExpression(m_generator.IdentifierName("WriteEvent"),
                                          new[] {
                                             m_generator.Argument(m_generator.LiteralExpression(eventAttributeInfo.EventId)),
                                          }.Concat(overloadInfo.Parameters.Select(parameter => m_generator.Argument(
                                                        m_generator.IdentifierName(parameter.Parameter.Name))
                                             )
                                          )
                                       )
                                    );

            if (overloadInfo.NeedsConverter)
            {
               // If this method has a wrapper method, then the IsEnabled() check has already been made, so we skip that here
               // and just call the WriteEvent() method.
               eventMethod = m_generator.WithStatements(eventMethod, new[] { writeEventStatement });
            }
            else
            {
               // Otherwise we want to check the IsEnabled() flag first.
               eventMethod = m_generator.WithStatements(eventMethod,
                  new[]
                  {
                     m_generator.IfStatement(
                        // Condition
                        m_generator.InvocationExpression(m_generator.IdentifierName("IsEnabled")),

                        // True-Statements
                        new[]
                        {
                           writeEventStatement
                        }
                     )
                  }
               );
            }

            // Add all attributes from the source method. (Well, with translation of the TemplateEventAttribute).
            eventMethod = m_generator.AddAttributes(eventMethod, eventAttributeInfo.Attributes);

            // And some warning comments as usual.
            eventMethod = eventMethod.WithLeadingTrivia(eventMethod.GetLeadingTrivia().AddRange(CreateWarningComment()));

            yield return eventMethod;
         }
      }
Exemple #39
0
        internal ScriptWriter(
            TextReader cmdletizationXmlReader,
            string moduleName,
            string defaultObjectModelWrapper,
            InvocationInfo invocationInfo,
            GenerationOptions generationOptions)
        {
            Dbg.Assert(cmdletizationXmlReader != null, "Caller should verify that cmdletizationXmlReader != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleName), "Caller should verify that moduleName != null");
            Dbg.Assert(invocationInfo != null, "Caller should verify that invocationInfo != null");
            Dbg.Assert(!string.IsNullOrEmpty(defaultObjectModelWrapper), "Caller should verify that defaultObjectModelWrapper != null");

            XmlReader xmlReader = XmlReader.Create(cmdletizationXmlReader, ScriptWriter.s_xmlReaderSettings);
            try
            {
                var xmlSerializer = new PowerShellMetadataSerializer();
                _cmdletizationMetadata = (PowerShellMetadata)xmlSerializer.Deserialize(xmlReader);
            }
            catch (InvalidOperationException e)
            {
#if !CORECLR    // No XmlSchema Validation In CoreCLR
                XmlSchemaException schemaException = e.InnerException as XmlSchemaException;
                if (schemaException != null)
                {
                    throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition);
                }
#endif
                XmlException xmlException = e.InnerException as XmlException;
                if (xmlException != null)
                {
                    throw xmlException;
                }

                if (e.InnerException != null)
                {
                    string message = string.Format(
                        CultureInfo.CurrentCulture,
                        CmdletizationCoreResources.ScriptWriter_ConcatenationOfDeserializationExceptions,
                        e.Message,
                        e.InnerException.Message);

                    throw new InvalidOperationException(message, e.InnerException);
                }

                throw;
            }

            string objectModelWrapperName = _cmdletizationMetadata.Class.CmdletAdapter ?? defaultObjectModelWrapper;
            _objectModelWrapper = (Type)LanguagePrimitives.ConvertTo(objectModelWrapperName, typeof(Type), CultureInfo.InvariantCulture);
            TypeInfo objectModelWrapperTypeInfo = _objectModelWrapper.GetTypeInfo();
            if (objectModelWrapperTypeInfo.IsGenericType)
            {
                string message = string.Format(
                    CultureInfo.CurrentCulture,
                    CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperIsStillGeneric,
                    objectModelWrapperName);
                throw new XmlException(message);
            }
            Type baseType = _objectModelWrapper;
            TypeInfo baseTypeInfo = objectModelWrapperTypeInfo;
            while ((!baseTypeInfo.IsGenericType) || baseTypeInfo.GetGenericTypeDefinition() != typeof(CmdletAdapter<>))
            {
                baseType = baseTypeInfo.BaseType;
                if (baseType == typeof(object))
                {
                    string message = string.Format(
                        CultureInfo.CurrentCulture,
                        CmdletizationCoreResources.ScriptWriter_ObjectModelWrapperNotDerivedFromObjectModelWrapper,
                        objectModelWrapperName,
                        typeof(CmdletAdapter<>).FullName);
                    throw new XmlException(message);
                }
                baseTypeInfo = baseType.GetTypeInfo();
            }
            _objectInstanceType = baseType.GetGenericArguments()[0];

            _moduleName = moduleName;
            _invocationInfo = invocationInfo;
            _generationOptions = generationOptions;
        }
 public EventParameterInfo(IParameterSymbol parameter, GenerationOptions options, IParameterConverter converter)
 {
     m_converter = converter;
     m_options = options;
     m_parameter = parameter;
 }
Exemple #41
0
 public static void Read(
     IWindsorContainer container, string fileName, string environment,
     GenerationOptions generationOptions, params string[] namespaces)
 {
     try
     {
         Execute(container, GetConfigurationInstanceFromFile(
             fileName, environment, container, generationOptions, namespaces));
     }
     finally
     {
         NeedSecondPassRegistrations = null;
     }
 }
Exemple #42
0
 public static void Read(
     IWindsorContainer container, CustomUri uri,
     GenerationOptions generationOptions, string name,
     string environment, params string[] namespaces)
 {
     try
     {
         using (AbstractConfigurationRunner.UseLocalContainer(container))
         {
             AbstractConfigurationRunner conf = GetConfigurationInstanceFromResource(
                 name, environment, container, uri, generationOptions, namespaces);
             conf.Run();
             foreach (INeedSecondPassRegistration needSecondPassRegistration in NeedSecondPassRegistrations)
             {
                 needSecondPassRegistration.RegisterSecondPass();
             }
         }
     }
     finally
     {
         NeedSecondPassRegistrations = null;
     }
 }
		/// <summary>
		///     Компилирует модель из кода B#
		/// </summary>
		/// <param name="options"></param>
		/// <param name="codeFiles"></param>
		/// <returns></returns>
		public static PersistentModel Compile(GenerationOptions options ,params string[] codeFiles)
		{
			return new PersistentModel{GenerationOptions = options}.Setup(BSharpCompiler.Compile(codeFiles));
		}
 private IEnumerable<SyntaxNode> CreateSingletonProperty(INamedTypeSymbol sourceClass, GenerationOptions options)
 {
    yield return m_generator.FieldDeclaration(
       name: "s_instance",
       type: m_generator.IdentifierName(options.TargetClassName),
       accessibility: Accessibility.Private,
       modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly,
       initializer: m_generator.ObjectCreationExpression(m_generator.IdentifierName(options.TargetClassName))
    ).WithLeadingTrivia(CreateRegionTriviaList("Singleton Accessor")).AddLeadingTrivia(CreateWarningComment());
    
    yield return m_generator.PropertyDeclaration(
       name: "Log",
       type: m_generator.IdentifierName(sourceClass.Name),
       accessibility: Accessibility.Public,
       modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly,
       getAccessorStatements: new[]
       {
          m_generator.ReturnStatement(m_generator.IdentifierName("s_instance"))
       }
    ).WithLeadingTrivia(CreateWarningComment()).WithTrailingTrivia(CreateEndRegionTriviaList().Add(SF.EndOfLine(Environment.NewLine)).Add(SF.EndOfLine(Environment.NewLine)));
 }
      private GenerationOptions ParseGenerationOptions(INamedTypeSymbol sourceClass)
      {
         AttributeData eventSourceTemplateAttribute = GetCustomAttribute(sourceClass, TemplateEventSourceAttributeName);

         GenerationOptions options = new GenerationOptions(m_targetFramework.Version);

         if (eventSourceTemplateAttribute != null)
         {
            foreach (var namedArgument in eventSourceTemplateAttribute.NamedArguments)
            {
               if (namedArgument.Value.Value != null)
               {
                  var propertyInfo = typeof(GenerationOptions).GetProperty(namedArgument.Key);
                  if (propertyInfo != null)
                  {
                     if (!namedArgument.Value.Value.GetType().Equals(propertyInfo.PropertyType))
                     {
                        throw new CodeGeneratorException($"The value for argument {namedArgument.Key} of attribute {TemplateEventSourceAttributeName} on {sourceClass.Name} has the wrong type. Expected {propertyInfo.PropertyType.Name}, found {namedArgument.Value.Value.GetType()}.");
                     }
                     else
                     {
                        propertyInfo.SetValue(options, namedArgument.Value.Value);
                     }
                  }
               }
            }
         }

         if (options.TargetClassName == null)
         {
            if (sourceClass.Name.EndsWith("Base"))
            {
               options.TargetClassName = sourceClass.Name.Substring(0, sourceClass.Name.Length - "Base".Length);
            }
            else if (sourceClass.Name.EndsWith("Template"))
            {
               options.TargetClassName = sourceClass.Name.Substring(0, sourceClass.Name.Length - "Template".Length);
            }
            else
            {
               options.TargetClassName = sourceClass.Name + "Impl";
            }
         }

         return options;
      }
Exemple #46
0
        private static AbstractConfigurationRunner GetConfigurationInstance(
			string name, string environment, ICompilerInput input,
			GenerationOptions generationOptions, ICompilerStep autoReferenceStep,
			params string[] namespaces)
        {
            BooCompiler compiler = new BooCompiler();
            compiler.Parameters.Ducky = true;
            if (generationOptions == GenerationOptions.Memory)
                compiler.Parameters.Pipeline = new CompileToMemory();
            else
                compiler.Parameters.Pipeline = new CompileToFile();

            compiler.Parameters.Pipeline.Insert(1, autoReferenceStep);
            compiler.Parameters.Pipeline.Insert(2, new BinsorCompilerStep(environment, namespaces));
            compiler.Parameters.Pipeline.Replace(
                typeof (ProcessMethodBodiesWithDuckTyping),
                new TransformUnknownReferences());
            compiler.Parameters.Pipeline.InsertAfter(typeof (TransformUnknownReferences),
                                                     new RegisterComponentAndFacilitiesAfterCreation());

            compiler.Parameters.OutputType = CompilerOutputType.Library;
            compiler.Parameters.Input.Add(input);
            compiler.Parameters.References.Add(typeof (BooReader).Assembly);
            compiler.Parameters.References.Add(typeof (MacroMacro).Assembly);

            TryAddAssembliesReferences(compiler.Parameters, "Rhino.Commons.NHibernate", "Rhino.Commons.ActiveRecord");

            CompilerContext run = compiler.Run();
            if (run.Errors.Count != 0)
            {
                throw new CompilerError(string.Format("Could not compile configuration! {0}", run.Errors.ToString(true)));
            }
            Type type = run.GeneratedAssembly.GetType(name.Replace('.', '_'));
            return Activator.CreateInstance(type) as AbstractConfigurationRunner;
        }
Exemple #47
0
        public static AbstractConfigurationRunner Read(
			IWindsorContainer container, string fileName, string environment,
			GenerationOptions generationOptions, params string[] namespaces)
        {
            var conf = GetConfigurationInstanceFromFile(fileName, environment, container, generationOptions, namespaces);
            Execute(container, conf);
            return conf;
        }
Exemple #48
0
        public static AbstractConfigurationRunner Read(
			IWindsorContainer container, Stream stream,
			GenerationOptions generationOptions, string name,
			string environment, params string[] namespaces)
        {
            using (AbstractConfigurationRunner.UseLocalContainer(container))
            {
                var conf = GetConfigurationInstanceFromStream(name, environment, container, stream, generationOptions, namespaces);
                conf.Run();
                return conf;
            }
        }
        private void GenerateWorld(byte cx, byte cy)
        {
            var width = cx * CHUNK_SIZE;
            var height = cy * CHUNK_SIZE;

            var genOptions = new GenerationOptions
            {
                Frequency = .007f,
                Roughness = .4f,
                NoiseType = NoiseType.Simplex,
                OctaveCount = 6,
                //By default we will just pick a random seed, cap at 10,000 because really high seeds cause problems during noise generation
                Seed = new Random().Next(10000),
                SizeX = width,
                SizeY = height
            };

            var floatMap = HeightMapGenerator.GenerateHeightMap(genOptions);
            floatMap.Normalize(NORMALIZE_LOW, NORMALIZE_HIGH);

            if (m_Environment.Terrain == null)
            {
                m_Environment.Terrain = new DualHeightMap(floatMap)
                {
                    ByteChangeAction = OnByteChange
                };
                return;
            }

            lock (m_Environment.Terrain)
            {
                m_Environment.Terrain = new DualHeightMap(floatMap)
                {
                    ByteChangeAction = OnByteChange
                };
            }
        }
        public void Generate(GenerationOptions options)
        {
            try
            {
                if (options.GenerateContactStatuses)
                {
                    if (ContactStatusInfoProvider.GetContactStatuses().OnSite(mSiteId).Any())
                    {
                        Information("Contact statuses already exists");
                    }
                    else
                    {
                        new SampleContactStatusesGenerator(mSiteId).Generate();
                        Information("Contact statuses generated");
                    }
                }
                if (options.ContactsCount > 0)
                {
                    if (options.ContactsWithRealNames && options.ContactsCount > 100)
                    {
                        Error("Contacts where not generated. \"Contacts with real names\" setting shouldn't be used for generating more than 100 contacts at once.");
                    }
                    else
                    {
                        IPersonalDataGenerator personalDataGenerator = options.ContactsWithRealNames ?
                            new RealPersonalDataGenerator() :
                            (IPersonalDataGenerator)new StupidPersonalDataGenerator();
                        SampleContactsGenerator generator = new SampleContactsGenerator(personalDataGenerator, mSiteId);
                        var batch = 10000;
                        var count = options.ContactsCount;
                        while (count > batch)
                        {
                            generator.Generate(batch);
                            count -= batch;
                        }
                        generator.Generate(count);
                        Information(options.ContactsCount + " contacts generated");
                    }
                }
                if (options.GenerateMergedContacts)
                {
                    var personalDataGenerator = new StupidPersonalDataGenerator();
                    var generator = new SampleContactsGenerator(personalDataGenerator, mSiteId);
                    generator.GenerateMergedContacts();
                    Information(options.ContactsCount + " merged contacts generated");
                }
                if (options.GenerateContactRelationships)
                {
                    var generator = new ContactRelationshipsGenerator();
                    int generated = generator.GenerateContactRelationships(SiteContext.CurrentSite);
                    Information(generated + " relationships between contact and user generated");
                }
                if (options.GeneratePersonas)
                {
                    ISamplePersonasGenerator personaGenerator = options.ContactsWithRealNames ?
                        new RealPersonasGenerator() :
                        (ISamplePersonasGenerator)new StupidPersonasGenerator();
                    personaGenerator.GeneratePersonas(mSiteId);
                    Information("Sample personas generated");
                }
                if (options.GenerateContactGroups > 0)
                {
                    int generatedCGs = new SampleContactGroupsGenerator().GenerateContactGroups(options.GenerateContactGroups);

                    Information(generatedCGs + " contact groups generated");
                }
                if (options.ScoresCount > 0)
                {
                    new SampleScoresGenerator().GenerateScores(options.ScoresCount, mSiteId);
                    Information(options.ScoresCount + " scores generated");
                }
                if (options.ActivitiesForEachExistingContactCount > 0)
                {
                    var contacts = ContactInfoProvider.GetContacts().OnSite(mSiteId);

                    var documents = DocumentHelper.GetDocuments()
                                                  .PublishedVersion()
                                                  .OnSite(mSiteId)
                                                  .ToList();

                    int activitiesGenerated = 0;
                    contacts.ForEachPage(page => activitiesGenerated += new SampleActivitiesGenerator().GenerateActivitiesForContacts(page, options.ActivitiesForEachExistingContactCount, documents), 10000);

                    Information(activitiesGenerated + " activities generated");
                }
            }
            catch (Exception e)
            {
                Error(e.Message);
            }
        }
Exemple #51
0
        public static AbstractConfigurationRunner GetConfigurationInstanceFromFile(
			string fileName, string environment, IWindsorContainer container,
			GenerationOptions generationOptions, params string[] namespaces)
        {
            string baseDirectory = Path.GetDirectoryName(fileName);
            UrlResolverDelegate urlResolver = CreateWindorUrlResolver(container);
            using (TextReader reader = urlResolver(fileName, null))
            {
                return GetConfigurationInstance(
                    Path.GetFileNameWithoutExtension(fileName), environment,
                    new ReaderInput(Path.GetFileNameWithoutExtension(fileName), reader),
                    generationOptions,
                    new AutoReferenceFilesCompilerStep(baseDirectory, urlResolver),
                    namespaces);
            }
        }
      private IEnumerable<SyntaxNode> GenerateWriteEventOverloads(CollectedGenerationInfo overloads, GenerationOptions options, EventSourceTypeInfo eventSourceTypeInfo)
      {
         foreach (WriteEventOverloadInfo overload in overloads.Overloads)
         {
            SyntaxNode method = m_generator.MethodDeclaration("WriteEvent",
               new[] { m_generator.ParameterDeclaration("eventId", m_generator.TypeExpression(SpecialType.System_Int32)) }
               .Concat(overload.Parameters.Select((pi, idx) => m_generator.ParameterDeclaration($"arg{idx}", m_generator.TypeExpression(pi.TargetType)))),
               accessibility: Accessibility.Private);

            method = WithUnsafeModifier(method);

            method = m_generator.AddAttributes(method, m_generator.Attribute(
               m_generator.TypeExpression(
                  m_semanticModel.Compilation.GetTypeByMetadataName(eventSourceTypeInfo.EventSourceNamespace.GetFullName() + ".NonEventAttribute")
               )));
            List<SyntaxNode> statements = new List<SyntaxNode>();

            for (int i = 0; i < overload.Parameters.Length; i++)
            {
               if (overload.Parameters[i].TargetType.SpecialType == SpecialType.System_String)
               {
                  statements.Add(m_generator.IfStatement(m_generator.ReferenceEqualsExpression(m_generator.IdentifierName($"arg{i}"), m_generator.NullLiteralExpression()),
                     new[]
                     {
                        m_generator.AssignmentStatement(m_generator.IdentifierName($"arg{i}"),
                           m_generator.MemberAccessExpression(m_generator.TypeExpression(SpecialType.System_String), "Empty")
                        )
                     }
                  ));
               }
               else if (overload.Parameters[i].TargetType.TypeKind == TypeKind.Array && ((IArrayTypeSymbol)overload.Parameters[i].TargetType).ElementType.SpecialType == SpecialType.System_Byte)
               {
                  statements.Add(m_generator.IfStatement(m_generator.ReferenceEqualsExpression(m_generator.IdentifierName($"arg{i}"), m_generator.NullLiteralExpression()),
                     new[]
                     {
                        m_generator.AssignmentStatement(m_generator.IdentifierName($"arg{i}"),
                           m_generator.ArrayCreationExpression(
                              m_generator.TypeExpression(SpecialType.System_Byte),
                              m_generator.LiteralExpression(0)
                           )
                        )
                     }
                  ));
               }
               else if (overload.Parameters[i].TargetType.SpecialType == SpecialType.System_DateTime)
               {
                  statements.Add(
                     m_generator.LocalDeclarationStatement(
                        m_generator.TypeExpression(SpecialType.System_Int64),
                        $"fileTime{i}",
                        m_generator.InvocationExpression(
                           m_generator.MemberAccessExpression(
                              m_generator.IdentifierName($"arg{i}"),
                              m_generator.IdentifierName("ToFileTimeUtc")
                           )
                        )
                     )
                  );
               }
               else if (overload.Parameters[i].TargetType.TypeKind == TypeKind.Enum)
               {
                  INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)overload.Parameters[i].TargetType;
                  statements.Add(
                     m_generator.LocalDeclarationStatement(
                        m_generator.TypeExpression(namedTypeSymbol.EnumUnderlyingType),
                        $"enumValue{i}",
                        m_generator.CastExpression(
                           m_generator.TypeExpression(namedTypeSymbol.EnumUnderlyingType),
                           m_generator.IdentifierName($"arg{i}")
                        )
                     )
                  );
               }
            }

            // Descriptor length. A byte-array actually takes up two descriptor-slots (length + data), so we calculate the total size here.");
            int descrLength = overload.Parameters.Select(pi => pi.TargetType.IsByteArray() ? 2 : 1).Sum();

            string eventDataTypeFullName = eventSourceTypeInfo.EventSourceClass.GetFullName() + "+EventData";
            INamedTypeSymbol eventDataType = m_compilation.GetTypeByMetadataName(eventDataTypeFullName);
            if (eventDataType == null)
               throw new CodeGeneratorException($"Failed to lookup type {eventDataTypeFullName}.");

            TypeSyntax eventDataTypeSyntax = (TypeSyntax)m_generator.TypeExpression(eventDataType);

            //EventData* descrs = stackalloc EventData[{descrLength}];
            statements.Add(
               SF.LocalDeclarationStatement(
                  SF.VariableDeclaration(
                     SF.PointerType(
                        eventDataTypeSyntax
                     ),
                     SF.SingletonSeparatedList(
                        SF.VariableDeclarator(
                           SF.Identifier("descrs"),
                           null,
                           SF.EqualsValueClause(
                              SF.Token(SyntaxKind.EqualsToken),
                              SF.StackAllocArrayCreationExpression(
                                 SF.ArrayType(
                                    eventDataTypeSyntax,
                                    SF.SingletonList(
                                       SF.ArrayRankSpecifier(
                                          SF.SingletonSeparatedList(
                                             m_generator.LiteralExpression(descrLength) as ExpressionSyntax
                                          )
                                       )
                                    )
                                 )
                              )
                           )
                        )
                     )
                  )
               )
            );


            List<SyntaxNode> innerStatements = new List<SyntaxNode>();
            int descrPos = 0;
            for (int i = 0; i < overload.Parameters.Length; i++, descrPos++)
            {
               if (overload.Parameters[i].TargetType.IsByteArray())
               {
                  // ==> int length{i} = arg{i}.Length;
                  innerStatements.Add(
                     m_generator.LocalDeclarationStatement(
                        m_generator.TypeExpression(SpecialType.System_Int32),
                        $"length{i}",
                        m_generator.MemberAccessExpression(m_generator.IdentifierName($"arg{i}"), "Length")
                     )
                  );

                  // ==> descrs[{descrPos}].DataPointer = (IntPtr)(&length{i});
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "DataPointer", AddressOfVariableAsIntPtrSyntax($"length{i}"))
                  );

                  // ==> descrs[{descrPos}].Size = 4;
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "Size", m_generator.LiteralExpression(4))
                  );

                  descrPos++;

                  // ==> descrs[{descrPos}].DataPointer = (IntPtr)bin{i}
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "DataPointer", m_generator.CastExpression(IntPtrType, m_generator.IdentifierName($"bin{i}")))
                  );

                  // ==> descrs[{descrPos}].Size = length{i}
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "Size", m_generator.IdentifierName($"length{i}"))
                  );
               }
               else if (overload.Parameters[i].TargetType.SpecialType == SpecialType.System_String)
               {
                  // ==> descrs[{descrPos}].DataPointer = (IntPtr)str{i}
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "DataPointer", m_generator.CastExpression(IntPtrType, m_generator.IdentifierName($"str{i}")))
                  );

                  // ==> descrs[{descrPos}].Size = (arg{i}.Length + 1) * 2;
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "Size",
                        m_generator.MultiplyExpression(
                           m_generator.AddExpression(
                              m_generator.MemberAccessExpression(
                                 m_generator.IdentifierName($"arg{i}"),
                                 m_generator.IdentifierName($"Length")
                              ),
                              m_generator.LiteralExpression(1)
                           ),
                           m_generator.LiteralExpression(2)
                        )
                     )
                  );
               }
               else if (overload.Parameters[i].TargetType.SpecialType == SpecialType.System_DateTime)
               {
                  // ==> descrs[{descrPos}].DataPointer = (IntPtr)(&fileTime{i});
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "DataPointer", AddressOfVariableAsIntPtrSyntax($"fileTime{i}"))
                  );

                  // ==> descrs[{descrPos}].Size = 8;
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "Size", m_generator.LiteralExpression(8))
                  );
               }
               else if (overload.Parameters[i].TargetType.TypeKind == TypeKind.Enum)
               {
                  INamedTypeSymbol namedTypeSymbol = (INamedTypeSymbol)overload.Parameters[i].TargetType;
                  // ==> descrs[{descrPos}].DataPointer = (IntPtr)(&enumValue{i});
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "DataPointer", AddressOfVariableAsIntPtrSyntax($"enumValue{i}"))
                  );

                  // ==> descrs[{descrPos}].Size = 8;
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "Size", GetTypeSize(overload.Parameters[i].TargetType))
                  );
               }
               else
               {
                  // ==> descrs[{descrPos}].DataPointer = (IntPtr)(&arg{i});
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "DataPointer", AddressOfVariableAsIntPtrSyntax($"arg{i}"))
                  );

                  // ==> descrs[{descrPos}].Size = 8;
                  innerStatements.Add(
                     AssignDescrSyntax("descrs", descrPos, "Size", GetTypeSize(overload.Parameters[i].TargetType))
                  );

               }
            }

            innerStatements.Add(
               m_generator.ExpressionStatement(
                  m_generator.InvocationExpression(
                     m_generator.IdentifierName("WriteEventCore"),
                     m_generator.IdentifierName("eventId"),
                     m_generator.LiteralExpression(descrLength),
                     m_generator.IdentifierName("descrs")
                  )
               )
            );
           
            // Create fixed statements
            BlockSyntax fixedContent = SF.Block(innerStatements.Cast<StatementSyntax>());

            FixedStatementSyntax fixedStatementSyntax = null;
            for (int i = 0; i < overload.Parameters.Length; i++)
            {
               FixedStatementSyntax current = null;
               if (overload.Parameters[i].TargetType.SpecialType == SpecialType.System_String)
               {
                  current = GetFixedStatement(SyntaxKind.CharKeyword, fixedContent, $"str{i}", $"arg{i}");
               }
               else if (overload.Parameters[i].TargetType.IsByteArray())
               {
                  current = GetFixedStatement(SyntaxKind.ByteKeyword, fixedContent, $"bin{i}", $"arg{i}");
               }

               if (current != null)
               {
                  if (fixedStatementSyntax == null)
                  {
                     fixedStatementSyntax = current;
                  }
                  else
                  {
                     fixedStatementSyntax = current.WithStatement(SF.Block(fixedStatementSyntax));
                  }
               }

            }

            if (fixedStatementSyntax != null)
            {
               statements.Add(fixedStatementSyntax);
            }
            else
            {
               statements.Add(fixedContent);
            }

            method = m_generator.WithStatements(method, statements);

            method = method.PrependLeadingTrivia(CreateWarningComment());

            yield return method;
         }
      }
        private void Generate(string templatePath, string outputPath, EnumModel model, GenerationOptions options = GenerationOptions.AllowOverwrite)
        {
            if (templatePath == null)
                throw new ArgumentNullException("templatePath");
            if (outputPath == null)
                throw new ArgumentNullException("outputPath");

            m_textHost.CurrentInterface = null;
            m_textHost.CurrentPlatform = null;
            m_textHost.CurrentEnum = model;

            m_textHost.TemplateFile = ResolveTemplatePath(templatePath);
            string templateText = GetTemplateText(m_textHost.TemplateFile);

            DateTime lastUpdated = File.Exists(outputPath) ? File.GetLastWriteTimeUtc(outputPath) : DateTime.MinValue;
            if (!File.Exists(outputPath) || (options.HasFlag(GenerationOptions.AllowOverwrite) && DateTime.Compare(lastUpdated, model.UpdatedAt) < 0))
                GenerateFile(outputPath, templateText);
        }
 public TerrainGeneratorNode(GenerationOptions options)
     : base(options)
 {
 }