PageRenderTime 29ms CodeModel.GetById 11ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/V2.2/trunk/CAL/Desktop/Composite.Tests/CompilerHelper.Desktop.cs

#
C# | 200 lines | 156 code | 24 blank | 20 comment | 9 complexity | cb2a271e7f3c4e2ec30ce50f39dfcc16 MD5 | raw file
  1//===================================================================================
  2// Microsoft patterns & practices
  3// Composite Application Guidance for Windows Presentation Foundation and Silverlight
  4//===================================================================================
  5// Copyright (c) Microsoft Corporation.  All rights reserved.
  6// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
  7// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
  8// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  9// FITNESS FOR A PARTICULAR PURPOSE.
 10//===================================================================================
 11// The example companies, organizations, products, domain names,
 12// e-mail addresses, logos, people, places, and events depicted
 13// herein are fictitious.  No association with any real company,
 14// organization, product, domain name, email address, logo, person,
 15// places, or events is intended or should be inferred.
 16//===================================================================================
 17using System;
 18using System.CodeDom.Compiler;
 19using System.Collections.Generic;
 20using System.IO;
 21using System.Reflection;
 22using System.Text;
 23using Microsoft.CSharp;
 24using Microsoft.Practices.Composite.Modularity;
 25using Microsoft.VisualStudio.TestTools.UnitTesting;
 26
 27namespace Microsoft.Practices.Composite.Tests
 28{
 29    public class CompilerHelper 
 30    {
 31        private static string moduleTemplate =
 32            @"using System;
 33            using Microsoft.Practices.Composite.Modularity;
 34
 35            namespace TestModules
 36            {
 37                #module#
 38	            public class #className#Class : IModule
 39	            {
 40                    public void Initialize()
 41                    {
 42                       Console.WriteLine(""#className#.Start"");
 43                    }
 44                }
 45            }";
 46
 47        public static Assembly CompileFileAndLoadAssembly(string input, string output, params string[] references)
 48        {
 49            return CompileFile(input, output, references).CompiledAssembly;
 50        }
 51
 52        public static CompilerResults CompileFile(string input, string output, params string[] references)
 53        {
 54            CreateOutput(output);
 55
 56            List<string> referencedAssemblies = new List<string>(references.Length + 3);
 57
 58            referencedAssemblies.AddRange(references);
 59            referencedAssemblies.Add("System.dll");
 60            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
 61            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));
 62
 63            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
 64            CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);
 65
 66            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
 67            {
 68                if (stream == null)
 69                {
 70                    throw new ArgumentException("input");
 71                }
 72
 73                StreamReader reader = new StreamReader(stream);
 74                string source = reader.ReadToEnd();
 75                CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
 76                ThrowIfCompilerError(results);
 77                return results;
 78            }
 79        }
 80
 81        public static void CreateOutput(string output)
 82        {
 83            string dir = Path.GetDirectoryName(output);
 84            if (!Directory.Exists(dir))
 85            {
 86                Directory.CreateDirectory(dir);
 87            }
 88            else
 89            {
 90                //Delete the file if exists
 91                if (File.Exists(output))
 92                {
 93                    try
 94                    {
 95                        File.Delete(output);
 96                    }
 97                    catch (UnauthorizedAccessException)
 98                    {
 99                        //The file might be locked by Visual Studio, so rename it
100                        if (File.Exists(output + ".locked"))
101                            File.Delete(output + ".locked");
102                        File.Move(output, output + ".locked");
103                    }
104                }
105            }
106        }
107
108        public static CompilerResults CompileCode(string code, string output)
109        {
110            CreateOutput(output);
111            List<string> referencedAssemblies = new List<string>();
112            referencedAssemblies.Add("System.dll");
113            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
114            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));
115
116            CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(
117                new CompilerParameters(referencedAssemblies.ToArray(), output), code);
118
119            ThrowIfCompilerError(results);
120
121            return results;
122        }
123
124        public static string GenerateDynamicModule(string assemblyName, string moduleName, string outpath, params string[] dependencies)
125        {
126            CreateOutput(outpath);
127
128            // Create temporary module.
129            string moduleCode = moduleTemplate.Replace("#className#", assemblyName);
130            if (!string.IsNullOrEmpty(moduleName))
131            {
132                moduleCode = moduleCode.Replace("#module#", String.Format("[Module(ModuleName = \"{0}\") #dependencies#]", moduleName));
133            }
134            else
135            {
136                moduleCode = moduleCode.Replace("#module#", "");
137            }
138
139            string depString = string.Empty;
140
141            foreach (string module in dependencies)
142            {
143                depString += String.Format(", ModuleDependency(\"{0}\")", module);
144            }
145
146            moduleCode = moduleCode.Replace("#dependencies#", depString);
147
148            CompileCode(moduleCode, outpath);
149
150            return outpath;
151        }
152
153        public static string GenerateDynamicModule(string assemblyName, string moduleName, params string[] dependencies)
154        {
155            string assemblyFile = assemblyName + ".dll";
156            string outpath = Path.Combine(assemblyName, assemblyFile);
157
158            return GenerateDynamicModule(assemblyName, moduleName, outpath, dependencies);
159        }
160
161        public static void ThrowIfCompilerError(CompilerResults results)
162        {
163            if (results.Errors.HasErrors)
164            {
165                StringBuilder sb = new StringBuilder();
166                sb.AppendLine("Compilation failed.");
167                foreach (CompilerError error in results.Errors)
168                {
169                    sb.AppendLine(error.ToString());
170                }
171                Assert.IsFalse(results.Errors.HasErrors, sb.ToString());
172            }
173        }
174
175        public static void CleanUpDirectory(string path)
176        {
177            if (!Directory.Exists(path))
178            {
179                Directory.CreateDirectory(path);
180            }
181            else
182            {
183                foreach (string file in Directory.GetFiles(path))
184                {
185                    try
186                    {
187                        File.Delete(file);
188                    }
189                    catch (UnauthorizedAccessException)
190                    {
191                        //The file might be locked by Visual Studio, so rename it
192                        if (File.Exists(file + ".locked"))
193                            File.Delete(file + ".locked");
194                        File.Move(file, file + ".locked");
195                    }
196                }
197            }
198        }
199    }
200}