Пример #1
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            Console.WriteLine("\n\nGenerating Entities...");

            var codeMapFile = GetCodeMapFile(opts);

            var template = Path.Combine(codeGenRunner.TemplateFolder, "TrackableClass.razt");

            if (!File.Exists(template))
            {
                throw new GoliathDataException($"template file {template} not found.");
            }

            if (!Directory.Exists(codeGenRunner.WorkingFolder))
            {
                Directory.CreateDirectory(codeGenRunner.WorkingFolder);
            }

            var map = MapConfig.Create(codeMapFile, true);

            map.Settings.AssemblyName         = opts.AssemblyName;
            map.Settings.Namespace            = opts.Namespace;
            map.Settings.AdditionalNamespaces = codeGenRunner.Settings.AdditionalNamespaces;
            map.Settings.GenerateLinkTable    = codeGenRunner.Settings.GenerateLinkTable;

            codeGenRunner.GenerateClasses(map, opts.ExtendedProperties, opts.ExcludedArray);
        }
Пример #2
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            Console.WriteLine("\n\nGenerating for all entities...");

            var codeMapFile = GetCodeMapFile(opts);

            var template = Path.Combine(codeGenRunner.TemplateFolder, opts.TemplateName);

            if (!File.Exists(template))
            {
                throw new GoliathDataException(string.Format("template file {0} not found.", template));
            }

            var map = MapConfig.Create(codeMapFile, true);

            map.Settings.AssemblyName         = opts.AssemblyName;
            map.Settings.Namespace            = opts.Namespace;
            map.Settings.AdditionalNamespaces = codeGenRunner.Settings.AdditionalNamespaces;
            map.Settings.GenerateLinkTable    = codeGenRunner.Settings.GenerateLinkTable;

            if (!Directory.Exists(codeGenRunner.WorkingFolder))
            {
                Directory.CreateDirectory(codeGenRunner.WorkingFolder);
            }

            codeGenRunner.GenerateClassesFromTemplate(map, template, codeGenRunner.WorkingFolder,
                                                      (name, iteration) => GetFileName(name, iteration, opts.OutputFile), opts.ExtendedProperties, opts.ExcludedArray);
        }
Пример #3
0
        public void SetUp()
        {
            string pdir = AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("src"));

            string autoIncrementFileName = "ZooDb_auto_increment.db";
            //string guidFileName = string.Format("ZooDb_guid.{0}.db",  DateTime.Now.Ticks);

            string mappingFolder = Path.Combine(pdir, "src", "Goliath.Data.Tests", "Entities", "WebZoo");
            string scriptFolder  = Path.Combine(pdir, "src", "Goliath.Data.Tests", "Scripts", "Sqlite", "AutoIncrement");
            string dbfile        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, autoIncrementFileName);
            string cs            = string.Format("Data Source={0}; Version=3", dbfile);


            string mapfile = Path.Combine(mappingFolder, MapFileName);

            MapConfig config = MapConfig.Create(mapfile);

            config.Settings.ConnectionString = cs;
            DatabaseInit.CreateSqliteDatabase(config, scriptFolder, dbfile);

            var sessionFactory = new Database().Configure(config)
                                 .RegisterProvider(new SqliteProvider()).Init();

            SessionHelper.SetFactory(sessionFactory);
        }
Пример #4
0
        /// <summary>
        /// Generates the code for each entity map.
        /// </summary>
        /// <param name="templateFile">The templateFile.</param>
        /// <param name="workingFolder">The working folder.</param>
        /// <param name="mapfile">The mapfile.</param>
        /// <param name="fileNameFunction">The file name function.</param>
        /// <param name="excludedTables">The excluded tables.</param>
        /// <param name="properties"></param>
        public void GenerateCodeForEachEntityMap(string templateFile, string workingFolder, string mapfile,
                                                 Func <string, int?, string> fileNameFunction = null, IDictionary <string, string> properties = null, params string[] excludedTables)
        {
            var project = MapConfig.Create(mapfile, true);

            GenerateCodeForEachEntityMap(templateFile, workingFolder, project, fileNameFunction, properties, excludedTables);
        }
Пример #5
0
        /// <summary>
        /// Configures the specified map stream.
        /// </summary>
        /// <param name="mapStream">The map stream.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="sessionStore">The session store.</param>
        /// <param name="generators">The generators.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">mapStream</exception>
        public IConfigurationManager Configure(Stream mapStream, ProjectSettings settings, ISessionStore sessionStore = null, params IKeyGenerator[] generators)
        {
            if (mapStream == null)
            {
                throw new ArgumentNullException(nameof(mapStream));
            }

            var map = settings != null?MapConfig.Create(mapStream, settings, false, generators) : MapConfig.Create(mapStream, false, generators);

            return(Configure(map, sessionStore));
        }
Пример #6
0
        public void Sort_test_if_map_is_sorted()
        {
            string testMapfile = Path.Combine(SessionHelper.BaseDirectory, "TestFiles", "MapConfigTests", "sort_data.map.xml");
            var    config      = MapConfig.Create(testMapfile, true, new FakeIdGenerator());

            //var sorter = new MapSorter();
            //var sorted = sorter.Sort(config.EntityConfigs);
            config.Sort();

            config.Save(@"C:\junk\sortedmap.xml", true);
        }
Пример #7
0
        private void SetUpUpdate(int itemsUpdateCount, int configUpdateCount, int mapXSize = 1, int mapYSize = 1)
        {
            var mapConfig  = MapConfig.Create(mapXSize, mapYSize);
            var coordinate = new Coordinate(0, 0);
            var tiles      = new[] { new Tile(new TileData(null, string.Empty, null), coordinate) };

            var units       = new[] { new Unit(new UnitData(null, string.Empty, null), coordinate) };
            var construct   = new Construct(new ConstructData(null, string.Empty, null), coordinate);
            var constructs  = new[] { construct };
            var strongholds = new Stronghold[1];

            _mockConfigRepository
            .Setup(r => r.GetObservableStream())
            .Returns(Observable.Repeat(mapConfig, configUpdateCount));

            _mockTilesRepository
            .Setup(r => r.GetObservableStream())
            .Returns(Observable.Repeat(tiles, itemsUpdateCount));

            _mockUnitsRepository
            .Setup(r => r.GetObservableStream())
            .Returns(Observable.Create <IReadOnlyList <Unit> >(
                         observer =>
            {
                for (var i = 0; i < itemsUpdateCount; i++)
                {
                    observer.OnNext(new[] { new Unit(new UnitData(null, (i + 1).ToString(), null), coordinate) });
                }

                observer.OnCompleted();

                return(Disposable.Empty);
            }));

            _mockConstructsRepository
            .Setup(r => r.GetObservableStream())
            .Returns(Observable.Repeat(constructs, itemsUpdateCount));

            _mockStrongholdsRepository
            .Setup(r => r.GetObservableStream())
            .Returns(Observable.Repeat(strongholds, itemsUpdateCount));

            _expectedMapWithSetUpMock = new Map(tiles, units, constructs, strongholds, mapConfig);

            _mapGetService = new MapGetService(
                _mockConfigRepository.Object,
                _mockTilesRepository.Object,
                _mockUnitsRepository.Object,
                _mockConstructsRepository.Object,
                _mockStrongholdsRepository.Object
                );
        }
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            var codeMapFile = GetCodeMapFile(opts);
            var map         = MapConfig.Create(codeMapFile, true);

            map.Settings.AssemblyName         = opts.AssemblyName;
            map.Settings.Namespace            = opts.Namespace;
            map.Settings.AdditionalNamespaces = codeGenRunner.Settings.AdditionalNamespaces;
            map.Settings.GenerateLinkTable    = codeGenRunner.Settings.GenerateLinkTable;

            if (string.IsNullOrWhiteSpace(opts.TemplateName))
            {
                throw new GoliathDataException("Template file to use is required for generate operation. Please make sure that -in=\"Template_File_name.razt\" argument is passed in.");
            }

            var template = Path.Combine(codeGenRunner.TemplateFolder, opts.TemplateName);

            if (!File.Exists(template))
            {
                throw new GoliathDataException($"template file {template} not found.");
            }

            if (string.IsNullOrWhiteSpace(opts.OutputFile))
            {
                throw new GoliathDataException("Output file is required for generate operation. Please make sure that -out=\"YOUR_FILE.EXT\" argument is passed in.");
            }

            if (!Directory.Exists(codeGenRunner.WorkingFolder))
            {
                Directory.CreateDirectory(codeGenRunner.WorkingFolder);
            }

            if (!string.IsNullOrWhiteSpace(opts.EntityModel))
            {
                Logger.Log(LogLevel.Debug, $"Extracting model {opts.EntityModel} from map entity models.");

                if (map.EntityConfigs.TryGetValue(opts.EntityModel, out var entMap))
                {
                    codeGenRunner.GenerateCodeFromTemplate(entMap, template, codeGenRunner.WorkingFolder, opts.OutputFile);
                }
            }
            else
            {
                codeGenRunner.GenerateCodeFromTemplate(map, template, codeGenRunner.WorkingFolder, opts.OutputFile, opts.ExtendedProperties);
            }
        }
Пример #9
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            var codeMapFile = GetCodeMapFile(opts);
            var mainMap     = MapConfig.Create(codeMapFile, true);

            string mapfile2 = opts.TemplateName;

            if (!File.Exists(mapfile2))
            {
                throw new GoliathDataException(string.Format("map file {0} does not exist", mapfile2));
            }

            var secondMap = MapConfig.Create(mapfile2, true);

            mainMap.MergeMap(secondMap);
            CodeGenRunner.ProcessMappedStatements(mainMap);
            mainMap.Save(codeMapFile, true);
        }
Пример #10
0
        /// <summary>
        /// Configures the specified map file.
        /// </summary>
        /// <param name="mapFile">The map file.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="sessionStore">The session store.</param>
        /// <returns></returns>
        public IConfigurationManager Configure(string mapFile, ProjectSettings settings, ISessionStore sessionStore = null, params IKeyGenerator[] generators)
        {
            if (string.IsNullOrWhiteSpace(mapFile))
            {
                throw new ArgumentNullException(nameof(mapFile));
            }

            MapConfig map;

            if (settings != null)
            {
                map = MapConfig.Create(mapFile, settings, false, generators);
            }
            else
            {
                map = MapConfig.Create(mapFile, false, generators);
            }

            return(Configure(map, sessionStore));
        }
Пример #11
0
        private static void CreateAndSaveAsset(GameEnvironment gameEnvironment,
                                               string fullPath,
                                               string levelDataFilename,
                                               string gameEnvironmentFilename,
                                               string mapConfigFilename,
                                               string worldConfigFilename,
                                               string environmentName)
        {
            //create new instances as they cannot be referencing the old configs
            var levelDataScriptable = LevelDataScriptable.Create(
                gameEnvironment.LevelData
                );
            var mapConfiguration = MapConfig.Create(
                gameEnvironment.MapConfiguration.GetMap2DActualWidth(),
                gameEnvironment.MapConfiguration.GetMap2DActualHeight()
                );
            var worldConfiguration = WorldConfig.Create(
                gameEnvironment.WorldConfiguration.UpAxis,
                gameEnvironment.WorldConfiguration.InnerRadius
                );

            var gameEnvironmentScriptable = GameEnvironmentScriptable.Create(
                environmentName,
                mapConfiguration,
                worldConfiguration,
                levelDataScriptable
                );

            AssetDatabase.CreateAsset(levelDataScriptable, $"{fullPath}/{levelDataFilename}");
            AssetDatabase.CreateAsset(mapConfiguration, $"{fullPath}/{mapConfigFilename}");
            AssetDatabase.CreateAsset(worldConfiguration, $"{fullPath}/{worldConfigFilename}");
            AssetDatabase.CreateAsset(
                gameEnvironmentScriptable,
                $"{fullPath}/{gameEnvironmentFilename}"
                );
        }
Пример #12
0
        /// <summary>
        /// Loads the specified map file.
        /// </summary>
        /// <param name="mapFile">The map file.</param>
        /// <returns></returns>
        public IConfigurationManager Load(string mapFile)
        {
            MapConfig config = MapConfig.Create(mapFile);

            return(Load(config));
        }
Пример #13
0
 public void SetUp()
 {
     _service      = new LevelDataScriptableValidationService();
     _3X3MapConfig = MapConfig.Create(3, 3);
 }
Пример #14
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            bool zipFile = false || !string.IsNullOrWhiteSpace(opts.TemplateName) && opts.TemplateName.ToUpper().EndsWith(".ZIP");

            var codeMapFile = GetCodeMapFile(opts);
            var map         = MapConfig.Create(codeMapFile, true);

            map.Settings.AssemblyName         = opts.AssemblyName;
            map.Settings.Namespace            = opts.Namespace;
            map.Settings.AdditionalNamespaces = codeGenRunner.Settings.AdditionalNamespaces;

            var importRdbms     = GetRdbms(opts.ImportSqlDialect);
            var providerFactory = new ProviderFactory();
            var dbConnector     = providerFactory.CreateDbConnector(importRdbms, opts.ConnectionString);

            //var dialect = providerFactory.CreateDialect(importRdbms);

            Logger.Log(LogLevel.Debug, $"Importing using {importRdbms}");

            if (!Directory.Exists(codeGenRunner.WorkingFolder))
            {
                Directory.CreateDirectory(codeGenRunner.WorkingFolder);
            }

            if (zipFile)
            {
                var inputFile = Path.Combine(opts.WorkingFolder, opts.TemplateName);
                if (!File.Exists(inputFile))
                {
                    throw new ArgumentException($"Could not find the input file: {inputFile}");
                }

                using (var fs = File.Open(inputFile, FileMode.Open, FileAccess.Read))
                {
                    fs.Unzip(opts.WorkingFolder);
                }
            }

            var files = Directory.EnumerateFiles(opts.WorkingFolder, "*.xml").ToDictionary(Path.GetFileNameWithoutExtension);

            using (var conn = dbConnector.CreateNewConnection() as SqlConnection)
            {
                if (conn == null)
                {
                    throw new InvalidOperationException("Import is only supported on SQL Server for now.");
                }

                conn.Open();
                var transaction = conn.BeginTransaction();

                try
                {
                    foreach (var table in map.EntityConfigs)
                    {
                        if (!files.TryGetValue(table.Name, out var file))
                        {
                            continue;
                        }

                        Logger.Log(LogLevel.Debug, $"Reading: {file}");
                        ImportData(map, conn, transaction, opts, file);
                    }

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    transaction.Dispose();
                }
            }
        }
Пример #15
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            var codeMapFile = GetCodeMapFile(opts);
            var map         = MapConfig.Create(codeMapFile, true);

            map.Settings.AssemblyName         = opts.AssemblyName;
            map.Settings.Namespace            = opts.Namespace;
            map.Settings.AdditionalNamespaces = codeGenRunner.Settings.AdditionalNamespaces;
            map.Settings.GenerateLinkTable    = codeGenRunner.Settings.GenerateLinkTable;

            var providerFactory = new ProviderFactory();

            var importRdbms = GetRdbms(opts.ImportSqlDialect);
            var exportRdbms = GetRdbms(opts.ExportSqlDialect);

            var dbConnector = providerFactory.CreateDbConnector(importRdbms, opts.ConnectionString);

            if (string.IsNullOrWhiteSpace(opts.TemplateName))
            {
                throw new GoliathDataException("Template file to use is required for generate operation. Please make sure that -in=\"Template_File_name.razt\" argument is passed in.");
            }

            var template = Path.Combine(codeGenRunner.TemplateFolder, opts.TemplateName);

            if (!File.Exists(template))
            {
                throw new GoliathDataException($"template file {template} not found.");
            }

            if (string.IsNullOrWhiteSpace(opts.OutputFile))
            {
                throw new GoliathDataException("Output file is required for generate operation. Please make sure that -out=\"YOUR_FILE.EXT\" argument is passed in.");
            }

            if (string.IsNullOrWhiteSpace(opts.Include))
            {
                Logger.Log(LogLevel.Warning, "No table to read for enum provided. Please make sure you set the include parameter properly");
                return;
            }

            var tables = opts.Include.Split(new string[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);


            var exporter = new DataExporterAdapter(providerFactory.CreateDialect(importRdbms), providerFactory.CreateDialect(exportRdbms),
                                                   dbConnector, new TypeConverterStore());

            var counter = 0;

            List <string>      errors = new List <string>();
            List <ExportModel> models = new List <ExportModel>();

            foreach (var tbl in tables)
            {
                try
                {
                    Logger.Log(LogLevel.Info, $"Processing entity {tbl}");
                    var entityMap = map.GetEntityMap($"{opts.Namespace}.{tbl}");

                    counter++;
                    var data = exporter.Export(entityMap, opts.ExportIdentityColumn, opts.ExportDatabaseGeneratedColumns);
                    //var fileName = GetFileName(entityMap.Name, counter, opts.OutputFile);

                    if (data == null || data.DataBag.Count == 0)
                    {
                        Logger.Log(LogLevel.Warning, $"No data found for {tbl}");
                        continue;
                    }

                    models.Add(data);
                }
                catch (Exception ex)
                {
                    errors.Add($"Error entity [{tbl}]: {ex.ToString()}");
                }
            }

            if (!Directory.Exists(codeGenRunner.WorkingFolder))
            {
                Directory.CreateDirectory(codeGenRunner.WorkingFolder);
            }

            codeGenRunner.GenerateCodeFromTemplate(models, template, codeGenRunner.WorkingFolder, opts.OutputFile, opts.ExtendedProperties);
            Logger.Log(LogLevel.Info, $"Enums generated file: {opts.OutputFile}");

            if (errors.Count > 0)
            {
                Console.WriteLine($"\n\nEncountered {errors.Count} Errors");
                Console.ForegroundColor = ConsoleColor.Red;
                foreach (var err in errors)
                {
                    Console.WriteLine(err);
                }

                Console.ResetColor();
            }
        }
Пример #16
0
 public void SetUp()
 {
     _coordinateService = new CoordinateService();
     _3X3Config         = MapConfig.Create(3, 3);
 }
Пример #17
0
        public override void Execute(AppOptionInfo opts, CodeGenRunner codeGenRunner)
        {
            var codeMapFile = GetCodeMapFile(opts);
            var map         = MapConfig.Create(codeMapFile, true);

            map.Settings.AssemblyName         = opts.AssemblyName;
            map.Settings.Namespace            = opts.Namespace;
            map.Settings.AdditionalNamespaces = codeGenRunner.Settings.AdditionalNamespaces;

            var providerFactory = new ProviderFactory();

            var importRdbms = GetRdbms(opts.ImportSqlDialect);
            var exportRdbms = GetRdbms(opts.ExportSqlDialect);

            var  dbConnector = providerFactory.CreateDbConnector(importRdbms, opts.ConnectionString);
            bool exportToxml = string.IsNullOrWhiteSpace(opts.TemplateName);

            if (!exportToxml && string.IsNullOrWhiteSpace(opts.TemplateName))
            {
                throw new GoliathDataException("Template file to use is required for generate operation. Please make sure that -in=\"Template_File_name.razt\" argument is passed in.");
            }

            var template = Path.Combine(codeGenRunner.TemplateFolder, opts.TemplateName ?? "");

            if (!exportToxml && !File.Exists(template))
            {
                throw new GoliathDataException($"template file {template} not found.");
            }

            if (string.IsNullOrWhiteSpace(opts.OutputFile))
            {
                throw new GoliathDataException("Output file is required for generate operation. Please make sure that -out=\"YOUR_FILE.EXT\" argument is passed in.");
            }

            var exporter = new DataExporterAdapter(providerFactory.CreateDialect(importRdbms), providerFactory.CreateDialect(exportRdbms),
                                                   dbConnector, new TypeConverterStore());

            List <string>    errors       = new List <string>();
            List <EntityMap> mapsToImport = new List <EntityMap>();

            if (!string.IsNullOrWhiteSpace(opts.Include))
            {
                var split = opts.Include.Split(new string[] { ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var s in split)
                {
                    if (s.StartsWith("*"))
                    {
                        var q = map.EntityConfigs.Where(c => c.Name.EndsWith(s.Trim().Replace("*", string.Empty))).ToList();
                        if (q.Count > 0)
                        {
                            mapsToImport.AddRange(q);
                        }
                    }

                    if (s.EndsWith("*"))
                    {
                        var q = map.EntityConfigs.Where(c => c.Name.StartsWith(s.Trim().Replace("*", string.Empty))).ToList();
                        if (q.Count > 0)
                        {
                            mapsToImport.AddRange(q);
                        }
                    }

                    var query = map.EntityConfigs.Where(c => c.Name.Equals(s.Trim()));
                    mapsToImport.AddRange(query);
                }
            }
            else
            {
                string[] split = new string[] { };
                if (!string.IsNullOrWhiteSpace(opts.Excluded))
                {
                    split = opts.Excluded.Split(new string[] { ",", "|" }, StringSplitOptions.RemoveEmptyEntries);
                }

                foreach (var mapEntityConfig in map.EntityConfigs)
                {
                    if (IsExcluded(mapEntityConfig.Name, split))
                    {
                        continue;
                    }
                    mapsToImport.Add(mapEntityConfig);
                }
            }

            var files = new List <string>();

            foreach (var entityMap in mapsToImport)
            {
                try
                {
                    var data = exporter.Export(entityMap, opts.ExportIdentityColumn, opts.ExportDatabaseGeneratedColumns);
                    if (data == null || data.DataBag.Count == 0)
                    {
                        continue;
                    }

                    if (exportToxml)
                    {
                        ExportToXml(data, opts, entityMap, codeGenRunner, files);
                    }
                    else
                    {
                        ExportToSql(data, opts, entityMap, codeGenRunner, template, files);
                    }
                }
                catch (Exception ex)
                {
                    errors.Add($"Error table [{entityMap.TableName}]: {ex}");
                }
            }

            if (errors.Count > 0)
            {
                Logger.Log(LogLevel.Warning, $"\n\nEncountered {errors.Count} Errors");
                Console.ForegroundColor = ConsoleColor.Red;
                foreach (var err in errors)
                {
                    Logger.Log(LogLevel.Error, err);
                }

                throw new Exception($"Export completed with {errors.Count} errors.");
            }

            if (opts.Compress)
            {
                var dbName = FileHelperMethods.GetDatabaseNameFromConnectionString(opts.ConnectionString);
                Compress(opts, $"{dbName}_exports.zip", files);
                DeleteAll(files);
            }
        }