Exemple #1
0
        protected IList <UCommerceProduct> GenerateVariants(UmbracoDbContext context, ProductWithDefinition[] products,
                                                            string[] mediaIds)
        {
            uint batchSize       = 100_000;
            uint numberOfBatches = (uint)Math.Ceiling(1.0 * Count / batchSize);

            Console.Write($"Generating {Count:N0} {EntityNamePlural} in {numberOfBatches} batches of {batchSize}. ");
            var insertedProducts = new List <UCommerceProduct>((int)Count);

            using (var p = new ProgressBar())
            {
                var variantBatches =
                    GeneratorHelper.Generate(() => GenerateVariant(mediaIds, products),
                                             Count)
                    .DistinctBy(a => a.UniqueIndex())
                    .Batch(batchSize);

                variantBatches.EachWithIndex((variants, index) =>
                {
                    var listOfVariants = variants.ToList();
                    context.BulkInsert(listOfVariants, options => options.SetOutputIdentity = true);
                    insertedProducts.AddRange(listOfVariants);
                    p.Report(1.0 * index / numberOfBatches);
                });

                return(insertedProducts);
            }
        }
Exemple #2
0
        private void BuildTestClass(NodeFeature feature)
        {
            List <string>   privateContents   = new List <string>();
            List <string>   publicContents    = new List <string>();
            List <NodeStep> filterUniqueSteps = new List <NodeStep>();

            foreach (var scenario in feature.Scenarios)
            {
                AddScenario(scenario, feature.Hooks, publicContents);
                if ((scenario.Steps.Count > 0) && (feature.Scenarios.First() == scenario))
                {
                    OpenTestClassPrivateSection(privateContents);
                }
                AddSteps(GeneratorHelper.FindUniqueSteps(filterUniqueSteps, scenario.Steps), scenario, privateContents);
            }

            OpenTestClassPublicSection(feature.Hooks);

            Contents.AddRange(publicContents);

            if (privateContents.Count > 0)
            {
                Contents.AddRange(privateContents);
            }
        }
        public void GenerateNewScene(ISceneForSceneGenerator scene, IEnumerable <IPlayer> players, int seed)
        {
            Tile[][] sceneTiles = scene.SetupEmptyTileSet(20, 20);
            for (int x = 0; x < sceneTiles.Length; x++)
            {
                for (int y = 0; y < sceneTiles[x].Length; y++)
                {
                    scene.CreateTile(tileSet[x, y], x, y, null);
                }
            }

            List <IPlayer> tempPlayers = players.ToList();

            if (tempPlayers.Count != 2)
            {
                throw new ArgumentException("Players count should be 2", "players");
            }

            for (int i = 0; i < 2; i++)
            {
                if (tempPlayers[i].KeyActorsGen.Count > 5)
                {
                    throw new ArgumentException("Actors count should be less than 5. Thrown on player " + tempPlayers[i].Id, "players.keyActors");
                }

                Player tempScenePlayer = GeneratorHelper.ConvertExternalPlayerFromGeneration(scene, tempPlayers[i], i);
                for (int j = 0; j < tempPlayers[i].KeyActorsGen.Count; j++)
                {
                    tempScenePlayer.KeyActors.Add(GeneratorHelper.ConvertExternalActorFromGeneration(scene, tempScenePlayer, sceneTiles[1 + (i * 17)][2 + (j * 2)], tempPlayers[i].KeyActorsGen[j], null));
                }
            }
        }
Exemple #4
0
        /// <summary>
        ///     Move a <see cref="Tetrimino" /> towards a <see cref="MoveDirection" /> if permits.
        ///     The <see cref="Tetrimino" /> will not be changed if the operation fails.
        /// </summary>
        /// <param name="collisionChecker">
        ///     A <see cref="Func{Block, Boolean}" /> which returns true.
        ///     when the block will collide
        /// </param>
        /// <param name="direction">Direction to move</param>
        /// <returns>Whether the <see cref="TryMove(MoveDirection, Func{Block, bool})" /> step succeeds</returns>
        public bool TryMove(MoveDirection direction, Func <Block, bool> collisionChecker)
        {
            var position = Position;

            if (direction == MoveDirection.Down)
            {
                var row = position.Y + 1;
                position = new Position(position.X, row);
            }
            else
            {
                var delta  = direction == MoveDirection.Right ? 1 : -1;
                var column = position.X + delta;
                position = new Position(column, position.Y);
            }

            var newBlocks = GeneratorHelper.CreateOffsetBlocks(Kind, position, FacingDirection);

            if (newBlocks.Any(collisionChecker))
            {
                return(false);
            }
            GeneratorHelper.MapAtomicNumberForNewBlocks(Blocks, newBlocks);

            Position = position;
            Blocks   = newBlocks;
            return(true);
        }
Exemple #5
0
        public override FileInfo FileWrite(OutputInstruction instruction)
        {
            if (instruction == null || instruction.Data == null || !instruction.Data.Any())
            {
                return(null);
            }

            var        filePath   = GeneratorHelper.GetFilePath(instruction.OutputName, instruction.OutputLocation, _fileNameFormat);
            XmlWriter  xmlWriter  = null;
            GZipStream gZipStream = null;

            if (_isGzip)
            {
                gZipStream = new GZipStream(FileCreate(filePath + ".gz"), CompressionMode.Compress);
                xmlWriter  = FileWriterCreate(gZipStream);
            }
            else
            {
                xmlWriter = FileWriterCreate(filePath);
            }

            var serializer = GetSerializer(instruction.Data.First().GetType(), string.Empty);

            using (xmlWriter)
            {
                serializer.Serialize(xmlWriter, instruction.Data);
            }

            if (gZipStream != null)
            {
                gZipStream.Close();
            }

            return(new FileInfo(filePath));
        }
        public override void Seed(UmbracoDbContext context)
        {
            int[] productIds = context.UCommerceProduct
                               .Where(product => product.UCommerceCategoryProductRelation.Count == 0)
                               .Where(product => product.ParentProductId == null) // not variants
                               .Select(x => x.ProductId).ToArray();

            int[] categoryIds = context.UCommerceCategory.Select(x => x.CategoryId).ToArray();

            uint batchSize  = 100_000;
            uint batchCount = (uint)Math.Ceiling(1.0 * Count / batchSize);

            Console.Write(
                $"Generating {Count:N0} relations for {productIds.Length:N0} products and {categoryIds.Length:N0} categories in batches of {batchSize:N0}. ");
            using (var p = new ProgressBar())
            {
                var relationBatches = GeneratorHelper
                                      .Generate(() => GenerateRelation(productIds, categoryIds), Count)
                                      .DistinctBy(a => a.UniqueIndex())
                                      .Batch(batchSize);

                relationBatches.EachWithIndex((relations, index) =>
                {
                    context.BulkInsert(relations.ToList(), options => options.SetOutputIdentity = false);
                    p.Report(1.0 * index / batchCount);
                });
            }
        }
Exemple #7
0
        public async Task <IActionResult> Create([FromServices] IUserRepository userRepository, [FromBody] User user)
        {
            try
            {
                var userExists = await userRepository.ExistsEmailOrUsername(user);

                if (userExists)
                {
                    return(BadRequest(new ErrorModel
                    {
                        Message = "O usuário já existe"
                    }));
                }

                user.Created = user.Updated = DateTime.Now;

                user.Password = GeneratorHelper.GeneratePassword(user.Password);

                await userRepository.Insert(user);

                return(Ok(new SuccessModel
                {
                    Message = Constants.SUCCESS_CREATE_DATA,
                    Result = user.CreateToken()
                }));
            }
            catch
            {
                return(BadRequest(new ErrorModel
                {
                    Message = Constants.ERROR_CREATE_DATA
                }));
            }
        }
Exemple #8
0
        private void GenerateFillDictionary(CollectionMetaToken collectionToken, Type dictionaryType, LocalBuilder objectIdLocal)
        {
            var countLocal = generator.DeclareLocal(typeof(Int32));

            GenerateReadPrimitive(typeof(Int32));
            generator.Emit(OpCodes.Stloc, countLocal);             // read dictionary elements count

            var addMethodArgumentTypes = new [] {
                collectionToken.FormalKeyType,
                collectionToken.FormalValueType
            };
            var addMethod = dictionaryType.GetMethod("Add", addMethodArgumentTypes) ??
                            dictionaryType.GetMethod("TryAdd", addMethodArgumentTypes);

            if (addMethod == null)
            {
                throw new InvalidOperationException(string.Format(CouldNotFindAddErrorMessage, dictionaryType));
            }

            GeneratorHelper.GenerateLoop(generator, countLocal, lc => {
                PushDeserializedObjectOntoStack(objectIdLocal);
                generator.Emit(OpCodes.Castclass, dictionaryType);

                GenerateReadField(collectionToken.FormalKeyType, false);
                GenerateReadField(collectionToken.FormalValueType, false);

                generator.Emit(OpCodes.Callvirt, addMethod);
                if (addMethod.ReturnType != typeof(void))
                {
                    generator.Emit(OpCodes.Pop);                     // remove returned unused value from stack
                }
            });
        }
Exemple #9
0
        private void GenerateReadReadOnlyCollection(Type type, LocalBuilder objectIdLocal)
        {
            var elementFormalType = type.GetGenericArguments()[0];

            var lengthLocal = generator.DeclareLocal(typeof(Int32));
            var arrayLocal  = generator.DeclareLocal(elementFormalType.MakeArrayType());

            GenerateReadPrimitive(typeof(Int32));
            generator.Emit(OpCodes.Stloc, lengthLocal);             // read number of elements in the collection

            generator.Emit(OpCodes.Ldloc, lengthLocal);
            generator.Emit(OpCodes.Newarr, elementFormalType);
            generator.Emit(OpCodes.Stloc, arrayLocal);             // create array

            GeneratorHelper.GenerateLoop(generator, lengthLocal, lc => {
                generator.Emit(OpCodes.Ldloc, arrayLocal);
                generator.Emit(OpCodes.Ldloc, lc);
                GenerateReadField(elementFormalType);
                generator.Emit(OpCodes.Stelem, elementFormalType);
            });

            SaveNewDeserializedObject(objectIdLocal, () => {
                generator.Emit(OpCodes.Ldloc, arrayLocal);
                generator.Emit(OpCodes.Castclass, typeof(IList <>).MakeGenericType(elementFormalType));
                generator.Emit(OpCodes.Newobj, type.GetConstructor(new [] { typeof(IList <>).MakeGenericType(elementFormalType) }));
            });
        }
Exemple #10
0
        private static void ParseFieldText(string fieldText, bool isReadOnly, out string fieldName, out string fieldType, out string defaultValue)
        {
            Match match = fieldRegex.Match(fieldText);

            if (!match.Success)
            {
                match = fieldRegexFallback.Match(fieldText);
            }
            if (!match.Success)
            {
                match = fieldRegexFallback2.Match(fieldText);
            }

            if (match.Success)
            {
                fieldName    = match.Groups["FLD"].Value;
                fieldType    = GeneratorHelper.DetermineFieldTypeFromDocumentation(match.Groups["TYPE"].Value, fieldName, isReadOnly);
                defaultValue = match.Groups["DEFAULT"].Value;
            }
            else
            {
                fieldName    = "Unknown";
                fieldType    = "UNKNOWN /*" + fieldText + "*/";
                defaultValue = null;
            }
        }
Exemple #11
0
 public static Tetrimino ByPosition(TetriminoKind kind, Position position, Direction facingDirection)
 {
     return(new Tetrimino(kind,
                          position,
                          GeneratorHelper.GetFirstBlockPositionByPosition(position, kind, facingDirection),
                          facingDirection));
 }
Exemple #12
0
    //boss被击中时回调改方法
    void OnHit(float energy)
    {
        blood -= energy;
        if (blood < halfBlood && !underHalfBlood)
        {
            underHalfBlood = true;
            //半血时回调
            bossController.OnBossHalfBlood(blood);
        }
        else if (blood < quarterBlood && !underQuarterBlood)
        {
            underQuarterBlood = true;
            // 四分之一血时回调
            bossController.OnBossQuarterBlood(blood);
        }

        // 没血了销毁自身,弹出MissionCompleted提示
        if (blood <= 0)
        {
            Destroy(gameObject);
            Instantiate(explosion, transform.position, Quaternion.identity);
            GameObject parent = GameObject.Find("EnemyController");
            GeneratorHelper.GeneratorGameObject(new Vector3(0f, 3f, -5f), missionCompleted, parent);
        }
    }
Exemple #13
0
        private static void AddStepDefinitonToIntelliSenseProject(List <NodeFeature> features, string pathToFeatureFile, string pathToIntelliSenseProject)
        {
            foreach (var feature in features)
            {
                List <StepInstance> si = new List <StepInstance>();
                var steps = new List <NodeStep>();
                feature.Scenarios.ForEach(s => steps.AddRange(s.Steps));
                var uniqueSteps = GeneratorHelper.FindUniqueSteps(new List <NodeStep>(), steps);

                foreach (var step in uniqueSteps)
                {
                    StepDefinitionType    type;
                    StepDefinitionKeyword keyword;
                    string stepNameWithoutType;

                    if (step.Name.StartsWith("Given"))
                    {
                        type                = StepDefinitionType.Given;
                        keyword             = StepDefinitionKeyword.Given;
                        stepNameWithoutType = step.Name.Substring("Given".Length);
                    }
                    else if (step.Name.StartsWith("When"))
                    {
                        type                = StepDefinitionType.When;
                        keyword             = StepDefinitionKeyword.When;
                        stepNameWithoutType = step.Name.Substring("When".Length);
                    }
                    else
                    {
                        type                = StepDefinitionType.Then;
                        keyword             = StepDefinitionKeyword.Then;
                        stepNameWithoutType = step.Name.Substring("Then".Length);
                    }
                    string scenarioName = feature.Scenarios.First(scenario => scenario.Steps.Contains(step)).Name;
                    si.Add(new StepInstance(type, keyword, stepNameWithoutType, stepNameWithoutType, new StepContext(feature.Name, scenarioName, new List <string>(), CultureInfo.CurrentCulture)));
                }

                var stepDefSkeleton = new StepDefinitionSkeletonProvider(new SpecFlowCSkeletonTemplateProvider(), new StepTextAnalyzer());
                var template        = stepDefSkeleton.GetBindingClassSkeleton(TechTalk.SpecFlow.ProgrammingLanguage.CSharp, si.ToArray(), "CppUnitTest", feature.Name, StepDefinitionSkeletonStyle.MethodNamePascalCase, CultureInfo.CurrentCulture);

                string basePathToFeatures            = Path.GetDirectoryName(pathToFeatureFile);
                string basePathToIntelliSenseProject = Path.GetDirectoryName(pathToIntelliSenseProject);
                _csProj = _csProj ?? GetUnloadedProject(pathToIntelliSenseProject);

                var stepDefinitionDirPathInProj = string.Format("Steps\\{0}\\", PROJECT_NAME);
                var stepDefinitionDirPath       = string.Format("{0}\\{1}", basePathToIntelliSenseProject, stepDefinitionDirPathInProj);

                var filePathInProjFile = string.Format("{0}{1}_step.cs", stepDefinitionDirPathInProj, feature.Name);
                var filePath           = string.Format("{0}{1}_step.cs", stepDefinitionDirPath, feature.Name);

                if (!_csProj.GetItems("Compile").Any(item => item.UnevaluatedInclude == filePathInProjFile))
                {
                    Console.WriteLine(string.Format("Generating Step Definition file for IntelliSense support: {0}", filePathInProjFile));
                    Directory.CreateDirectory(stepDefinitionDirPath);
                    File.WriteAllText(filePath, template);
                    _csProj.AddItem("Compile", filePathInProjFile);
                    _isDirtyCsProj = true;
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Build the Dictionary that associate a token of an index-name-1 to its hash + name.
        /// </summary>
        /// <param name="indexes">The Array of Index Symbol Definition</param>
        /// <param name="ownerDefinition">The Owner of the definition that contains the INDEXED BY clause</param>
        /// <returns>The Dictionary</returns>
        private static Dictionary <Compiler.Scanner.Token, string> BuiltIndexMap(Node rootNode, List <string> rootProcedures, List <Tuple <string, string> > rootVariableName, SymbolDefinition[] indexes, TypeCobol.Compiler.Nodes.DataDefinition ownerDefinition)
        {
            Dictionary <Compiler.Scanner.Token, string> map = new Dictionary <Compiler.Scanner.Token, string>(indexes.Length);
            List <string> pathProcedures;
            List <string> pathVariables;

            GeneratorHelper.ComputeProperPaths(ownerDefinition, out pathProcedures, out pathVariables);
            List <string> list_items = new List <string>();

            //list_items.AddRange(pathProcedures);

            //Add root procedures

            for (int j = rootProcedures.Count - 1; j >= 0; j--)
            {
                list_items.Add(rootProcedures[j]);
            }

            //Add Root variables
            for (int j = rootVariableName.Count - 1; j >= 0; j--)
            {
                list_items.Add(rootVariableName[j].Item1);
                if (j != 0 && rootVariableName[j].Item2 != null && rootVariableName[j].Item2.Trim().Length > 0)
                {
                    list_items.Add(rootVariableName[j].Item2);
                }
            }

            list_items.AddRange(pathVariables);
            string qn = string.Join(".", list_items.ToArray());

            AddIndexMap(rootNode, rootNode.QualifiedName.ToString(), indexes, map);
            AddIndexMap(ownerDefinition, qn, indexes, map);
            return(map);
        }
        private List <UCommerceCategory> GenerateSubCategories(DataContext context,
                                                               int[] definitionIds, string[] mediaIds, IEnumerable <UCommerceCategory> topLevelCategories)
        {
            uint batchSize       = 100_000;
            uint numberOfBatches = (uint)Math.Ceiling(4.0 * Count / 5.0 / batchSize);

            Console.Write($"Generating {4 * Count / 5:N0} subcategories in batches of {batchSize}. ");
            var insertedCategories = new List <UCommerceCategory>((int)Count / 5);

            using (var p = new ProgressBar())
            {
                var categoryBatches = GeneratorHelper
                                      .Generate(() => GenerateSubCategory(definitionIds, mediaIds, topLevelCategories), 4 * Count / 5)
                                      .DistinctBy(a => a.UniqueIndex())
                                      .Batch(batchSize);

                categoryBatches.EachWithIndex((categories, index) =>
                {
                    var listOfCats = categories.ToList();
                    context.Ucommerce.BulkInsert(listOfCats, options => options.SetOutputIdentity = true);
                    insertedCategories.AddRange(listOfCats);
                    p.Report(1.0 * index / numberOfBatches);
                });

                return(insertedCategories);
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            bool   helpFlag              = false;
            String language              = null;
            String outputPath            = null;
            String messageDefinitionPath = null;

            OptionSet optionSet = new OptionSet()
            {
                { "lang=", "the {LANGUAGE} of generated code [default: CSharp]", v => language = v },
                { "defPath=", "the {PATH} of Message Definitions files.", v => messageDefinitionPath = v },
                { "outputPath=", "the {PATH} of output files.", v => outputPath = v },
                { "h|help", "show this message and exit", v => helpFlag = v != null },
            };

            string codeBase        = Assembly.GetExecutingAssembly().CodeBase;
            string applicationName = Path.GetFileName(codeBase);

            try
            {
                optionSet.Parse(args);

                if (String.IsNullOrWhiteSpace(messageDefinitionPath))
                {
                    throw new Exception("defPath must be provided");
                }

                if (String.IsNullOrWhiteSpace(outputPath))
                {
                    throw new Exception("outputPath must be provided");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine($"Use '{applicationName} --help' for more information.");
                return;
            }

            if (helpFlag)
            {
                ShowHelp(applicationName, optionSet);
                return;
            }

            Console.WriteLine($"The files will be generated in folder '{outputPath}'");
            Console.WriteLine("Press [Enter] key to generate files");
            Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine($"Generating files in folder '{outputPath}' ...");

            GeneratorHelper.GenerateFiles(messageDefinitionPath, outputPath, language);

            Console.WriteLine();
            Console.WriteLine($"Generation succeeded in folder '{outputPath}'");
            Console.WriteLine("Press [Enter] key to quit...");
            Console.ReadLine();
        }
        private void CreateStones(GeneratorParameter param, Tile[,] tiles)
        {
            float[,] heatMap = CreateStoneHeatMap(param.size, tiles);

            List <Room> rooms = null;

            while (rooms == null || rooms.Count < MIN_RES_ROOMS)
            {
                int block = (int)(BLOCKING_PERC - BLOCKING_PERC_DELTA / 2 + ((1 - param.resourceSize) * BLOCKING_PERC_DELTA));

                bool[,] automata = CellularAutomata.Generate(param.size, SMOOTH_ITERATIONS, block, false, random.Next());

                for (int y = 0; y < param.size.Y; y++)
                {
                    for (int x = 0; x < param.size.X; x++)
                    {
                        if (automata[x, y] || heatMap[x, y] < 0.5f || !tiles[x, y].AllHeightsAreSame())
                        {
                            automata[x, y] = true;
                        }
                    }
                }

                rooms = GeneratorHelper.GetCellularAutomataAsRooms(automata);
            }

            rooms.Shuffle(random);

            int coalIndex = (int)(STONE_PERCENTAGE * rooms.Count);
            int oreIndex  = (int)((STONE_PERCENTAGE + COAL_PERCENTAGE) * rooms.Count);
            int oilIndex  = (int)((STONE_PERCENTAGE + COAL_PERCENTAGE + ORE_PERCENTAGE) * rooms.Count);

            for (int i = 0; i < rooms.Count; ++i)
            {
                TileType res = TileType.Stone;
                if (i >= oilIndex)
                {
                    res = TileType.Oil;
                }
                else if (i >= oreIndex)
                {
                    res = TileType.Ore;
                }
                else if (i >= coalIndex)
                {
                    res = TileType.Coal;
                }

                foreach (Point p in rooms[i].Tiles)
                {
                    if (tiles[p.X, p.Y].type == TileType.Nothing)
                    {
                        tiles[p.X, p.Y].type       = res;
                        tiles[p.X, p.Y].onTopIndex = param.tileset.GetRandomIndex(res);
                    }
                }
            }
        }
        /// <summary>
        /// Process the generator.
        /// </summary>
        /// <param name="projectFile">The project file to work from.</param>
        public void Generate(string projectFile)
        {
            this.logger.LogInformation($"Loading {Path.GetFileName(projectFile)}...");

            var projectFolder = Path.GetDirectoryName(projectFile);

            // First we need to register the project.
            var project = this.workspace.RegisterProject(projectFile);

            // Register the pattern interface.
            var patternInterfaceDeclaration = this.workspace.RegisterFile("./Patterns/Itf/IModelPattern.cs")
                                              .Declarations.Single() as IInterfaceDeclaration;

            // Register the pattern implementation.
            var patternImplementationDeclaration = this.workspace.RegisterFile("./Patterns/Impl/ModelPattern.cs")
                                                   .Declarations.Single() as IGenericDeclaration <SyntaxNode>;

            // Load the project and its project dependencies. (Note that for now we only load the sources.
            // The binary assembly dependencies are not taken into account)
            var resolver = this.workspace.DeepLoad();

            // Get the base interface in order to find all extended interfaces that need to be implemented.
            var modelBaseInterface = resolver.Find("SoloX.GeneratorTools.Core.CSharp.Examples.Core.IModelBase").Single() as IGenericDeclaration <SyntaxNode>;

            // Setup a locator that will tell the location where the generated classes must be written.
            var locator = new RelativeLocator(projectFolder, project.RootNameSpace, suffix: "Impl");

            // Create the Implementation Generator with a file generator, the locator and the pattern interface/class.
            var generator = new ImplementationGenerator(
                new FileGenerator(".generated.cs"),
                locator,
                patternInterfaceDeclaration,
                patternImplementationDeclaration);

            // Loop on all interface extending the base interface.
            foreach (var modelInterface in modelBaseInterface.ExtendedBy.Where(d => d != patternInterfaceDeclaration))
            {
                this.logger.LogInformation(modelInterface.FullName);

                var implName = GeneratorHelper.ComputeClassName(modelInterface.Name);

                // Create the property writer what will use all properties from the model interface to generate
                // and write the corresponding code depending on the given patterns.
                var propertyWriter = new PropertyWriter(
                    patternInterfaceDeclaration.Properties.Single(),
                    modelInterface.Properties);

                // Setup some basic text replacement writer.
                var itfNameWriter  = new StringReplaceWriter(patternInterfaceDeclaration.Name, modelInterface.Name);
                var implNameWriter = new StringReplaceWriter(patternImplementationDeclaration.Name, implName);

                // Create the writer selector.
                var writerSelector = new WriterSelector(propertyWriter, itfNameWriter, implNameWriter);

                // And generate the class implementation.
                generator.Generate(writerSelector, (IInterfaceDeclaration)modelInterface, implName);
            }
        }
Exemple #19
0
        private void GenerateFillCollection(Type elementFormalType, Type collectionType, LocalBuilder objectIdLocal)
        {
            var countLocal = generator.DeclareLocal(typeof(Int32));

            GenerateReadPrimitive(typeof(Int32));
            generator.Emit(OpCodes.Stloc, countLocal);             // read collection elements count

            var addMethod = collectionType.GetMethod("Add", new [] { elementFormalType }) ??
                            collectionType.GetMethod("Enqueue", new [] { elementFormalType }) ??
                            collectionType.GetMethod("Push", new [] { elementFormalType });

            if (addMethod == null)
            {
                throw new InvalidOperationException(string.Format(CouldNotFindAddErrorMessage, collectionType));
            }

            if (collectionType == typeof(Stack) ||
                (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(Stack <>)))
            {
                var tempArrLocal = generator.DeclareLocal(elementFormalType.MakeArrayType());

                generator.Emit(OpCodes.Ldloc, countLocal);
                generator.Emit(OpCodes.Newarr, elementFormalType);
                generator.Emit(OpCodes.Stloc, tempArrLocal);                 // creates temporal array

                GeneratorHelper.GenerateLoop(generator, countLocal, cl => {
                    generator.Emit(OpCodes.Ldloc, tempArrLocal);
                    generator.Emit(OpCodes.Ldloc, cl);
                    GenerateReadField(elementFormalType, false);
                    generator.Emit(OpCodes.Stelem, elementFormalType);
                });

                GeneratorHelper.GenerateLoop(generator, countLocal, cl => {
                    PushDeserializedObjectOntoStack(objectIdLocal);
                    generator.Emit(OpCodes.Castclass, collectionType);

                    generator.Emit(OpCodes.Ldloc, tempArrLocal);
                    generator.Emit(OpCodes.Ldloc, cl);
                    generator.Emit(OpCodes.Ldelem, elementFormalType);
                    generator.Emit(OpCodes.Callvirt, collectionType.GetMethod("Push"));
                }, true);
            }
            else
            {
                GeneratorHelper.GenerateLoop(generator, countLocal, cl => {
                    PushDeserializedObjectOntoStack(objectIdLocal);
                    generator.Emit(OpCodes.Castclass, collectionType);
                    GenerateReadField(elementFormalType, false);
                    generator.Emit(OpCodes.Callvirt, addMethod);

                    if (addMethod.ReturnType != typeof(void))
                    {
                        generator.Emit(OpCodes.Pop);                         // remove returned unused value from stack
                    }
                });
            }
        }
Exemple #20
0
 protected Tetrimino(TetriminoKind kind, Position position, Position firstBlockPosition,
                     Direction facingDirection)
 {
     Kind               = kind;
     Position           = position;
     FacingDirection    = facingDirection;
     FirstBlockPosition = firstBlockPosition;
     Blocks             = GeneratorHelper.CreateOffsetBlocks(kind, Position, facingDirection);
 }
 public override void Seed(DataContext context)
 {
     Console.Write($"Generating {Count:N0} product relation types. ");
     using (var p = new ProgressBar())
     {
         var dataTypes = GeneratorHelper.Generate(Generate, Count);
         p.Report(0.5);
         context.Ucommerce.BulkInsert(dataTypes, options => options.SetOutputIdentity = false);
     }
 }
Exemple #22
0
        protected string GetRealJwtToken(int tokenLife = Constants.TOKEN_LIFE)
        {
            //NOTE: Generating real jwt token for validation tests :)
            var generatorHelper = new GeneratorHelper();
            var jwtPrivateKey   = generatorHelper.GetJwtPrivateKey();
            var jwtIssuer       = generatorHelper.GetJwtIssuer();
            var jwtToken        = generatorHelper.GetJwtToken(jwtPrivateKey, jwtIssuer, tokenLife);

            return(jwtToken);
        }
 private List <UCommerceDataType> GenerateDataTypes(DataContext context, int[] definitionIds)
 {
     Console.Write($"Generating {Count:N0} data types.");
     using (var p = new ProgressBar())
     {
         var dataTypes = GeneratorHelper.Generate(() => Generate(definitionIds), Count).ToList();
         p.Report(0.5);
         context.Ucommerce.BulkInsert(dataTypes);
         return(dataTypes);
     }
 }
Exemple #24
0
 public AutomatedGenericStrategy(
     IGenericDeclaration <SyntaxNode> pattern,
     IGenericDeclaration <SyntaxNode> declaration,
     IDeclarationResolver resolver)
 {
     this.declaration           = declaration;
     this.pattern               = pattern;
     this.resolver              = resolver;
     this.targetDeclarationName = GeneratorHelper.ComputeClassName(declaration.Name);
     this.targetPatternName     = GeneratorHelper.ComputeClassName(pattern.Name);
 }
        private int GetMaxObjectDepth(Expression expression, int currentDepth)
        {
            string expressionType;

            if (currentDepth == 0) //if is root element
            {
                //Frameworks can add theType { dynamicType} - strip out the {dynamic type}
                expressionType = GeneratorHelper.GetSubClassFromType(expression.Type);
            }
            else
            {
                //members of objects have a type of: object { theType } - strip out object { }
                expressionType = GeneratorHelper.GetBaseClassFromType(expression.Type);
            }


            //No members and can't be resolved to a single type (equivalent of having no members)
            if (expression.DataMembers.Count > 0 && GeneratorHelper.IsSerializable(expression.Name) &&
                !GeneratorHelper.CanBeExpressedAsSingleType(expressionType))
            {
                List <Expression> dataMembers = expression.DataMembers.Cast <Expression>().ToList();

                for (int i = 0; i < dataMembers.Count; i++)
                {
                    Expression currentMember = dataMembers[i];

                    //Add to current list, bring base members up one level
                    if (GeneratorHelper.IsBase(currentMember))
                    {
                        dataMembers.AddRange(currentMember.DataMembers.Cast <Expression>());
                    }
                    else
                    {
                        if (_maxDepth >= _cutoff)
                        {
                            return(_maxDepth);                      //Stop calculating
                        }
                        if (currentDepth > _maxDepth)
                        {
                            _maxDepth = currentDepth;
                        }

                        bool isValid = _ruleSetValidator.ValidateAllSubRules(expressionType, currentMember.Name);

                        if (isValid)
                        {
                            GetMaxObjectDepth(currentMember, currentDepth + 1);
                        }
                    }
                }
            }

            return(_maxDepth);
        }
Exemple #26
0
 public override void Seed(DataContext context)
 {
     Console.Write($"Generating {Count:N0} product definitions. ");
     using (var p = new ProgressBar())
     {
         var productDefinitions = GeneratorHelper.Generate(Generate, Count);
         p.Report(0.33);
         productDefinitions.ConsecutiveSortOrder((def, val) => { def.SortOrder = (int)val; });
         p.Report(0.66);
         context.Ucommerce.BulkInsert(productDefinitions, options => options.SetOutputIdentity = false);
     }
 }
Exemple #27
0
 public override void Seed(UmbracoDbContext context)
 {
     Console.Write($"Generating {Count:N0} order number series. ");
     using (var p = new ProgressBar())
     {
         p.Report(0.1);
         var orderNumberSeries =
             GeneratorHelper.Generate(() => _faker.Generate(), Count);
         p.Report(0.5);
         context.BulkInsert(orderNumberSeries);
     }
 }
        public MethodMetadata(
            int no,
            MethodInfo mi,
            CommandType commandType,
            MethodType memberType,
            bool returnValueAsResult,
            IReadOnlyList <INode> nodes,
            IReadOnlyList <ParameterEntry> parameters,
            IReadOnlyList <DynamicParameterEntry> dynamicParameters)
        {
            No                  = no;
            MethodInfo          = mi;
            CommandType         = commandType;
            MethodType          = memberType;
            ReturnValueAsResult = returnValueAsResult;
            Nodes               = nodes;
            Parameters          = parameters;
            DynamicParameters   = dynamicParameters;

            var isAsyncEnumerable = GeneratorHelper.IsAsyncEnumerable(mi.ReturnType);

            IsAsync          = mi.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null || isAsyncEnumerable;
            EngineResultType = !IsAsync || isAsyncEnumerable
                ? mi.ReturnType
                : (mi.ReturnType.IsGenericType ? mi.ReturnType.GetGenericArguments()[0] : typeof(void));

            Provider = mi.GetCustomAttribute <ProviderAttribute>();
            Timeout  = mi.GetCustomAttribute <CommandTimeoutAttribute>();
            SqlSize  = mi.GetCustomAttribute <SqlSizeAttribute>();

            foreach (var pmi in mi.GetParameters())
            {
                if (ParameterHelper.IsTimeoutParameter(pmi))
                {
                    TimeoutParameter = pmi;
                }

                if (ParameterHelper.IsCancellationTokenParameter(pmi))
                {
                    CancelParameter = pmi;
                }

                if (ParameterHelper.IsConnectionParameter(pmi))
                {
                    ConnectionParameter = pmi;
                }

                if (ParameterHelper.IsTransactionParameter(pmi))
                {
                    TransactionParameter = pmi;
                }
            }
        }
 private List <UCommerceDefinitionField> GenerateFields(DataContext context, int[] definitionIds,
                                                        int[] dataTypeIds)
 {
     Console.Write($"Generating {Count:N0} definition fields. ");
     using (var p = new ProgressBar())
     {
         var fields = GeneratorHelper.Generate(() => GenerateField(definitionIds, dataTypeIds), Count).ToList();
         fields.ConsecutiveSortOrder((f, v) => { f.SortOrder = (int)v; });
         p.Report(0.5);
         context.Ucommerce.BulkInsert(fields);
         return(fields);
     }
 }
        /// <summary>
        /// Creates a float heat map that indicates how probable a tile is to contain a resource.
        /// This will be used in conjunction with cellular automata to create resource distribution.
        /// Tiles that are water, cities, roads (not empty in general) are less likely to become resource.
        /// For stone
        /// </summary>
        /// <returns></returns>
        private float[,] CreateStoneHeatMap(Point mapSize, Tile[,] tiles)
        {
            float[,] heatMap = new float[mapSize.X, mapSize.Y];

            //init heat map values to 1
            for (int y = 0; y < mapSize.Y; y++)
            {
                for (int x = 0; x < mapSize.X; x++)
                {
                    heatMap[y, x] = 1f;
                }
            }


            for (int y = 0; y < mapSize.Y; y++)
            {
                for (int x = 0; x < mapSize.X; x++)
                {
                    if (tiles[x, y].type != TileType.Nothing || x == 0 || y == 0 || x == mapSize.X - 1 || y == mapSize.Y - 1)
                    {
                        heatMap[x, y] = 0f;

                        for (int iy = -NEAR_PENALTY_DIST; iy <= NEAR_PENALTY_DIST; ++iy)
                        {
                            for (int ix = -NEAR_PENALTY_DIST; ix <= NEAR_PENALTY_DIST; ++ix)
                            {
                                if (GeneratorHelper.IsInRange(x + ix, y + iy))
                                {
                                    heatMap[x + ix, y + iy] -= NEAR_PENALTY;
                                }
                            }
                        }
                    }
                }
            }

            //cap the heat map values to [0,1]

            /*for (int y = 0; y < mapSize.Y; y++)
             * {
             *  for (int x = 0; x < mapSize.X; x++)
             *  {
             *      if (heatMap[y, x] < 0f)
             *          heatMap[y, x] = 0f;
             *      else if (heatMap[y, x] > 1f)
             *          heatMap[y, x] = 1f;
             *  }
             * }*/

            return(heatMap);
        }