public void SharedCodeService_Methods()
        {
            string projectPath, outputPath;

            TestHelper.GetProjectPaths("STS4", out projectPath, out outputPath);
            var clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);

            var logger = new ConsoleLogger();

            using (var scs = CodeGenHelper.CreateSharedCodeService(clientProjectPath, logger))
            {
                CodeMemberShareKind shareKind = scs.GetMethodShareKind(typeof(TestValidator).AssemblyQualifiedName, "IsValid", new string[] { typeof(TestEntity).AssemblyQualifiedName, typeof(ValidationContext).AssemblyQualifiedName });
                Assert.AreEqual(CodeMemberShareKind.SharedByReference, shareKind, "Expected TestValidator.IsValid to be shared by reference");

                shareKind = scs.GetMethodShareKind(typeof(TestEntity).AssemblyQualifiedName, "ServerAndClientMethod", new string[0]);
                Assert.AreEqual(CodeMemberShareKind.SharedByReference, shareKind, "Expected TestValidator.ServerAndClientMethod to be shared by reference");

                shareKind = scs.GetMethodShareKind(typeof(TestEntity).AssemblyQualifiedName, "ServerMethod", new string[0]);
                Assert.AreEqual(CodeMemberShareKind.NotShared, shareKind, "Expected TestValidator.ServerMethod not to be shared");

                shareKind = scs.GetMethodShareKind(typeof(TestValidatorServer).AssemblyQualifiedName, "IsValid", new string[] { typeof(TestEntity).AssemblyQualifiedName, typeof(ValidationContext).AssemblyQualifiedName });
                Assert.AreEqual(CodeMemberShareKind.NotShared, shareKind, "Expected TestValidator.IsValid not to be shared");

                TestHelper.AssertNoErrorsOrWarnings(logger);
            }
        }
Exemple #2
0
        /// <summary>
        /// Creates a new CreateClientFilesTask instance to use to generate code
        /// </summary>
        /// <param name="relativeTestDir"></param>
        /// <param name="includeClientOutputAssembly">if <c>true</c> include clients own output assembly in analysis</param>
        /// <returns>A new task instance that can be invoked to do code gen</returns>
        public static CreateClientFilesTask CreateClientFilesTaskInstance_CopyClientProjectToOutput(string serverProjectPath, string clientProjectPath, bool includeClientOutputAssembly)
        {
            CreateClientFilesTask task = new CreateClientFilesTask();

            MockBuildEngine mockBuildEngine = new MockBuildEngine();

            task.BuildEngine = mockBuildEngine;

            task.Language = "C#";

            task.ServerProjectPath         = serverProjectPath;
            task.ServerAssemblies          = new TaskItem[] { new TaskItem(CodeGenHelper.ServerClassLibOutputAssembly(task.ServerProjectPath)) };
            task.ServerReferenceAssemblies = MsBuildHelper.AsTaskItems(CodeGenHelper.ServerClassLibReferences(task.ServerProjectPath)).ToArray();
            task.ClientFrameworkPath       = CodeGenHelper.GetRuntimeDirectory();

            // Generate the code to our deployment directory
            string tempFolder = CodeGenHelper.GenerateTempFolder();

            task.OutputPath        = Path.Combine(tempFolder, "FileWrites");
            task.GeneratedCodePath = Path.Combine(tempFolder, "Generated_Code");

            string clientProjectFileName = Path.GetFileName(clientProjectPath);
            string clientProjectDestPath = Path.Combine(tempFolder, clientProjectFileName);

            File.Copy(clientProjectPath, clientProjectDestPath);
            task.ClientProjectPath         = clientProjectDestPath;
            task.ClientReferenceAssemblies = MsBuildHelper.AsTaskItems(CodeGenHelper.ClientClassLibReferences(clientProjectPath, includeClientOutputAssembly)).ToArray();
            task.ClientSourceFiles         = MsBuildHelper.AsTaskItems(CodeGenHelper.ClientClassLibSourceFiles(clientProjectPath)).ToArray();

            return(task);
        }
Exemple #3
0
        public void SharedSourceFiles_Types()
        {
            string projectPath = null;
            string outputPath  = null;

            TestHelper.GetProjectPaths("SFT", out projectPath, out outputPath);
            string        clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);
            List <string> sourceFiles       = CodeGenHelper.ClientClassLibSourceFiles(clientProjectPath);
            ConsoleLogger logger            = new ConsoleLogger();
            FilenameMap   filenameMap       = new FilenameMap();

            using (SourceFileLocationService locationService = new SourceFileLocationService(new[] { new PdbSourceFileProviderFactory(/*symbolSearchPath*/ null, logger) }, filenameMap))
            {
                SharedSourceFiles ssf = new SharedSourceFiles(locationService, filenameMap, sourceFiles);

                int[] fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateTypeKey(typeof(TestEntity)));
                Assert.IsNotNull(fileIds, "Expected TestEntity to have non-null file ID's because it is shared");
                Assert.AreEqual(2, fileIds.Length, "Expected TestEntity to be found in exactly 2 files");
                foreach (int i in fileIds)
                {
                    string file = filenameMap[i];
                    Assert.IsTrue(file.Contains("TestEntity.linked.cs") || file.Contains("TestEntity.reverse.linked.cs"), "Expected exactly these 2 files to be shared");
                }

                fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateTypeKey(typeof(TestValidator)));
                Assert.IsNotNull(fileIds, "Expected TestValidator to have non-null file ID's because it is shared");
                Assert.AreEqual(1, fileIds.Length, "Expected TestValidator to be found in exactly one file");
                Assert.IsTrue(filenameMap[fileIds[0]].Contains("TestValidator.linked.cs"), "expected this to be the sole shared file for TestValidator");

                fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateTypeKey(typeof(TestValidatorServer)));
                Assert.IsNull(fileIds, "Expected TestValidatorServer to have no shared file ids");
            }
        }
Exemple #4
0
        public void SharedSourceFiles_Methods()
        {
            string projectPath = null;
            string outputPath  = null;

            TestHelper.GetProjectPaths("SFT", out projectPath, out outputPath);
            string        clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);
            List <string> sourceFiles       = CodeGenHelper.ClientClassLibSourceFiles(clientProjectPath);
            ConsoleLogger logger            = new ConsoleLogger();
            FilenameMap   filenameMap       = new FilenameMap();

            using (SourceFileLocationService locationService = new SourceFileLocationService(new[] { new PdbSourceFileProviderFactory(/*symbolSearchPath*/ null, logger) }, filenameMap))
            {
                SharedSourceFiles ssf = new SharedSourceFiles(locationService, filenameMap, sourceFiles);

                int[] fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateMethodKey(typeof(TestValidator).GetMethod("IsValid")));
                Assert.IsNotNull(fileIds, "Expected TestValidator.IsValid to have non-null file ID's because it is shared");
                Assert.AreEqual(1, fileIds.Length, "Expected TestValidator.IsValid to be found in exactly one file");
                Assert.IsTrue(filenameMap[fileIds[0]].Contains("TestValidator.linked.cs"), "Expected TestValidator.IsValid to be in TestValidator.linked.cs");

                fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateMethodKey(typeof(TestEntity).GetMethod("ServerAndClientMethod")));
                Assert.IsNotNull(fileIds, "Expected TestEntity.ServerAndClientMethod to have non-null file ID's because it is shared");
                Assert.AreEqual(1, fileIds.Length, "Expected TestEntity.ServerAndClientMethod to be found in exactly one file");
                Assert.IsTrue(filenameMap[fileIds[0]].Contains("TestEntity.linked.cs"), "Expected TestEntity.ServerAndClientMethod to be in TestEntity.linked.cs");

                fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateMethodKey(typeof(TestEntity).GetMethod("ServerMethod")));
                Assert.IsNull(fileIds, "Expected TestEntity.ServerMethod to have null file ids");

                fileIds = ssf.GetSharedFileIds(CodeMemberKey.CreateMethodKey(typeof(TestValidatorServer).GetMethod("IsValid")));
                Assert.IsNull(fileIds, "Expected TestValidatorServer.IsValid to have null file ids");
            }
        }
        public void SharedCodeService_Types()
        {
            string projectPath, outputPath;

            TestHelper.GetProjectPaths("STS1", out projectPath, out outputPath);
            var clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);

            var logger = new ConsoleLogger();

            using (var scs = CodeGenHelper.CreateSharedCodeService(clientProjectPath, logger))
            {
                // TestEntity is shared because it is linked
                CodeMemberShareKind shareKind = scs.GetTypeShareKind(typeof(TestEntity).AssemblyQualifiedName);
                Assert.AreEqual(CodeMemberShareKind.SharedByReference, shareKind, "Expected TestEntity type to be shared by reference");

                // TestValidator is shared because it is linked
                shareKind = scs.GetTypeShareKind(typeof(TestValidator).AssemblyQualifiedName);
                Assert.AreEqual(CodeMemberShareKind.SharedByReference, shareKind, "Expected TestValidator type to be shared by reference");

                // SharedClass is shared because it is linked
                shareKind = scs.GetTypeShareKind(typeof(SharedClass).AssemblyQualifiedName);
                Assert.IsTrue(shareKind == CodeMemberShareKind.SharedBySource, "Expected SharedClass type to be shared in source");

                // TestValidatorServer exists only on the server and is not shared
                shareKind = scs.GetTypeShareKind(typeof(TestValidatorServer).AssemblyQualifiedName);
                Assert.IsTrue(shareKind == CodeMemberShareKind.NotShared, "Expected TestValidatorServer type not to be shared");

                // CodelessType exists on both server and client, but lacks all user code necessary
                // to determine whether it is shared.  Because it compiles into both projects, it should
                // be considered shared by finding the type in both assemblies
                shareKind = scs.GetTypeShareKind(typeof(CodelessType).AssemblyQualifiedName);
                Assert.IsTrue(shareKind == CodeMemberShareKind.SharedByReference, "Expected CodelessType type to be shared in assembly");
            }
        }
Exemple #6
0
        public void ClientFilesTask_Safe_File_Move()
        {
            CleanClientFilesTask task            = new CleanClientFilesTask();
            MockBuildEngine      mockBuildEngine = new MockBuildEngine();

            task.BuildEngine = mockBuildEngine;

            string tempFolder = CodeGenHelper.GenerateTempFolder();

            try
            {
                // Do a simple move
                string file1 = Path.Combine(tempFolder, "File1.txt");
                string file2 = Path.Combine(tempFolder, "File2.txt");
                File.AppendAllText(file1, "stuff");

                bool success = task.SafeFileMove(file1, file2);
                Assert.IsTrue(success, "SafeFileMove reported failure");

                Assert.IsTrue(File.Exists(file2), "File2 did not get created");
                Assert.IsFalse(File.Exists(file1), "File1 still exists after move");

                string content = File.ReadAllText(file2);
                Assert.AreEqual("stuff", content, "File2 did not get right content");

                string errorMessage = String.Empty;

                // Finally, try a clearly illegal move and catch the error
                using (FileStream fs = new FileStream(file2, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    try
                    {
                        File.Move(file2, file1);
                    }
                    catch (IOException iox)
                    {
                        errorMessage = iox.Message;
                    }
                    success = task.SafeFileMove(file2, file1);
                }

                Assert.IsFalse(success, "Expected illegal move to report failure");

                string expectedWarning = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Rename_File, file2, file1, errorMessage);
                TestHelper.AssertContainsWarnings(mockBuildEngine.ConsoleLogger, expectedWarning);
            }

            finally
            {
                CodeGenHelper.DeleteTempFolder(tempFolder);
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates a new CreateClientFilesTask instance to use to generate code
        /// using the TestWap project.
        /// </summary>
        /// <param name="relativeTestDir"></param>
        /// <returns>A new task instance that can be invoked to do code gen</returns>
        public static CreateClientFilesTask CreateClientFilesTaskInstanceForWAP(string relativeTestDir)
        {
            var    deploymentDir = Path.GetDirectoryName(typeof(CodeGenHelper).Assembly.Location);
            string projectPath, outputPath;

            TestHelper.GetProjectPaths(relativeTestDir, out projectPath, out outputPath);

            Assert.IsTrue(File.Exists(projectPath), "Could not locate " + projectPath + " necessary for test.");
            string serverProjectPath = ServerWapProjectPath(projectPath);
            string clientProjectPath = ClientClassLibProjectPath(projectPath);

            return(CodeGenHelper.CreateClientFilesTaskInstance(serverProjectPath, clientProjectPath, false));
        }
Exemple #8
0
        /// <summary>
        /// Creates a new CreateClientFilesTask instance to use to generate code
        /// </summary>
        /// <param name="relativeTestDir"></param>
        /// <param name="includeClientOutputAssembly">if <c>true</c> include clients own output assembly in analysis</param>
        /// <returns>A new task instance that can be invoked to do code gen</returns>
        public static CreateClientFilesTask CreateClientFilesTaskInstance_CopyClientProjectToOutput(string relativeTestDir, bool includeClientOutputAssembly)
        {
            string deploymentDir = Path.GetDirectoryName(typeof(CodeGenHelper).Assembly.Location);
            string projectPath   = null;
            string outputPath    = null;

            TestHelper.GetProjectPaths(relativeTestDir, out projectPath, out outputPath);

            Assert.IsTrue(File.Exists(projectPath), "Could not locate " + projectPath + " necessary for test.");
            string serverProjectPath = CodeGenHelper.ServerClassLibProjectPath(projectPath);
            string clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);

            return(CodeGenHelper.CreateClientFilesTaskInstance_CopyClientProjectToOutput(serverProjectPath, clientProjectPath, includeClientOutputAssembly));
        }
Exemple #9
0
        public void SharedAssemblies_Matches_MsCorLib()
        {
            Type[] sharedTypes = new Type[] {
                typeof(Int32),
                typeof(string),
                typeof(Decimal),
            };

            Type[] nonSharedTypes = new Type[] {
                typeof(SerializableAttribute),
                typeof(System.Xml.Linq.XElement)
            };

            MethodBase[] sharedMethods = new MethodBase[] {
                typeof(string).GetMethod("CopyTo"),
            };

            string projectPath, outputPath;

            TestHelper.GetProjectPaths("SAT", out projectPath, out outputPath);
            string clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);
            List<string> assemblies = CodeGenHelper.ClientClassLibReferences(clientProjectPath, true);

            var logger = new ConsoleLogger();
            var sa = new SharedAssemblies(assemblies, Enumerable.Empty<string>(), logger);

            foreach (Type t in sharedTypes)
            {
                Type sharedType = sa.GetSharedType(t.AssemblyQualifiedName);
                Assert.IsNotNull(sharedType, "Expected type " + t.Name + " to be considered shared.");
            }

            foreach (MethodBase m in sharedMethods)
            {
                string[] parameterTypes = m.GetParameters().Select<ParameterInfo, string>(p => p.ParameterType.AssemblyQualifiedName).ToArray();
                MethodBase sharedMethod = sa.GetSharedMethod(m.DeclaringType.AssemblyQualifiedName, m.Name, parameterTypes);
                Assert.IsNotNull(sharedMethod, "Expected method " + m.DeclaringType.Name + "." + m.Name + " to be considered shared.");
            }

            foreach (Type t in nonSharedTypes)
            {
                Type sType = sa.GetSharedType(t.AssemblyQualifiedName);
                Assert.IsNull(sType, "Expected type " + t.Name + " to be considered *not* shared.");
            }

        }
        public void SharedCodeService_Properties()
        {
            string projectPath, outputPath;

            TestHelper.GetProjectPaths("STS2", out projectPath, out outputPath);
            var clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);

            var logger = new ConsoleLogger();

            using (var scs = CodeGenHelper.CreateSharedCodeService(clientProjectPath, logger))
            {
                CodeMemberShareKind shareKind = scs.GetPropertyShareKind(typeof(TestEntity).AssemblyQualifiedName, "ServerAndClientValue");
                Assert.AreEqual(CodeMemberShareKind.SharedByReference, shareKind, "Expected TestEntity.ServerAndClientValue property to be shared by reference.");

                shareKind = scs.GetPropertyShareKind(typeof(TestEntity).AssemblyQualifiedName, "TheValue");
                Assert.AreEqual(CodeMemberShareKind.NotShared, shareKind, "Expected TestEntity.TheValue property not to be shared in source.");
            }
        }
Exemple #11
0
        public void SharedTypes_CodeGen_Errors_On_Existing_Generated_Entity()
        {
            CreateClientFilesTask task = null;

            try
            {
                task = CodeGenHelper.CreateClientFilesTaskInstance("STT", /*includeClientOutputAssembly*/ true);
                var mockBuildEngine = (MockBuildEngine)task.BuildEngine;

                bool success = task.Execute();
                Assert.IsFalse(success, "Expected build to fail");
                string entityMsg = string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_EntityTypesCannotBeShared_Reference, "ServerClassLib.TestEntity");
                TestHelper.AssertContainsErrors(mockBuildEngine.ConsoleLogger, entityMsg);
            }
            finally
            {
                CodeGenHelper.DeleteTempFolder(task);
            }
        }
        public void SharedCodeService_Ctors()
        {
            string projectPath = null;
            string outputPath  = null;

            TestHelper.GetProjectPaths("STS5", out projectPath, out outputPath);
            string clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);

            ConsoleLogger logger = new ConsoleLogger();

            using (SharedCodeService sts = CodeGenHelper.CreateSharedCodeService(clientProjectPath, logger))
            {
                ConstructorInfo ctor = typeof(TestValidator).GetConstructor(new Type[] { typeof(string) });
                Assert.IsNotNull("Failed to find string ctor on TestValidator");
                CodeMemberShareKind shareKind = sts.GetMethodShareKind(typeof(TestValidator).AssemblyQualifiedName, ctor.Name, new string[] { typeof(string).AssemblyQualifiedName });
                Assert.AreEqual(CodeMemberShareKind.SharedByReference, shareKind, "Expected TestValidator ctor to be shared by reference");
                TestHelper.AssertNoErrorsOrWarnings(logger);
            }
        }
Exemple #13
0
        public void PdbReader_Finds_Types_Files()
        {
            string projectPath = null;
            string outputPath  = null;

            TestHelper.GetProjectPaths("PDB", out projectPath, out outputPath);
            string        serverProjectPath = CodeGenHelper.ServerClassLibProjectPath(projectPath);
            string        clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);
            ConsoleLogger logger            = new ConsoleLogger();
            FilenameMap   filenameMap       = new FilenameMap();

            using (SourceFileLocationService locationService = new SourceFileLocationService(new[] { new PdbSourceFileProviderFactory(/*symbolSearchPath*/ null, logger) }, filenameMap))
            {
                List <string> files = new List <string>(locationService.GetFilesForType(typeof(TestEntity)));
                Assert.AreEqual(4, files.Count);

                CodeGenHelper.AssertContainsFiles(files, serverProjectPath, new string[] { "TestEntity.cs", "TestEntity.shared.cs", "TestEntity.linked.cs" });
                CodeGenHelper.AssertContainsFiles(files, clientProjectPath, new string[] { "TestEntity.reverse.linked.cs" });
            }
        }
Exemple #14
0
        /// <summary>
        /// Extract the list of assemblies both generated and referenced by client.
        /// Not coincidently, this list is what a client project needs to reference.
        /// </summary>
        /// <returns></returns>
        public static List <string> GetClientAssemblies(string relativeTestDir)
        {
            var assemblies = new List <string>();

            string projectPath, outputPath;   // output path for current project, used to infer output path of test project

            TestHelper.GetProjectPaths(relativeTestDir, out projectPath, out outputPath);

            // Our current project's folder
            var projectDir = Path.GetDirectoryName(projectPath);

            // Folder of project we want to build
            var testProjectDir = Path.GetFullPath(Path.Combine(projectDir, @"..\..\Luma.SimpleEntity.Client"));

            var testProjectFile = Path.Combine(testProjectDir, @"Luma.SimpleEntity.Client.csproj");

            Assert.IsTrue(File.Exists(testProjectFile), "This test could not find its required project at " + testProjectFile);

            // Retrieve all the assembly references from the test project (follows project-to-project references too)
            MsBuildHelper.GetReferenceAssemblies(testProjectFile, assemblies);

            var outputAssembly = MsBuildHelper.GetOutputAssembly(testProjectFile);

            if (!string.IsNullOrEmpty(outputAssembly))
            {
                assemblies.Add(outputAssembly);
            }

            var frameworkDirectory  = CodeGenHelper.GetRuntimeDirectory();
            var frameworkAssemblies = Directory.EnumerateFiles(frameworkDirectory, "*.dll");

            foreach (var frameworkAssembly in frameworkAssemblies)
            {
                if (!assemblies.Contains(frameworkAssembly))
                {
                    assemblies.Add(frameworkAssembly);
                }
            }

            return(assemblies);
        }
        /// <summary>
        /// Helper class to validate the cache contains what we expect it to
        /// contain after loading the real ServerClassLib project
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="projectPath"></param>
        private void ValidateProjectSourceFileCache(ProjectSourceFileCache cache, string projectPath)
        {
            string serverProjectPath  = CodeGenHelper.ServerClassLibProjectPath(projectPath);
            string server2ProjectPath = CodeGenHelper.ServerClassLib2ProjectPath(projectPath);

            string[] expectedServerFiles  = new string[] { "TestEntity.shared.cs" };
            string[] expectedServer2Files = new string[] { "ServerClassLib2.shared.cs" };

            // Ask cache for all known projects.  It should open the .csproj and find project references
            IEnumerable <string> projects = cache.GetAllKnownProjects();

            Assert.IsNotNull(projects);

            // We expect to find ServerClassLib and ServerClassLib2 in the set of known projects.
            // There may be others due to normal project references, but we don't care about them
            Assert.IsTrue(projects.Contains(serverProjectPath), "Expected to find " + serverProjectPath + " in list of known projects");
            Assert.IsTrue(projects.Contains(server2ProjectPath), "Expected to find " + server2ProjectPath + " in list of known projects");

            IEnumerable <string> serverFiles = cache.GetSourceFilesInProject(serverProjectPath);

            Assert.IsNotNull(serverFiles);
            Assert.IsTrue(serverFiles.Count() >= expectedServerFiles.Length);
            foreach (string file in expectedServerFiles)
            {
                string expectedFile = Path.Combine(Path.GetDirectoryName(serverProjectPath), file);
                Assert.IsTrue(serverFiles.Contains(expectedFile), "Expected to see " + expectedFile + " in list of server files");
            }

            IEnumerable <string> server2Files = cache.GetSourceFilesInProject(server2ProjectPath);

            Assert.IsNotNull(server2Files);
            Assert.IsTrue(server2Files.Count() >= expectedServer2Files.Length);
            foreach (string file in expectedServer2Files)
            {
                string expectedFile = Path.Combine(Path.GetDirectoryName(server2ProjectPath), file);
                Assert.IsTrue(server2Files.Contains(expectedFile), "Expected to see " + expectedFile + " in list of server files");
            }
        }
Exemple #16
0
        public void SharedAssemblies_Methods()
        {
            string projectPath, outputPath;
            TestHelper.GetProjectPaths("SAT", out projectPath, out outputPath);
            var clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);
            var assemblies = CodeGenHelper.ClientClassLibReferences(clientProjectPath, true);

            var logger = new ConsoleLogger();
            var sa = new SharedAssemblies(assemblies, Enumerable.Empty<string>(), logger);

            var sharedMethod = sa.GetSharedMethod(typeof(TestValidator).AssemblyQualifiedName, "IsValid", new[] { typeof(TestEntity).AssemblyQualifiedName, typeof(ValidationContext).AssemblyQualifiedName });
            Assert.IsNotNull(sharedMethod, "Expected TestValidator.IsValid to be shared");
            Assert.IsTrue(sharedMethod.DeclaringType.Assembly.Location.Contains("ClientClassLib"), "Expected to find method in client class lib");

            sharedMethod = sa.GetSharedMethod(typeof(TestEntity).AssemblyQualifiedName, "ServerAndClientMethod", new string[0]);
            Assert.IsNotNull(sharedMethod, "Expected TestEntity.ServerAndClientMethod to be shared");
            Assert.IsTrue(sharedMethod.DeclaringType.Assembly.Location.Contains("ClientClassLib"), "Expected to find method in client class lib");

            sharedMethod = sa.GetSharedMethod(typeof(TestValidator).AssemblyQualifiedName, "ServertMethod", new string[0]);
            Assert.IsNull(sharedMethod, "Expected TestValidator.ServerMethod not to be shared");

            TestHelper.AssertNoErrorsOrWarnings(logger);

        }
Exemple #17
0
        public void SharedAssemblies_Types()
        {
            string projectPath = null;
            string outputPath = null;
            TestHelper.GetProjectPaths("SAT", out projectPath, out outputPath);
            string clientProjectPath = CodeGenHelper.ClientClassLibProjectPath(projectPath);
            List<string> assemblies = CodeGenHelper.ClientClassLibReferences(clientProjectPath, true);

            var logger = new ConsoleLogger();
            var sa = new SharedAssemblies(assemblies, Enumerable.Empty<string>(), logger);

            Type sharedType = sa.GetSharedType(typeof(TestEntity).AssemblyQualifiedName);
            Assert.IsNotNull(sharedType, "Expected TestEntity type to be shared");
            Assert.IsTrue(sharedType.Assembly.Location.Contains("ClientClassLib"), "Expected to find type in client class lib");

            sharedType = sa.GetSharedType(typeof(TestValidator).AssemblyQualifiedName);
            Assert.IsNotNull(sharedType, "Expected TestValidator type to be shared");
            Assert.IsTrue(sharedType.Assembly.Location.Contains("ClientClassLib"), "Expected to find type in client class lib");

            sharedType = sa.GetSharedType(typeof(TestValidatorServer).AssemblyQualifiedName);
            Assert.IsNull(sharedType, "Expected TestValidatorServer type not to be shared");

            TestHelper.AssertNoErrorsOrWarnings(logger);
        }
Exemple #18
0
        public void PdbReader_Finds_Method_Files()
        {
            string projectPath = null;
            string outputPath  = null;

            TestHelper.GetProjectPaths("PDB", out projectPath, out outputPath);

            using (ISourceFileProvider pdbReader = new PdbSourceFileProviderFactory(/*symbolSearchPath*/ null, /*logger*/ null).CreateProvider())
            {
                string serverProjectPath = CodeGenHelper.ServerClassLibProjectPath(projectPath);

                Type         testEntityType = typeof(TestEntity);
                PropertyInfo pInfo          = testEntityType.GetProperty("TheKey");
                Assert.IsNotNull(pInfo);

                // Must find TheKey in only TestEntity.cs -- it is readonly and has no setter
                string actualFile   = pdbReader.GetFileForMember(pInfo.GetGetMethod());
                string expectedFile = Path.Combine(Path.GetDirectoryName(serverProjectPath), "TestEntity.cs");
                Assert.AreEqual(expectedFile.ToUpperInvariant(), actualFile.ToUpperInvariant());

                // Must find TheValue in only TestEntity.cs
                pInfo        = testEntityType.GetProperty("TheValue");
                actualFile   = pdbReader.GetFileForMember(pInfo.GetGetMethod());
                expectedFile = Path.Combine(Path.GetDirectoryName(serverProjectPath), "TestEntity.cs");

                // Must find TheSharedValue in only TestEntity.shared.cs -- validates we locate shared files
                pInfo        = testEntityType.GetProperty("TheSharedValue");
                actualFile   = pdbReader.GetFileForMember(pInfo.GetGetMethod());
                expectedFile = Path.Combine(Path.GetDirectoryName(serverProjectPath), "TestEntity.shared.cs");

                // Must find ServerAndClientValue in only TestEntity.linked.cs -- validates we locate linked files
                pInfo        = testEntityType.GetProperty("ServerAndClientValue");
                actualFile   = pdbReader.GetFileForMember(pInfo.GetGetMethod());
                expectedFile = Path.Combine(Path.GetDirectoryName(serverProjectPath), "TestEntity.linked.cs");
            }
        }
Exemple #19
0
        public void ClientFilesTask_Safe_File_Copy()
        {
            CleanClientFilesTask task            = new CleanClientFilesTask();
            MockBuildEngine      mockBuildEngine = new MockBuildEngine();

            task.BuildEngine = mockBuildEngine;

            string tempFolder = CodeGenHelper.GenerateTempFolder();

            try
            {
                // Do a simple copy with no special handling for attributes
                string file1 = Path.Combine(tempFolder, "File1.txt");
                string file2 = Path.Combine(tempFolder, "File2.txt");
                File.AppendAllText(file1, "stuff");

                bool success = task.SafeFileCopy(file1, file2, /*isProjectFile*/ false);
                Assert.IsTrue(success, "SafeFileCopy reported failure");

                Assert.IsTrue(File.Exists(file2), "File2 did not get created");
                string content = File.ReadAllText(file2);
                Assert.AreEqual("stuff", content, "File2 did not get right content");

                FileAttributes fa = File.GetAttributes(file2);
                Assert.AreEqual(0, (int)(fa & FileAttributes.ReadOnly), "Expected RO bit not to be set");

                Assert.IsFalse(task.FilesWereWritten, "Should not have marked files as written");
                File.Delete(file2);

                // Repeat, but ask for it to be treated as a project file
                success = task.SafeFileCopy(file1, file2, /*isProjectFile*/ true);
                Assert.IsTrue(success, "SafeFileCopy reported failure");

                Assert.IsTrue(File.Exists(file2), "File2 did not get created");
                content = File.ReadAllText(file2);
                Assert.AreEqual("stuff", content, "File2 did not get right content");

                fa = File.GetAttributes(file2);
                Assert.AreEqual((int)FileAttributes.ReadOnly, (int)(fa & FileAttributes.ReadOnly), "Expected RO bit to be set");

                Assert.IsTrue(task.FilesWereWritten, "Should have marked files as written");
                task.SafeFileDelete(file2);

                string errorMessage = String.Empty;

                // Finally, try a clearly illegal copy and catch the error
                using (FileStream fs = new FileStream(file1, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    try
                    {
                        File.Copy(file1, file2, true);
                    }
                    catch (IOException iox)
                    {
                        errorMessage = iox.Message;
                    }
                    success = task.SafeFileCopy(file1, file2, /*isProjectFile*/ false);
                }

                Assert.IsFalse(success, "Expected illegal copy to report failure");


                string expectedWarning = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Copy_File, file1, file2, errorMessage);
                TestHelper.AssertContainsWarnings(mockBuildEngine.ConsoleLogger, expectedWarning);
            }

            finally
            {
                CodeGenHelper.DeleteTempFolder(tempFolder);
            }
        }
        public void CleanClientFiles_Deletes_Generated_Files()
        {
            CreateClientFilesTask task = null;
            MockBuildEngine       mockBuildEngine;

            try
            {
                // ====================================================
                // Test setup -- generate code by calling Create task
                // ====================================================
                task = CodeGenHelper.CreateClientFilesTaskInstance("CLRCF1", /*includeClientOutputAssembly*/ false);
                bool success = task.Execute();
                if (!success)
                {
                    mockBuildEngine = task.BuildEngine as MockBuildEngine;
                    Assert.Fail("CreateClientFilesTask failed:\r\n" + mockBuildEngine.ConsoleLogger.Errors);
                }

                string generatedCodeOutputFolder = task.GeneratedCodePath;
                Assert.IsTrue(Directory.Exists(generatedCodeOutputFolder), "Expected task to have created " + generatedCodeOutputFolder);

                string[] files = Directory.GetFiles(generatedCodeOutputFolder);
                Assert.AreEqual(2, files.Length, "Code gen should have generated 3 code files");

                string generatedFile = Path.Combine(generatedCodeOutputFolder, "ServerClassLib.g.cs");
                Assert.IsTrue(File.Exists(generatedFile), "Expected task to have generated " + generatedFile);

                string copiedFile = Path.Combine(generatedCodeOutputFolder, "TestEntity.shared.cs");
                Assert.IsTrue(File.Exists(copiedFile), "Expected task to have copied " + copiedFile);

                string outputFolder = task.OutputPath;
                Assert.IsTrue(Directory.Exists(outputFolder), "Expected task to have created " + outputFolder);

                files = Directory.GetFiles(outputFolder);
                string generatedFiles = string.Empty;
                foreach (string file in files)
                {
                    generatedFiles += (file + Environment.NewLine);
                }

                Assert.AreEqual(5, files.Length, "Code gen should have generated this many ancillary files but instead saw:" + Environment.NewLine + generatedFiles);

                string fileList = Path.Combine(outputFolder, "ClientClassLib.SimpleEntityFiles.txt");
                Assert.IsTrue(File.Exists(fileList), "Expected code gen to have created " + fileList + " but saw:" +
                              Environment.NewLine + generatedFiles);

                string refList = Path.Combine(outputFolder, "ClientClassLib.SimpleEntityClientRefs.txt");
                Assert.IsTrue(File.Exists(refList), "Expected code gen to have created " + refList + " but saw:" +
                              Environment.NewLine + generatedFiles);

                refList = Path.Combine(outputFolder, "ClientClassLib.SimpleEntityServerRefs.txt");
                Assert.IsTrue(File.Exists(refList), "Expected code gen to have created " + refList + " but saw:" +
                              Environment.NewLine + generatedFiles);

                string sourceFileList = Path.Combine(outputFolder, "ClientClassLib.SimpleEntitySourceFiles.txt");
                Assert.IsTrue(File.Exists(sourceFileList), "Expected code gen to have created " + sourceFileList + " but saw:" +
                              Environment.NewLine + generatedFiles);

                string riaLinkList = Path.Combine(outputFolder, "ClientClassLib.SimpleEntityLinks.txt");
                Assert.IsTrue(File.Exists(riaLinkList), "Expected code gen to have created " + riaLinkList + " but saw:" +
                              Environment.NewLine + generatedFiles);

                // ==========================================
                // Main body of test -- the Clean
                // ==========================================

                // Step 1: instantiate Clean task instance and execute it, giving it same info as the Create task
                CleanClientFilesTask cleanTask = new CleanClientFilesTask();
                mockBuildEngine             = new MockBuildEngine();
                cleanTask.BuildEngine       = mockBuildEngine;
                cleanTask.OutputPath        = task.OutputPath;
                cleanTask.GeneratedCodePath = task.GeneratedCodePath;
                cleanTask.ClientProjectPath = task.ClientProjectPath;
                success = cleanTask.Execute();
                Assert.IsTrue(success, "Clean task returned false");

                // No errors or warnings allowed
                TestHelper.AssertNoErrorsOrWarnings(mockBuildEngine.ConsoleLogger);

                // Step 2: validate files created above are gone
                // TODO, 244509: we no longer remove empty folder
                // Assert.IsFalse(Directory.Exists(generatedCodeOutputFolder), "Expected clean to have deleted " + generatedCodeOutputFolder);
                Assert.IsFalse(File.Exists(fileList), "Expected clean to have deleted " + fileList);
                Assert.IsFalse(File.Exists(refList), "Expected clean to have deleted " + refList);
                Assert.IsFalse(File.Exists(sourceFileList), "Expected clean to have deleted " + sourceFileList);
                Assert.IsFalse(File.Exists(riaLinkList), "Expected clean to have deleted " + riaLinkList);

                // Step 3: verify redundant clean does no harm and succeeds
                success = cleanTask.Execute();
                Assert.IsTrue(success, "Clean task returned false");
            }
            finally
            {
                CodeGenHelper.DeleteTempFolder(task);
            }
        }
        public void ProjectSourceFileCache_Loads_Real_Project()
        {
            string projectPath = null;
            string outputPath  = null;

            TestHelper.GetProjectPaths("SSFC", out projectPath, out outputPath);
            string        serverProjectPath = CodeGenHelper.ServerClassLibProjectPath(projectPath);
            string        breadCrumbFile    = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".txt");
            ConsoleLogger logger            = new ConsoleLogger();

            using (ProjectFileReader projectFileReader = new ProjectFileReader(logger))
            {
                try
                {
                    // Instantiate the cache.
                    ProjectSourceFileCache cache = new ProjectSourceFileCache(serverProjectPath, breadCrumbFile, logger, projectFileReader);

                    // Initially, it will not have loaded anything
                    Assert.AreEqual(0, cache.SourceFilesByProject.Count);

                    // -------------------------------------------------------------
                    // Validate cache is loaded correctly from .csproj files
                    // -------------------------------------------------------------
                    this.ValidateProjectSourceFileCache(cache, projectPath);

                    // Ask to write out the breadcrumb file
                    Assert.IsFalse(File.Exists(breadCrumbFile));
                    bool success = cache.SaveCacheToFile();
                    Assert.IsTrue(success);
                    Assert.IsTrue(File.Exists(breadCrumbFile));

                    // Clear the cache and force it to read from breadcrumb
                    cache.SourceFilesByProject.Clear();

                    success = cache.LoadCacheFromFile();
                    Assert.IsTrue(success, "Failed to load from breadCrumb file");
                    Assert.IsTrue(cache.IsFileCacheCurrent, "Loading from file should have marked cache as current with file.");

                    // -------------------------------------------------------------
                    // Validate cache is loaded correctly from breadcrumb file
                    // -------------------------------------------------------------
                    this.ValidateProjectSourceFileCache(cache, projectPath);

                    // Now mark the breadcrumb file as if it had been written before the ServerClassLib project
                    cache.SourceFilesByProject.Clear();

                    DateTime serverLastWriteTime       = File.GetLastWriteTime(serverProjectPath);
                    DateTime beforeServerLastWriteTime = new DateTime(serverLastWriteTime.Ticks - 1000);
                    File.SetLastWriteTime(breadCrumbFile, beforeServerLastWriteTime);

                    // -------------------------------------------------------------
                    // Validate cache is *not* loaded if timestamp is before project's
                    // -------------------------------------------------------------
                    success = cache.LoadCacheFromFile();
                    Assert.IsFalse(success, "Expected breadCrumbFile time stamp to be caught and reject load");
                    Assert.IsFalse(cache.IsFileCacheCurrent, "Failed load from file should have marked cache as *not* current with file.");

                    // Cache should still be empty
                    Assert.AreEqual(0, cache.SourceFilesByProject.Count);

                    // -------------------------------------------------------------
                    // Validate cache loaded in presence of out-of-date breadcrumb
                    // file loads correctly
                    // -------------------------------------------------------------
                    this.ValidateProjectSourceFileCache(cache, projectPath);

                    Assert.IsFalse(cache.IsFileCacheCurrent, "Loading from project should have marked cache as *not* current with file.");
                }
                finally
                {
                    if (File.Exists(breadCrumbFile))
                    {
                        File.Delete(breadCrumbFile);
                    }
                }
            }
        }
Exemple #22
0
        public void SharedTypes_CodeGen_Skips_Shared_Types_And_Properties()
        {
            CreateClientFilesTask task = null;
            var expectedOutputFiles    = new[] {
                "ServerClassLib.g.cs",          // generated
                "TestEntity.shared.cs",         // via server project
                "ServerClassLib2.shared.cs"     // via P2P
            };

            try
            {
                task = CodeGenHelper.CreateClientFilesTaskInstance("STT", /*includeClientOutputAssembly*/ false);
                MockBuildEngine mockBuildEngine = task.BuildEngine as MockBuildEngine;

                // Work Item 199139:
                // We're stripping ServerClassLib2 from the reference assemblies since we cannot depend on Visual Studio
                // to reliably produce a full set of dependencies. This will force the assembly resolution code to
                // search for ServerClassLib2 during codegen.
                // Note: Our assembly resolution code is only exercised when running against an installed product. When
                // we're running locally, resolution occurs without error.
                task.ServerReferenceAssemblies = task.ServerReferenceAssemblies.Where(item => !item.ItemSpec.Contains("ServerClassLib2")).ToArray();

                bool success = task.Execute();
                if (!success)
                {
                    Assert.Fail("CreateClientFilesTask failed:\r\n" + mockBuildEngine.ConsoleLogger.Errors);
                }

                ITaskItem[] outputFiles = task.OutputFiles.ToArray();
                Assert.AreEqual(expectedOutputFiles.Length, outputFiles.Length);

                string generatedFile = CodeGenHelper.GetOutputFile(outputFiles, expectedOutputFiles[0]);

                string generatedCode = string.Empty;
                using (StreamReader t1 = new StreamReader(generatedFile))
                {
                    generatedCode = t1.ReadToEnd();
                }

                ConsoleLogger logger = new ConsoleLogger();
                logger.LogMessage(generatedCode);
                CodeGenHelper.AssertGenerated(generatedCode, "public sealed partial class TestEntity : Entity");
                CodeGenHelper.AssertGenerated(generatedCode, "public string TheKey");
                CodeGenHelper.AssertGenerated(generatedCode, "public int TheValue");

                // This property is in shared code (via link) and should not have been generated
                CodeGenHelper.AssertNotGenerated(generatedCode, "public int ServerAndClientValue");

                // The automatic property in shared code should have been generated because
                // the PDB would lack any info to know it was shared strictly at the source level
                CodeGenHelper.AssertGenerated(generatedCode, "public string AutomaticProperty");

                // The server-only IsValid method should have emitted a comment warning it is not shared
                CodeGenHelper.AssertGenerated(generatedCode, "// [CustomValidationAttribute(typeof(ServerClassLib.TestValidatorServer), \"IsValid\")]");

                // The TestDomainSharedService already had a matching TestDomainSharedContext DomainContext
                // pre-built into the client project.  Verify we did *NOT* regenerate a 2nd copy
                // TODO: Do it
                // CodeGenHelper.AssertNotGenerated(generatedCode, "TestDomainShared");
                // CodeGenHelper.AssertNotGenerated(generatedCode, "TestEntity2");

                // Test that we get an informational message about skipping this shared domain context
                // TODO: Do it
                // string msg = string.Format(CultureInfo.CurrentCulture, Resource.Shared_DomainContext_Skipped, "TestDomainSharedService");
                // TestHelper.AssertContainsMessages(mockBuildEngine.ConsoleLogger, msg);

                // This property is in shared code in a p2p referenced assembly and should not have been generated
                CodeGenHelper.AssertNotGenerated(generatedCode, "public int SharedProperty_CL2");
            }
            finally
            {
                CodeGenHelper.DeleteTempFolder(task);
            }
        }