Click here to Skip to main content
15,892,298 members
Articles / Programming Languages / C#

Resolving Symbolic References in a CodeDOM (Part 7)

Rate me:
Please Sign up or sign in to vote.
4.75/5 (6 votes)
2 Dec 2012CDDL12 min read 19.4K   509   14  
Resolving symbolic references in a CodeDOM.
// Nova.CodeDOM usage examples.
// Copyright (C) 2007-2012 Inevitable Software, all rights reserved.
// Released under the Common Development and Distribution License, CDDL-1.0: http://opensource.org/licenses/cddl1.php

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;

using Nova.CodeDOM;
using Nova.Utilities;

namespace Nova.Test
{
    /// <summary>
    /// This program contains tests for the Nova.CodeDOM C# object model library.
    /// </summary>
    class Program
    {
        #region /* MAIN METHOD */

        private static string _baseDirectory;
        private static string _executionDirectory;

        static void Main(string[] arguments)
        {
            _executionDirectory = Directory.GetCurrentDirectory();
            _baseDirectory = FileUtil.GetBaseDirectory();

            // Allow the base directory to be overridden (where it looks for files to be loaded)
            if (arguments != null && arguments.Length > 0)
                _baseDirectory = arguments[0];

            // Determine the application name and if we're running in VS
            string appName = AppDomain.CurrentDomain.FriendlyName;
            if (appName.EndsWith(".exe"))
                appName = appName.Substring(0, appName.Length - 4);
            if (appName.EndsWith(".vshost"))
                appName = appName.Substring(0, appName.Length - 7);

            // Change from the output directory to the project root, so files can be found
            Directory.SetCurrentDirectory(_baseDirectory);

            Version appVersion = typeof(Program).Assembly.GetName().Version;
            string appDescription = appName + " " + appVersion.Major + "." + appVersion.Minor;
            Console.WriteLine(appDescription + "  -  C# CodeDOM Test Utility.\nCopyright (C) 2011-2012 Inevitable Software, all rights reserved.");

            // Execute all public tests in this class
            Log.WriteLine("\nExecuting Nova.CodeDOM tests...\n");
            MethodInfo[] methodInfos = Assembly.GetExecutingAssembly().GetType("Nova.Test.Program").GetMethods(BindingFlags.Public | BindingFlags.Static);
            foreach (MethodInfo methodInfo in methodInfos)
            {
                Log.WriteLine("===== Executing Test: " + methodInfo.Name + " =====");
                try
                {
                    methodInfo.Invoke(null, null);
                }
                catch (Exception ex)
                {
                    Log.Exception(ex, "executing test");
                }
                Log.WriteLine("===== " + methodInfo.Name + " Completed =====\n");
            }

            // Wait for a key press before exiting if running in VS
            if (Debugger.IsAttached)
            {
                Console.WriteLine("DONE.  Press any key to exit.");
                Console.ReadKey();
            }
        }

        #endregion

        #region /* TESTS */

        /// <summary>
        /// Manually generate the Simple test and display it.
        /// </summary>
        public static void GenerateSimpleTest()
        {
            const string name = "Simple";
            Log.WriteLine("Generating code for '" + name + "'...");
            CodeObject codeObject = ManualTests.GenerateSimpleTest("name", null);
            Log.WriteLine(codeObject.AsText(CodeObject.RenderFlags.SuppressNewLine));
        }

        /// <summary>
        /// Manually generate the Method test and display it.
        /// </summary>
        public static void GenerateMethodTest()
        {
            const string name = "Method";
            Log.WriteLine("Generating code for '" + name + "'...");
            CodeObject codeObject = ManualTests.GenerateMethodTest("name", null);
            Log.WriteLine(codeObject.AsText(CodeObject.RenderFlags.SuppressNewLine));
        }

        /// <summary>
        /// Load the FullTest.cs file, and save it as FullTest.saved.cs.
        /// </summary>
        public static void SaveFullTest()
        {
            string filePath = FileUtil.FindFile("FullTest.cs");
            if (filePath != null)
            {
                // Use a separate project for this test, with special references
                Project project = CreateMiscellaneousProject("FullTest",
                    new AssemblyReference("Nova.CodeDOM", _executionDirectory));
                CodeUnit codeUnit = project.AddFile(filePath);
                project.ParseAndResolveCodeUnits();
                string fileName = Path.ChangeExtension(filePath, ".saved.cs");
                Log.WriteLine("Saving '" + fileName + "'...");
                codeUnit.SaveAs(fileName);
            }
            else
                Log.WriteLine("ERROR: Couldn't find file 'FullTest.cs' in order to load/save it.  Please specify the path of this file as a command-line argument.");
        }

        /// <summary>
        /// Manually generate the code in FullTest.cs, save it in FullTest.generated.cs, and compare to FullTest.saved.cs.
        /// </summary>
        public static void GenerateFullTest()
        {
            Project project = CreateMiscellaneousProject("FullTest.generated",
                new AssemblyReference("Nova.CodeDOM", _executionDirectory));
            const string fileName = "FullTest.generated.cs";
            Log.WriteLine("Generating code for '" + fileName + "'...");
            CodeUnit codeUnit = ManualTests.GenerateFullTest(fileName, project);
            Log.WriteLine("Saving '" + fileName + "'...");
            codeUnit.Save();

            string file2 = FileUtil.FindFile("FullTest.saved.cs");
            if (file2 != null)
                CompareFiles(fileName, file2);
            else
                Log.WriteLine("ERROR: Couldn't find file 'FullTest.saved.cs' in order to compare to it.");
        }

        private static Project CreateMiscellaneousProject(string name, params Reference[] references)
        {
            // Create a miscellaneous project file, and add typical references
            Project project = new Project(name, null);
            project.AddDefaultAssemblyReferences();
            project.AddAssemblyReference("System.Configuration");
            project.AddAssemblyReference("PresentationCore");
            project.AddAssemblyReference("PresentationFramework");
            project.AddAssemblyReference("UIAutomationProvider");
            project.AddAssemblyReference("WindowsBase");
            foreach (Reference reference in references)
                project.References.Add(reference);
            project.LoadReferencedAssembliesAndTypes(true);
            return project;
        }

        private static void CompareFiles(string fileName1, string fileName2)
        {
            Log.WriteLine("Comparing '" + fileName1 + "' to '" + fileName2 + "'...");
            int line = 0;
            using (StreamReader fileStream1 = new StreamReader(fileName1))
            using (StreamReader fileStream2 = new StreamReader(fileName2))
            {
                while (!fileStream1.EndOfStream && !fileStream2.EndOfStream)
                {
                    string file1Line = fileStream1.ReadLine();
                    string file2Line = fileStream2.ReadLine();
                    ++line;
                    if (file1Line != file2Line)
                    {
                        Log.WriteLine("FAIL: Files differ at line " + line + "!");
                        return;
                    }
                }
                if (!fileStream1.EndOfStream)
                    Log.WriteLine("FAIL: First file is longer!");
                else if (!fileStream1.EndOfStream)
                    Log.WriteLine("FAIL: Second file is longer!");
                else
                    Log.WriteLine("PASS: Files are identical.");
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


Written By
Software Developer (Senior)
United States United States
I've been writing software since the late 70's, currently focusing mainly on C#.NET. I also like to travel around the world, and I own a Chocolate Factory (sadly, none of my employees are oompa loompas).

Comments and Discussions