public static void InstallUpdates(UpdateCollection DownloadedUpdates) { Console.WriteLine("Installing updates now..."); UpdateSession UpdateSession = new UpdateSession(); UpdateInstaller InstallAgent = UpdateSession.CreateUpdateInstaller() as UpdateInstaller; InstallAgent.Updates = DownloadedUpdates; //Starts a synchronous installation of the updates. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods if (DownloadedUpdates.Count > 0) { IInstallationResult InstallResult = InstallAgent.Install(); if (InstallResult.ResultCode == OperationResultCode.orcSucceeded) { Console.WriteLine("Updates installed succesfully"); if (InstallResult.RebootRequired == true) { Console.WriteLine("Reboot is required for one of more updates."); } } else { Console.WriteLine("Updates failed to install do it manually"); } } else { Console.WriteLine("The computer that this script was executed is up to date"); } }
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 static void InstallUpdates(UpdateCollection DownloadedUpdates) { UpdateSession UpdateSession = new UpdateSession(); UpdateInstaller InstallAgent = UpdateSession.CreateUpdateInstaller() as UpdateInstaller; InstallAgent.Updates = DownloadedUpdates; //Starts a synchronous installation of the updates. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods IInstallationResult InstallResult = InstallAgent.Install(); }
static void InstallUpdatesT() { try { if (EV.WaitOne(1000) == false) { return; } EV.Reset(); Status.Text = "Checking for updates"; UpdateSession UpdateSession = new UpdateSession(); UpdateSession.ClientApplicationID = "Fox SDC Update Controller"; IUpdateSearcher upd = UpdateSession.CreateUpdateSearcher(); ISearchResult res = upd.Search("IsInstalled=0 and Type='Software' and IsHidden=0"); for (int i = 0; i < res.Updates.Count; i++) { Status.Text = "Downloading " + res.Updates[i].Title + " (" + (i + 1).ToString() + " of " + res.Updates.Count.ToString() + ")"; UpdateDownloader downloader = UpdateSession.CreateUpdateDownloader(); downloader.Updates = new WUApiLib.UpdateCollection(); downloader.Updates.Add(res.Updates[i]); downloader.Download(); } for (int i = 0; i < res.Updates.Count; i++) { Status.Text = "Installing " + res.Updates[i].Title + " (" + (i + 1).ToString() + " of " + res.Updates.Count.ToString() + ")"; IUpdateInstaller installer = UpdateSession.CreateUpdateInstaller(); if (installer.IsBusy == true) { return; } installer.Updates = new WUApiLib.UpdateCollection(); installer.Updates.Add(res.Updates[i]); IInstallationResult ires = installer.Install(); } } catch (Exception ee) { FoxEventLog.WriteEventLog("Failed to install WU " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error); return; } finally { Status.Text = "Idle"; EV.Set(); } return; }
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); } }
public void iInstallationComplete() { iInstallationResult = iUpdateInstaller.EndInstall(iInstallationJob); if (iInstallationResult.ResultCode == OperationResultCode.orcSucceeded) { this.toolStripStatusLabel1.Text = "Installation Complete..."; } else { string message = "The Installation has failed: " + iInstallationResult.ResultCode + "."; string caption = "DownInstallationload Failed!"; MessageBoxButtons buttons = MessageBoxButtons.OK; MessageBoxIcon icon = MessageBoxIcon.Error; MessageBox.Show(message, caption, buttons, icon); Application.Exit(); } }
/// <summary> /// Callback for completed installation operations. /// </summary> private void EndInstallUpdates(IInstallationResult result, IUpdateCollection updates) { Log.Debug("Installation result callback received: " + result.ResultCode.ToString("G")); using (ll.Lock(StateLock)) { if (result.ResultCode == OperationResultCode.orcSucceeded) { IEnumerable <IUpdate> notInstalledUpdates; using (ll.Lock(UpdateHolderLock)) { notInstalledUpdates = UpdateHolder.GetSelectedUpdates((u) => !u.IsInstalled); } if (result.RebootRequired || SystemInfo.IsRebootRequired()) { EnterStateWhenAllowed(new WuStateRebootRequired()); } else if (notInstalledUpdates.Any(u => !u.EulaAccepted || u.InstallationBehavior.CanRequestUserInput)) { if (IsValidTransition <WuStateUserInputRequired>()) { string reason = (notInstalledUpdates.Any(u => !u.EulaAccepted)) ? "Some selected updates were not installed. Please accept the eulas for these updates." : "Some updates were not installed because they can request user input."; EnterState(new WuStateUserInputRequired(reason)); } } else { EnterStateWhenAllowed(new WuStateInstallCompleted(updates, result.HResult)); } } else if (result.ResultCode == OperationResultCode.orcSucceededWithErrors) { EnterStateWhenAllowed(new WuStateInstallPartiallyFailed(null, "Could not install all updates: HResult " + result.HResult)); } else { if (_currentState is WuStateInstallFailed) { return; } EnterStateWhenAllowed(new WuStateInstallFailed(null, "Could not install updates: HResult " + result.HResult.ToString())); } } }
protected void OnInstalationCompleted(IInstallationJob installationJob, bool Install) { if (installationJob != mInstalationJob) { return; } mInstalationJob = null; mCallback = null; IInstallationResult InstallationResults = null; try { if (Install) { InstallationResults = mInstaller.EndInstall(installationJob); } else { InstallationResults = mInstaller.EndUninstall(installationJob); } } catch (Exception err) { AppLog.Line(Program.fmt("(Un)Installing updates failed, Error: {0}", err.Message)); OnFinished(false); return; } if (InstallationResults.ResultCode == OperationResultCode.orcSucceeded) { AppLog.Line(Program.fmt("Updates (Un)Installed succesfully")); if (InstallationResults.RebootRequired == true) { AppLog.Line(Program.fmt("Reboot is required for one of more updates.")); } } else { AppLog.Line(Program.fmt("Updates failed to (Un)Install do it manually")); } OnFinished(InstallationResults.ResultCode == OperationResultCode.orcSucceeded, InstallationResults.RebootRequired); }
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}"); } } }
protected override void ProcessRecord() { base.ProcessRecord(); foreach (WUApiLib.IUpdate thisUpdate in Update) { if (thisUpdate.IsDownloaded) { updatesToInstall.Add(thisUpdate); if (thisUpdate.InstallationBehavior.RebootBehavior > 0) { RebootRequired = true; } IUpdateInstaller updateInstaller = Globals.updateSession.CreateUpdateInstaller(); updateInstaller.Updates = updatesToInstall; IInstallationResult installationResult = updateInstaller.Install(); WriteVerbose(installationResult.HResult.ToString()); } } }
public void Should_CallCompletedCallback_When_InstallingCompletes() { ManualResetEvent callbackSignal = new ManualResetEvent(false); IInstallationResult result = null; WuStateInstalling.InstallCompletedCallback callback = (x, u) => { result = x; callbackSignal.Set(); }; IUpdateCollection updates = new UpdateCollectionFake(); UpdateInstallerFake installer = new UpdateInstallerFake(); installer.FakeInstallResult = CommonMocks.GetInstallationResult(OperationResultCode.orcSucceeded); var state = new WuStateInstalling(installer, updates, callback, (x, y) => { }, null, 100); state.EnterState(new WuStateReady()); if (!callbackSignal.WaitOne(1000)) { Assert.Fail($"callback was not called"); } Assert.AreSame(installer.FakeInstallResult, result); }
internal void InstallationComplete() { /* * public enum OperationResultCode * { * orcNotStarted = 0, * orcInProgress = 1, * orcSucceeded = 2, * orcSucceededWithErrors = 3, * orcFailed = 4, * orcAborted = 5, * } * */ _installationResult = _updateInstaller.EndInstall(_installationJob); _installationJob = null; if (_installationResult.ResultCode == OperationResultCode.orcSucceeded) { this.ShowProgressMessage("progress_install", ""); this.AppendString("安装完成。\r\n"); } else { this.AppendString("安装更新失败。错误码: " + _installationResult.ResultCode); if (_installationResult.RebootRequired == true) { OnAllComplete(); MessageBox.Show(this, "请重新启动电脑"); return; } // 全部结束 } OnAllComplete(); }
private static void InstallUpdates(UpdateCollection installableUpdates) { Logger.Write("Trying to install update(s)."); try { UpdateSession uSession = new UpdateSession(); UpdateDownloader uDownloader = uSession.CreateUpdateDownloader(); IUpdateInstaller uInstaller = uSession.CreateUpdateInstaller(); if (installableUpdates.Count != 0) { Logger.Write(installableUpdates.Count + " update(s) to install."); uInstaller.ClientApplicationID = "InstallPendingUpdates"; uInstaller.AllowSourcePrompts = false; uDownloader.ClientApplicationID = "InstallPendingUpdates"; uDownloader.Updates = installableUpdates; Logger.Write("Starting to download update(s)."); uDownloader.Download(); Logger.Write("Download finnish."); uInstaller.Updates = installableUpdates; Logger.Write("Starting to install " + installableUpdates.Count + " update(s)."); IInstallationResult installResult = uInstaller.Install(); OperationResultCode resultCode = installResult.ResultCode; Logger.Write("Finnish to install update(s). Result : " + resultCode.ToString()); } else { Logger.Write("No udpdate to install."); } } catch (Exception ex) { Logger.Write("Problem when installing update(s). " + ex.Message); } }
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 static Operations.SavedOpData ErrorResult(Operations.SavedOpData update, IInstallationResult installationRes, string message) { update.success = false.ToString().ToLower(); update.error = message + ": " + installationRes.HResult + ", Result code: " + installationRes.ResultCode; Logger.Log("Update Failed to Install: {0}", LogLevel.Info, update.filedata_app_name + ", Error: " + update.error); return update; }
public UpdateInstallFailed(IInstallationResult result) { var message = GetMessageForResult(result.HResult); Issue = string.Format("One or more updates failed to install ({0}): {1}", result.ResultCode, message); }
/// <summary> /// The <see cref="Execute(CodeActivityContext)"/> method inherited from <see cref="CodeActivity{TResult}"/>. /// </summary> /// <param name="context">The current <see cref="CodeActivity"/> context.</param> /// <returns>A DateTime object.</returns> /// <inheritdoc cref="SwedishCodeActivity{T}"/> protected override object Execute(CodeActivityContext context) { UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); try { ISearchResult searchResult = updateSearcher.Search("IsInstalled=0 And IsHidden=0"); foreach (IUpdate update in searchResult.Updates) { if (update.EulaAccepted == false) { update.AcceptEula(); } } UpdateDownloader updateDownloader = updateSession.CreateUpdateDownloader(); updateDownloader.Priority = DownloadPriority.dpHigh; updateDownloader.Updates = searchResult.Updates; IDownloadResult downloadResult = updateDownloader.Download(); while (downloadResult.ResultCode == OperationResultCode.orcInProgress) { Thread.Sleep(10); } // Check that the updates downloaded successfully. if (downloadResult.ResultCode == OperationResultCode.orcSucceeded || downloadResult.ResultCode == OperationResultCode.orcSucceededWithErrors) { UpdateCollection updateCollection = new UpdateCollection(); foreach (IUpdate update in searchResult.Updates) { if (update.IsDownloaded) { updateCollection.Add(update); } } IUpdateInstaller updateInstaller = updateSession.CreateUpdateInstaller(); updateInstaller.Updates = updateCollection; IInstallationResult installationResult = updateInstaller.Install(); if (installationResult.ResultCode == OperationResultCode.orcSucceeded || installationResult.ResultCode == OperationResultCode.orcSucceededWithErrors) { if (installationResult.RebootRequired) { // Restart the system. // For the reason these particular flags are used, see: https://docs.microsoft.com/en-us/windows/desktop/Shutdown/system-shutdown-reason-codes InitiateSystemShutdownEx(null, null, 0, true, true, ShutdownReason.SHTDN_REASON_MAJOR_OPERATINGSYSTEM | ShutdownReason.SHTDN_REASON_MINOR_HOTFIX | ShutdownReason.SHTDN_REASON_FLAG_PLANNED); return("Updates completed and machine is rebooting."); } else { return("Updates completed."); } } } else { return("There was a problem downloading updates."); } } catch (COMException e) { if (e.HResult == -2145124316) { return("No updates were found. Exiting..."); } else { return($"Exception {e.HResult}: {e.Message} was hit. Exiting..."); } } return(string.Empty); }
// 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); } }
internal void InstallationComplete() { /* public enum OperationResultCode { orcNotStarted = 0, orcInProgress = 1, orcSucceeded = 2, orcSucceededWithErrors = 3, orcFailed = 4, orcAborted = 5, } * */ _installationResult = _updateInstaller.EndInstall(_installationJob); _installationJob = null; if (_installationResult.ResultCode == OperationResultCode.orcSucceeded) { this.ShowProgressMessage("progress_install", ""); this.AppendString("安装完成。\r\n"); } else { this.AppendString("安装更新失败。错误码: " + _installationResult.ResultCode); if (_installationResult.RebootRequired == true) { OnAllComplete(); MessageBox.Show(this, "请重新启动电脑"); return; } // 全部结束 } OnAllComplete(); }
private static Operations.SavedOpData ErrorResult(Operations.SavedOpData update, IInstallationResult installationRes, string message) { update.success = false.ToString().ToLower(); update.error = message + ": " + installationRes.HResult + ", Result code: " + installationRes.ResultCode; Logger.Log("Update Failed to Install: {0}", LogLevel.Info, update.filedata_app_name + ", Error: " + update.error); return(update); }
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 } }
// 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); } } }
protected void OnInstalationCompleted(IInstallationJob installationJob, List <MsUpdate> Updates) { if (installationJob != mInstalationJob) { return; } mInstalationJob = null; mCallback = null; IInstallationResult InstallationResults = null; try { if (mCurOperation == AgentOperation.InstallingUpdates) { InstallationResults = mInstaller.EndInstall(installationJob); } else if (mCurOperation == AgentOperation.RemoveingUpdtes) { InstallationResults = mInstaller.EndUninstall(installationJob); } } catch (Exception err) { AppLog.Line("(Un)Installing updates failed"); LogError(err); OnFinished(false); return; } if (InstallationResults.ResultCode == OperationResultCode.orcSucceeded) { AppLog.Line("Updates (Un)Installed succesfully"); foreach (MsUpdate Update in Updates) { if (mCurOperation == AgentOperation.InstallingUpdates) { if (RemoveFrom(mPendingUpdates, Update)) { Update.Attributes |= (int)MsUpdate.UpdateAttr.Installed; mInstalledUpdates.Add(Update); } } else if (mCurOperation == AgentOperation.RemoveingUpdtes) { if (RemoveFrom(mInstalledUpdates, Update)) { Update.Attributes &= ~(int)MsUpdate.UpdateAttr.Installed; mPendingUpdates.Add(Update); } } } if (InstallationResults.RebootRequired == true) { AppLog.Line("Reboot is required for one of more updates"); } } else { AppLog.Line("Updates failed to (Un)Install"); } OnUpdatesChanged(); OnFinished(InstallationResults.ResultCode == OperationResultCode.orcSucceeded, InstallationResults.RebootRequired); }
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); } }
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"); }
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)); }
private void InstallPatches(UpdateSession session, List <IUpdate5> updates, bool rebootIfNeeded, Stream output) { Bender.WriteLine("Installing " + updates.Count + " patches...", output); bool reboot = false; foreach (IUpdate5 update in updates.OrderBy(u => u.Title)) { if (update.IsInstalled) { Bender.WriteLine("Patch is already installed: " + update.Title, output); continue; } else if (!update.IsDownloaded) { Bender.WriteLine("Patch isn't downloaded yet: " + update.Title, output); } else { try { Bender.WriteLine("Installing: " + update.Title, output); UpdateCollection updateCollection = new UpdateCollection(); updateCollection.Add(update); IUpdateInstaller installer = session.CreateUpdateInstaller(); installer.Updates = updateCollection; IInstallationResult installresult = installer.Install(); if (installresult.ResultCode == OperationResultCode.orcSucceeded) { if (installresult.RebootRequired) { reboot = true; } } else { Bender.WriteLine("Couldn't install patch: " + installresult.ResultCode + ": 0x" + installresult.HResult.ToString("X"), output); } } catch (COMException ex) { Bender.WriteLine("Couldn't download patch: 0x" + ex.HResult.ToString("X"), output); } } } string regpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"; if (reboot || CheckIfLocalMachineKeyExists(regpath)) { if (rebootIfNeeded) { Bender.WriteLine("Rebooting.", output); IntPtr hToken; TOKEN_PRIVILEGES tkp; OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken); tkp.PrivilegeCount = 1; tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED; LookupPrivilegeValue("", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid); AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero, IntPtr.Zero); if (!ExitWindowsEx(6, 0)) { Bender.WriteLine("Couldn't reboot.", output); } } else { Bender.WriteLine("Reboot required.", output); } } }
public static WindowsUpdateResult InstallUpdates(JobClientInterface jci) { UpdateSession updateSession = new UpdateSession(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); UpdateCollection updatesToDownload = new UpdateCollection(); jci.LogString("Searching For Updates..."); ISearchResult sr = updateSearcher.Search("IsInstalled=0 and Type='Software' and AutoSelectOnWebSites=1"); if (sr.Updates.Count == 0) { jci.LogString("No New Updates Found"); return(new WindowsUpdateResult(false, false)); } for (int i = 0; i < sr.Updates.Count; i++) { IUpdate update = sr.Updates[i]; if (!update.IsDownloaded) { if (update.InstallationBehavior.CanRequestUserInput) { jci.LogString("Ignoring update \"" + update.Title + "\" because it could require user input."); continue; } jci.LogString("Queuing Download of :" + update.Title); updatesToDownload.Add(update); } } if (updatesToDownload.Count > 0) { jci.LogString("Downloading Updates..."); UpdateDownloader downloader = updateSession.CreateUpdateDownloader(); downloader.Updates = updatesToDownload; downloader.Download(); } UpdateCollection updatesToInstall = new UpdateCollection(); for (int i = 0; i < sr.Updates.Count; i++) { IUpdate update = sr.Updates[i]; if (update.IsDownloaded) { if (!update.EulaAccepted) { update.AcceptEula(); } if (update.InstallationBehavior.CanRequestUserInput) { jci.LogString("Ignoring update \"" + update.Title + "\" because it could require user input."); continue; } jci.LogString("Queuing Install of :" + update.Title); updatesToInstall.Add(update); } } if (updatesToInstall.Count > 0) { jci.LogString("Installing Updates..."); IUpdateInstaller installer = updateSession.CreateUpdateInstaller(); installer.Updates = updatesToInstall; IInstallationResult installationResult = installer.Install(); jci.LogString("Installation Finished"); jci.LogString("Update Result Code: " + installationResult.ResultCode.ToString()); bool rebootRequired = installationResult.RebootRequired; if (rebootRequired) { jci.LogString("Reboot Required"); } return(new WindowsUpdateResult(true, rebootRequired)); } else { jci.LogString("No New Updates Found"); return(new WindowsUpdateResult(false, false)); } }
internal static string IInstallationResultToString(IInstallationResult r) { return($"{nameof(r.HResult)}:{r.HResult}" + $", {nameof(r.ResultCode)}:{r.ResultCode}" + $", {nameof(r.RebootRequired)}:{r.RebootRequired}"); }
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); } }
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(); }