/// <summary> /// if no choice is set and there is firmware set highest pri firmware to install first /// for now this will default to UEFI /// XMLWriter.SetRegErrCode(RegistryErrorCode, line); /// </summary> /// <param name="InputTestFilePath"></param> /// <param name="infName"></param> /// <returns></returns> internal static void SetRegErrCode(string RegistryErrorCode, string line) { try { Logger.FunctionEnter(); var testInputData = XDocument.Load(Program.InputTestFilePathBAK); var regCodes = testInputData.Descendants("RegistryErrorCodes"); foreach (var regCode in regCodes.Elements()) { regCode.Attribute("RegistryErrorCode").Value = RegistryErrorCode; regCode.Attribute("FailedFirmware").Value = line; } testInputData.Save(Program.InputTestFilePathBAK); Logger.FunctionLeave(); } catch (Exception ex) { GetData.GetExceptionMessage(ex); } }
/// <summary> /// Start a service if it is currently stopped /// StartStopServices.StartService(serviceName); /// </summary> /// <param name="serviceName"></param> internal static void StartService(string serviceName) { // is the service stopped. string startMode = "Automatic"; ServiceController sc2 = new ServiceController { ServiceName = serviceName }; Console.WriteLine("The " + serviceName + " service status is currently set to {0}", sc2.Status.ToString()); Logger.Comment("The " + serviceName + " service status is currently set to {0}", sc2.Status.ToString()); if (!sc2.StartType.Equals(startMode)) { ServiceStartModeUpdate(serviceName, startMode); } if (sc2.Status == ServiceControllerStatus.Stopped) { // Start it if it is stopped. Console.WriteLine("Stopping the " + serviceName + " service..."); Logger.Comment("Stopping the " + serviceName + " service..."); try { sc2.Start(); sc2.WaitForStatus(ServiceControllerStatus.Running); Console.WriteLine("The " + serviceName + " service status is now set to {0}.", sc2.Status.ToString()); Logger.Comment("The " + serviceName + " service status is now set to {0}.", sc2.Status.ToString()); } catch (Exception ex) { GetData.GetExceptionMessage(ex); } } }
/// <summary> /// read the XML to find the number of times it will need to loop through the list /// </summary> /// <param name="InputTestFilePath"></param> /// <returns></returns> internal static string IndexFromINF(string InputTestFilePath, string line) { string result = null; try { Logger.FunctionEnter(); var testInputData = XDocument.Load(InputTestFilePath); var driversPathList = testInputData.Descendants("InfDirectories"); foreach (var driverPath in driversPathList.Elements()) { string testLine = driverPath.Attribute("InfPath").Value.ToLower(); //Console.WriteLine("IndexFromINF finds testLine : " + testLine); //Console.ReadKey(); if (line.Equals(testLine)) { string index = driverPath.Attribute("InfIndex").Value; //Console.WriteLine("IndexFromINF finds InfIndex : " + index); //Console.ReadKey(); result = index; } else { continue; } } Logger.FunctionLeave(); return(result); } catch (Exception ex) { GetData.GetExceptionMessage(ex); return(result); } }
/// <summary> /// adds a runonce key so the executable will start again after a required reboot /// </summary> /// <param name="reStartBAT"></param> internal static void SetStartUpRegistry(string reStartBAT) { try { Logger.FunctionEnter(); Logger.Comment("trying to set reboot regKey..."); var rs = new RegistrySecurity(); string user = Environment.UserName; rs.AddAccessRule(new RegistryAccessRule(user, RegistryRights.WriteKey | RegistryRights.SetValue | RegistryRights.Delete, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow)); RegistryKey regkey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", true); regkey.SetAccessControl(rs); regkey.SetValue("DriverStressRebootKey", reStartBAT, RegistryValueKind.String); Logger.FunctionLeave(); } catch (Exception ex) { GetData.GetExceptionMessage(ex); } }
/// <summary> /// if exists find the oem##.inf file and delete it before attempting rollback /// GetDataFromReg.GetOEMinfNameFromReg(infName, hardwareID); /// </summary> /// <param name="infName"></param> /// <param name="hardwareID"></param> /// <returns></returns> internal static string GetOEMinfNameFromRegSTR(string actualInfName, string hardwareID, string classGUID) { string result = string.Empty; string infNameFromReg = string.Empty; Logger.FunctionEnter(); try { RegistryKey baseRk2; baseRk2 = Registry.LocalMachine.OpenSubKey(@"SYSTEM\ControlSet001\Control\Class\"); string[] subKeyList2 = baseRk2.GetSubKeyNames(); foreach (string subKey2 in subKeyList2) { if (string.IsNullOrEmpty(subKey2)) { continue; } RegistryKey regkey2 = baseRk2.OpenSubKey(subKey2); if (regkey2.ToString().Contains(classGUID)) { string[] keyValueNamesList2 = regkey2.GetSubKeyNames(); foreach (string keySubKeyValueName in keyValueNamesList2) { if (string.IsNullOrEmpty(keySubKeyValueName)) { continue; } if (keySubKeyValueName.Equals("Properties")) { continue; } RegistryKey SUBregkey2 = regkey2.OpenSubKey(keySubKeyValueName); string[] subSubkeyValueNamesList2 = SUBregkey2.GetValueNames(); foreach (string subSUBsubKeyValueName in subSubkeyValueNamesList2) { if (string.IsNullOrEmpty(subSUBsubKeyValueName)) { continue; } if (subSUBsubKeyValueName.Equals("MatchingDeviceId")) { string matchDevIDkey = SUBregkey2.GetValue("MatchingDeviceId").ToString().ToLower(); if (matchDevIDkey.Contains(hardwareID.ToLower())) { infNameFromReg = SUBregkey2.GetValue("InfPath").ToString(); result = infNameFromReg; Console.WriteLine(infNameFromReg); } } } } } } } catch (Exception ex) { Logger.Comment("exception thrown in GetDataFromReg getting oem inf name string..."); GetData.GetExceptionMessage(ex); } Logger.FunctionLeave(); return(result); }
/// <summary> /// if exists find the oem##.inf file and delete it before attempting rollback /// GetDataFromReg.GetOEMinfNameFromReg(infName, hardwareID); /// </summary> /// <param name="infName"></param> /// <param name="hardwareID"></param> /// <returns></returns> internal static void GetOEMinfNameFromReg(string actualInfName, string hardwareID, string classGUID) { string infNameFromReg = string.Empty; Logger.FunctionEnter(); try { RegistryKey baseRk2; baseRk2 = Registry.LocalMachine.OpenSubKey(@"SYSTEM\ControlSet001\Control\Class\"); string[] subKeyList2 = baseRk2.GetSubKeyNames(); foreach (string subKey2 in subKeyList2) { if (string.IsNullOrEmpty(hardwareID)) { break; } if (string.IsNullOrEmpty(subKey2)) { continue; } RegistryKey regkey2 = baseRk2.OpenSubKey(subKey2); if (regkey2.ToString().Contains(classGUID)) { string[] keyValueNamesList2 = regkey2.GetSubKeyNames(); foreach (string keySubKeyValueName in keyValueNamesList2) { if (string.IsNullOrEmpty(keySubKeyValueName)) { continue; } if (keySubKeyValueName.Equals("Properties")) { continue; } RegistryKey SUBregkey2 = regkey2.OpenSubKey(keySubKeyValueName); string[] subSubkeyValueNamesList2 = SUBregkey2.GetValueNames(); foreach (string subSUBsubKeyValueName in subSubkeyValueNamesList2) { if (string.IsNullOrEmpty(subSUBsubKeyValueName)) { continue; } if (subSUBsubKeyValueName.Equals("MatchingDeviceId")) { string matchDevIDkey = SUBregkey2.GetValue("MatchingDeviceId").ToString().ToLower(); if (matchDevIDkey.Contains(hardwareID.ToLower())) { infNameFromReg = SUBregkey2.GetValue("InfPath").ToString(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("infNameFromReg : " + infNameFromReg); Console.ForegroundColor = ConsoleColor.White; foreach (string infToCheck in Directory.EnumerateFiles(oemInfPath)) { if (infToCheck.Contains(infNameFromReg)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("deleting the oem##.inf file : " + infNameFromReg); Console.ForegroundColor = ConsoleColor.White; Logger.Comment("deleting the oem##.inf file : " + infNameFromReg); File.Delete(oemInfPath + infNameFromReg); } } } } } } } } } catch (Exception ex) { Logger.Comment("exception thrown in GetDataFromReg getting oem inf name..."); GetData.GetExceptionMessage(ex); } Logger.FunctionLeave(); }
///// <summary> ///// check the registry to be sure firmware is installed ///// still testing this ///// GetDataFromReg.CheckRegDriverIsInstalled(classGUID, infName, hardwareID, expectedDriverVersion, line); ///// </summary> ///// <param name="infName"></param> ///// <returns> value of LastAttempStatus or 0x12345678 if there was an error reading data </returns> //internal static bool CheckRegDriverIsInstalled(string classGUID, string infName, string hardwareID, string expectedDriverVersion, string line) //{ // Logger.FunctionEnter(); // bool isInstalledREGcheck = false; // string attemptVersionValue; // bool result = false; // string actualInfName = Path.GetFileNameWithoutExtension(infName); // RegistryKey baseRk; // baseRk = Registry.LocalMachine.OpenSubKey(@"SYSTEM\ControlSet001\Control\Class\"); // string[] subKeyList = baseRk.GetSubKeyNames(); // string[] textInput = File.ReadAllLines(line); // try // { // if (string.IsNullOrEmpty(hardwareID)) // { // foreach (string subKey in subKeyList) // { // RegistryKey regkey = baseRk.OpenSubKey(subKey); // if (Regex.Match(subKey, classGUID, RegexOptions.IgnoreCase).Success) // { // // get the "LastAttemptStatus" "LastAttemptVersion" "Version" // // using what I need to when needed may use them all eventually // // for now just gathering Version ...likely all I need // if (!subKey.Contains("Version")) { continue; } // attemptStatusValue = regkey.GetValue("LastAttemptStatus").ToString(); // versionValue = regkey.GetValue("Version").ToString(); // attemptVersionValue = regkey.GetValue("LastAttemptVersion").ToString(); // // int attemptStatusValueINT = Convert.ToInt32(attemptStatusValue); // foreach (string textLine in textInput) // { // if (Regex.Match(textLine, "Class=System", RegexOptions.IgnorePatternWhitespace).Success) // { // break; // } // if (Regex.Match(textLine, versionValue).Success) // { // if (attemptStatusValue.Equals("0")) // { // isInstalledREGcheck = true; // Logger.Comment("Matched the HW REV in the inf and Registry : " + attemptVersionValue); // } // } // } // Logger.Comment("result from the registry isInstalledREGcheck : " + attemptVersionValue); // result = isInstalledREGcheck; // } // else { continue; } // } // } // else if (isInstalledREGcheck == false) // { // foreach (string subKey in subKeyList) // { // RegistryKey regkey = baseRk.OpenSubKey(subKey); // if (Regex.Match(subKey, hardwareID, RegexOptions.IgnoreCase).Success) // { // attemptStatusValue = regkey.GetValue("LastAttemptStatus").ToString(); // versionValue = regkey.GetValue("Version").ToString(); // attemptVersionValue = regkey.GetValue("LastAttemptVersion").ToString(); // //int attemptStatusValueINT = Convert.ToInt32(attemptStatusValue); // foreach (string textLine in textInput) // { // if (Regex.Match(textLine, "Class=System", RegexOptions.IgnorePatternWhitespace).Success) // { // break; // } // if (Regex.Match(textLine, versionValue).Success) // { // if (attemptStatusValue.Equals("0")) // { // isInstalledREGcheck = true; // Logger.Comment("Matched the HW REV in the inf and Registry : " + attemptVersionValue); // } // } // } // Logger.Comment("result from the registry isInstalledREGcheck : " + attemptVersionValue); // result = isInstalledREGcheck; // } // else { continue; } // } // } // // ----------- // else // { // RegistryKey baseRk2; // baseRk2 = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\WIndows\Current\CurrentVersion\Uninstall\"); // string[] subKeyList2 = baseRk2.GetSubKeyNames(); // foreach (string subKey2 in subKeyList2) // { // RegistryKey regkey = baseRk.OpenSubKey(subKey2); // if (Regex.Match(subKey2, hardwareID, RegexOptions.IgnoreCase).Success) // { // string uninstallSTR = regkey.GetValue("UninstallString").ToString(); // versionValue = regkey.GetValue("DisplayVersion").ToString(); // //attemptVersionValue = regkey.GetValue("LastAttemptVersion").ToString(); // int attemptStatusValueINT = Convert.ToInt32(attemptStatusValue); // foreach (string textLine in textInput) // { // if (Regex.Match(textLine, "Class=System", RegexOptions.IgnorePatternWhitespace).Success) // { // break; // } // if (textLine.Contains(versionValue)) // { // if (uninstallSTR.Contains(infName)) // { // isInstalledREGcheck = true; // } // } // } // Logger.Comment("result from the registry isInstalledREGcheck : " + isInstalledREGcheck); // result = isInstalledREGcheck; // } // else { continue; } // } // } // //------------ // } // catch (Exception ex) // { // Logger.Comment("exception thrown in GetDataFromReg checking if driver is installed..."); // GetData.GetExceptionMessage(ex); // } // Logger.Comment("result from the registry isInstalledREGcheck : " + result); // return result; //} #endregion // 0: Success // 1: Unsuccessful // 2: Insufficient resources // 3: Incorrect version // 4: Invalid image format // 5: Authentication error // 6: Power event - AC not connected // 7: Power event - Insufficient battery /// <summary> /// check the registry to be sure firmware is installed /// GetDataFromReg.CheckRegIsInstalled(infName, hardwareID); /// </summary> /// <param name="infName"></param> /// <returns> value of LastAttempStatus or 0x12345678 if there was an error reading data </returns> internal static string CheckRegCapsuleIsInstalled(string infName, string hardwareID, string expectedDriverVersion, string line) { Logger.FunctionEnter(); string isInstalledREGcheck = string.Empty; string attemptVersionValue; string result = string.Empty; string actualInfName = Path.GetFileNameWithoutExtension(infName); RegistryKey baseRk; baseRk = Registry.LocalMachine.OpenSubKey(@"HARDWARE\UEFI\ESRT"); string[] subKeyList = baseRk.GetSubKeyNames(); string[] textInput = File.ReadAllLines(line); try { foreach (string subKey in subKeyList) { RegistryKey regkey = baseRk.OpenSubKey(subKey); if (Regex.Match(subKey, hardwareID, RegexOptions.IgnoreCase).Success) { attemptStatusValue = regkey.GetValue("LastAttemptStatus").ToString(); int attemptStatusValueINT = Convert.ToInt32(attemptStatusValue); versionValue = regkey.GetValue("Version").ToString(); int versionValueINT = Convert.ToInt32(versionValue); var regValHex = versionValueINT.ToString("X"); string regValueHex = "0x" + regValHex.ToLower(); string searchString = "HKR,,FirmwareVersion,%REG_DWORD%,"; attemptVersionValue = regkey.GetValue("LastAttemptVersion").ToString(); string isInstalled = string.Empty; foreach (string textLine in textInput) { if (textLine.StartsWith(searchString)) { string matchedValue = textLine.Split(',')[4].ToLower(); if (regValueHex.Equals(matchedValue)) { switch (isInstalled) { case string failed when(attemptStatusValueINT == 1): isInstalledREGcheck = "unsuccessful"; break; case string InsufficientResources when(attemptStatusValueINT == 2): isInstalledREGcheck = "InsufficientResources"; break; case string IncorrectVersion when(attemptStatusValueINT == 3): isInstalledREGcheck = "IncorrectVersion"; break; case string invalidImage when(attemptStatusValueINT == 4): isInstalledREGcheck = "invalidImage"; break; case string authenticationERR when(attemptStatusValueINT == 5): isInstalledREGcheck = "authenticationERR"; break; case string ACnotConnected when(attemptStatusValueINT == 6): isInstalledREGcheck = "ACnotConnected"; break; case string insufficientPower when(attemptStatusValueINT == 7): isInstalledREGcheck = "insufficientPower"; break; default: isInstalledREGcheck = "pass"; Logger.Comment("Matched the HW REV in the inf and Registry : " + isInstalledREGcheck); Logger.Comment("which means it definitely installed..."); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Matched the HW REV in the inf and Registry : " + isInstalledREGcheck); Console.WriteLine("which means it definitely installed..."); Console.WriteLine("regValueHex : " + regValueHex); Console.ForegroundColor = ConsoleColor.White; break; } } } } result = isInstalledREGcheck; } else { continue; } } } catch (Exception ex) { Logger.Comment("exception thrown in GetDataFromReg checking if firmware is installed..."); GetData.GetExceptionMessage(ex); } Logger.Comment("result from the registry isInstalledREGcheck : " + result); return(result); }
/// <summary> /// attempt to move the devMgr window over to the left after it opens /// so it is easier to monitor when running locally if need be /// currently not moving though /// </summary> /// <param name="hWnd"></param> /// <param name="X"></param> /// <param name="Y"></param> /// <param name="nWidth"></param> /// <param name="nHeight"></param> /// <param name="bRepaint"></param> /// <returns></returns> internal static void Main(string[] args) { bool show_help = false; List <string> extra = new List <string>(); ShowWindow(ThisConsole, MAXIMIZE); try { // create the .bat file used by the runonce registry entry to start testing again post-reboot if (!File.Exists(reStartBAT)) { File.WriteAllText(reStartBAT, "cd " + dirName + Environment.NewLine + stressAppPath); } string stressLog = "DriverCapsuleStressLog.txt"; Logger.AppendToFile = true; Logger.LogFileName = stressLog; Logger.LogDirName = dirName; if (!File.Exists(stressLog)) { Logger.AddLogFile(stressLog); } //Logger.Verbose(); if (!File.Exists(InputTestFilePath)) { // get user input parameters if there is not already an XML file to run from var p = new OptionSet() { { "r|randomizeList", "True or False - randomize the execution of the INFs", v => randomizeList = v }, { "i|loopCount", "the number of {TIMES} to stress drivers\\capsules. this must be an integer.", v => loopCount = v }, { "s|startChoice", "Choose driver\\capsule to install first(default will be UEFI", v => startChoice = v }, { "e|stopOnErrorSTR", "Stop testing if there is an error or failure and collect logs", v => stopOnErrorSTR = v }, { "g|groupFirmwareSTR", "Install all firmware then reboot rather than install\reboot for each", v => groupFirmwareSTR = v }, { "c|custom", "Install all drivers in a custom order using comma seperated list of INF names (e.g. SurfaceUEFI.inf,IntcAudioBus.inf,IntcOED.inf) or enter 'none'", v => custom = v }, { "h|help", "show this message and exit", v => show_help = v != null }, }; if (show_help) { ShowHelp(p); return; } extra = p.Parse(args); if (extra.Count > 0) { // is the WTT service started. StartStopServices.StopService("wttsvc"); // start testing here if starting fresh CreateListOrder.RandomizeList(args[1], args[3], args[5], args[7], args[9], args[11]); } else { ShowHelp(p); return; } } else { // is the WTT service started. StartStopServices.StopService("wttsvc"); // starts here if there is already an XML file written to run from XDocument xdoc = XDocument.Load(InputTestFilePath); string infIndexListString = XMLReader.GetSeed(InputTestFilePathBAK); int executionCount = XMLReader.GetExecutionCount(InputTestFilePath); supportFolderLOC = xdoc.XPathSelectElement("/Tests/TestChoices/SupportFolder").Value.ToString(); Array infListFromXML = xdoc.XPathSelectElements("/Tests/InfDirectories/InfDir").ToArray(); bool randomize = GetData.GetRandomChoice(InputTestFilePath); ExecuteFromList.ExecuteTheList(randomize, executionCount, startChoice); } } catch (Exception ex) { GetData.GetExceptionMessage(ex); } }
/// <summary> /// executes the stress in the order given by the list that was created /// only changed during execution when it finds firmware or the users choice to start first /// also groups firmware if chosen at runtime to install all firmware and reboot only once rather /// than rebooting for each firmware install seperately /// </summary> /// <param name="randomize"></param> /// <param name="executionCount"></param> /// <param name="dirName"></param> /// <param name="InputTestFilePath"></param> /// <param name="supportFolderLOC"></param> /// <param name="seedFilePath"></param> /// <param name="startChoice"></param> internal static void ExecuteTheList(bool randomize, int executionCount, string startChoice) { Process devMgr = new Process(); devMgr.StartInfo.FileName = @"C:\Windows\System32\mmc.exe"; devMgr.StartInfo.Arguments = "devmgmt.msc"; devMgr.Start(); try { List <string> DriverPathList = GetData.GetInfPathsList(Program.dirName); CheckWhatInstalled.CheckInstalledCSV(); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Waiting 3 seconds to be sure device is up and running..."); Console.ForegroundColor = ConsoleColor.White; Thread.Sleep(3000); if (RegCheck.IsRebootPending()) { Logger.Comment("there is a pending reboot..."); RebootAndContinue.RebootCmd(true); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Checking for last installed..."); Console.WriteLine("if it exists we'll check that it was successfull then..."); Console.WriteLine("... ExecuteTheList..."); Console.ForegroundColor = ConsoleColor.White; // check if lastInstalled in the XML was successfully installed post-reboot string tmpLine = XMLReader.GetLastInstalled(); if (string.IsNullOrEmpty(tmpLine)) { Console.WriteLine("no previous driver installed to check just yet..."); } else { string installCheck = GetData.IsInstalledAfterReboot(tmpLine); switch (installCheck) { case string unsuccessful when installCheck.Equals("unsuccessful"): DoThisIfFailedPostReboot(); break; case string InsufficientResources when installCheck.Equals("InsufficientResources"): DoThisIfFailedPostReboot(); break; case string IncorrectVersion when installCheck.Equals("IncorrectVersion"): DoThisIfFailedPostReboot(); break; case string invalidImage when installCheck.Equals("invalidImage"): DoThisIfFailedPostReboot(); break; case string authenticationERR when installCheck.Equals("authenticationERR"): DoThisIfFailedPostReboot(); break; case string ACnotConnected when installCheck.Equals("ACnotConnected"): DoThisIfFailedPostReboot(); break; case string insufficientPower when installCheck.Equals("insufficientPower"): DoThisIfFailedPostReboot(); break; default: installCheck.Equals("pass"); break; } } // making sure there is a driver path to test in the XML file // if they have all been removed they are all done and we need to rewrite the XML int infListCount = XMLReader.GetInfsPathListCount(Program.InputTestFilePathBAK); string infIndexListString = XMLReader.GetSeed(Program.InputTestFilePathBAK); if (string.IsNullOrEmpty(infIndexListString)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("infListCount = " + infListCount); Console.ForegroundColor = ConsoleColor.White; executionCount = XMLReader.GetExecutionCount(Program.InputTestFilePath); DriverStressInit.RewriteXMLContinue(executionCount, infListCount); } // double check the current executin count in the XML to be sure we proceed correctly int TMPexecutionCount = XMLReader.GetExecutionCount(Program.InputTestFilePath); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("executionCount : " + TMPexecutionCount); Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("time to check the executionCount and decide what to do..."); Console.WriteLine("...waiting 10 seconds for Windows to catch up to me......"); Console.WriteLine("----------------------------------------------------------"); Console.ForegroundColor = ConsoleColor.White; Thread.Sleep(10000); // if the execution count is now zero it is time to collect logs etc if (TMPexecutionCount == 0) { Console.WriteLine("waiting before continue to see if this is where it is dying....sometimes..."); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("-----------------------------------------"); Console.WriteLine("at this point...I think I am done...am I?"); Console.WriteLine("-----------------------------------------"); Console.ForegroundColor = ConsoleColor.White; ParseForResults.ParseFromdpinstLog(@"C:\Windows\DPINST.LOG"); File.Create(Program.dirName + @"\DONE.TXT"); CheckWhatInstalled.CheckInstalledCSV(); Logger.Comment("Copy the the driverstress log and DPINST.LOG to our folder..."); Utilities.CopyFile(@"C:\Windows\DPINST.LOG", Program.dpinstLog); Utilities.CopyFile(Program.InputTestFilePathBAK, Program.resultsLogDir + @"\DriverCapsuleStress.xml.BAK"); Utilities.CopyFile(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverCapsuleStressLog.txt"); Thread.Sleep(5000); Console.WriteLine("Everything should be completed including copying logs to the Reults folder on the desktop"); // is the WTT service stopped. StartStopServices.StartService("wttsvc"); Logger.FunctionLeave(); } while (TMPexecutionCount >= 1) { string seedStr = XMLReader.GetSeed(Program.InputTestFilePathBAK); XDocument xdoc = XDocument.Load(Program.InputTestFilePath); infIndexListString = XMLReader.GetSeed(Program.InputTestFilePathBAK); Console.WriteLine("infIndexListString = " + infIndexListString); if (randomize) { // if random is set to true this will take the list of index' for each INF // into a list and shuffle the numbers out of order randomly using random seed // then run through the list in that new order // this will be done uniquely each time through the list for the executionCount executionCount = XMLReader.GetExecutionCount(Program.InputTestFilePath); foreach (int seedIndex in infIndexListString.Split(',').Select(Int32.Parse).ToList <int>()) { if (seedIndex == 0) { break; } if (RegCheck.IsRebootPending()) { Logger.Comment("there is a pending reboot..."); Thread.Sleep(3000); RebootAndContinue.RebootCmd(true); } string index = Convert.ToString(seedIndex); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Current infIndex to be tested : " + index); Console.ForegroundColor = ConsoleColor.White; DriverPathList = GetData.GetInfPathsList(Program.dirName); string line = XMLReader.FromINFIndex(infListCount, Program.InputTestFilePath, seedIndex, executionCount).ToLower(); if (string.IsNullOrEmpty(line)) { XMLWriter.UpdateSeedXML(seedIndex); break; } string infName = Path.GetFileName(line); GetData.CreateIfMissing(Program.resultsLogDir); bool isCapsule = GetData.CheckDriverIsFirmware(line, executionCount, infListCount); switch (isCapsule) { case true: Logger.Comment("this is firmware treat it as such and reboot or rollback\reboot..."); infListCount--; CapsuleOrNotInstallCalls.IfIsCapsule(seedIndex, infIndexListString, infListCount, infName, DriverPathList, line, Program.InputTestFilePathBAK, Program.installer, executionCount, Program.dirName, Program.startChoice, Program.rollbackLine, Program.InputTestFilePath); break; default: Logger.Comment("this is NOT firmware check for reboot afer installed"); infListCount--; CapsuleOrNotInstallCalls.IsNotCapsule(seedIndex, infIndexListString, infListCount, infName, DriverPathList, line, Program.InputTestFilePathBAK, Program.installer, executionCount, Program.dirName, Program.startChoice, Program.rollbackLine, Program.InputTestFilePath); break; } } RebootAndContinue.RebootCmd(true); } else { // straight through the list 1-# accounting for other parameters below // groupFirmware or not as well as user choice first string testIsStartChoice = GetData.GetTestFirst(Program.InputTestFilePath); if (testIsStartChoice.Equals("none") & (Directory.EnumerateDirectories(Program.dirName, "uefi")).Equals(true)) { XMLWriter.SetTestFirst("uefi"); } else if (testIsStartChoice.Equals("none") & (Directory.EnumerateDirectories(Program.dirName, "sam")).Equals(true)) { XMLWriter.SetTestFirst("sam"); } else { testIsStartChoice = "none"; } // add ability to group install all firmware together with only one reboot // in this case the firmware would all install individually but have only one reboot // user should see each different color bar during reboot\install of all firmware bool groupFirmware = XMLReader.GetGroupFirmware(Program.InputTestFilePathBAK); int capListCount = 0; if (groupFirmware) { executionCount = XMLReader.GetExecutionCount(Program.InputTestFilePath); foreach (int seedIndex in infIndexListString.Split(',').Select(Int32.Parse).ToList <int>()) { Console.WriteLine("if (groupFirmware) - seedIndex : " + seedIndex); string line = XMLReader.FromINFIndex(infListCount, Program.InputTestFilePath, seedIndex, executionCount).ToLower(); if (string.IsNullOrEmpty(line)) { XMLWriter.UpdateSeedXML(seedIndex); break; } Console.WriteLine("if (groupFirmware) - line : " + line); bool isCapsule = GetData.CheckDriverIsFirmware(line, executionCount, infListCount); if (isCapsule) { capListCount++; capList.Add(line); } else { continue; } } while (capListCount > 1) { // if this is set to true this will get the firmware in the list to install // install each one and reboot at the end rather than rebooting for each install // replicating more of what a user might see at home when getting more than one // firmware update from WU foreach (string groupedFirmware in capList) { { string seedIndexSTR = XMLReader.IndexFromINF(Program.InputTestFilePath, groupedFirmware); int seedIndex = Convert.ToInt32(seedIndexSTR); XMLWriter.RemoveXMLElemnt(Program.InputTestFilePath, groupedFirmware, seedIndex); Console.WriteLine("seedIndex : " + seedIndex); string friendlyDriverName = XMLReader.GetFriendlyDriverName(Program.InputTestFilePath, groupedFirmware); string hardwareID = GetData.FirmwareInstallGetHID(groupedFirmware); string expectedDriverVersion = GetData.GetDriverVersion(groupedFirmware); Logger.Comment("IfIsCapsule From RegCheck before IF : " + expectedDriverVersion); string infNameToTest = Path.GetFileNameWithoutExtension(groupedFirmware); string expectedDriverDate = GetData.GetDriverDate(groupedFirmware); bool isInstalled = CheckWhatInstalled.CheckInstalled(groupedFirmware, hardwareID, friendlyDriverName, infNameToTest, expectedDriverVersion, expectedDriverDate); switch (isInstalled) { case true: string infFileContent = File.ReadAllText(groupedFirmware).ToUpper(); string infName = Path.GetFileNameWithoutExtension(groupedFirmware); SafeNativeMethods.RollbackInstall(seedIndex, groupedFirmware, infName, infFileContent, hardwareID, rebootRequired = true, Program.InputTestFilePath); break; case false: string groupedFirmwareDIR = Path.GetDirectoryName(groupedFirmware); string installArgs = " /C /A /Q /SE /F /PATH " + groupedFirmwareDIR; SafeNativeMethods.Install_Inf(groupedFirmware, Program.installer, installArgs, seedIndex); break; } } capListCount--; } RebootAndContinue.RebootCmd(true); } } executionCount = XMLReader.GetExecutionCount(Program.InputTestFilePath); foreach (int seedIndex in infIndexListString.Split(',').Select(Int32.Parse).ToList <int>()) { if (seedIndex == 0) { break; } string index = Convert.ToString(seedIndex); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Current infIndex to be tested : " + index); Console.ForegroundColor = ConsoleColor.White; if (index.Equals(null)) { continue; } GetData.CreateIfMissing(Program.resultsLogDir); string line = XMLReader.FromINFIndex(infListCount, Program.InputTestFilePath, seedIndex, executionCount).ToLower(); if (string.IsNullOrEmpty(line)) { XMLWriter.UpdateSeedXML(seedIndex); break; } string infName = Path.GetFileNameWithoutExtension(line); testIsStartChoice = GetData.GetTestFirst(Program.InputTestFilePath); string testInfName = infName.ToLower(); infIndexListString = XMLReader.GetSeed(Program.InputTestFilePathBAK); // the tool will skip to here if none of the other above are met // then looking for a choice set to install first from the list // only works when random is set to False if (line.Contains(testIsStartChoice.ToLower())) { Logger.Comment("This is the start first choice : " + line); bool isCapsule = GetData.CheckDriverIsFirmware(line, executionCount, infListCount); switch (isCapsule) { case true: infListCount--; Logger.Comment("re-add the reg key to start post reboot..."); CapsuleOrNotInstallCalls.IfIsCapsule(seedIndex, infIndexListString, infListCount, infName, DriverPathList, line, Program.InputTestFilePathBAK, Program.installer, executionCount, Program.dirName, Program.startChoice, Program.rollbackLine, Program.InputTestFilePath); break; default: Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("NOT MATCHING to the startChoice"); Console.ForegroundColor = ConsoleColor.White; infListCount--; CapsuleOrNotInstallCalls.IsNotCapsule(seedIndex, infIndexListString, infListCount, infName, DriverPathList, line, Program.InputTestFilePathBAK, Program.installer, executionCount, Program.dirName, Program.startChoice, Program.rollbackLine, Program.InputTestFilePath); break; } } } infIndexListString = XMLReader.GetSeed(Program.InputTestFilePathBAK); foreach (int seedIndex in infIndexListString.Split(',').Select(Int32.Parse).ToList <int>()) { if (seedIndex == 0) { break; } string index = Convert.ToString(seedIndex); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Current infIndex to be tested : " + index); Console.ForegroundColor = ConsoleColor.White; string indexString = Convert.ToString(index); if (index.Equals(null)) { continue; } string line = XMLReader.FromINFIndex(infListCount, Program.InputTestFilePath, seedIndex, executionCount).ToLower(); if (string.IsNullOrEmpty(line)) { XMLWriter.UpdateSeedXML(seedIndex); break; } bool isCapsule = GetData.CheckDriverIsFirmware(line, executionCount, infListCount); string infName = Path.GetFileName(line); testIsStartChoice = GetData.GetTestFirst(Program.InputTestFilePath); switch (isCapsule) { case true: Logger.Comment("this is firmware and will need to reboot..."); infListCount--; CapsuleOrNotInstallCalls.IfIsCapsule(seedIndex, infIndexListString, infListCount, infName, DriverPathList, line, Program.InputTestFilePathBAK, Program.installer, executionCount, Program.dirName, Program.startChoice, Program.rollbackLine, Program.InputTestFilePath); break; default: Logger.Comment("THIS IS NOT FIRMWARE..."); infListCount--; CapsuleOrNotInstallCalls.IsNotCapsule(seedIndex, infIndexListString, infListCount, infName, DriverPathList, line, Program.InputTestFilePathBAK, Program.installer, executionCount, Program.dirName, Program.startChoice, Program.rollbackLine, Program.InputTestFilePath); break; } } RebootAndContinue.RebootCmd(true); } executionCount--; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("executionCount :: " + executionCount); Console.WriteLine("outside of the while loop"); Console.WriteLine("should be getting smaller correctly"); Console.ForegroundColor = ConsoleColor.White; } } catch (Exception ex) { GetData.GetExceptionMessage(ex); } }
/// <summary> /// Determine if a reboot is needed to apply updates /// </summary> /// <returns></returns> internal static bool IsRebootPending() { Logger.FunctionEnter(); const string psFile = @".\CheckRebootState.ps1"; bool rc = false; try { // next requires wu service to be running //WUApiLib.UpdateInstaller inst = new UpdateInstaller(); //rc = inst.RebootRequiredBeforeInstallation; if (!rc && File.Exists(psFile) && !CloudUtilities.IsCloudOS()) { if (PS.RunPSCommand(@"-File " + psFile, out string outstr, true)) { Logger.Debug("output string from PS: " + outstr); rc = outstr.ToLower().Contains("true"); } } if (!rc) { Logger.Debug("Com lookup returned false, checking registry to confirm"); // check registry keys for potential pending updates const string _rebootKey1 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\"; const string _rebootKey2 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\"; const string _rebootValue = "RebootRequired"; const string _sessionMgrKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\"; const string _pendingRenameValue = "PendingFileRenameOperations"; Logger.Debug("Checking for {0}", _sessionMgrKey); RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); RegistryKey subKey = baseKey.OpenSubKey(_sessionMgrKey); if (subKey != null) { Logger.Debug("Getting Subkey {0}", _pendingRenameValue); var value = subKey.GetValue(_pendingRenameValue); if (value != null) { var stringList = new List <string>(value as string[]); if (stringList.Count > 0) { Logger.Comment("Pending Reboot Detected: Pending rename registry key setting found"); rc = true; } } } // NOTE: the next may fail on domain-joined machines due to MS domain admin policies. // this should run ok for WTT machines which is the intended target. Logger.Debug("Checking {0}", _rebootKey1); subKey = baseKey.OpenSubKey(_rebootKey1); if (subKey != null) { string[] subKeys = subKey.GetSubKeyNames(); if (subKeys.Contains(_rebootValue)) { Logger.Comment("Pending Reboot Detected: Pending reboot required registry key found"); rc = true; } } Logger.Debug("Checking {0}", _rebootKey2); subKey = baseKey.OpenSubKey(_rebootKey2); if (subKey != null) { string[] subKeys = subKey.GetSubKeyNames(); if (subKeys.Contains(_rebootValue)) { Logger.Comment("Pending Reboot Detected: Pending reboot required registry key found"); rc = true; } } } } catch (Exception ex) { GetData.GetExceptionMessage(ex); } Logger.Debug("Reboot Pending Query Returning {0}", rc); Logger.FunctionLeave(); return(rc); }
/// <summary> /// creates the XML that this executable uses to actually run the testing /// </summary> /// <param name="dirName"></param> /// <param name="randomize"></param> /// <param name="seedFileText"></param> /// <param name="stringList"></param> /// <param name="startChoice"></param> /// <param name="executionCount"></param> /// <param name="supportFolderLOC"></param> /// <param name="InputTestFilePath"></param> internal static void CreateXML(string dirName, bool randomize, string seedFileText, string stringList, string startChoice, int executionCount, string supportFolderLOC, string InputTestFilePath, string stopOnErrorSTR, string groupFirmwareSTR, string dumpFilePath, string custom) { string lastInstalled = string.Empty; string dumpExist = "False"; string logString = string.Empty; string RegistryErrorCode = string.Empty; string infName = string.Empty; XmlWriter xmlWriter = XmlWriter.Create(InputTestFilePath); int infIndex = 0; int infsPathListCount = 0; List <string> infsPathList = new List <string>(); xmlWriter.WriteStartDocument(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("Tests"); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("InfDirectories"); xmlWriter.WriteWhitespace("\n"); if (custom.Equals("none")) { infsPathList = GetData.GetInfPathsList(dirName); infsPathListCount = infsPathList.Count; foreach (string infDir in infsPathList) { infName = Path.GetFileNameWithoutExtension(infDir); // string friendlyInfName = GetData.FindFriendlyNameInCSV(infName); // TRIED TO USE THE DICTIONARY BUT I CAN HAVE DUP VALUES FOR INF NAMES // IN CSV FILE WITHOUT ISSUE BUT DICTIONARY FAILS WITH DUP VALUES string friendlyInfName = Names_Dictionary.GetNamesMatch(infName); infIndex++; xmlWriter.WriteStartElement("InfDir"); xmlWriter.WriteAttributeString("InfName", friendlyInfName); xmlWriter.WriteAttributeString("InfPath", infDir); xmlWriter.WriteAttributeString("InfIndex", infIndex.ToString()); xmlWriter.WriteAttributeString("ErrorCount", "0"); xmlWriter.WriteAttributeString("FailedCount", "0"); xmlWriter.WriteAttributeString("SuccessfullInstalls", "0"); xmlWriter.WriteAttributeString("SuccessfullUninstalls", "0"); xmlWriter.WriteAttributeString("RollbacksErrorCount", "0"); xmlWriter.WriteAttributeString("RollbacksFailedCount", "0"); xmlWriter.WriteAttributeString("SuccessfullRollbacks", "0"); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); } } else { infsPathList = CustomExecutionOrder.CustomOrder(custom); infsPathListCount = GetData.GetPathListCount(Program.dirName); foreach (string infDir in infsPathList) { infName = Path.GetFileNameWithoutExtension(infDir); // string friendlyInfName = GetData.FindFriendlyNameInCSV(infName); // TRIED TO USE THE DICTIONARY BUT I CAN HAVE DUP VALUES FOR INF NAMES // IN CSV FILE WITHOUT ISSUE BUT DICTIONARY FAILS WITH DUP VALUES string friendlyInfName = Names_Dictionary.GetNamesMatch(infName); infIndex++; xmlWriter.WriteStartElement("InfDir"); xmlWriter.WriteAttributeString("InfName", friendlyInfName); xmlWriter.WriteAttributeString("InfPath", infDir); xmlWriter.WriteAttributeString("InfIndex", infIndex.ToString()); xmlWriter.WriteAttributeString("ErrorCount", "0"); xmlWriter.WriteAttributeString("FailedCount", "0"); xmlWriter.WriteAttributeString("SuccessfullInstalls", "0"); xmlWriter.WriteAttributeString("SuccessfullUninstalls", "0"); xmlWriter.WriteAttributeString("RollbacksErrorCount", "0"); xmlWriter.WriteAttributeString("RollbacksFailedCount", "0"); xmlWriter.WriteAttributeString("SuccessfullRollbacks", "0"); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); infsPathListCount = infIndex; } } xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("TestChoices"); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("SupportFolder"); xmlWriter.WriteString(supportFolderLOC); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("randomizeList"); xmlWriter.WriteString(randomize.ToString()); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("GroupFirmware"); xmlWriter.WriteString(groupFirmwareSTR); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("StartChoice"); xmlWriter.WriteString(startChoice); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("StopOnError"); xmlWriter.WriteString(stopOnErrorSTR); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("ExecutionCount"); xmlWriter.WriteString(executionCount.ToString()); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("StartSeed"); xmlWriter.WriteString(seedFileText); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("CurrentSeed"); xmlWriter.WriteString(stringList); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("DumpExists"); xmlWriter.WriteString(dumpExist); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("DumpFilePath"); xmlWriter.WriteString(dumpFilePath); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("FailedErroredINFs"); xmlWriter.WriteString(logString); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("InfsPathListCount"); xmlWriter.WriteString(infsPathListCount.ToString()); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("LastInstalled"); xmlWriter.WriteString(lastInstalled); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteStartElement("RegistryErrorCodes"); xmlWriter.WriteAttributeString("RegistryErrorCode", RegistryErrorCode); xmlWriter.WriteAttributeString("FailedFirmware", infName); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteEndElement(); xmlWriter.WriteWhitespace("\n"); xmlWriter.WriteEndDocument(); xmlWriter.Close(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("check the XML..."); Console.ForegroundColor = ConsoleColor.White; }
/// <summary> /// check if the driver we are about to install has already been installed /// if it has and is firmware then rollback if is not then just uninstall /// </summary> /// <param name="infNameToTest"></param> /// <param name="expectedDriverVersion"></param> /// <returns></returns> internal static bool CheckInstalled(string line, string hardwareID, string friendlyDriverName, string infNameToTest, string expectedDriverVersion, string expectedDriverDate) { Logger.FunctionEnter(); string installedDriversCSVPath = Program.dirName + @"\installledDrivers.csv"; string csvFileName = "DeviceName-InfName.czv"; string csvFileFullPath = Program.dirName + csvFileName; string infName = string.Empty; string infNameFromReg = string.Empty; string installedDriverVersion = string.Empty; string installedDeviceName = string.Empty; bool result = false; string classGUID = GetData.GetClassGUID(line); if (string.IsNullOrEmpty(hardwareID)) { //do nothing for now hardwareID = "0x00000000"; Console.WriteLine("not getting a hardwareID...??"); Logger.Comment("no hardwareID in the INF so we can't use it to check if driver is installed"); } else { infNameFromReg = GetDataFromReg.GetOEMinfNameFromRegSTR(infName, hardwareID, classGUID); } try { using (ManagementObjectSearcher s2 = new ManagementObjectSearcher( "root\\CIMV2", "SELECT * FROM Win32_PnPSignedDriver")) foreach (ManagementObject WmiObject in s2.Get()) { if (WmiObject["InfName"] == null) { continue; } else { infName = WmiObject["InfName"].ToString(); } if (WmiObject["DriverVersion"] == null) { continue; } else { installedDriverVersion = WmiObject["DriverVersion"].ToString(); } if (WmiObject["DeviceName"] == null) { continue; } else { installedDeviceName = WmiObject["DeviceName"].ToString(); } // there are zeros in driver versions in inf files that are not in the devMgr // and viceVersa will have to remove\replace all zeros with "" if (expectedDriverVersion.EndsWith("0")) { expectedDriverVersion = expectedDriverVersion.TrimEnd('0'); expectedDriverVersion = expectedDriverVersion.TrimEnd('.'); expectedDriverVersion = expectedDriverVersion.TrimEnd('0'); } if (installedDriverVersion.EndsWith("0")) { installedDriverVersion = installedDriverVersion.TrimEnd('0'); installedDriverVersion = installedDriverVersion.TrimEnd('.'); installedDriverVersion = installedDriverVersion.TrimEnd('0'); } if (installedDeviceName.Contains(" ")) { installedDeviceName = installedDeviceName.Replace(" ", ""); } if (infName.Contains(" ")) { infName = infName.Replace(" ", ""); } if (infNameToTest.Contains(" ")) { infNameToTest = infNameToTest.Replace(" ", ""); } if (friendlyDriverName.Contains(" ")) { friendlyDriverName = friendlyDriverName.Replace(" ", ""); } infNameToTest = infNameToTest.Split('.')[0]; if (infNameToTest.Equals("SurfaceEC")) { infNameToTest = "SurfaceEmbeddedControllerFirmware"; } string lineContains = string.Empty; switch (lineContains) { case string infNameFromR when infName.Equals(infNameFromReg): if (expectedDriverVersion.Equals(installedDriverVersion)) { Logger.Comment(infNameToTest); result = true; Logger.Comment("result from checkInstalled TRUE infName/version : "); } break; case string installedDeviceNam when friendlyDriverName.Equals(installedDeviceName): if (expectedDriverVersion.Equals(installedDriverVersion)) { Logger.Comment(infNameToTest); result = true; Logger.Comment("result from checkInstalled TRUE infName/version : "); } break; case string failedResult when Regex.Match(infName, friendlyDriverName).Success: if (expectedDriverVersion.Equals(installedDriverVersion)) { Logger.Comment(infNameToTest); result = true; Logger.Comment("result from checkInstalled TRUE infName/version : "); } break; case string successinstallResult when infName.Equals(infNameFromReg): if (expectedDriverVersion.Equals(installedDriverVersion)) { Logger.Comment(infNameToTest); result = true; Logger.Comment("result from checkInstalled TRUE infName/version : "); } break; case string last when installedDeviceName.Contains(infNameToTest): if (expectedDriverVersion.Equals(installedDriverVersion)) { Logger.Comment(infNameToTest); result = true; Logger.Comment("result from checkInstalled TRUE infName/version : "); } break; default: continue; } } } catch (Exception ex) { GetData.GetExceptionMessage(ex); } Logger.Comment("result actually being returned from checkInstalled : " + result); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("result actually being returned from checkInstalled : " + result); Console.ForegroundColor = ConsoleColor.White; Logger.FunctionLeave(); return(result); }
/// <summary> /// This does the driver\capsule installation and checks for the exit code to /// decide what to do next /// </summary> /// <param name="line"></param> /// <param name="installer"></param> /// <param name="installArgs"></param> internal static void Install_Inf(string line, string installer, string installArgs, int seedIndex) { Logger.FunctionEnter(); #region STRINGS AND THINGS string failureCause = "None"; string expectedDriverVersion = "N/A"; string beforeDriverStatus = "N/A"; string afterDriverStatus = "N/A"; bool deviceRuning = true; string errorCodeMessage; string installationExitCode; int TimeOut = 120; //string notInstalledExitCode = "0x800"; string couldNotFindInfToDelete = "0x80000000"; string ElementNotFoundCode = "0x490"; string DeviceCanNotStartCode = "0x10"; string InfFileAlteredCode = "0x80010000"; string NoMatchingDevice = "0xB7"; #endregion try { // starts the installation and checks for exit code // Logger.Comment("...trying to install now"); Logger.Comment("========================="); Logger.Comment(line); Logger.Comment(installer + installArgs); string runCommandinstallArgs = installArgs; Process process = Utilities.RunCommand(installer, runCommandinstallArgs, true); string errorMessage = process.StandardError.ReadToEnd(); string stdOutput = process.StandardOutput.ReadToEnd(); int exitCode = process.ExitCode; string exitCodeInHex = ConvertExitCodeToHex(exitCode); string tmpInstExitCode = "0x" + exitCodeInHex; if (tmpInstExitCode.Equals("0x1")) { tmpInstExitCode = "0x11100000"; } else if (tmpInstExitCode.Equals("0x0")) { tmpInstExitCode = "0x00000000"; } if (tmpInstExitCode.Length <= 5) { installationExitCode = tmpInstExitCode; } else { installationExitCode = tmpInstExitCode.Remove(5); } Console.WriteLine("installationExitCode : " + installationExitCode); // sets a timeout period to wait so the program doesn't get stuck waiting endlessly bool notTimeOut = process.WaitForExit(TimeOut); bool stopOnError = XMLReader.GetStopOnError(Program.InputTestFilePathBAK); if (stopOnError) { string lineContains = string.Empty; switch (lineContains) { case string noMatching when stdOutput.Contains(NoMatchingDevice): GetData.GetExitCode(installationExitCode, stdOutput, errorMessage); Logger.Comment("got exit code 0xB7, No Matching Device : " + line); Console.WriteLine("got exit code 0xB7, No Matching Device : " + line); Logger.Comment("Copy the driverstress log and DPINST.LOG to our folder..."); Utilities.CopyFile(@"C:\Windows\DPINST.LOG", Program.dpinstLog); Utilities.CopyFile(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverSDriverCapsuleStressLogtressLog.txt"); Console.ReadKey(); Environment.Exit(13); break; case string elementNotFound when installationExitCode.Equals(ElementNotFoundCode): GetData.GetExitCode(installationExitCode, stdOutput, errorMessage); Logger.Comment("got exit code 49, try to re-install : " + line); Logger.Comment("Elemnt not found error, trying to uninstall a device that is not currently installed"); Console.WriteLine("got exit code 49, try to re-install : " + line); Console.WriteLine("Elemnt not found error, trying to uninstall a device that is not currently installed"); Logger.Comment("Copy the driverstress log and DPINST.LOG to our folder..."); Utilities.CopyFile(@"C:\Windows\DPINST.LOG", Program.dpinstLog); Utilities.CopyFile(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverCapsuleStressLog.txt"); Console.ReadKey(); Environment.Exit(13); break; case string cannotStart when installationExitCode.Equals(DeviceCanNotStartCode): Logger.Comment("CODE 10 : device cannot start error for " + line); Console.WriteLine("CODE 10 : device cannot start error for " + line); Logger.Comment("Copy the driverstress log and DPINST.LOG to our folder..."); Utilities.CopyFile(@"C:\Windows\DPINST.LOG", Program.dpinstLog); Utilities.CopyFile(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverCapsuleStressLog.txt"); Console.ReadKey(); Environment.Exit(13); break; case string couldNotFindInf when installationExitCode.Equals(couldNotFindInfToDelete): Logger.Comment("could Not Find Inf To Delete...what is up...check the logs later..."); Console.WriteLine("could Not Find Inf To Delete...what is up...check the logs later..."); Logger.Comment("Just move the driverstress log and DPINST.LOG to our folder..."); File.Move(@"C:\Windows\DPINST.LOG", Program.dpinstLog + ".ERR"); File.Move(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverCapsuleStressLog-ERR.txt"); Environment.Exit(13); break; case string InfFileAltered when installationExitCode.Equals(InfFileAlteredCode): Logger.Comment("this was not installed because the inf file has been altered"); Console.WriteLine("this was not installed because the inf file has been altered"); Logger.Comment("Copy the driverstress log and DPINST.LOG to our folder..."); Utilities.CopyFile(@"C:\Windows\DPINST.LOG", Program.dpinstLog); Utilities.CopyFile(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverCapsuleStressLog.txt"); Environment.Exit(13); break; default: if (notTimeOut == false) { failureCause = "Driver installation Timed-Out"; errorCodeMessage = string.Format(line + " Driver installation Timed-Out"); Logger.Comment(line + " Driver installation Failed due to Time-Out::: " + errorCodeMessage, expectedDriverVersion, DateTime.Now.ToString("MM/dd/yyyy H:mm:ss:fff"), beforeDriverStatus, afterDriverStatus, deviceRuning, failureCause); Logger.Comment("Copy the driverstress log and DPINST.LOG to our folder..."); Utilities.CopyFile(@"C:\Windows\DPINST.LOG", Program.dpinstLog); Utilities.CopyFile(Program.dirName + @"\DriverCapsuleStressLog.txt", Program.resultsLogDir + @"\DriverCapsuleStressLog.txt"); Console.ReadKey(); Environment.Exit(13); } break; } } process.Dispose(); } catch (Exception ex) { GetData.GetExceptionMessage(ex); } Logger.FunctionLeave(); }
/// <summary> /// this is called when installing firmware to perform the extra actions needed such as regkey writes and reboot /// </summary> /// <param name="infName"></param> /// <param name="infFileContent"></param> /// <param name="hardwareID"></param> /// <param name="rebootRequired"></param> /// <param name="rollBackLine"></param> /// <param name="installer"></param> /// <param name="installArgs"></param> /// <param name="InputTestFilePath"></param> internal static void RollbackInstall(int seedIndex, string line, string infName, string infFileContent, string hardwareID, bool rebootRequired, string InputTestFilePath) { Logger.FunctionEnter(); string installArgs; string fullRollBackFile = string.Empty; string fullRollBackDIR = string.Empty; string fullRollBackDIRdir = string.Empty; try { XMLWriter.RemoveXMLElemnt(Program.InputTestFilePath, line, seedIndex); RegCheck.CreatePolicyRegKeyAndSetValue(hardwareID, rebootRequired.Equals(true)); fullRollBackDIR = GetData.CheckRollbacksExist(line, infName); if (string.IsNullOrEmpty(fullRollBackDIR)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("should i even be trying to rollback at all???"); Console.ForegroundColor = ConsoleColor.White; } else { fullRollBackDIRdir = Path.GetDirectoryName(fullRollBackDIR); } installArgs = " /C /U " + line + " /Q /D"; string tmpfileName = string.Empty; string tmpVersion = GetData.GetDriverVersion(line); var binsList = Directory.EnumerateFiles(@"C:\Windows\Firmware\"); foreach (string binFileToDelete in binsList) { tmpfileName = Path.GetFileNameWithoutExtension(binFileToDelete); tmpVersion = tmpVersion.TrimEnd('0').TrimEnd('0').TrimEnd('.'); if (Regex.Match(tmpfileName, tmpVersion).Success) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("binFileToDelete exists : " + tmpfileName); File.Delete(tmpfileName); Console.ForegroundColor = ConsoleColor.White; break; } else { continue; } } Install_Inf(line, Program.installer, installArgs, seedIndex); Logger.Comment("Uninstall Operation should be complete: " + line); installArgs = " /C /A /Q /SE /F /PATH " + fullRollBackDIRdir; Logger.Comment("start rollback..."); XMLWriter.SetLastInstalled(fullRollBackDIR); Install_Inf(line, Program.installer, installArgs, seedIndex); string classGUID = GetData.GetClassGUID(line); string expectedDriverVersion = GetData.GetDriverVersion(line); GetDataFromReg.GetOEMinfNameFromReg(infName, hardwareID, classGUID); if (RegCheck.IsRebootPending()) { Logger.Comment("there is a pending reboot..."); RebootAndContinue.RebootCmd(true); } } catch (Exception ex) { GetData.GetExceptionMessage(ex); } Logger.FunctionLeave(); }
/// <summary> /// firmware or regular driver will still call this to do the actual installation /// </summary> /// <param name="infName"></param> /// <param name="line"></param> /// <param name="installer"></param> /// <param name="installArgs"></param> /// <param name="InputTestFilePath"></param> /// <param name="rebootRequired"></param> /// <param name="hardwareID"></param> /// SafeNativeMethods.InstallUninstallCall(seedIndex, rebootRequired, infName, line, installer, InputTestFilePath); internal static void InstallUninstallCall(int seedIndex, bool rebootRequired, string infName, string line, string installer, string InputTestFilePath) { try { Logger.FunctionEnter(); string expectedDriverVersion = GetData.GetDriverVersion(line); string infNameToTest = Path.GetFileNameWithoutExtension(line); string expectedDriverDate = GetData.GetDriverDate(line); string infPath = Path.GetDirectoryName(line); string installArgs; string friendlyDriverName = XMLReader.GetFriendlyDriverName(InputTestFilePath, line); Console.WriteLine(line + " and " + seedIndex); Console.WriteLine("RemoveXMLElement now"); XMLWriter.RemoveXMLElemnt(Program.InputTestFilePath, line, seedIndex); Console.WriteLine("check the xml please.."); string hardwareID = GetData.FirmwareInstallGetHID(line); bool isInstalled = CheckWhatInstalled.CheckInstalled(line, hardwareID, friendlyDriverName, infNameToTest, expectedDriverVersion, expectedDriverDate); if (isInstalled) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("THIS PnP DRIVER VERSION IS INSTALLED UN-INSTALLING NOW...."); Console.WriteLine(infName); Console.WriteLine("----------------------------------------------------------"); Console.ForegroundColor = ConsoleColor.White; Logger.Comment("rebootRequired is showing as : " + rebootRequired); installArgs = " /C /U " + line + " /Q /D"; Install_Inf(line, installer, installArgs, seedIndex); Logger.Comment("Operation should be complete: " + line); string classGUID = GetData.GetClassGUID(line); GetDataFromReg.GetOEMinfNameFromReg(infName, hardwareID, classGUID); if (RegCheck.IsRebootPending()) { Logger.Comment("there is a pending reboot..."); RebootAndContinue.RebootCmd(true); } } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("---------------------------------------------------------------"); Console.WriteLine("THIS PnP DRIVER VERSION WAS NOT INSTALLED YET INSTALLING NOW..."); Console.WriteLine(infName); Console.WriteLine("---------------------------------------------------------------"); Console.ForegroundColor = ConsoleColor.White; Logger.Comment("rebootRequired is showing as : " + rebootRequired); installArgs = " /C /A /Q /SE /F /PATH " + infPath; Install_Inf(line, installer, installArgs, seedIndex); string classGUID = GetData.GetClassGUID(line); XMLWriter.SetLastInstalled(line); //can we check registry simiarly to firmware for PnP drivers? Logger.Comment("Operation should be complete: " + line); if (RegCheck.IsRebootPending()) { Logger.Comment("there is a pending reboot..."); RebootAndContinue.RebootCmd(true); } } Logger.FunctionLeave(); } catch (Exception ex) { GetData.GetExceptionMessage(ex); } }
/// <summary> /// logPath will be the location or the DPINST.LOG /// </summary> /// ParseForResults.ParseFromdpinstLog(logPath); /// <param name="logPath"></param> internal static void ParseFromdpinstLog(string logPath) { List <string> infsPathsList = GetData.GetInfPathsList(Program.dirName); string line = string.Empty; string dumpExist = string.Empty; string logString = string.Empty; string lineContains = string.Empty; string dumpFilePath = string.Empty; try { using (FileStream fs = File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Inheritable)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { while ((line = sr.ReadLine()) != null) { foreach (string infPathTMP in infsPathsList) { string inNameTMP = Path.GetFileNameWithoutExtension(infPathTMP).ToLower(); if (line.Contains(inNameTMP.ToLower())) { switch (lineContains) { case string errorResult when line.Contains(errorCode): errorCount++; break; case string successUninstallResult when line.Contains(successUninstallResults): successUninstallCount++; break; case string failedResult when line.Contains(failedResults): failedCount++; break; case string successinstallResult when line.Contains(successinstallResults): successInstallCount++; break; } } } if (line.Contains(rollbackCheck)) { switch (lineContains) { case string errorResult when line.Contains(errorCode): rollBackErrorCount++; break; case string successinstallResult when line.Contains(successinstallResults): rollBackSuccessCount++; break; case string failedResult when line.Contains(failedResults): rollBackFailedCount++; break; } } } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("failedCount : " + failedCount); Console.WriteLine("successInstallCount : " + successInstallCount); Console.WriteLine("successUninstallCount : " + successUninstallCount); Console.WriteLine("errorCount : " + errorCount); Console.WriteLine("rollBackFailedCount : " + rollBackFailedCount); Console.WriteLine("rollBackSuccessInstallCount : " + (rollBackSuccessCount - successInstallCount)); Console.WriteLine("rollBackErrorCount : " + rollBackErrorCount); Console.ForegroundColor = ConsoleColor.White; } foreach (var dmpFileTest in Directory.EnumerateDirectories(Program.dirName, ".dmp", SearchOption.AllDirectories)) { dumpExist = "True"; dumpFilePath = dmpFileTest; } XMLWriter.LogResults(Program.InputTestFilePathBAK, errorCount.ToString(), failedCount.ToString(), successInstallCount.ToString(), successUninstallCount.ToString(), rollBackErrorCount.ToString(), rollBackFailedCount.ToString(), rollBackSuccessCount.ToString(), dumpExist, logString, dumpFilePath); } catch (Exception ex) { GetData.GetExceptionMessage(ex); } }