Beispiel #1
0
        // Invokes the code generator discovered via the host and options
        internal static string GenerateCode(ICodeGenerationHost host, ClientCodeGenerationOptions options, IEnumerable <Type> entityTypes)
        {
            IClientCodeGenerator generator = CreateCodeGenerator(host, options);
            EntityCatalog        catalog   = new EntityCatalog(entityTypes, host as ILogger);

            return(generator.GenerateCode(host, catalog.EntityDescriptions, options));
        }
Beispiel #2
0
        public void LoadEntities(List <EntityWithKey> entities, string storagePath, string path, bool useLock = false)
        {
            try
            {
                entityStructures = serializedStorageClient.GetEntityStructures(path);
                catalog          = serializedStorageClient.GetCatalog(storagePath);

                logger.StartNewLog();

                // Restore the entities and its dependencies.
                foreach (var entity in entities)
                {
                    EntityStructure entityStructure = entityStructures.Find(entity.EntityName);
                    if (entityStructure == null)
                    {
                        throw new TdsLogicException("The given entity/table name (" + entity.EntityName + ") is not found.");
                    }

                    InnerLoadEntity(entity.EntityName, entity.PrimaryKeyValues, storagePath, useLock);
                }

                dbClient.ExecuteTransaction();
            }
            catch (Exception exception)
            {
                visitedEntities.Clear();
                lockedEntities.Clear();

                throw exception;
            }

            visitedEntities.Clear();
            lockedEntities.Clear();
        }
Beispiel #3
0
        public void EntityCatalog_Ctors()
        {
            IEnumerable <string> empty  = new string[0];
            ConsoleLogger        logger = new ConsoleLogger();

            // Ctor taking assemblies -- null arg tests
            ExceptionHelper.ExpectArgumentNullExceptionStandard(() => new EntityCatalog((IEnumerable <string>)null, logger), "assembliesToLoad");
            ExceptionHelper.ExpectArgumentNullExceptionStandard(() => new EntityCatalog(empty, null), "logger");

            // Ctor taking multiple types -- null arg tests
            ExceptionHelper.ExpectArgumentNullExceptionStandard(() => new EntityCatalog((IEnumerable <Type>)null, logger), "entityTypes");
            ExceptionHelper.ExpectArgumentNullExceptionStandard(() => new EntityCatalog(new[] { typeof(EC_Entity) }, null), "logger");

            // Ctor taking assemblies -- legit
            string[] realAssemblies = new string[] { this.GetType().Assembly.Location,
                                                     typeof(string).Assembly.Location };

            // Assembly based ctors are tested more deeply in other test methods

            // Ctor taking multiple type -- legit
            var dsc          = new EntityCatalog(new[] { typeof(EC_Entity) }, logger);
            var descriptions = dsc.EntityDescriptions;

            Assert.IsNotNull(descriptions, "Did not expect null descriptions");
            Assert.AreEqual(1, descriptions.Count(), "Expected exactly one domain service description");
        }
Beispiel #4
0
        public void EntityCatalog_Message_BadImageFormat()
        {
            // Create fake DLL with bad image
            string assemblyFileName = Path.Combine(Path.GetTempPath(), (Guid.NewGuid().ToString() + ".dll"));

            File.WriteAllText(assemblyFileName, "neener neener neener");

            ConsoleLogger logger = new ConsoleLogger();
            EntityCatalog dsc    = new EntityCatalog(new string[] { assemblyFileName }, logger);
            ICollection <EntityDescription> descriptions = dsc.EntityDescriptions;

            Assert.IsNotNull(descriptions);
            Assert.AreEqual(0, descriptions.Count);
            Assert.AreEqual(0, logger.ErrorMessages.Count);
            Assert.AreEqual(0, logger.WarningMessages.Count);

            // Need to synthesize exactly the same message we'd expect from failed assembly load
            string exceptionMessage = null;

            try
            {
                AssemblyName.GetAssemblyName(assemblyFileName);
            }
            catch (BadImageFormatException bife)
            {
                exceptionMessage = bife.Message;
            }
            finally
            {
                File.Delete(assemblyFileName);
            }
            string expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Error, assemblyFileName, exceptionMessage);

            TestHelper.AssertContainsMessages(logger, expectedMessage);
        }
Beispiel #5
0
        public void EntityCatalog_Message_FileNotFound_Continues()
        {
            string assemblyFileName = @"c:\Nowhere\DontExist.dll";

            ConsoleLogger                   logger       = new ConsoleLogger();
            IEnumerable <string>            assemblies   = new[] { assemblyFileName, this.GetType().Assembly.Location };
            EntityCatalog                   dsc          = new EntityCatalog(assemblies, logger);
            ICollection <EntityDescription> descriptions = dsc.EntityDescriptions;

            Assert.IsNotNull(descriptions);

            // Need to synthesize exactly the same message we'd expect from failed assembly load
            string exceptionMessage = null;

            try
            {
                AssemblyName.GetAssemblyName(assemblyFileName);
            }
            catch (FileNotFoundException fnfe)
            {
                exceptionMessage = fnfe.Message;
            }
            string expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Error, assemblyFileName, exceptionMessage);

            TestHelper.AssertContainsMessages(logger, expectedMessage);

            Assert.IsTrue(descriptions.Count > 0);
        }
Beispiel #6
0
        public void EntityCatalog_Message_FileNotFound()
        {
            var assemblyFileName = @"c:\Nowhere\DontExist.dll";
            var logger           = new ConsoleLogger();
            var dsc          = new EntityCatalog(new[] { assemblyFileName }, logger);
            var descriptions = dsc.EntityDescriptions;

            Assert.IsNotNull(descriptions);
            Assert.AreEqual(0, descriptions.Count);
            Assert.AreEqual(0, logger.ErrorMessages.Count);
            Assert.AreEqual(0, logger.WarningMessages.Count);

            // Need to synthesize exactly the same message we'd expect from failed assembly load
            string exceptionMessage = null;

            try
            {
                AssemblyName.GetAssemblyName(assemblyFileName);
            }
            catch (FileNotFoundException fnfe)
            {
                exceptionMessage = fnfe.Message;
            }
            string expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Error, assemblyFileName, exceptionMessage);

            TestHelper.AssertContainsMessages(logger, expectedMessage);
        }
Beispiel #7
0
        public void EntityCatalog_Ignore_Entity_No_Default_Constructor()
        {
            var logger       = new ConsoleLogger();
            var dsc          = new EntityCatalog(new [] { typeof(EC_Entity_No_Default_Constructor) }, logger);
            var descriptions = dsc.EntityDescriptions;

            Assert.IsNotNull(descriptions);
            Assert.AreEqual(0, descriptions.Count);
        }
Beispiel #8
0
 public void SaveCatalog(EntityCatalog catalog, string path)
 {
     try
     {
         Serialize <EntityCatalog>(catalog, path + "\\Catalog.xml");
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
Beispiel #9
0
        private string GenerateCode()
        {
            var options = new ClientCodeGenerationOptions
            {
                Language            = _isCSharp ? "C#" : "VisualBasic",
                ClientProjectPath   = "MockProject.proj",
                ClientRootNamespace = "TestRootNS",
                UseFullTypeNames    = _useFullTypeNames
            };

            var host      = TestHelper.CreateMockCodeGenerationHost(ConsoleLogger, MockSharedCodeService);
            var generator = (_isCSharp) ? (CodeDomClientCodeGenerator) new CSharpCodeDomClientCodeGenerator() : (CodeDomClientCodeGenerator) new VisualBasicCodeDomClientCodeGenerator();

            _entityCatalog = new EntityCatalog(_entityTypes, ConsoleLogger);

            string generatedCode = generator.GenerateCode(host, _entityCatalog.EntityDescriptions, options);

            return(generatedCode);
        }
Beispiel #10
0
        public EntityCatalog GetCatalog(string storageFolder)
        {
            EntityCatalog catalog = null;

            try
            {
                catalog = Deserialize <EntityCatalog>(Path.Combine(storageFolder, Consts.Structure.STRUCTURE_FILE_DEFAULT_NAME));
            }
            catch (FileNotFoundException)
            {
                catalog = new EntityCatalog();
            }
            catch (Exception exception)
            {
                throw exception;
            }

            return(catalog);
        }
Beispiel #11
0
    public GameManager()
    {
        SpawnEntityFromConfig(EntityCatalog.TestGetPlayerConfig(), () => { return(Vector2.zero); });
        for (int i = 0; i < 10; ++i)
        {
            SpawnEntityFromConfig(EntityCatalog.TestGetEnemyConfig(), () => { return(new Vector2(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f) - 15)); });
        }
        Events             = new GameEvents();
        Events.EntityDied += UntrackDeadEntities;
        uint _spawnCounter = 0;

        OnFixedUpdate += () => {
            if (_spawnCounter == 60)
            {
                SpawnEntityFromConfig(EntityCatalog.TestGetEnemyConfig(), () => { return(new Vector2(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f) - 15)); });
                _spawnCounter = 0;
            }
            _spawnCounter++;
        };
    }
Beispiel #12
0
        static public EntityCatalog[] GenEntityCatalogs(this IList <EntityTable> tables)
        {
            List <EntityCatalog> catalogs = new List <EntityCatalog>();
            var tableGroupMap             = tables.GroupBy(table => table.Namespace);

            foreach (IGrouping <string, EntityTable> tableGroup in tableGroupMap)
            {
                var catalog = new EntityCatalog()
                {
                    Name = tableGroup.Key
                };
                foreach (var entityTable in tableGroup.ToList())
                {
                    var digest = entityTable.GenEntityDigest();
                    catalog.Digests.Add(digest);
                }
                catalogs.Add(catalog);
            }
            return(catalogs.ToArray());
        }
Beispiel #13
0
        public void EntityCatalog_Finds_All_Entities()
        {
            var logger     = new ConsoleLogger();
            var assemblies = new List <string>();

            // Add our current unit test assembly to those to load
            assemblies.Add(GetType().Assembly.Location);

            var expectedEntities = 0;

            foreach (var t in GetType().Assembly.GetExportedTypes())
            {
                if (IsEntity(t))
                {
                    ++expectedEntities;
                }
            }

            // Add all our assy references and also count any Entities there (don't expect any)
            foreach (AssemblyName an in GetType().Assembly.GetReferencedAssemblies())
            {
                var a = Assembly.Load(an);
                assemblies.Add(a.Location);
                foreach (var t in a.GetExportedTypes())
                {
                    if (IsEntity(t))
                    {
                        ++expectedEntities;
                    }
                }
            }

            var dsc          = new EntityCatalog(assemblies, logger);
            var descriptions = dsc.EntityDescriptions;

            Assert.IsNotNull(descriptions);
            Assert.IsTrue(descriptions.Count >= expectedEntities);
        }
Beispiel #14
0
        public void SaveEntities(List <EntityWithKey> entities, string storageFolder, string pathToStructure, bool useLock = false, bool overwrite = false)
        {
            try
            {
                entityStructures = serializedStorageClient.GetEntityStructures(pathToStructure);
                catalog          = serializedStorageClient.GetCatalog(storageFolder);
                serializedStorageClient.BeginTransaction();

                logger.StartNewLog();

                // Saves the entities and their dependencies.
                foreach (var entity in entities)
                {
                    EntityStructure entityStructure = entityStructures.Find(entity.EntityName);
                    if (entityStructure == null)
                    {
                        throw new TdsLogicException("The given entity/table name (" + entity.EntityName + ") is not found.");
                    }

                    InnerSaveEntity(entity.EntityName, entity.PrimaryKeyValues, storageFolder, useLock, overwrite);
                }

                serializedStorageClient.ExecuteTransaction();
                serializedStorageClient.SaveCatalog(catalog, storageFolder);
            }
            catch (Exception exception)
            {
                visitedEntities.Clear();
                lockedEntities.Clear();

                throw exception;
            }

            visitedEntities.Clear();
            lockedEntities.Clear();
        }
Beispiel #15
0
        /// <summary>
        /// Validates code gen for a specific language by comparing it against a file containing the expected output.
        /// </summary>
        /// <param name="codeGenOptions">The options specifying the type of validation to perform</param>
        /// <returns>A command that updates the comparison file</returns>
        internal static string ValidateLanguageCodeGen(CodeGenValidationOptions codeGenOptions)
        {
            Assert.IsFalse(string.IsNullOrEmpty(codeGenOptions.Language));

            var outDataDir  = GetOutputTestDataDir(codeGenOptions.RelativeDeployDir);
            var extension   = ExtensionFromLanguage(codeGenOptions.Language);
            var diffMessage = string.Empty;

            // Compose the abs path to where the test file got deployed by MSTest
            string referenceFileName = TestHelper.GetTestFileName(codeGenOptions.RelativeDeployDir, codeGenOptions.BaseReferenceFileName + extension);

            Assert.IsTrue(File.Exists(referenceFileName), "Cannot find reference file " + referenceFileName);
            string generatedCode = string.Empty;

            ClientCodeGenerationOptions options = new ClientCodeGenerationOptions()
            {
                Language            = codeGenOptions.Language,
                ClientRootNamespace = codeGenOptions.RootNamespace,
                ClientProjectPath   = "MockProject.proj",
                UseFullTypeNames    = codeGenOptions.UseFullTypeNames
            };

            MockCodeGenerationHost host  = TestHelper.CreateMockCodeGenerationHost(codeGenOptions.Logger, codeGenOptions.SharedCodeService);
            ILogger              logger  = host as ILogger;
            EntityCatalog        catalog = new EntityCatalog(codeGenOptions.EntityTypes, logger);
            IClientCodeGenerator generator;

            using (ClientCodeGenerationDispatcher dispatcher = new ClientCodeGenerationDispatcher())
            {
                generator = dispatcher.FindCodeGenerator(host, options, /*compositionAssemblies*/ null, /*codeGeneratorName*/ null);
            }
            Assert.IsNotNull(generator, "Failed to find a code generator");
            generatedCode = generator.GenerateCode(host, catalog.EntityDescriptions, options);

            ConsoleLogger consoleLogger = logger as ConsoleLogger;
            string        errors        = consoleLogger == null ? "" : consoleLogger.Errors;

            Assert.IsTrue(generatedCode.Length > 0, "No code was generated: " + errors);

            // Dump the generated code into a file for comparison
            bool   isCSharp          = options.Language.Equals("C#", StringComparison.InvariantCultureIgnoreCase);
            string generatedFileName = Path.Combine(outDataDir, Path.GetFileName(referenceFileName) + ".testgen");

            File.WriteAllText(generatedFileName, generatedCode);

            // TODO: (ron M3) Solve inability to get right MSBuild after checkin
            // First see if we compile
            List <string> referenceAssemblies = CompilerHelper.GetClientAssemblies(codeGenOptions.RelativeDeployDir);
            List <string> files = new List <string>();

            files.Add(generatedFileName);

            // Unconditionally force generation of Xml doc comments to catch errors
            string documentationFile = Path.GetTempFileName();

            try
            {
                if (isCSharp)
                {
                    files.AddRange(codeGenOptions.SharedFiles.Where(sharedFile => Path.GetExtension(sharedFile).Equals(".cs")));
                    CompilerHelper.CompileCSharpSource(files, referenceAssemblies, documentationFile);
                }
                else
                {
                    files.AddRange(codeGenOptions.SharedFiles.Where(sharedFile => Path.GetExtension(sharedFile).Equals(".vb")));
                    CompilerHelper.CompileVisualBasicSource(files, referenceAssemblies, options.ClientRootNamespace, documentationFile);
                }
            }
            finally
            {
                File.Delete(documentationFile);
            }

            // Do the diff
            if (codeGenOptions.FailOnDiff)
            {
                TestHelper.ValidateFilesEqual(codeGenOptions.RelativeTestDir, codeGenOptions.RelativeDeployDir, generatedFileName, referenceFileName, codeGenOptions.Language);
            }
            else
            {
                TestHelper.FilesMatch(codeGenOptions.RelativeTestDir, codeGenOptions.RelativeDeployDir, generatedFileName, referenceFileName, codeGenOptions.Language, out diffMessage);
            }

            return(diffMessage);
        }