/// <summary> /// Override for WindowSetup /// </summary> public override void WindowSetup() { if (xamlfile != null || xamlfile != string.Empty) { FileStream f = new FileStream(xamlfile, FileMode.Open, FileAccess.Read); this.window.Content = (FrameworkElement)XamlReader.Load(f); f.Close(); } else { GlobalLog.LogEvidence(new Exception("No xamlfile specified for window content.")); } if (resourceDictionary != null) { this.window.Resources.MergedDictionaries.Add(resourceDictionary); } if (this.window.Content is FrameworkElement) { // Setting Window.Content size to ensure same size of root element over all themes. // Different themes have diffent sized window chrome which will cause property dump // and vscan failures even though the rest of the content is the same. // 784x564 is the content size of a 800x600 window in Aero them. ((FrameworkElement)this.window.Content).Height = 564; ((FrameworkElement)this.window.Content).Width = 784; } else { this.window.Height = 600; this.window.Width = 800; } }
/// <summary> /// Instantiates Property Dump Core with Visual that is root of XML dump /// </summary> /// <param name="visualId"></param> /// <param name="visualRoot"></param> void FindDumpRoot(string visualId, DependencyObject visualRoot) { DependencyObject DumpRoot = null; if (visualId == null || visualId == string.Empty) { DumpRoot = visualRoot; } else { DumpRoot = LogicalTreeHelper.FindLogicalNode(visualRoot, visualId); } if (DumpRoot == null) { GlobalLog.LogEvidence(new NullReferenceException("Dump root cannot be null.")); return; } if (DumpRoot is Visual) { core = new PropertyDumpCore((Visual)DumpRoot); } else { FindDumpRoot(visualId, DumpRoot); } }
/// <summary> /// Execture test actions. /// </summary> /// <param name="activeTest"></param> /// <param name="log"></param> void ExecuteTestActions(LayoutTest activeTest, TestLog log) { GlobalLog.LogStatus("BEGIN LAYOUT TEST"); try { if (activeTest is CodeTest) { RunCodeTest(activeTest, log); } if (activeTest is PropertyDumpTest) { RunPropertyDumpTest(activeTest, log); } if (activeTest is VisualScanTest) { RunVisualScanTest(activeTest, log); } } catch (Exception ex) { GlobalLog.LogEvidence(ex); } GlobalLog.LogStatus("END LAYOUT TEST"); }
/// <summary> /// Iterate the VariationEnumerator. If there is another variation run it, signal Finished. /// </summary> private void RunNextVariation() { if (VariationEnumerator.MoveNext()) { if (!CurrentVariation.TestCase.IsDisabled) { // Instantiate a logger that wrapps the ClientTestRuntime implementation. variationLog = new TestLog(CurrentVariation.ToString()); CurrentSuite._caseNumber = CurrentVariation.TestCase.Id; InitializeVariation(); // Use a command line to initialize the state for given Variation. // Make sure that we don't try to continue running a test if it failed during setup. if (CurrentVariation != null && CurrentVariation.Result != VariationResult.Failed && Mode != RunnerMode.SetupOnly) { GlobalLog.LogEvidence("Running Test Variation"); RunVariation(); // Run test variation, will close logger at the end. // NOTE: Cleanup is done when the result of the test is logged, may be asynchronous from the call to Run. } } else { //just in case disabled case gets ran. GlobalLog.LogEvidence("This case is disabled."); NumberOfVariationsComplete++; EndVariation(); } } else { EndVariation(); } }
private void CreateTestInfoXml(Arguments arguments) { TestInfo = string.Format("TestInfo.xml"); XmlTextWriter writer = null; try { //Create the additional info xml document writer = new XmlTextWriter(testInfoFile, UTF8Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("TESTCASE"); foreach (PropertyInfo pi in arguments.GetType().GetProperties()) { writer.WriteElementString(pi.Name, pi.GetValue(arguments, null).ToString()); } writer.WriteEndElement(); writer.WriteEndDocument(); } catch (Exception e) { //throw e; GlobalLog.LogEvidence(e); } finally { if (writer != null) { writer.Flush(); writer.Close(); } } }
/// <summary> /// Compares dump and master /// </summary> /// <param name="masterPath"></param> /// <param name="renderedPath"></param> /// <returns></returns> public bool CompareXmlFiles(string masterPath, string renderedPath) { bool result = false; GlobalLog.LogStatus("MASTER : " + masterPath); GlobalLog.LogStatus("RENDERED : " + renderedPath); // check if master exist, if not bail out. if (!File.Exists(masterPath)) { GlobalLog.LogEvidence("MASTER NOT FOUND"); result = false; return(result); } // Load master xml XmlDocument masterDoc = new XmlDocument(); masterDoc.PreserveWhitespace = false; masterDoc.Load(masterPath); // Load rendered xml XmlDocument renderedDoc = new XmlDocument(); renderedDoc.PreserveWhitespace = false; renderedDoc.Load(renderedPath); // Compare master and rendered result = CompareXmlFiles(masterDoc.DocumentElement, renderedDoc.DocumentElement); return(result); }
/// <summary> /// /// </summary> /// <param name="activeTest"></param> /// <param name="log"></param> void RunCodeTest(LayoutTest activeTest, TestLog log) { try { //create window ((CodeTest)activeTest).CreateWindow(); CommonFunctionality.FlushDispatcher(); //load test info.. ((CodeTest)activeTest).WindowSetup(); CommonFunctionality.FlushDispatcher(); //call test actions.. ((CodeTest)activeTest).TestActions(); CommonFunctionality.FlushDispatcher(); ////call verify.. ((CodeTest)activeTest).TestVerify(); CommonFunctionality.FlushDispatcher(); ((CodeTest)activeTest).CloseWindow(); CommonFunctionality.FlushDispatcher(); } catch (Exception ex) { GlobalLog.LogEvidence(ex); activeTest.Result = false; } }
internal static Window CreateWindow(bool isTransparent) { Window window; if (BrowserInteropHelper.IsBrowserHosted) { window = Application.Current.MainWindow; } else { GlobalLog.LogEvidence("Creating a Window"); Window winsw = new Window(); window = winsw; if (isTransparent) { GlobalLog.LogEvidence("Setting Window to Allow Transparency"); window.WindowStyle = WindowStyle.None; window.AllowsTransparency = isTransparent; } GlobalLog.LogEvidence("Showing the Window"); window.Show(); DispatcherHelper.DoEvents(0, DispatcherPriority.Input); } return(window); }
/// <summary> /// Compares XML files and logs result. /// </summary> /// <returns></returns> public bool CompareLogShow(Arguments arguments) { bool comparison = false; if (File.Exists(arguments.FilterPath)) { this.Core.Filter.XmlFilterPath = arguments.FilterPath; } else if (File.Exists(arguments.DefaultFilterPath)) { this.Core.Filter.XmlFilterPath = arguments.DefaultFilterPath; } else { GlobalLog.LogEvidence(new FileNotFoundException("Could not find " + arguments.FilterFile)); return(false); } this.Core.SaveXmlDump(arguments.RenderedPath); GlobalLog.LogStatus(string.Format("Searching for {0}.....", arguments.MasterFile)); arguments.MissingMaster = !SearchMaster(arguments); if (!arguments.MissingMaster) { comparison = this.Core.CompareXmlFiles(arguments.ComparePath, arguments.RenderedPath); if (comparison) { GlobalLog.LogStatus("XML COMPARE SUCCEEDED."); } else { GlobalLog.LogEvidence("XML COMPARE FAILED."); } } else { GlobalLog.LogEvidence("NO MASTER FOUND"); arguments.MissingMaster = true; comparison = false; } if (!comparison) { DiffPackage failurePackage = new DiffPackage(arguments.RenderedPath, arguments.ComparePath, arguments.MasterSdPath); string packageLocation = failurePackage.Save(arguments); if (!arguments.MissingMaster) { GlobalLog.LogEvidence(string.Format("FAILED MASTER : {0}", arguments.ComparePath)); } GlobalLog.LogFile(packageLocation); } return(comparison); }
/// <summary> /// Compare an exception string thrown at runtime to the expected string in a resource file /// </summary> /// <param name="actual">String that you would like to compare to.</param> /// <param name="resourceId">The Id of the exception that will be looked up.</param> /// <param name="assembly">assembly that contains the object throwing the exception</param> /// <param name="resourceName">the resource containing the exception string</param> /// <returns></returns> public static bool CompareMessage(string actual, string resourceId, Assembly assembly, string resourceName) { string expected = GetMessage(resourceId, assembly, resourceName); if (expected == null) { GlobalLog.LogEvidence(string.Format("Could not find message with resourceId {0} in {1} assembly's {2} resource.", resourceId, assembly.ToString(), resourceName)); return(false); } return(CompareMessage(actual, expected)); }
/// <summary> /// Compare an exception string thrown at runtime to the expected string in a resource file /// </summary> /// <param name="actual">String that you would like to compare to.</param> /// <param name="resourceId">ID of resource to look up.</param> /// <param name="targetBinary">WPF Resource that contains the object throwing the exception.</param> /// <returns></returns> public static bool CompareMessage(string actual, string resourceId, WpfBinaries targetBinary) { string expected = GetMessage(resourceId, targetBinary); if (expected == null) { GlobalLog.LogEvidence(string.Format("Could not find message with resourceId {0} in binary {1}.", resourceId, targetBinary.ToString())); return(false); } return(CompareMessage(actual, expected)); }
///// <summary> ///// Add additional files to the package ///// </summary> ///// <param name="filename">The filename (including path) of the file to add</param> //public void AddAdditionalFile(string filename) //{ // if (additionalFiles == null) // { // additionalFiles = new ArrayList(); // } // additionalFiles.Add(Path.GetFullPath(filename)); //} ///// <summary> ///// Gets the list of additional files in the package ///// </summary> ///// <returns>The list of full paths to the additional files</returns> //public string[] GetAdditionalFiles() //{ // if (additionalFiles != null) // { // return (string[])additionalFiles.ToArray(typeof(string)); // } // return null; //} /// <summary> /// Save the package on disk /// </summary> /// <param name="packageFilename"></param> /// <param name="arguments"></param> /// <returns></returns> public string Save(string packageFilename, Arguments arguments) { // Set the package to the given filename string package = arguments.Name; if (Path.GetExtension(package).Length == 0) { package += defaultExtension; } if (resultFile == null || !File.Exists(resultFile)) { //throw new Exception("The package MUST contain a result file before being saved"); GlobalLog.LogEvidence(new Exception("The package MUST contain a result file before being saved")); } // Fully expand the archiver name to ensure it is saved in the requested place // Create archiver archiver = Archiver.Create(Path.GetFullPath(package), true); // Add Master File if (masterFile != null) { AddFileFromPath(MasterFile, masterKey); } // Add the Result File AddResultFileFromPath(); // Add info xml File CreateInfoXmlFile(arguments); if (File.Exists(infoXmlFile)) { archiver.AddFile(infoXmlFile, infoKey, true); } //creates test info file for future use in master update app. CreateTestInfoXml(arguments); if (File.Exists(TestInfo)) { //AddFileFromPath(TestInfoFile, "TestInfoFile"); archiver.AddFile(TestInfo, testInfoKey, true); } // Generate package archiver.GenerateArchive(); // Return the full path to the archive return(Path.GetFullPath(package)); }
//Evaluate the rules for a UIHandlers that care about this UI private void ProcessUIHandlers(IntPtr topLevelhWnd, IntPtr hWnd, Process process, string title, UIHandlerNotification notification) { foreach (UIHandlerRule rule in handlerRules) { string procName; try { procName = process.ProcessName; } catch (InvalidOperationException) { // The process has exited so we do not need to process any more handlers GlobalLog.LogDebug("Tried to evaluate UI \"" + title + "\" but process had already exited."); return; } if (rule.Evaluate(title, procName, notification, hWnd)) { rule.HasBeenInvoked = true; UIHandlerAction action = UIHandlerAction.Abort; if (Debugger.IsAttached) { // If a debugger is attached then don't try catch since it makes debugging inconvenient action = rule.Handler.HandleWindow(topLevelhWnd, hWnd, process, title, notification); } else { // We can't trust the UIHandler to not throw an unhandled exception (crashes the app since the callback in on another thread) try { action = rule.Handler.HandleWindow(topLevelhWnd, hWnd, process, title, notification); } catch (Exception e) { // If an exception occurs log the exception and return abort GlobalLog.LogEvidence(e.ToString()); } } //If the action was handled then stop processing rules if (action == UIHandlerAction.Handled) { break; } //If the action was aborted then set the abort signal and stop processing rules else if (action == UIHandlerAction.Abort) { abortSignal.Set(); break; } } } }
private void SetWindow(Window testwin) { GlobalLog.LogStatus("VISUAL COMPARE"); WindowInteropHelper iwh = new WindowInteropHelper(testwin); HWND = iwh.Handle; if (iwh == null || HWND == IntPtr.Zero) { GlobalLog.LogEvidence(new Exception("Could not find the hwnd of the main window")); } }
public static void LogRunAllResults(int fail, int total) { string message = string.Empty; if (fail == 0) { message = "PASS - All tests passed"; } else { message = string.Format("FAIL - {0} out of {1} tests passed", total - fail, total); } GlobalLog.LogEvidence(message); }
/// <summary> /// Write the additional information to the info file /// </summary> private void CreateInfoXmlFile(Arguments arguments) { XmlTextWriter textWriter = null; try { //Create the additional info xml document textWriter = new XmlTextWriter(infoXmlFile, System.Text.UTF8Encoding.UTF8); textWriter.Formatting = Formatting.Indented; textWriter.WriteStartDocument(); textWriter.WriteStartElement("info"); //If the master location is not set then use the path to the master that was given if (MasterLocation == null && masterFile != null) { MasterLocation = arguments.ComparePath; } if (MasterLocation != null) { //Write the master location to the file if it exists textWriter.WriteElementString("master", masterLocation); } if (MasterSDPath != null) { //Write the master sd path to the file if it exists textWriter.WriteElementString("sdpath", masterSDPath); } if (CompareType != null) { //Write the compare tool to the file if it exists textWriter.WriteElementString("compare", compareType); } textWriter.WriteEndElement(); textWriter.WriteEndDocument(); } catch (Exception e) { //throw e; GlobalLog.LogEvidence(e); } finally { if (textWriter != null) { textWriter.Flush(); textWriter.Close(); } } }
// Since we're running in a different process than the loader, we need // to log a failure if there is an unhandled exception. private void _OnDispatcherException(object sender, DispatcherUnhandledExceptionEventArgs e) { if (TestLog.Current != null) { TestLog.Current.LogEvidence("Unhandled exception occurred in dispatcher."); TestLog.Current.LogEvidence(e.Exception.ToString()); TestLog.Current.Result = TestResult.Fail; } else { GlobalLog.LogEvidence("Unhandled exception occurred in dispatcher."); GlobalLog.LogEvidence(e.Exception.ToString()); } e.Handled = true; this.EndTest(); }
/// <summary></summary> /// <param name="element"></param> /// <returns></returns> internal static RECT GetElementRECT(FrameworkElement element) { Rectangle rc = GetTopLevelClientRelativeRect(element); IntPtr windowHandle = GetWindowHandleFromElement(element); if (windowHandle == IntPtr.Zero) { //throw new Exception( "Element has no associated window/HWND" ); GlobalLog.LogEvidence(new Exception("Element has no associated window/HWND")); } RECT rcWin32 = new RECT((int)rc.Left, (int)rc.Top, (int)rc.Right, (int)rc.Bottom); MapWindowPoints(windowHandle, IntPtr.Zero, ref rcWin32, 2); return(rcWin32); }
// ------------------------------------------------------------------ // Dump paragraph offset. // ------------------------------------------------------------------ private static Visual DumpParagraphOffset(XmlNode writer, ParagraphResultW paragraph, Visual visualParent) { if (writer == null) { throw new ArgumentNullException("writer"); } if (paragraph == null) { throw new ArgumentNullException("paragraph"); } if (visualParent == null) { throw new ArgumentNullException("visualParent"); } object paraClient = paragraph.GetField("_paraClient"); Type paraClientType = paraClient.GetType(); //PropertyInfoSW prop = TypeSW.Wrap(paraClientType).GetProperty("Visual", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); PropertyInfo prop = paraClientType.GetProperty("Visual", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); Visual visual = (Visual)prop.GetValue(paraClient, null); // Dump transform relative to its parent Matrix m; System.Windows.Media.GeneralTransform gt = visual.TransformToAncestor(visualParent); System.Windows.Media.Transform t = gt as System.Windows.Media.Transform; if (t == null) { //throw new System.ApplicationException("// GlobalLog.LogEvidence(new System.ApplicationException("//TODO: Handle GeneralTransform Case - introduced by Transforms Breaking Change")); } m = t.Value; Point point = new Point(0.0f, 0.0f) * m; if (point.X != 0 || point.Y != 0) { DumpPoint(writer, "Origin", point); } return(visual); }
/// <summary> /// This returns the position of the element. /// </summary> /// <param element="element"> element as a UIElement </param> /// <param ancestor="ancestor"> ancestor as a UIElement </param> /// <returns> Point of position X and Y of element </returns> public static System.Windows.Point GetElementPosition(UIElement element, UIElement ancestor) { System.Windows.Point position = new System.Windows.Point(); Matrix pt; System.Windows.Media.GeneralTransform gt = element.TransformToAncestor(ancestor); System.Windows.Media.Transform t = gt as System.Windows.Media.Transform; if (t == null) { //throw new System.ApplicationException("// GlobalLog.LogEvidence(new System.ApplicationException("//TODO: Handle GeneralTransform Case - introduced by Transforms Breaking Change")); } pt = t.Value; position.X = pt.OffsetX; position.Y = pt.OffsetY; return(position); }
/// <summary> /// Creates a FileHost with the Name specified by the Name property /// </summary> /// <returns>true</returns> protected override bool BeginStep() { if (UseUTF8Path) { if (UserDefinedDirectory != null) { GlobalLog.LogEvidence("WARNING: UserDefinedDirectory set as well as UseUTF8Path. Ignoring " + UserDefinedDirectory + " for randomly generated UTF-8 path"); } UserDefinedDirectory = GenerateRandomUTF8FileName(); GlobalLog.LogEvidence("Using UTF-8 folder name in file path: " + UserDefinedDirectory); } // Instantiate FileHost and upload support files fileHost = new FileHost(UserDefinedDirectory, UsingExternalServer); fileHost.PreserveDirectoryStructure = PreserveDirectoryStructure; foreach (SupportFile suppFile in SupportFiles) { if (suppFile.IncludeDependencies && !string.IsNullOrEmpty(suppFile.TargetDirectory)) { GlobalLog.LogEvidence("TargetDirectory with IncludeDependencies not yet implemented"); throw new NotImplementedException("TargetDirectory with IncludeDependencies not yet supported"); } if (suppFile.CustomTestScratchServerPath == null) { if (suppFile.IncludeDependencies) { fileHost.UploadFileWithDependencies(suppFile.Name); } else { fileHost.UploadFile(suppFile.Name, suppFile.TargetDirectory); } } else { fileHost.UploadFileNonDefaultServer(suppFile.Name, suppFile.CustomTestScratchServerPath); } } return(true); }
/// <summary> /// Runs original sources for LHCompiler loader as an AppMonitor LoaderStep, returns a value for success. /// </summary> public override bool DoStep() { GlobalLog.LogEvidence("AppMonitor Compilation Test step started"); string[] args = Arguments.Trim().Split(' '); ProjectFileExecutor filegenerator = new ProjectFileExecutor(); if (filegenerator.ParseCommandLine(args) == false) { GlobalLog.LogEvidence("Error encountered parsing command line args: \"" + Arguments + "\""); return(false); } filegenerator.InitializeLogger(); if (filegenerator.ReadSteps() == false) { TestLog.Current.Result = TestResult.Fail; Microsoft.Test.Utilities.Logger.LoggerInstance.Result(false); return(false); } // Let the config file specify what log stage we're in. // So now Build can = Initialize, Cleanup can = Cleanup. // Not necessary but it makes for nicely formatted logging. if (CurrentStage != TestStage.Unknown) { GlobalLog.LogEvidence("AppMonitor Compilation Test - Entering " + CurrentStage.ToString() + " stage"); TestLog.Current.Stage = CurrentStage; } if (filegenerator.Execute() == false) { filegenerator.CleanGeneratedFiles(); return(false); } GlobalLog.LogEvidence("AppMonitor Compilation Test - Cleaning generated files"); filegenerator.CleanGeneratedFiles(); return(true); }
private static IntPtr GetWindowHandleFromElement(System.Windows.FrameworkElement element) { System.Windows.PresentationSource isource = System.Windows.PresentationSource.FromVisual(element); if (isource == null) { //throw new Exception( "Could not get PresentationSource." ); GlobalLog.LogEvidence(new Exception("Could not get PresentationSource.")); } IWin32Window iwin = (IWin32Window)isource; if (iwin == null) { //throw new Exception( "Could not get IWin32Window." ); GlobalLog.LogEvidence(new Exception("Could not get IWin32Window.")); } return(iwin.Handle); }
/// <summary> /// /// </summary> /// <param name="activeTest"></param> /// <param name="log"></param> void RunVisualScanTest(LayoutTest activeTest, TestLog log) { try { //create window ((VisualScanTest)activeTest).CreateWindow(); CommonFunctionality.FlushDispatcher(); ((VisualScanTest)activeTest).WindowSetup(); CommonFunctionality.FlushDispatcher(); ((VisualScanTest)activeTest).CaptureAndCompare(); CommonFunctionality.FlushDispatcher(); ((VisualScanTest)activeTest).CloseWindow(); CommonFunctionality.FlushDispatcher(); } catch (Exception ex) { GlobalLog.LogEvidence(ex); activeTest.Result = false; } }
/// <summary> /// Saves XML dump to disc /// </summary> /// <param name="newXmlPath"></param> public void SaveXmlDump(string newXmlPath) { XmlNode node = DumpXml(); XmlTextWriter writer = null; try { writer = new XmlTextWriter(newXmlPath, System.Text.UTF8Encoding.UTF8); writer.Formatting = Formatting.Indented; node.WriteTo(writer); } catch (Exception e) { GlobalLog.LogEvidence(e); } finally { if (writer != null) { writer.Close(); } } }
private static Rectangle GetTopLevelClientRelativeRect( UIElement element) { // Get top-most visual. System.Windows.Media.Visual parent = element; while (System.Windows.Media.VisualTreeHelper.GetParent(parent) != null) { parent = (System.Windows.Media.Visual)System.Windows.Media.VisualTreeHelper.GetParent(parent); } // Get the points for the rectangle and transform them. double height = element.RenderSize.Height; double width = element.RenderSize.Width; System.Windows.Point[] points = new System.Windows.Point[4]; points[0] = new System.Windows.Point(0, 0); points[1] = new System.Windows.Point(width, 0); points[2] = new System.Windows.Point(0, height); points[3] = new System.Windows.Point(width, height); System.Windows.Media.Matrix m; System.Windows.Media.GeneralTransform gt = element.TransformToAncestor(parent); System.Windows.Media.Transform t = gt as System.Windows.Media.Transform; if (t == null) { //throw new System.ApplicationException("// GlobalLog.LogEvidence(new System.ApplicationException("//TODO: Handle GeneralTransform Case - introduced by Transforms Breaking Change")); } m = t.Value; m.Transform(points); System.Windows.Point topLeft, bottomRight; CalculateBoundingPoints(points, out topLeft, out bottomRight); return(new Rectangle( (int)topLeft.X, (int)topLeft.Y, (int)bottomRight.X - (int)topLeft.X, (int)bottomRight.Y - (int)topLeft.Y)); }
public static void Main(string wait) { DrtRunner driver = new DrtRunner(); try { GlobalLog.LogStatus("Clearing click once cache."); // string exeName = DriverState.DriverParameters["exe"]; string exeArgs = DriverState.DriverParameters["args"]; if (exeArgs == null) { exeArgs = "-catchexceptions"; } else if (!exeArgs.Contains("-catchexceptions")) { exeArgs += " -catchexceptions"; } exeArgs += $" {wait}"; TestLog log = new TestLog(DriverState.TestName); long startTime = DateTime.Now.Ticks; driver.Run(log, exeName, exeArgs); long endTime = DateTime.Now.Ticks; log.Close(); } catch (Exception e) { // Driver should always handle its exceptions becuase it is vastly more performant // then making a JitDebugger do it. GlobalLog.LogEvidence("Driver Error: " + e.ToString()); } }
/// <summary> /// Fills the member variables from the additional information file /// </summary> /// <param name="infoFile">The full path to the additional information file on the disk</param> private void ParseInfoXmlFile(string infoFile) { XmlDocument xmlDoc = null; try { //Load the information document xmlDoc = new XmlDocument(); xmlDoc.Load(infoFile); //Get the master location if it is contained in the Information file XmlNode nodeMasterLocation = xmlDoc.DocumentElement.SelectSingleNode("master"); if ((nodeMasterLocation != null) && (nodeMasterLocation.InnerText.Length != 0)) { MasterLocation = nodeMasterLocation.InnerText; } //Get the master sd path if it is contained in the Information file XmlNode nodeMasterSDPath = xmlDoc.DocumentElement.SelectSingleNode("sdpath"); if ((nodeMasterSDPath != null) && (nodeMasterSDPath.InnerText.Length != 0)) { masterSDPath = nodeMasterSDPath.InnerText; } //Get the compare tool if it is contained in the Information file XmlNode nodeCompare = xmlDoc.DocumentElement.SelectSingleNode("compare"); if ((nodeCompare != null) && (nodeCompare.InnerText.Length != 0)) { compareType = nodeCompare.InnerText; } } catch (Exception e) { GlobalLog.LogEvidence(e); //throw e; } }
// Used in XamlTest // internal static NavigationWindow CreateNavigationWindow(string filename, string callingAssembly, LoadCompletedEventHandler handler) { NavigationWindow navigationWindow; if (BrowserInteropHelper.IsBrowserHosted) { GlobalLog.LogDebug("Browser hosted"); navigationWindow = (NavigationWindow)Application.Current.MainWindow; } else { GlobalLog.LogDebug("not Browser hosted"); GlobalLog.LogEvidence("Creating a NavigationWindow"); NavigationWindow navwinsw = new NavigationWindow(); navigationWindow = navwinsw; } if (handler != null) { navigationWindow.LoadCompleted += handler; } string strUri = "pack://application:,,,/" + callingAssembly + ";component/" + filename; GlobalLog.LogEvidence("Navigating to " + strUri); navigationWindow.Navigate(new Uri(strUri, UriKind.RelativeOrAbsolute)); if (!BrowserInteropHelper.IsBrowserHosted) { GlobalLog.LogEvidence("Showing the Window"); navigationWindow.Show(); } DispatcherHelper.DoEvents(0, DispatcherPriority.Input); return(navigationWindow); }
/// <summary> /// Performs the Activation step /// </summary> /// <returns>returns true if the rest of the steps should be executed, otherwise, false</returns> protected override bool BeginStep() { //Create ApplicationMonitor appMonitor = new ApplicationMonitor(); // If defined, set a value in property bag. Used for communication test variations to target app if (PropertyBagValue != "") { // Update this code to allow > 1 prop bag values being set at once string[] values = PropertyBagValue.Trim().Split('='); if (values.Length == 2) { DictionaryStore.Current[values[0].Trim()] = values[1].Trim(); } else { throw new System.ArgumentException("Values must be a single 'foo=bar' format"); } } if (hostingPolicyResetter != null) { hostingPolicyResetter.Dispose(); } if (StrictHostingMode) { hostingPolicyResetter = HostingRuntimePolicyHelper.SetHostingRuntimePolicyValues( doNotLaunchV3AppInV4Runtime: true); } else { hostingPolicyResetter = HostingRuntimePolicyHelper.SetHostingRuntimePolicyValues( doNotLaunchV3AppInV4Runtime: false); } // upload files to FileHost is specified and scheme is not local if (Scheme != ActivationScheme.Local) { if (SupportFiles.Length > 0) { // Create host to copy files to... fileHost = new FileHost(UserDefinedDirectory, (Scheme == ActivationScheme.HttpInternetExternal)); // Upload each file foreach (SupportFile suppFile in SupportFiles) { // Whether to copy foo\bar\baz.xbap to the foo\bar created on the remote machine or just flattened fileHost.PreserveDirectoryStructure = suppFile.PreserveDirectoryStructure; if (suppFile.IncludeDependencies && !string.IsNullOrEmpty(suppFile.TargetDirectory)) { GlobalLog.LogEvidence("TargetDirectory with IncludeDependencies not yet implemented"); throw new NotImplementedException("TargetDirectory with IncludeDependencies not yet supported"); } if (suppFile.CustomTestScratchServerPath == null) { if (suppFile.IncludeDependencies) { fileHost.UploadFileWithDependencies(suppFile.Name); } else { fileHost.UploadFile(suppFile.Name, suppFile.TargetDirectory); } } else { fileHost.UploadFileNonDefaultServer(suppFile.Name, suppFile.CustomTestScratchServerPath); } } } // If no support files are listed, check the parent steps to see if one is a FileHostStep. // If this is the case, no need to upload the files as the FileHostStep has already. // Don't set throttle rate; this should be set in the markup for the parent's filehost. else { LoaderStep parent = this.ParentStep; while (parent != null) { if (parent.GetType() == typeof(Microsoft.Test.Loaders.Steps.FileHostStep)) { this.fileHost = ((FileHostStep)parent).fileHost; break; } // Failed to find it in the immediate parent: try til we hit null or the right one parent = parent.ParentStep; } } } // register UIHandlers foreach (UIHandler handler in UIHandlers) { if (handler.NamedRegistration != null) { appMonitor.RegisterUIHandler(handler, handler.NamedRegistration, handler.Notification); } else { appMonitor.RegisterUIHandler(handler, handler.ProcessName, handler.WindowTitle, handler.Notification); } } string param = ""; if (FileName.StartsWith("&") && FileName.EndsWith("&")) { param = DictionaryStore.Current[FileName.Substring(1, FileName.Length - 2)]; if (param == null) { throw new InvalidOperationException(FileName + " is not defined in the property bag; cannot be used to launch app"); } } else { // Allows for launching things in %program files%, which is localized. param = Environment.ExpandEnvironmentVariables(FileName); } if (Scheme != ActivationScheme.Local) { FileHostUriScheme hostScheme = FileHostUriScheme.Unc; if (Scheme != ActivationScheme.HttpInternetExternal) { hostScheme = (FileHostUriScheme)Enum.Parse(typeof(FileHostUriScheme), Scheme.ToString()); } param = fileHost.GetUri(FileName, hostScheme).ToString(); } // Clear the fusion cache by default. Can be disabled for custom ClickOnce scenarios if (ClearFusionCache) { ApplicationDeploymentHelper.CleanClickOnceCache(); } // Clear IE History but only if specified (defaults to false). Only matters for history-based navigation if (ClearIEHistory) { ApplicationDeploymentHelper.ClearIEHistory(); } // Launch the appropriate handler... switch (Method) { case ActivationMethod.Launch: { // This only works for local paths for security reasons. if (PresentationHostDebugMode) { param = Path.GetFullPath(param); // Workaround ... for some reason on XP64 there's no guarantee that it will actually find PresHost // Even though it verily is in the SysWOW64 directory. Solution... find the right one before we try string presHostPath = "presentationhost.exe"; if ((Environment.OSVersion.Version.Major == 5)) { presHostPath = (Directory.GetFiles(Environment.GetEnvironmentVariable("SystemRoot"), "PresentationHost.exe", SearchOption.AllDirectories))[0]; } appMonitor.StartProcess(presHostPath, " -debug \"" + param + "\""); } else { // Launch process with specified arguments. If shell: specified, then start that way. // If the arguments are for the URL, directly concatenate them. if ((Arguments.Length > 6) && (Arguments.ToLowerInvariant().StartsWith("shell:"))) { appMonitor.StartProcess(param, Environment.ExpandEnvironmentVariables(Arguments.Substring(6))); } else if ((Arguments.Length > 11) && (Arguments.ToLowerInvariant().StartsWith("currentdir:"))) { appMonitor.StartProcess(param, Path.Combine(Environment.CurrentDirectory, Arguments.Substring(11))); } else { appMonitor.StartProcess(param + Arguments); } } break; } case ActivationMethod.Navigate: { // If local we need to fully qualify the path if (Scheme == ActivationScheme.Local) { param = Path.GetFullPath(param); } // Fail to IE, since it has far more tests. string defaultBrowserExecutable = "iexplore.exe"; try { defaultBrowserExecutable = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Clients\StartMenuInternet", null, "iexplore.exe").ToString(); } catch (Exception) { try { defaultBrowserExecutable = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Clients\StartMenuInternet", null, "iexplore.exe").ToString(); } catch (Exception) { // Do nothing, some machines have been seen in weird states where this is undefined. Log it anyways. GlobalLog.LogDebug("Unable to get StartMenuInternet key, FireFox or other non-standard browser tests may be affected. Contact Microsoft if this is the case"); } } // Handle the case where this value exists but isnt set to anything usable. IE is far more common so fall back to it. if (string.IsNullOrEmpty(defaultBrowserExecutable)) { defaultBrowserExecutable = "iexplore.exe"; } // start the default browser... currently just FF or IE. if (defaultBrowserExecutable.ToLowerInvariant().Contains("iexplore")) { // Create & register IE navigation handler // IE can be strange: About:NavigateIE sometimes gets a cancelled navigation // Workaround: Be less sensitive about the window title we trigger on. appMonitor.RegisterUIHandler(new NavigateIE(param + Arguments), "iexplore", "RegExp:(Internet Explorer)", UIHandlerNotification.All); appMonitor.StartProcess("iexplore.exe", "about:NavigateIE"); } else if (defaultBrowserExecutable.ToLowerInvariant().Contains("firefox")) { if (Scheme == ActivationScheme.Unc) { param = param.Replace("file:", "").Replace("/", @"\"); } } else { throw new InvalidOperationException("Don't know how to navigate an instance of \"" + defaultBrowserExecutable + "\" browser!!! Contact Microsoft with this message."); } break; } // GOTO used here for fallthrough since there's only 2 lines difference. case ActivationMethod.EHome: goto case ActivationMethod.EHomeFullScreen; case ActivationMethod.EHomeFullScreen: { // If local we need to fully qualify the path if (Scheme == ActivationScheme.Local) { param = Path.GetFullPath(param); } // Get a reference to the path for the ehome exe... string eHomePath = Environment.GetEnvironmentVariable("SystemRoot") + "\\ehome\\ehshell.exe"; // Fail hard if EHome isnt present on the system. // Need to mark testcases accurately in test DB to avoid this. if (!File.Exists(eHomePath)) { throw new InvalidOperationException("\"Ehome\" or \"EHomeFullScreen\" method selected but case was run on non-Media-Center-enabled SKU! \n Contact Microsoft for more info on this issue."); } // Construct args with path to content to launch (MUST be a Uri) string eHomeArgs = "/url:\"" + param + "\""; // Tack on the argument for full screen if requested if (Method == ActivationMethod.EHomeFullScreen) { eHomeArgs += " /directmedia:general"; } // Start MCE... appMonitor.StartProcess(eHomePath, eHomeArgs); break; } } // Store the activation path into the property bag. This way apps or child steps can directly figure out the deployment URI DictionaryStore.Current["ActivationStepUri"] = param; return(true); }