void OnInstallationComplete(IInstallationResult installResult) { //todo can there be partial success, and we miss some results? if (installResult.ResultCode != OperationResultCode.orcSucceeded && installResult.ResultCode != OperationResultCode.orcSucceededWithErrors) { DebugLog($"Installation failed with code: {installResult.ResultCode}"); InstallationCompleted?.Invoke(false, false); return; } for (int i = 0; i < updateInstaller.Updates.Count; i++) { var resultCode = installResult.GetUpdateResult(i).ResultCode; var title = updateInstaller.Updates[i].Title; if (resultCode != OperationResultCode.orcSucceeded) { //the title must be there //but if it is not for some reason we will detect this (via dict. exception) updateResults[title].Error = resultCode.ToString(); updateResults[title].IsInstalled = false; } else { updateResults[title].IsInstalled = true; } DebugLog($"Installation status for update {title}: {resultCode}"); } DebugLog($"Is reboot required? : {installResult.RebootRequired}"); InstallationCompleted?.Invoke(true, installResult.RebootRequired); }
private OperationResultCode InstallUpdatesUtil(CancellationToken cancellationToken) { try { TimeSpan operationTimeOut = TimeSpan.FromMinutes(this.GetRemainingInstallationTimeout()); UpdateCollection updatesToInstall = new UpdateCollection(); foreach (WUUpdateWrapper item in this._wuCollectionWrapper.Collection.Values) { if (item.IsDownloaded && !item.IsInstalled) { updatesToInstall.Add(item.Update); } } // if no updates to install if (updatesToInstall.Count == 0) { _eventSource.InfoMessage("No updates to install."); return(OperationResultCode.orcSucceeded); } IUpdateInstaller uInstaller = this._uSession.CreateUpdateInstaller(); uInstaller.Updates = updatesToInstall; InstallationCompletedCallback installationCompletedCallback = new InstallationCompletedCallback(); IInstallationJob installationJob = uInstaller.BeginInstall(new InstallationProgressChangedCallback(), installationCompletedCallback, null); if ( !this._helper.WaitOnTask(installationCompletedCallback.Task, (int)operationTimeOut.TotalMilliseconds, cancellationToken)) { _eventSource.Message("installationJob : Requested Abort"); installationJob.RequestAbort(); } IInstallationResult uResult = uInstaller.EndInstall(installationJob); for (int i = 0; i < updatesToInstall.Count; i++) { var hResult = uResult.GetUpdateResult(i).HResult; var updateID = updatesToInstall[i].Identity.UpdateID; this._wuCollectionWrapper.Collection[updateID].IsInstalled = (hResult == 0); this._wuCollectionWrapper.Collection[updateID].HResult = hResult; if (hResult != 0) { _eventSource.WarningMessage(string.Format("Install for update ID {0} returned hResult {1}", updateID, hResult)); } } return(uResult.ResultCode); } catch (Exception e) { _eventSource.InfoMessage("Exception while installing Windows-Updates: {0}", e); return(OperationResultCode.orcFailed); } }
public void installUpdates() { try { UpdateSession uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type ='Software'"); if (uResult.Updates.Count != 0) { UpdateDownloader downloader = uSession.CreateUpdateDownloader(); downloader.Updates = uResult.Updates; downloader.Download(); UpdateCollection updatesToInstall = new UpdateCollection(); foreach (IUpdate update in uResult.Updates) { if (update.IsDownloaded) { updatesToInstall.Add(update); } } IUpdateInstaller installer = uSession.CreateUpdateInstaller(); installer.Updates = updatesToInstall; IInstallationResult installationRes = installer.Install(); for (int i = 0; i < updatesToInstall.Count; i++) { if (installationRes.GetUpdateResult(i).HResult == 0) { Console.WriteLine("INSTALLED : " + updatesToInstall[i].Title); } else { Console.WriteLine("FAILED : " + updatesToInstall[i].Title); } } } else { Console.WriteLine("THERE IS NOTHING TO INSTALL"); } } catch (Exception exception_log) { Console.Clear(); Console.Write("=======================================================================================================================\n"); Console.WriteLine(exception_log.ToString() + "\n"); Console.Write("=======================================================================================================================\n"); Console.WriteLine("FETCHING OR INSTALLATION ERROR - OPERATION FAILED"); Thread.Sleep(5000); } }
internal static void WsusInstaller(UpdateCollection updatesToInstall) { IUpdateInstaller installer = new UpdateInstaller(); installer.Updates = updatesToInstall; IInstallationResult installationRes = installer.Install(); for (int i = 0; i < updatesToInstall.Count; i++) { if (installationRes.GetUpdateResult(i).HResult == 0) { Program.LogInfo($"Installed : {updatesToInstall[i].Title}"); } else { Program.LogInfo($"Failed : {updatesToInstall[i].Title}"); } } }
private string install(IUpdate update, int installBatch) { string resultText; try { UpdateCollection updates = new UpdateCollection(); updates.Add(update); uInstaller = uSession.CreateUpdateInstaller(); uInstaller.Updates = updates; IInstallationResult result = uInstaller.Install(); IUpdateInstallationResult upd_result = result.GetUpdateResult(0); resultText = this.getResultText(upd_result); Program.Dash.setUpdateInstalledAt(update, installBatch); } catch (Exception e) { resultText = string.Format("There was a problem installing update '{0}' : {1}", update.Title, e.Message); Program.Events.WriteEntry(string.Format("There was a problem installing update '{0}' : {1}", update.Title, e.Message), EventLogEntryType.Error); } return(resultText); }
private void SetInstalledUpdatesObject(IInstallationResult result,UpdateCollection updates) { try { if (string.IsNullOrWhiteSpace(InstalledObjectKey)) return; var installed = new UpdateCollection(); for (var index = 0; index < updates.Count; index++ ) { var updateResult = result.GetUpdateResult(index); if (updateResult.ResultCode != OperationResultCode.orcSucceeded) continue; installed.Add(updates[index]); } SettingsManager.SetTemporaryObject(InstalledObjectKey, installed); } catch (Exception e) { Log.WarnFormat("An issue occurred while attempting to set the installed updates object: {0}", e.Message); } }
private void LogInstallResult(IEnumerable updates, IInstallationResult results) { try { var count = 0; var succeeded = 0; foreach (IUpdate update in updates) { var result = results.GetUpdateResult(count); if (result.ResultCode == OperationResultCode.orcSucceeded) { Log.DebugFormat("{0} installed successfully!", update.Title); ReportInstallResult(update, "Update Installed"); count++; succeeded++; continue; } var issue = new UpdateInstallFailed(string.Format("Unable to download {0}", update.Title), result); Log.Warn(issue.Issue); count++; } if (count == succeeded) Log.InfoFormat("{0} updates installed successfully", count); else Log.WarnFormat("{0} of {1} updates installed successfully", succeeded, count); } catch (Exception e) { Log.WarnFormat("An exception occurred while logging update results: {0}", e.Message); } }
private static IResult ConvertToResult(IInstallationResult result, IUpdateCollection updates) { if (result.ResultCode == OperationResultCode.orcAborted) return new UpdateOperationCancelled(); if (result.ResultCode == OperationResultCode.orcSucceeded) return new NextResult(); if (result.ResultCode == OperationResultCode.orcSucceededWithErrors) return new NextResult(); if (updates.Count != 1) return new UpdateInstallFailed(result); var update = updates[0]; return new UpdateInstallFailed(string.Format("{0} installation failed", update.Title), result.GetUpdateResult(0)); }
static void Main(string[] args) { ISearchResult uResult = null; UpdateSession uSession = null; // Check if we have access to Windows Update online, if not let's get access temporarily Log2File("Program starting", "Information"); var DisableWUA = GetLMRegKeyValue("SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate", "DisableWindowsUpdateAccess"); var UseWUServer = GetLMRegKeyValue("SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU", "UseWUServer"); bool ServiceRestart = false; if (DisableWUA != null && DisableWUA.ToString() == "1") { Log2File("Opening 'DisableWindowsUpdateAccess' registry key", "Information"); SetLMRegKeyValue("SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate", "DisableWindowsUpdateAccess", 0); ServiceRestart = true; RestoreDisableWUA = true; } if (UseWUServer != null && UseWUServer.ToString() == "1") { Log2File("Opening 'UseWUServer' registry key", "Information"); SetLMRegKeyValue("SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU", "UseWUServer", 0); ServiceRestart = true; RestoreUseWUServer = true; } if (ServiceRestart) { RestartService("wuauserv", 30); } // Search for a driver updates try { Log2File("Creating update session", "Information"); uSession = new UpdateSession(); IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); uSearcher.Online = true; Log2File("Searching for available driver updates", "Information"); uResult = uSearcher.Search("IsInstalled=0 and Type = 'Driver'"); } catch (Exception ex) { Log2File(ex.Message, "Error"); RestoreWURegKeys(); Environment.Exit(1); } // Exit if none found if (uResult.Updates.Count == 0) { // No updates found Log2File("No driver updates found!", "Warning"); RestoreWURegKeys(); Environment.Exit(0); } // Check if the desired update is found foreach (IUpdate update in uResult.Updates) { if (update.Title.StartsWith(DriverTitle)) { Log2File($"Found update: {update.Title}", "Information"); ConexantUpdate = update; } } // If the desired update is found if (ConexantUpdate != null && ConexantUpdate.Title.StartsWith(DriverTitle)) { UpdateCollection uCollection = new UpdateCollection(); // Check if need to download it if (ConexantUpdate.IsDownloaded == false) { uCollection.Add(ConexantUpdate); try { Log2File("Downloading update", "Information"); UpdateDownloader downloader = uSession.CreateUpdateDownloader(); downloader.Updates = uCollection; downloader.Download(); } catch (Exception ex) { Log2File(ex.Message, "Error"); RestoreWURegKeys(); Environment.Exit(1); } // Check it was downloaded if (uCollection[0].IsDownloaded == false) { Log2File("The update was not downloaded successfully!", "Error"); RestoreWURegKeys(); Environment.Exit(1); } } else { Log2File("Update already downloaded", "Information"); } // Install the update IInstallationResult installationRes = null; try { Log2File("Installing update", "Information"); IUpdateInstaller installer = uSession.CreateUpdateInstaller(); installer.Updates = uCollection; installationRes = installer.Install(); } catch (Exception ex) { Log2File(ex.Message, "Error"); RestoreWURegKeys(); Environment.Exit(1); } // Check the installation if (installationRes.GetUpdateResult(0).HResult == 0) { if (installationRes.RebootRequired == true) { Log2File("Update was successfully installed. A reboot is required.", "Information"); } else { Log2File("Update was successfully installed.", "Information"); } } } else { Log2File($"No driver update matching '{DriverTitle}' found!", "Warning"); RestoreWURegKeys(); Environment.Exit(0); } // Restore previous Windows Update settings if necessary RestoreWURegKeys(); }
public void Start(bool showProgress) { this.ShowProgress = showProgress; Console.WriteLine("WUA_Starting"); IUpdateSession updateSession = new UpdateSessionClass(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); IUpdateDownloader updateDownloader = updateSession.CreateUpdateDownloader(); IUpdateInstaller updateInstaller = updateSession.CreateUpdateInstaller(); if (updateInstaller.IsBusy) { Console.WriteLine("WUA_IsBusy"); return; } // SEARCHING Console.WriteLine("WUA_FindingUpdates"); ISearchResult searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'"); if (searchResult.Updates.Count.Equals(0)) { Console.WriteLine("WUA_NoApplicableUpdates"); return; } // LISTING UpdateCollection updateToDownload = new UpdateCollectionClass(); for (int i = 0; i < searchResult.Updates.Count; i++) { IUpdate update = searchResult.Updates[i]; Console.WriteLine("WUA_UpdateItem:{0}|{1}", i + 1, update.Title); if (!update.IsDownloaded) { updateToDownload.Add(update); } } // DOWNLOADING if (!updateToDownload.Count.Equals(0)) { Console.WriteLine("WUA_DownloadingStarted"); updateDownloader.Updates = updateToDownload; updateDownloader.IsForced = true; updateDownloader.Priority = DownloadPriority.dpHigh; IDownloadJob job = updateDownloader.BeginDownload(this, this, updateDownloader); IDownloadResult downloaderResult = updateDownloader.EndDownload(job); Console.WriteLine("WUA_DownloadingCompleted:{0}", downloaderResult.ResultCode); } // INSTALLATION updateInstaller.Updates = searchResult.Updates; updateInstaller.IsForced = true; Console.WriteLine("WUA_InstallationStarted"); IInstallationJob installationJob = updateInstaller.BeginInstall(this, this, updateInstaller); IInstallationResult result = updateInstaller.EndInstall(installationJob); Console.WriteLine("WUA_InstallationCompleted:{0}|{1}", result.ResultCode, result.RebootRequired); // RESULT for (int i = 0; i < searchResult.Updates.Count; i++) { IUpdateInstallationResult resultItem = result.GetUpdateResult(i); Console.WriteLine("WUA_InstallationResult:{0}|{1}|{2}", i + 1, resultItem.ResultCode, resultItem.RebootRequired); } Console.WriteLine("WUA_Finish"); }
// Token: 0x06000003 RID: 3 RVA: 0x000020E8 File Offset: 0x000002E8 public void DoUpdate() { if (this.ConsoleDiagnostics) { Console.WriteLine("Checking for Updates."); } try { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_StartScan, null, new string[0]); IUpdateSession updateSession = new UpdateSessionClass(); updateSession.ClientApplicationID = "Exchange12"; IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); ISearchResult searchResult = updateSearcher.Search("IsInstalled=0 and CategoryIDs contains 'ab62c5bd-5539-49f6-8aea-5a114dd42314'"); UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_StopScan, null, new string[0]); if (searchResult.Updates.Count == 0) { if (this.ConsoleDiagnostics) { Console.WriteLine("No Updates."); } } else { foreach (object obj in searchResult.Updates) { IUpdate update = (IUpdate)obj; UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_PatchAvailable, null, new string[] { update.Title }); if (this.ConsoleDiagnostics) { Console.WriteLine("Title: {0}", update.Title); } } UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_StartDownload, null, new string[0]); UpdateDownloader updateDownloader = updateSession.CreateUpdateDownloader(); updateDownloader.Priority = 3; updateDownloader.Updates = searchResult.Updates; IDownloadResult downloadResult = updateDownloader.Download(); UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_StopDownload, null, new string[0]); for (int i = 0; i < updateDownloader.Updates.Count; i++) { if (downloadResult.GetUpdateResult(i).ResultCode == 4 || downloadResult.GetUpdateResult(i).ResultCode == 5) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_DownloadFailure, null, new string[] { updateDownloader.Updates[i].Title, downloadResult.GetUpdateResult(i).HResult.ToString() }); if (this.ConsoleDiagnostics) { Console.WriteLine("Errors: {0}: {1}", updateDownloader.Updates[i].Title, downloadResult.GetUpdateResult(i).HResult); } } } bool flag = false; foreach (object obj2 in updateDownloader.Updates) { IUpdate update2 = (IUpdate)obj2; if (update2.IsDownloaded) { flag = true; } } if (!flag) { if (this.ConsoleDiagnostics) { Console.WriteLine("Nothing to Install."); } } else { if (this.ConsoleDiagnostics) { Console.WriteLine("Starting Installation."); } UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_StartInstall, null, new string[0]); IUpdateInstaller updateInstaller = updateSession.CreateUpdateInstaller(); updateInstaller.Updates = updateDownloader.Updates; IInstallationResult installationResult = updateInstaller.Install(); UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_StopInstall, null, new string[0]); for (int j = 0; j < updateInstaller.Updates.Count; j++) { IUpdate update3 = updateInstaller.Updates[j]; if (installationResult.GetUpdateResult(j).ResultCode == 4 || installationResult.GetUpdateResult(j).ResultCode == 3) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_InstallFailure, null, new string[] { updateInstaller.Updates[j].Title, installationResult.GetUpdateResult(j).HResult.ToString() }); if (this.ConsoleDiagnostics) { Console.WriteLine("Errors: {0}: {1}", updateInstaller.Updates[j].Title, installationResult.GetUpdateResult(j).HResult); } } } if (this.ConsoleDiagnostics) { Console.WriteLine("Finished."); } } } } catch (COMException ex) { UpdateSvcEventLogger.LogEvent(AntispamUpdateServiceEventLogConstants.Tuple_WuaFail, null, new string[] { ex.Message }); if (this.ConsoleDiagnostics) { Console.WriteLine("Failed: {0}", ex.Message); } } }
// Method for using WUAPI to install the named update - "Windows Update" service needs turning on before calling this method public void installUpdate() { try { Logger.instance.Debug("Installing update"); List <Update> updates = new List <Update>(); IUpdateSession uSession; IUpdateSearcher uSearcher; uSession = new UpdateSession(); //Create an Update interface in WUA Logger.instance.Debug("Creating searcher"); uSearcher = uSession.CreateUpdateSearcher(); // Search for available Updates Logger.instance.Debug("Creating holder for updates"); UpdateCollection updatesToDownload = new UpdateCollection(); Logger.instance.Debug("Searching for specific update"); ISearchResult uResult = uSearcher.Search("Type='Software' And IsAssigned = 1"); //Save the result of the search Logger.instance.Debug("Creating update collection"); UpdateCollection updatesToInstall = new UpdateCollection(); for (int i = 0; i < uResult.Updates.Count; i++) { if (uResult.Updates[i].Title.ToString().Equals(this.Name)) { updatesToInstall.Add(uResult.Updates[i]); //save all the queued updates to the downloader queue break; } } if (updatesToInstall.Count > 0) { Logger.instance.Debug("Creating update installer"); IUpdateInstaller installer = uSession.CreateUpdateInstaller(); //create an interface for installation of updates installer.Updates = updatesToInstall; Logger.instance.Debug("Installing update"); IInstallationResult installationRes = installer.Install(); if (installationRes.GetUpdateResult(0).HResult == 0) // 0 (zero) code means succeeded { this.isInstalled = true; this.DateTimeInstalled = DateTime.UtcNow; save(); } else // For status codes other than 0 (zero) { String result = "Failed to install update " + Name + ". It returned windows update error code = " + installationRes.GetUpdateResult(0).HResult.ToString(); Insight ins = new Insight(); ins.InsightText = result; ins.Save(); Logger.instance.Warning(result); } } } catch (Exception e) { Logger.instance.Error(e); } }
public static void InstallAllUpdates(EnumPolicy.WuType wuType) { Logger.Info("Running Windows Update."); var updateSession = new UpdateSession(); var updateSearchResult = updateSession.CreateUpdateSearcher(); var updateCollection = new UpdateCollection(); var installCollection = new UpdateCollection(); updateSearchResult.Online = true; if (wuType == EnumPolicy.WuType.Microsoft || wuType == EnumPolicy.WuType.MicrosoftSkipUpgrades) { updateSearchResult.ServerSelection = ServerSelection.ssWindowsUpdate; } else if (wuType == EnumPolicy.WuType.Wsus || wuType == EnumPolicy.WuType.WsusSkipUpgrades) { updateSearchResult.ServerSelection = ServerSelection.ssManagedServer; } else { Logger.Debug("Could Not Determine Windows Update Server Selection."); return; } updateSearchResult.IncludePotentiallySupersededUpdates = false; try { Logger.Debug("Searching For Available Windows Updates. "); var searchResults = updateSearchResult.Search("IsInstalled=0 and Type='Software'"); if (wuType == EnumPolicy.WuType.MicrosoftSkipUpgrades || wuType == EnumPolicy.WuType.WsusSkipUpgrades) { foreach (IUpdate u in searchResults.Updates) { var isFeatureUpgrade = false; var unknownCategory = false; foreach (ICategory ic in u.Categories) { if (string.IsNullOrEmpty(ic.Name)) { Logger.Debug("Could Not Determine Windows Update Category. Skipping Update."); Logger.Debug(u.Title + " " + u.Identity.UpdateID + " "); unknownCategory = true; break; } if (ic.Name.Equals("Upgrades")) { isFeatureUpgrade = true; } break; } if (isFeatureUpgrade || unknownCategory) { continue; } Logger.Debug(u.Title + " " + u.Identity.UpdateID + " "); u.AcceptEula(); updateCollection.Add(u); } } else //include feature upgrades { foreach (IUpdate u in searchResults.Updates) { Logger.Debug(u.Title + " " + u.Identity.UpdateID + " "); u.AcceptEula(); updateCollection.Add(u); } } if (updateCollection.Count == 0) { Logger.Info("No Updates Found."); return; } UpdateDownloader downloader = updateSession.CreateUpdateDownloader(); downloader.Updates = updateCollection; downloader.Download(); foreach (IUpdate update in updateCollection) { if (update.IsDownloaded) { installCollection.Add(update); } } IUpdateInstaller installer = updateSession.CreateUpdateInstaller(); installer.Updates = installCollection; IInstallationResult result = installer.Install(); Logger.Debug("Windows Update Result: " + result.ResultCode); Logger.Debug("Reboot Required: " + result.RebootRequired); for (int i = 0; i < installCollection.Count; i++) { Logger.Debug(installCollection[i].Title + " " + result.GetUpdateResult(i).ResultCode); } } catch { //Ignored } }