/// <summary> /// Project Finished Event handler, logs to build log file. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void eventSource_ProjectFinishedEvent(object sender, ProjectFinishedEventArgs e) { LogToBuildLog(""); // Print the project file currently building if (e.ProjectFile != null) { string strblanks = ""; for (int i = 0; i < projectfilestack.Count; i++) { if (i - 1 > 0) { strblanks += " "; } } Console.WriteLine("{0}Done Compiling - {1}", strblanks, e.ProjectFile); globalcurrentprojfile = e.ProjectFile; if (String.IsNullOrEmpty(globalcurrentprojfile) == false) { globalcurrentprojfile = PathSW.GetFullPath(globalcurrentprojfile); // Removing current project file that finished from stack. projectfilestack.Pop(); LogToBuildLog("Compiling project file - " + globalcurrentprojfile + " finished."); } } tabcount = 0; this.LogToBuildLog(e, true); }
/// <summary> /// Read additional file information. /// </summary> /// <param name="xmldatafile"></param> /// <returns></returns> public override bool Read(string xmldatafile) { defaultfiledata.FileName = PathSW.GetFileNameWithoutExtension(xmldatafile); defaultfiledata.FileExtension = PathSW.GetExtension(xmldatafile); return(base.Read(xmldatafile)); }
/// <summary> /// Project Started Event handler, logs to build log file. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void eventSource_ProjectStartedEvent(object sender, ProjectStartedEventArgs e) { // Print the project file currently building if (e.ProjectFile != null) { string strblanks = ""; for (int i = 0; i < projectfilestack.Count; i++) { strblanks += " "; } if (projectfilestack.Count > 0) { Console.WriteLine(); } Console.Write("{0}Compiling - {1} ", strblanks, e.ProjectFile); string currentprojfile = e.ProjectFile; if (String.IsNullOrEmpty(currentprojfile) == false) { currentprojfile = PathSW.GetFullPath(currentprojfile); //Console.WriteLine(Directory.GetCurrentDirectory()); //Console.WriteLine(currentprojfile); // Pushing current project file into stack. projectfilestack.Push(currentprojfile); LogToBuildLog("Current project file - " + currentprojfile); } } tabcount = 0; this.LogToBuildLog(e, true); }
/// <summary> /// Return the Generated Assembly from the list. /// </summary> /// <param name="text"></param> /// <param name="node"></param> /// <returns></returns> internal string GetGeneratedAssembly(string text, XmlNode node) { int index = -1; string filetype = "withoutextension"; if (text.Contains("[") || text.Contains("]")) { index = text.IndexOf("["); if (index < 0) { index = text.IndexOf("]"); filetype = text.Substring(0, index); } else { if (text.Contains("]")) { filetype = text.Substring(index + 1, text.IndexOf("]") - index - 1); } } } index = text.IndexOf(':'); if (index < 0) { return(null); } text = text.Substring(index + 1, text.Length - index - 1); index = Convert.ToInt16(text); if (_generatedassembliestable.Contains(index)) { GeneratedAssemblyInfo asseminfo = (GeneratedAssemblyInfo)_generatedassembliestable[index]; text = asseminfo.GeneratedAssembly; } if (filetype.ToLowerInvariant() == "withoutextension") { text = PathSW.GetFileNameWithoutExtension(text); } return(text); }
// 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> /// Log to Build warning file and to Build Log file. /// </summary> /// <param name="e"></param> private void LogToBuildWarning(BuildWarningEventArgs e) { if (e != null) { StringBuilder sb = new StringBuilder(); StringBuilder tab = new StringBuilder(); StringBuilder warningstring = new StringBuilder(); //if (String.IsNullOrEmpty(buildwaringfile) == false) //{ // buildwarning = new StreamWriter(buildwaringfile, true); //} for (int i = 0; i < tabcount; i++) { tab.Append("\t"); } //sb.AppendFormat("{0} - ",e.Timestamp.ToString()); string currentprojfile = null; if (projectfilestack.Count > 0) { currentprojfile = projectfilestack.Peek().ToString(); } if (e.File != null && e.File.ToLowerInvariant() != currentprojfile) { sb.Append(e.File.ToString() + " "); //if (buildwarning != null) //{ // buildwarning.Write(PathSW.GetFullPath(e.File.ToString()) + " "); //buildwarning.Write(currentprojfile + " : " + e.File.ToString() + " "); warningstring.Append(currentprojfile + " : " + e.File.ToString() + " "); //} if (e.LineNumber >= 0 && e.ColumnNumber >= 0) { sb.Append("(" + e.LineNumber + "," + e.ColumnNumber + ") " + " :"); //if (buildwarning != null) //{ // buildwarning.Write("(" + e.LineNumber + "," + e.ColumnNumber + ") " + " :"); //} warningstring.Append("(" + e.LineNumber + "," + e.ColumnNumber + ") " + " :"); } } else { sb.AppendFormat("{0} - :", PathSW.GetFileName(currentprojfile)); //if (buildwarning != null) //{ // buildwarning.Write("{0} - :", currentprojfile); //} warningstring.AppendFormat("{0} - :", currentprojfile); } if (e.Code != null) { sb.Append(" warning " + e.Code + ": "); //if (buildwarning != null) //{ // buildwarning.Write(" warning " + e.Code + ": "); //} warningstring.Append(" warning " + e.Code + ": "); } sb.Append(e.Message); //if (buildwarning != null) //{ // buildwarning.Write(e.Message); // buildwarning.WriteLine(); //} warningstring.Append(e.Message + "\n"); //if (buildwarning != null) //{ // //buildwarning.WriteLine(sb.ToString()); // buildwarning.Close(); // buildwarning = null; //} if (String.IsNullOrEmpty(buildwaringfile) == false) { MSBuildEngineCommonHelper.SaveToMemory(warningstring.ToString(), ref warningmemorystream, buildwaringfile); MSBuildEngineCommonHelper.WritetoFilefromMemory(ref warningmemorystream, buildwaringfile); } MSBuildEngineCommonHelper.LogWarning = sb.ToString(); LogToBuildLog(tab.ToString() + sb.ToString()); sb = null; tab = null; } }
/// <summary> /// Overloaded Build log method, logs to buildlogfile. /// </summary> /// <param name="e"></param> /// <param name="binsertnewline"></param> private void LogToBuildLog(BuildEventArgs e, bool binsertnewline) { BuildWarningEventArgs warningeventargs = null; BuildErrorEventArgs erroreventargs = e as BuildErrorEventArgs; string currentprojectfile = null; StringBuilder sb = new StringBuilder(); string filename = null, errorid = null; int linenumber = -1, columnnumber = -1; if (erroreventargs == null) { warningeventargs = e as BuildWarningEventArgs; if (warningeventargs == null) { goto NonWarningErrorEvent; } filename = currentprojectfile; if (warningeventargs.LineNumber >= 0 && warningeventargs.ColumnNumber >= 0) { linenumber = warningeventargs.LineNumber; columnnumber = warningeventargs.ColumnNumber; } if (String.IsNullOrEmpty(warningeventargs.Code) == false) { errorid = warningeventargs.Code; } } else { filename = erroreventargs.File; if (erroreventargs.LineNumber >= 0 && erroreventargs.ColumnNumber >= 0) { linenumber = erroreventargs.LineNumber; columnnumber = erroreventargs.ColumnNumber; } if (String.IsNullOrEmpty(erroreventargs.Code) == false) { errorid = erroreventargs.Code; } } if (projectfilestack.Count == 0) { if (String.IsNullOrEmpty(globalcurrentprojfile) == false) { currentprojectfile = globalcurrentprojfile; } } else { currentprojectfile = projectfilestack.Peek().ToString(); } if (filename != null && String.IsNullOrEmpty(currentprojectfile) == false && filename.ToLowerInvariant() != PathSW.GetFileName(currentprojectfile).ToLowerInvariant()) { sb.Append(filename.ToString() + " "); if (linenumber >= 0 && columnnumber >= 0) { sb.Append("(" + linenumber + "," + columnnumber + ") " + " :"); } } if (errorid != null) { sb.Append(" warning " + errorid + ": "); } NonWarningErrorEvent: //if (_btimestamp && baddtimestamp) //{ // //sb.AppendFormat("{0} ms: {1} - ", e.Timestamp.ToString(), e.Timestamp.Millisecond.ToString()); ; // sb.AppendFormat("{0}:{1}:{2}:{3} - ", e.Timestamp.Hour.ToString(), e.Timestamp.Minute.ToString(), e.Timestamp.Second.ToString(), e.Timestamp.Millisecond.ToString()); //} sb.Append(e.Message); StringBuilder tab = new StringBuilder(); for (int i = 0; i < tabcount; i++) { tab.Append("\t"); } LogToBuildLog(tab.ToString() + sb.ToString()); if (binsertnewline) { LogToBuildLog(""); } sb = null; tab = null; }
/// <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> /// Generate the application definition file. /// </summary> /// <param name="xamlFile"></param> /// <param name="hostType"></param> /// <param name="targetType"></param> /// <param name="language"></param> /// <param name="additionalAppMarkup"></param> private void GenerateAppdef(string xamlFile, string hostType, string targetType, Languages language, string additionalAppMarkup) { TextWriterSW appdefFile = new StreamWriterSW(_appDefFileName); const string sysXmlns = "clr-namespace:System;assembly=mscorlib"; switch (hostType) { case "Application": if (targetType != "Container") { if (!String.IsNullOrEmpty(additionalAppMarkup)) { appdefFile.WriteLine("<Application x:Class=\"Application__\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" StartupUri=\"" + PathSW.GetFileName(xamlFile) + "\" DispatcherUnhandledException=\"HandleException\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:sys=\"" + sysXmlns + "\">"); } else { appdefFile.WriteLine("<Application x:Class=\"Application__\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" StartupUri=\"" + PathSW.GetFileName(xamlFile) + "\" DispatcherUnhandledException=\"HandleException\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">"); } } else if (!String.IsNullOrEmpty(additionalAppMarkup)) { appdefFile.WriteLine("<Application x:Class=\"Application__\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" DispatcherUnhandledException=\"HandleException\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:sys=\"" + sysXmlns + "\">"); } else { appdefFile.WriteLine("<Application x:Class=\"Application__\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" DispatcherUnhandledException=\"HandleException\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">"); } break; default: throw new TestSetupException("Parameter hostType has invalid value of " + hostType + ". The only valid value is Application"); } if (!String.IsNullOrEmpty(additionalAppMarkup)) { appdefFile.WriteLine(additionalAppMarkup); } appdefFile.WriteLine("<x:Code>"); appdefFile.WriteLine(" <![CDATA["); if (language == Languages.CSharp) { if (AutoCloseWindow) { appdefFile.WriteLine(" protected override void OnStartup(System.Windows.StartupEventArgs e)"); appdefFile.WriteLine(" {"); appdefFile.WriteLine(" Microsoft.Test.Logging.GlobalLog.LogStatus(\"In TestParserApp.OnStartup()...\");"); appdefFile.WriteLine(" Microsoft.Test.Logging.GlobalLog.LogStatus(\"Current directory: \" + Microsoft.Test.Security.Wrappers.EnvironmentSW.CurrentDirectory);"); appdefFile.WriteLine(" System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();"); appdefFile.WriteLine(" timer.Interval = TimeSpan.FromSeconds(10);"); appdefFile.WriteLine(" timer.Tick += delegate (object o, EventArgs args) {((System.Windows.Threading.DispatcherTimer)o).Stop(); System.Windows.Application.Current.Shutdown();};"); appdefFile.WriteLine(" timer.Start();"); appdefFile.WriteLine(" }"); } appdefFile.WriteLine(" public void HandleException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)"); appdefFile.WriteLine(" {"); appdefFile.WriteLine(" if(null != e.Exception)"); appdefFile.WriteLine(" {"); appdefFile.WriteLine(" e.Handled = true;"); appdefFile.WriteLine(" Microsoft.Test.Serialization.SerializationHelper.StoreException(e.Exception);"); appdefFile.WriteLine(" System.Windows.Application.Current.Shutdown();"); appdefFile.WriteLine(" }"); appdefFile.WriteLine(" }"); } else // Languages.VisualBasic { if (AutoCloseWindow) { appdefFile.WriteLine(" Protected Overrides Sub OnStartup(ByVal e As System.Windows.StartupEventArgs)"); appdefFile.WriteLine(" Dim timer As New System.Windows.Threading.DispatcherTimer()"); appdefFile.WriteLine(" timer.Interval = TimeSpan.FromSeconds(5)"); appdefFile.WriteLine(" AddHandler timer.Tick, AddressOf TimerHandler"); appdefFile.WriteLine(" timer.Start()"); appdefFile.WriteLine(" End Sub"); appdefFile.WriteLine(" Private Sub TimerHandler(ByVal o As Object, ByVal args As EventArgs)"); appdefFile.WriteLine(" Dim timer As System.Windows.Threading.DispatcherTimer"); appdefFile.WriteLine(" timer = o"); appdefFile.WriteLine(" timer.Stop()"); appdefFile.WriteLine(" System.Windows.Application.Current.Shutdown()"); appdefFile.WriteLine(" End Sub"); } appdefFile.WriteLine(" Sub HandleException(ByVal sender As Object, ByVal e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs)"); appdefFile.WriteLine(" If Not (e.Exception is Nothing)"); appdefFile.WriteLine(" e.Handled = True"); appdefFile.WriteLine(" Microsoft.Test.Serialization.SerializationHelper.StoreException(e.Exception)"); appdefFile.WriteLine(" System.Windows.Application.Current.Shutdown()"); appdefFile.WriteLine(" End If"); appdefFile.WriteLine(" End Sub"); } appdefFile.WriteLine(" ]]>"); appdefFile.WriteLine("</x:Code>"); // Write end tags. switch (hostType) { case "Application": appdefFile.Write("</Application>"); break; } appdefFile.Close(); }
/// <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); }
static Compiler() { msbuildDirectory = PathSW.GetDirectoryName(AssemblySW.Wrap(typeof(object).Assembly).Location); }
/// <summary> /// Encapsulated method - taking 3 input params /// Does the file generation. /// First based on inputs decides the final file name for the file to be generated. /// </summary> /// <param name="scenarioid"></param> /// <param name="variationstring"></param> private void GenerateFile(string scenarioid, string variationstring) { // If no scenarioid is defined set to all. if (scenarioid == null) { scenarioid = "_all"; } // If newfiledata is null make a bunch of checks to come up with final name and fileextension. FileData tempfiledata = definedfiledata; if (String.IsNullOrEmpty(tempfiledata.FileName)) { // Use default filename (defined in Attribute or element in TemplateData). Refer GetTemplateData method. tempfiledata.FileName = defaultfiledata.FileName; } if (String.IsNullOrEmpty(tempfiledata.FileExtension)) { // Use default fileextension (defined in Attribute or element in TemplateData). Refer GetTemplateData method. tempfiledata.FileExtension = defaultfiledata.FileExtension; } // Generate XmlDocument with defaultdata document innerxml. if (base.canvasdoc == null) { UtilsLogger.LogError = "Variation document is null"; return; } if (base.canvasdoc.GetElementsByTagName(Constants.TemplateDataElement) == null) { UtilsLogger.LogError = "Variation document did not contain TemplateData element"; return; } if (base.canvasdoc.GetElementsByTagName(Constants.TemplateDataElement).Count > 1) { UtilsLogger.LogError = "Variation document contained more than one TemplateData element"; return; } // Generated file name. if (_retainfilename == false) { if (variationstring != null) { generatedFile = tempfiledata.FileName + "_Sc" + scenarioid + "_Var" + variationstring + tempfiledata.FileExtension; } else { generatedFile = tempfiledata.FileName + "_Sc" + scenarioid + "_Var" + "all" + tempfiledata.FileExtension; } } else { generatedFile = tempfiledata.FileName + tempfiledata.FileExtension; } if (String.IsNullOrEmpty(_fileoutputdirectory) == false) { if (DirectorySW.Exists(_fileoutputdirectory)) { generatedFile = _fileoutputdirectory + PathSW.DirectorySeparatorChar + generatedFile; } } if (generatedFile.Contains(PathSW.DirectorySeparatorChar.ToString())) { string directoryname = PathSW.GetDirectoryName(generatedFile); if (string.IsNullOrEmpty(directoryname) == false) { if (DirectorySW.Exists(directoryname) == false) { if (DirectorySW.Exists(directoryname) == false) { DirectorySW.CreateDirectory(directoryname); } } } } if (_isxmldocument) { XmlDocumentSW tempdoc = new XmlDocumentSW(); tempdoc.LoadXml(base.canvasdoc.DocumentElement.InnerXml); GenerateFile(ref tempdoc); tempdoc = null; } else { GenerateFile(base.canvasdoc.DocumentElement.InnerText); } }