// Todo: Need to improve this to check absolute path, relative path, server and // other paths are not supported. /// <summary> /// Helper method to check if an existing file exists. /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string VerifyFileExists(string filename) { if (String.IsNullOrEmpty(filename)) { return(null); } // Todo: Can cause an Arguement exception need to handle that. string filepath = PathSW.GetFullPath(filename.ToLowerInvariant()); if (!FileSW.Exists(filepath.ToLowerInvariant())) { return(null); } // Todo: First try didn't get anywhere. // Next return(filepath); }
/// <summary> /// Helper method to check if file exists. /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string VerifyFileExists(string filename) { if (filename == null) { return(null); } string filepath = PathSW.GetFullPath(filename.ToLowerInvariant()); if (FileSW.Exists(filepath)) { return(filepath); } if (PathSW.IsPathRooted(filename.ToLowerInvariant()) == true) { string rootpath = PathSW.GetPathRoot(filename); filepath = rootpath + PathSW.DirectorySeparatorChar + PathSW.GetFileName(filename); return(filepath); } // Use additional search paths provided by user. for (int i = 0; _searchpaths != null && i < _searchpaths.Length; i++) { if (String.IsNullOrEmpty(_searchpaths[i]) == false) { filepath = _searchpaths[i] + PathSW.DirectorySeparatorChar + filename; if (FileSW.Exists(filepath)) { return(PathSW.GetFullPath(filepath)); } } } Console.WriteLine("{0} could not be found", filename); return(null); }
/// <summary> /// Enables logging LHCompiler debug info to file. /// </summary> /// <value></value> public static void LogToFile(string write) { if (String.IsNullOrEmpty(logfilename)) { logfilename = @"LHCompiler.log"; } logfilename = PathSW.GetFullPath(logfilename); switch (write) { case "Overwrite": sw = new StreamWriterSW(logfilename); sw.Flush(); break; case "Append": if (FileSW.Exists(logfilename)) { sw = new StreamWriterSW(logfilename, true); } else { sw = new StreamWriterSW(logfilename); sw.Flush(); } break; default: break; } if (sw != null) { sw.Close(); } }
/// <summary> /// From an Assembly get the error/warning description. /// </summary> /// <param name="node"></param> /// <returns>Assembly resource found result</returns> private bool GetErrorWarningInfoFromAssemblyResources(XmlNode node) { if (node == null) { return(false); } XmlNode childnode = node.SelectSingleNode("./" + Constants.AssemblyResourceAssembly); if (childnode == null) { return(false); } AssemblySW assm = null; if (listofassembliesloaded == null) { listofassembliesloaded = new Hashtable(); } if (String.IsNullOrEmpty(childnode.InnerText)) { return(false); } string assemblyname = childnode.InnerText; if (assemblyname.Contains("Presentation")) { if (String.IsNullOrEmpty(presentationassemblyfullname)) { presentationassemblyfullname = MSBuildEngineCommonHelper.PresentationFrameworkFullName; } int startindex = presentationassemblyfullname.IndexOf(","); presentationassemblyfullname = presentationassemblyfullname.Substring(startindex); assemblyname = assemblyname + presentationassemblyfullname; } else { if (assemblyname.EndsWith(".dll") == false) { assemblyname += ".dll"; } if (String.IsNullOrEmpty(urtpath)) { urtpath = PathSW.GetDirectoryName(typeof(object).Assembly.Location) + PathSW.DirectorySeparatorChar; } assemblyname = urtpath + assemblyname; } childnode = node.SelectSingleNode("./" + Constants.AssemblyResoruceResourceName); if (childnode == null) { return(false); } if (String.IsNullOrEmpty(childnode.InnerText)) { return(false); } string resourcename = childnode.InnerText; if (listofresourcesloaded == null) { listofresourcesloaded = new Hashtable(); } childnode = node.SelectSingleNode("./" + Constants.AssemblyResourceErrorIdentifier); if (childnode == null) { return(false); } if (String.IsNullOrEmpty(childnode.InnerText)) { return(false); } string erroridentifier = childnode.InnerText; ResourceSetSW rs = null; string cultureinfo = null; if (listofresourcesloaded.Contains(resourcename) == false) { if (listofassembliesloaded.Contains(assemblyname)) { assm = (AssemblySW)listofassembliesloaded[assemblyname]; } else { if (FileSW.Exists(assemblyname)) { if (listofassembliesloaded.Contains(assemblyname) == false) { assm = AssemblySW.ReflectionOnlyLoadFrom(assemblyname); } else { assm = (AssemblySW)listofassembliesloaded[assemblyname]; } } else { //assm = Assembly.GetAssembly(typeof(Microsoft.Build.BuildEngine.BuildItem)); AssemblySW[] assmlist = AppDomainSW.CurrentDomain.GetAssemblies(); for (int i = 0; i < assmlist.Length; i++) { object obj = assmlist.GetValue(i); assm = (AssemblySW)obj; if (PathSW.GetFileNameWithoutExtension(assm.ManifestModule.Name).ToLowerInvariant() == assemblyname.ToLowerInvariant()) { break; } assm = null; obj = null; } assmlist = null; } } if (assm == null) { assm = AssemblySW.ReflectionOnlyLoad(assemblyname); if (assm == null) { throw new ApplicationException(assemblyname + " could not be loaded."); } } AssemblySW assm2 = null; try { assm2 = assm.GetSatelliteAssembly(System.Globalization.CultureInfo.CurrentUICulture); cultureinfo = System.Globalization.CultureInfo.CurrentUICulture.Name; assm = null; assm = assm2; assm2 = null; } catch (FileNotFoundException) { MSBuildEngineCommonHelper.LogDiagnostic = "Current UI culture = " + CultureInfo.CurrentUICulture.Name + " with full culture name"; MSBuildEngineCommonHelper.LogDiagnostic = "Assembly " + assm.FullName + " doesn't have a culture dependent resource assembly."; } try { assm2 = assm.GetSatelliteAssembly(System.Globalization.CultureInfo.CurrentUICulture.Parent); cultureinfo = System.Globalization.CultureInfo.CurrentUICulture.Parent.Name; assm = null; assm = assm2; assm2 = null; } catch (FileNotFoundException) { MSBuildEngineCommonHelper.LogDiagnostic = "Current UI culture = " + CultureInfo.CurrentUICulture.Parent.Name + " with full culture name"; MSBuildEngineCommonHelper.LogDiagnostic = "Assembly " + assm.FullName + " doesn't have a culture dependent resource assembly."; } string resourcenamewithculture = null; if (String.IsNullOrEmpty(cultureinfo) == false) { if (resourcename.Contains(".")) { string[] resourcesplit = resourcename.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (resourcesplit.Length >= 2) { if (resourcesplit[resourcesplit.Length - 1].ToLowerInvariant() == "resources") { int resindex = resourcename.IndexOf(".resources"); if (resindex > 0) { resourcenamewithculture = resourcename.Substring(0, resindex) + "." + cultureinfo + "." + resourcesplit[resourcesplit.Length - 1]; } } } resourcesplit = null; } } if (listofassembliesloaded.Contains(assemblyname) == false) { listofassembliesloaded.Add(assemblyname, assm); } string[] resourcenames = assm.GetManifestResourceNames(); bool resourcefound = false; for (int j = 0; j < resourcenames.Length; j++) { if (resourcename == resourcenames[j]) { resourcefound = true; break; } if (resourcenamewithculture == resourcenames[j]) { resourcefound = true; break; } } resourcenames = null; if (resourcefound) { StreamSW resourcestream = null; if (String.IsNullOrEmpty(cultureinfo)) { resourcestream = assm.GetManifestResourceStream(resourcename); rs = new ResourceSetSW(resourcestream.InnerObject); if (listofresourcesloaded.Contains(resourcename) == false) { listofresourcesloaded.Add(resourcename, rs); } resourcestream.Close(); } else { resourcestream = assm.GetManifestResourceStream(resourcenamewithculture); rs = new ResourceSetSW(resourcestream.InnerObject); if (listofresourcesloaded.Contains(resourcename) == false) { listofresourcesloaded.Add(resourcename, rs); } resourcestream.Close(); } resourcestream = null; } } else { rs = (ResourceSetSW)listofresourcesloaded[resourcename]; } if (rs != null) { string errordescription = rs.GetString(erroridentifier); if (String.IsNullOrEmpty(errordescription)) { return(false); } if (errordescription.StartsWith(id)) { try { Convert.ToInt16(id); } catch (FormatException) { errordescription = errordescription.Substring(id.Length); } //errordescription = errordescription.Substring(id.Length); startingmessage = errortype.ToString().ToLowerInvariant() + " " + id; errordescription = errordescription.Trim(); } if (errordescription.StartsWith(":")) { errordescription = errordescription.Substring(1).Trim(); } ConvertResourceDescriptionToArray(errordescription); errordescription = null; } else { MSBuildEngineCommonHelper.Log = "The following erroridentifier could not be found as resourceset was null."; MSBuildEngineCommonHelper.Log = "ErrorIdentifier = " + erroridentifier; MSBuildEngineCommonHelper.Log = "Resourcname = " + resourcename; MSBuildEngineCommonHelper.Log = "Culture = " + cultureinfo; MSBuildEngineCommonHelper.Log = "AssemblyName = " + assemblyname; } return(true); }
/// <summary> /// Deletes old app definition files, project files, and built components /// left over from previous runs. /// /// When we run in an automated test run, the previous test process may not have /// died completely, and it may still hold access /// to the files/directories we are trying to delete. Thus, we make multiple /// attempts to cleanup, sleeping for some time between attempts. /// </summary> public void CleanUpCompilation() { GlobalLog.LogStatus("Cleaning up compilation directory, if there is any...."); // Initialization for the multi-attempt logic bool cleanupDone = false; int maxAttempts = 5; int timeBetweenAttempts = 1000; // sleep time, in milliseconds int attempt = 0; while (!cleanupDone && attempt < maxAttempts) { attempt++; try { // Delete appdef file. if (FileSW.Exists(_appDefFileName)) { GlobalLog.LogStatus("Found appdef file " + _appDefFileName + ". Deleting..."); FileSW.Delete(_appDefFileName); } string currentFolder = DirectorySW.GetCurrentDirectory(); // Delete bin directory. string binPath = PathSW.Combine(currentFolder, "bin"); if (DirectorySW.Exists(binPath)) { GlobalLog.LogStatus("Found bin folder " + binPath + ". Deleting..."); DirectorySW.Delete(binPath, true); GlobalLog.LogStatus("Bin folder deleted."); } // Delete obj directory. string objPath = PathSW.Combine(currentFolder, "obj"); if (DirectorySW.Exists(objPath)) { GlobalLog.LogStatus("Found obj folder " + objPath + ". Deleting..."); DirectorySW.Delete(objPath, true); GlobalLog.LogStatus("Obj folder deleted."); } // Cleanup done! cleanupDone = true; } catch (Exception e) { // We catch only IOException or UnauthorizedAccessException // since those are thrown if some other process is using the // files and directories we are trying to delete. if (e is IOException || e is UnauthorizedAccessException) { GlobalLog.LogStatus("Cleanup attempt #" + attempt + " failed."); if ((1 == attempt) || (maxAttempts == attempt)) { GlobalLog.LogStatus("Here are the active processes on the system."); LogProcessesInfo(); } if (maxAttempts == attempt) { GlobalLog.LogStatus("Maximum no. of cleanup attempts reached. Bailing out...."); throw; } } else { throw; } } Thread.Sleep(timeBetweenAttempts); } }
/// <summary> /// Generates and compiles the application. /// </summary> /// <param name="xamlFiles">The first in this array is main page.</param> /// <param name="hostType">Host type. Could be Application</param> /// <param name="uiCulture"></param> /// <param name="extraFiles"></param> /// <param name="supportingAssemblies"></param> /// <param name="language"></param> /// <param name="additionalAppMarkup"></param> /// <param name="resources"></param> /// <param name="contents"></param> /// <param name="debugBaml"></param> public void CompileApp(string[] xamlFiles, string hostType, string uiCulture, List <string> extraFiles, List <string> supportingAssemblies, Languages language, string additionalAppMarkup, List <Resource> resources, List <Content> contents, bool debugBaml) { // Cleanup temp. Xaml file, if necessary. string _tempXamlFile = "__XamlTestRunnerTempFile.xaml"; if (FileSW.Exists(_tempXamlFile)) { FileSW.Delete(_tempXamlFile); } // Some Xaml files (e.g. those which contain events, <x:Code>, x:Name attributes etc.) // need to specify an x:Class attribute on the root tag. We add that here. string xClassName = "MySubclass"; // Load the original Xaml file into a DOM tree, add x:Class attribute to the root element, // and then save the DOM tree into a temporary Xaml file XmlDocumentSW doc = new XmlDocumentSW(); doc.PreserveWhitespace = true; doc.Load(xamlFiles[0]); XmlElement rootElement = doc.DocumentElement; if (AddClassAttribute) { rootElement.SetAttribute("Class", "http://schemas.microsoft.com/winfx/2006/xaml", xClassName); } if (rootElement.NamespaceURI.IndexOf("schemas.microsoft.com") != -1) //&& !verifierFound) { AutoCloseWindow = true; } doc.Save(_tempXamlFile); xamlFiles[0] = _tempXamlFile; GlobalLog.LogStatus("Start compilation..."); // Generate app definition file. GlobalLog.LogStatus("Generate app definition file..."); GenerateAppdef(_tempXamlFile, hostType, "winexe", language, additionalAppMarkup); CompilerParams compilerParams = new CompilerParams(true); // // Generate the 'proj' file. // GlobalLog.LogStatus("Generate project file..."); foreach (string xamlFile in xamlFiles) { compilerParams.XamlPages.Add(xamlFile); } compilerParams.OutputType = "winexe"; compilerParams.ApplicationDefinition = _appDefFileName; compilerParams.AssemblyName = _assemblyName; compilerParams.RootNamespace = "Avalon.Test.CoreUI.Parser.MyName"; compilerParams.Language = language; // Put debugging info (line,position) in Baml. if (debugBaml) { compilerParams.XamlDebuggingInformation = true; } if (uiCulture != null) { compilerParams.UICulture = uiCulture; } // Add extraFiles. They should be either xaml files or code files. for (int i = 0; extraFiles != null && i < extraFiles.Count; i++) { string fileName = extraFiles[i]; if (PathSW.GetExtension(fileName) == "xaml") { compilerParams.XamlPages.Add(fileName); } else { compilerParams.CompileFiles.Add(fileName); } } // Add code-behind files if they exist and they weren't in the extraFiles. // Always assume they should be added. for (int i = 0; i < compilerParams.XamlPages.Count; i++) { string fileName = compilerParams.XamlPages[i] + ".cs"; if (FileSW.Exists(fileName) && !compilerParams.CompileFiles.Contains(fileName)) { compilerParams.CompileFiles.Add(fileName); } } // Add supporting assemblies, if any, as references if (null != supportingAssemblies) { string currentDirectory = EnvironmentSW.CurrentDirectory; for (int i = 0; i < supportingAssemblies.Count; i++) { string assemblyName = supportingAssemblies[i]; compilerParams.References.Add(new Reference(assemblyName, currentDirectory + "\\" + assemblyName + ".dll")); } } if (References.Count > 0) { compilerParams.References.AddRange(References); } // Add Resources, if any if (null != resources) { foreach (Resource r in resources) { compilerParams.Resources.Add(r); } } // Add Contents, if any if (null != contents) { foreach (Content c in contents) { compilerParams.Contents.Add(c); } } // Also add any loose files specified by TestCaseInfo.SupportFiles // //TestDefinition td = TestDefinition.Current; //td. //if (currentTestCaseInfo != null) //{ // string[] currentSupportFiles = currentTestCaseInfo.SupportFiles; // if (currentSupportFiles != null) // { // foreach (string fileName in currentSupportFiles) // { // compilerParams.Contents.Add(new Content(fileName, "Always")); // } // } //} // // Compile project. // GlobalLog.LogStatus("Compiling project..."); Compiler compiler = new Compiler(compilerParams); List <ErrorWarningCode> buildErrorsAndWarnings = compiler.Compile(true); // // Check if Compiling project is successful by verifying that compiled app exists. // GlobalLog.LogStatus("Check if compiling project was successful..."); GlobalLog.LogStatus("Check if the BAML and the compiled app both exist."); string bamlPath = _objPath + PathSW.DirectorySeparatorChar + PathSW.ChangeExtension(xamlFiles[0], "baml"); bool compilerFailure = false; GlobalLog.LogStatus("Baml Path: " + bamlPath); if (!FileSW.Exists(bamlPath)) { GlobalLog.LogEvidence("Baml file did not exist"); compilerFailure = true; } GlobalLog.LogStatus("Compiled path: " + _compiledPath); if (!FileSW.Exists(_compiledPath)) { GlobalLog.LogEvidence("Compiled path did not exist"); compilerFailure = true; } if (compilerFailure) { //Save files to be used for debugging GlobalLog.LogStatus("Saving files used in compilation..."); GlobalLog.LogFile("__CompilerServicesSave.proj"); foreach (string file in compilerParams.XamlPages) { GlobalLog.LogFile(file); } foreach (string file in compilerParams.CompileFiles) { GlobalLog.LogFile(file); } // Get compilation error message string compileErrors = "Errors: \n"; string compileWarnings = "Warnings \n"; if ((null != buildErrorsAndWarnings) && (buildErrorsAndWarnings.Count > 0)) { // The list contains both errors and warnings. // Get the first error and get its description. foreach (ErrorWarningCode errAndWarn in buildErrorsAndWarnings) { if (errAndWarn.Type == ErrorType.Error) { compileErrors += errAndWarn.Description + "\n"; GlobalLog.LogStatus("\nBuild Error Found - " + errAndWarn.Description + "\n"); break; } else { compileWarnings += errAndWarn.Description + "\n"; GlobalLog.LogStatus("\nWarning - " + errAndWarn.Description + "\n"); } } } TestSetupException setupException = new TestSetupException("Compilation failed: " + compileErrors + compileWarnings); // Add the list of build errors and warnings as custom Exception data. // This can be used by callers to retrive the errors and warnings list. setupException.Data.Add("buildErrorsAndWarnings", buildErrorsAndWarnings); throw setupException; } }
private List <ErrorWarningCode> CompileInternal(bool saveProjFile) { if (FileSW.Exists("ClickOnceTest.pfx")) { MSBuildProjExecutor.CleanSignFile = false; } MSBuildProjExecutor build = new MSBuildProjExecutor(); build.CreateProject(); build.CreateBuildPropertyGroup(""); build.CreateBuildItemGroup(""); build.AddProperty("Configuration", SetupParams.Configuration); build.AddProperty("Platform", "AnyCPU"); build.AddProperty("XamlDebuggingInformation", Convert.ToString(SetupParams.XamlDebuggingInformation)); build.AddProperty("OutputType", SetupParams.OutputType); if (!IsLibrary() && SetupParams.GenerateManifests) { build.AddProperty("GenerateManifests", Convert.ToString(SetupParams.GenerateManifests)); } string hostInBrowser = "false"; if (SetupParams.HostInBrowser) { hostInBrowser = "true"; } build.AddProperty("HostinBrowser", hostInBrowser); string localPath = SetupParams.LocalPath; if (String.IsNullOrEmpty(localPath)) { localPath = DirectorySW.GetCurrentDirectory(); } if (!IsLibrary() && SetupParams.TargetZone == "") { // This is for Full Trust Compilation string appManifest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<asmv1:assembly manifestVersion=\"1.0\" xmlns=\"urn:schemas-microsoft-com:asm.v1\" xmlns:asmv1=\"urn:schemas-microsoft-com:asm.v1\" xmlns:asmv2=\"urn:schemas-microsoft-com:asm.v2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v2\">" + " <security>" + " <applicationRequestMinimum>" + " <PermissionSet class=\"System.Security.PermissionSet\" version=\"1\" Unrestricted=\"true\" ID=\"Custom\" SameSite=\"site\" />" + " <defaultAssemblyRequest permissionSetReference=\"Custom\" />" + " </applicationRequestMinimum>" + " </security>" + " </trustInfo>" + "</asmv1:assembly>"; string securityManifestFullTrust = "<Security>" + " <ApplicationRequestMinimum>" + " <PermissionSet ID=\"FT\" temp:Unrestricted=\"true\" />" + " <DefaultAssemblyRequest PermissionSetReference=\"FT\" />" + " </ApplicationRequestMinimum>" + "</Security>"; FileStreamSW fs = null; StreamWriterSW writer = null; if (!FileSW.Exists(app_manifest)) { try { string path = PathSW.Combine(localPath, app_manifest); fs = new FileStreamSW(path, FileMode.Create, FileAccess.Write); writer = new StreamWriterSW((Stream)fs.InnerObject); writer.Write(appManifest); } finally { if (writer != null) { writer.Close(); } if (fs != null) { fs.Close(); } } } if (!FileSW.Exists(SecurityManifestFullTrust)) { try { string path = PathSW.Combine(localPath, SecurityManifestFullTrust); fs = new FileStreamSW(path, FileMode.Create, FileAccess.Write); writer = new StreamWriterSW((Stream)fs.InnerObject); writer.Write(securityManifestFullTrust); } finally { if (writer != null) { writer.Close(); } if (fs != null) { fs.Close(); } } } build.AddProperty("TargetZone", "Custom"); build.AddItem("None", app_manifest); build.AddItem("None", SecurityManifestFullTrust); } build.AddProperty("AssemblyName", SetupParams.AssemblyName); build.AddProperty("OutputPath", SetupParams.OutputPath); build.AddProperty("RootNamespace", SetupParams.RootNamespace); build.AddProperty("UICulture", SetupParams.UICulture); if (!IsLibrary()) { build.AddItem("None", "ClickOnceTest.pfx"); build.AddProperty("SignManifests", "true"); build.AddProperty("ManifestKeyFile", "ClickOnceTest.pfx"); build.AddProperty("ManifestCertificateThumbprint", "cd582af19e477ae94a53102e0453e71b3c592a80"); } if (SetupParams.Language == Languages.CSharp) { build.AddImport(MSBuildDirectory + @"\Microsoft.CSharp.targets"); } else { build.AddImport(MSBuildDirectory + @"\Microsoft.VisualBasic.targets"); } build.AddImport(MSBuildDirectory + @"\Microsoft.WinFx.targets"); if (!String.IsNullOrEmpty(SetupParams.ApplicationDefinition)) { build.AddItem("ApplicationDefinition", SetupParams.ApplicationDefinition); } for (int i = 0; i < SetupParams.XamlPages.Count; i++) { build.AddItem("Page", SetupParams.XamlPages[i]); } for (int i = 0; i < SetupParams.CompileFiles.Count; i++) { build.AddItem("Compile", SetupParams.CompileFiles[i]); } for (int i = 0; i < SetupParams.Resources.Count; i++) { build.AddResource(SetupParams.Resources[i].FileName, SetupParams.Resources[i].FileStorage, ""); } for (int i = 0; i < SetupParams.Contents.Count; i++) { build.AddContent(SetupParams.Contents[i].FileName, SetupParams.Contents[i].CopyToOutputDirectory, ""); } for (int i = 0; i < SetupParams.References.Count; i++) { build.AddReference(SetupParams.References[i].FileName, "", SetupParams.References[i].HintPath, ""); } //HACK build.CommandLineArguements = "/t:Build"; if (saveProjFile) { build.SaveProjectFile = Path.Combine(localPath, "__CompilerServicesSave.proj"); } build.Build(); if (saveProjFile) { build.SaveProjectFile = Path.Combine(localPath, "__CompilerServicesSave.proj"); } if (build.OutputDirectory != null && !IsLibrary()) { string compiledExtension; if (SetupParams.HostInBrowser) { compiledExtension = ApplicationDeploymentHelper.BROWSER_APPLICATION_EXTENSION; } else { compiledExtension = ApplicationDeploymentHelper.STANDALONE_APPLICATION_EXTENSION; } if (SetupParams.GenerateManifests) { string fileToSign = PathSW.Combine(build.OutputDirectory, SetupParams.AssemblyName + compiledExtension); #if (!STRESS_RUNTIME) Microsoft.Test.Logging.GlobalLog.LogStatus("Signing file: " + fileToSign); #endif //MQ AvalonDeploymentHelper.SignManifest(fileToSign); } } return(build.UnhandledErrorsandWarningsList); }