PageRenderTime 47ms CodeModel.GetById 21ms 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. //===================================================================================
  17. using System;
  18. using System.CodeDom.Compiler;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Reflection;
  22. using System.Text;
  23. using Microsoft.CSharp;
  24. using Microsoft.Practices.Composite.Modularity;
  25. using Microsoft.VisualStudio.TestTools.UnitTesting;
  26. namespace Microsoft.Practices.Composite.Tests
  27. {
  28. public class CompilerHelper
  29. {
  30. private static string moduleTemplate =
  31. @"using System;
  32. using Microsoft.Practices.Composite.Modularity;
  33. namespace TestModules
  34. {
  35. #module#
  36. public class #className#Class : IModule
  37. {
  38. public void Initialize()
  39. {
  40. Console.WriteLine(""#className#.Start"");
  41. }
  42. }
  43. }";
  44. public static Assembly CompileFileAndLoadAssembly(string input, string output, params string[] references)
  45. {
  46. return CompileFile(input, output, references).CompiledAssembly;
  47. }
  48. public static CompilerResults CompileFile(string input, string output, params string[] references)
  49. {
  50. CreateOutput(output);
  51. List<string> referencedAssemblies = new List<string>(references.Length + 3);
  52. referencedAssemblies.AddRange(references);
  53. referencedAssemblies.Add("System.dll");
  54. referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
  55. referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));
  56. CSharpCodeProvider codeProvider = new CSharpCodeProvider();
  57. CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);
  58. using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
  59. {
  60. if (stream == null)
  61. {
  62. throw new ArgumentException("input");
  63. }
  64. StreamReader reader = new StreamReader(stream);
  65. string source = reader.ReadToEnd();
  66. CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
  67. ThrowIfCompilerError(results);
  68. return results;
  69. }
  70. }
  71. public static void CreateOutput(string output)
  72. {
  73. string dir = Path.GetDirectoryName(output);
  74. if (!Directory.Exists(dir))
  75. {
  76. Directory.CreateDirectory(dir);
  77. }
  78. else
  79. {
  80. //Delete the file if exists
  81. if (File.Exists(output))
  82. {
  83. try
  84. {
  85. File.Delete(output);
  86. }
  87. catch (UnauthorizedAccessException)
  88. {
  89. //The file might be locked by Visual Studio, so rename it
  90. if (File.Exists(output + ".locked"))
  91. File.Delete(output + ".locked");
  92. File.Move(output, output + ".locked");
  93. }
  94. }
  95. }
  96. }
  97. public static CompilerResults CompileCode(string code, string output)
  98. {
  99. CreateOutput(output);
  100. List<string> referencedAssemblies = new List<string>();
  101. referencedAssemblies.Add("System.dll");
  102. referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
  103. referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));
  104. CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(
  105. new CompilerParameters(referencedAssemblies.ToArray(), output), code);
  106. ThrowIfCompilerError(results);
  107. return results;
  108. }
  109. public static string GenerateDynamicModule(string assemblyName, string moduleName, string outpath, params string[] dependencies)
  110. {
  111. CreateOutput(outpath);
  112. // Create temporary module.
  113. string moduleCode = moduleTemplate.Replace("#className#", assemblyName);
  114. if (!string.IsNullOrEmpty(moduleName))
  115. {
  116. moduleCode = moduleCode.Replace("#module#", String.Format("[Module(ModuleName = \"{0}\") #dependencies#]", moduleName));
  117. }
  118. else
  119. {
  120. moduleCode = moduleCode.Replace("#module#", "");
  121. }
  122. string depString = string.Empty;
  123. foreach (string module in dependencies)
  124. {
  125. depString += String.Format(", ModuleDependency(\"{0}\")", module);
  126. }
  127. moduleCode = moduleCode.Replace("#dependencies#", depString);
  128. CompileCode(moduleCode, outpath);
  129. return outpath;
  130. }
  131. public static string GenerateDynamicModule(string assemblyName, string moduleName, params string[] dependencies)
  132. {
  133. string assemblyFile = assemblyName + ".dll";
  134. string outpath = Path.Combine(assemblyName, assemblyFile);
  135. return GenerateDynamicModule(assemblyName, moduleName, outpath, dependencies);
  136. }
  137. public static void ThrowIfCompilerError(CompilerResults results)
  138. {
  139. if (results.Errors.HasErrors)
  140. {
  141. StringBuilder sb = new StringBuilder();
  142. sb.AppendLine("Compilation failed.");
  143. foreach (CompilerError error in results.Errors)
  144. {
  145. sb.AppendLine(error.ToString());
  146. }
  147. Assert.IsFalse(results.Errors.HasErrors, sb.ToString());
  148. }
  149. }
  150. public static void CleanUpDirectory(string path)
  151. {
  152. if (!Directory.Exists(path))
  153. {
  154. Directory.CreateDirectory(path);
  155. }
  156. else
  157. {
  158. foreach (string file in Directory.GetFiles(path))
  159. {
  160. try
  161. {
  162. File.Delete(file);
  163. }
  164. catch (UnauthorizedAccessException)
  165. {
  166. //The file might be locked by Visual Studio, so rename it
  167. if (File.Exists(file + ".locked"))
  168. File.Delete(file + ".locked");
  169. File.Move(file, file + ".locked");
  170. }
  171. }
  172. }
  173. }
  174. }
  175. }