void BeginInstallation() { UpdateCollection installCollection = new UpdateCollection(); foreach (IUpdate update in this._updateCollection) { if (update.IsDownloaded) installCollection.Add(update); } if (installCollection.Count == 0) { this.AppendString("下载完成,但没有可供安装的更新。操作结束。\r\n"); OnAllComplete(); return; } this.AppendString("开始安装更新 ...\r\n"); _updateInstaller = _updateSession.CreateUpdateInstaller() as IUpdateInstaller; _updateInstaller.Updates = installCollection; // this._updateCollection; // TODO: 不但要安装本次下载的,也要安装以前下载了但没有安装的 _installationJob = _updateInstaller.BeginInstall(new InstallationProgressChangedFunc(this), new InstallCompletedFunc(this), null // new UpdateInstaller_state(this) ); }
static void Main(string[] args) { UpdateSession updateSession = new UpdateSession(); Console.WriteLine("1/3 searching"); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); ISearchResult searchResult = updateSearcher.Search("Type='Driver' And IsInstalled=0 And IsHidden=0"); foreach (IUpdate update in searchResult.Updates) { Console.WriteLine(update.Title); } Console.WriteLine("2/3 downloading"); IUpdateDownloader updateDownloader = updateSession.CreateUpdateDownloader(); updateDownloader.Updates = searchResult.Updates; updateDownloader.Download(); Console.WriteLine("3/3 installing"); IUpdateInstaller updateInstaller = updateSession.CreateUpdateInstaller(); updateInstaller.Updates = searchResult.Updates; updateInstaller.Install(); }
/// <summary> /// Creates a <see cref="WuApiController"/> which uses the given Interfaces to search, download and install updates. /// </summary> /// <param name="session">Session to be used.</param> /// <param name="updateCollectionFactory">Factory to create <see cref="IUpdateCollection"/>s.</param> /// <param name="systemInfo">System informations about the OS enviroment.</param> public WuApiController(IUpdateSession session, UpdateCollectionFactory updateCollectionFactory, ISystemInfo systemInfo) { if (session == null) { throw new ArgumentNullException(nameof(session)); } if (updateCollectionFactory == null) { throw new ArgumentNullException(nameof(updateCollectionFactory)); } if (systemInfo == null) { throw new ArgumentNullException(nameof(systemInfo)); } UpdateSession = session; UpdateSession.ClientApplicationID = this.GetType().FullName; UpdateSearcher = session.CreateUpdateSearcher(); UpdateDownloader = session.CreateUpdateDownloader(); UpdateInstaller = session.CreateUpdateInstaller(); UpdateCollectionFactory = updateCollectionFactory; SystemInfo = systemInfo; StateTransitions = SetupStateTransitions(); EnterState((SystemInfo.IsRebootRequired()) ? (WuProcessState) new WuStateRebootRequired() : new WuStateReady()); Log.Info("Initial state: " + _currentState.GetType().Name); if (Log.IsDebugEnabled) { OnStateChanged += (s, e) => { Log.Debug($"Event {nameof(OnStateChanged)} fired: {e.ToString()}"); }; OnAsyncOperationCompleted += (s, e) => { Log.Debug($"Event {nameof(OnAsyncOperationCompleted)} fired: {e.ToString()}"); }; OnProgressChanged += (s, e) => { Log.Debug($"Event {nameof(OnProgressChanged)} fired: {e.ToString()}"); }; } }
public void iInstallation() { iUpdateInstaller = UpdateSession.CreateUpdateInstaller() as IUpdateInstaller; iUpdateInstaller.Updates = this.NewUpdatesCollection; iInstallationJob = iUpdateInstaller.BeginInstall(new iUpdateInstaller_onProgressChanged(this), new iUpdateInstaller_onCompleted(this), new iUpdateInstaller_state(this)); }
void BeginInstallation() { UpdateCollection installCollection = new UpdateCollection(); foreach (IUpdate update in this._updateCollection) { if (update.IsDownloaded) { installCollection.Add(update); } } if (installCollection.Count == 0) { this.AppendString("下载完成,但没有可供安装的更新。操作结束。\r\n"); OnAllComplete(); return; } this.AppendString("开始安装更新 ...\r\n"); _updateInstaller = _updateSession.CreateUpdateInstaller() as IUpdateInstaller; _updateInstaller.Updates = installCollection; // this._updateCollection; // TODO: 不但要安装本次下载的,也要安装以前下载了但没有安装的 _installationJob = _updateInstaller.BeginInstall(new InstallationProgressChangedFunc(this), new InstallCompletedFunc(this), null // new UpdateInstaller_state(this) ); }
public async void InstallUpdates() { try { updateInstaller = updateSession.CreateUpdateInstaller(); updateInstaller.Updates = updateCollection; updateInstaller.AllowSourcePrompts = false; DebugLog("Starting update installation: " + Dump(updateInstaller)); //var result = updateInstaller.RunWizard("F*****g hell!!!"); //OnInstallationComplete(result); installationJob_ = updateInstaller.BeginInstall(this, this, null); } catch (Exception ex) { VMManagementTool.Log.Error("WinUpdatesManager::InstallUpdates", ex.ToString()); //this will allow the caller UI method to finish and //the event will be handled like expected asyncronously await Task.Yield(); InstallationCompleted?.Invoke(false, false); } }
public UpdateSessionFake(bool createMocksForCreateMethods = false) { if (createMocksForCreateMethods) { Downloader = new UpdateDownloaderFake(); Searcher = new UpdateSearcherFake(); Installer = new UpdateInstallerFake(); } }
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 Updater(IUpdateManifest manifest, IUpdateStatusProvider statusProvider, IUpdateDownloader downloader, IUpdateInstaller installer) { this.manifest = manifest; this.statusProvider = statusProvider; this.downloader = downloader; this.installer = installer; }
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 RetCodes UnInstallUpdates(List <MsUpdate> Updates) { if (mCallback != null) { return(RetCodes.Busy); } if (mInstaller == null) { mInstaller = mUpdateSession.CreateUpdateInstaller() as IUpdateInstaller; } mInstaller.Updates = new UpdateCollection(); foreach (MsUpdate Update in Updates) { IUpdate update = Update.GetUpdate(); if (update == null) { continue; } if (!update.IsUninstallable) { AppLog.Line("Update can not be uninstalled: {0}", update.Title); continue; } mInstaller.Updates.Add(update); } if (mDownloader.Updates.Count == 0) { AppLog.Line("No updates selected or eligible for uninstallation"); return(RetCodes.NoUpdated); } mCurOperation = AgentOperation.RemoveingUpdates; OnProgress(-1, 0, 0, 0); mCallback = new UpdateCallback(this); AppLog.Line("Removing Updates... This may take several minutes."); try { mInstalationJob = mInstaller.BeginUninstall(mCallback, mCallback, Updates); } catch (Exception err) { return(OnWuError(err)); } return(RetCodes.InProgress); }
private static void WaitForInstallerBusy(IUpdateInstaller wuaInstaller) { var count = 0; // Wait for some seconds while (wuaInstaller.IsBusy && count++ < 30) { Thread.Sleep(250); } if (count >= 20) { throw new TimeoutException("Update installer is busy"); } }
private static bool IsRebootRequireBeforeInstallation() { try { UpdateSession uSession = new UpdateSession(); IUpdateInstaller uInstaller = uSession.CreateUpdateInstaller(); Logger.Write("Require Reboot before installation : " + uInstaller.RebootRequiredBeforeInstallation.ToString()); return(uInstaller.RebootRequiredBeforeInstallation); } catch (Exception ex) { Logger.Write("Problem when determining if a reboot is require before installation. " + ex.Message); return(true); } }
/// <summary> /// アップデートのアンインストールを非同期に行う /// </summary> /// <param name="installer"></param> /// <param name="progress"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static Task <IInstallationResult> UninstallAsync(this IUpdateInstaller installer, Action <IInstallationProgress> progress, CancellationToken cancellationToken = default(CancellationToken)) { var task = new TaskCompletionSource <IInstallationResult>(); var job = null as IInstallationJob; var reg = null as IDisposable; job = installer.BeginUninstall(new InstallationProgressChangeCallback(progress), new InstallationCompletedCallback((_job2, args) => { try { try { task.TrySetResult(installer.EndUninstall(job)); } catch (Exception e) { task.TrySetException(e); } } finally { job = null; _job2?.CleanUp(); _job2 = null; reg?.Dispose(); reg = null; } }), null); reg = cancellationToken.Register(() => { task.TrySetCanceled(cancellationToken); try { if (job != null) { installer.EndUninstall(job); } } catch (Exception e) { task.TrySetException(e); } }); return(task.Task); }
private RetCodes InstallUpdates(List <MsUpdate> Updates) { if (mCallback != null) { return(RetCodes.Busy); } if (mInstaller == null) { mInstaller = mUpdateSession.CreateUpdateInstaller() as IUpdateInstaller; } mInstaller.Updates = new UpdateCollection(); foreach (MsUpdate Update in Updates) { IUpdate update = Update.GetUpdate(); if (update == null) { continue; } mInstaller.Updates.Add(update); } if (mInstaller.Updates.Count == 0) { AppLog.Line("No updates selected for instalation"); return(RetCodes.NoUpdated); } mCurOperation = AgentOperation.InstallingUpdates; OnProgress(-1, 0, 0, 0); mCallback = new UpdateCallback(this); AppLog.Line("Installing Updates... This may take several minutes."); try { mInstalationJob = mInstaller.BeginInstall(mCallback, mCallback, Updates); } catch (Exception err) { return(OnWuError(err)); } return(RetCodes.InProgress); }
private void installUpdates(UpdateCollection updateList) { uInstaller = uSession.CreateUpdateInstaller(); uInstaller.AllowSourcePrompts = false; if (!ShouldInstallUpdates || updateList.Count < 1) { return; } if (uInstaller.IsBusy) { Program.Dash.status("Update Installer Busy, Try Again"); return; } if (uInstaller.RebootRequiredBeforeInstallation) { Program.Dash.status("Reboot Required"); return; } Program.Dash.status("Installing " + updateList.Count + " Updates"); int counter = 0; int installBatch = Program.Dash.getLastInstallBatch() + 1; List <string> results = new List <string>(); foreach (IUpdate update in updateList) { counter++; string resultText; Program.Dash.status(string.Format("Installing update {0} of {1} : {2}", counter.ToString(), updateList.Count.ToString(), update.Title)); resultText = this.install(update, installBatch); results.Add(string.Format("Result for '{0}' : {1}", update.Title, resultText)); } // send the result notification string resultMessage = this.getResultMessage(results); Program.Dash.status(resultMessage); Program.Dash.InsertUpdateBatch(resultMessage, installBatch); }
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 CountPendingUpdates() { Console.WriteLine("WUA_Starting"); IUpdateSession updateSession = new UpdateSessionClass(); IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher(); IUpdateDownloader updateDownloader = updateSession.CreateUpdateDownloader(); IUpdateInstaller updateInstaller = updateSession.CreateUpdateInstaller(); // SEARCHING Console.WriteLine("WUA_FindingUpdates"); ISearchResult searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'"); Console.WriteLine(string.Format("WUA_Pending:{0}", searchResult.Updates.Count)); Console.WriteLine("WUA_Finish"); }
public WuStateInstalling(IUpdateInstaller uInstaller, IUpdateCollection updates, InstallCompletedCallback completedCallback, TimeoutCallback timeoutCallback, ProgressChangedCallback progressCallback, int timeoutSec) : base(WuStateId.Installing, "Installing Updates", timeoutSec, timeoutCallback, progressCallback) { if (uInstaller == null) { throw new ArgumentNullException(nameof(uInstaller)); } if (updates == null) { throw new ArgumentNullException(nameof(updates)); } if (completedCallback == null) { throw new ArgumentNullException(nameof(completedCallback)); } _uInstaller = uInstaller; _updates = updates; _completedCallback = completedCallback; }
private bool InstallUpdates(List <MsUpdate> Updates) { if (mCallback != null) { return(false); } if (mInstaller == null) { mInstaller = mUpdateSession.CreateUpdateInstaller() as IUpdateInstaller; } mInstaller.Updates = new UpdateCollection(); foreach (MsUpdate Update in Updates) { IUpdate update = Update.GetUpdate(); if (update == null) { continue; } mInstaller.Updates.Add(update); } if (mInstaller.Updates.Count == 0) { AppLog.Line("No updates selected for instalation"); return(false); } mCurOperation = AgentOperation.InstallingUpdates; OnProgress(-1, 0, 0, 0); mCallback = new UpdateCallback(this); AppLog.Line("Installing Updates... This may take several minutes."); mInstalationJob = mInstaller.BeginInstall(mCallback, mCallback, Updates); return(true); }
/// <summary> /// Install all downloaded updates /// Auto accept Eula /// </summary> public void BeginInstallation() { progressWindow = new ProgressWindow(); progressWindow.Show(); progressWindow.Title = "Installation..."; installationJob = null; installCollection = new UpdateCollection(); foreach (IUpdate update in this.sResult.Updates) { if (update.IsDownloaded) { //testen ob das funktioniert update.AcceptEula(); } // update.InstallationBehavior.RebootBehavior installCollection.Add(update); } installer = uSession.CreateUpdateInstaller(); installer.Updates = installCollection; installationJob = installer.BeginInstall(new InstallProgressChangedFunc(this), new InstallCompletedFunc(this), null); }
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); }
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(); }
// 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); } }
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); } } }
/// <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); }
// 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); } } }
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"); }
/// <summary> /// アップデートのアンインストールを非同期に行う /// </summary> /// <param name="installer"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static Task <IInstallationResult> UninstallAsync(this IUpdateInstaller installer, CancellationToken cancellationToken = default(CancellationToken)) => UninstallAsync(installer, null, cancellationToken);
void BeginInstallation() { _updateInstaller = _updateSession.CreateUpdateInstaller() as IUpdateInstaller; _updateInstaller.Updates = this._updateCollection; // TODO: 不但要安装本次下载的,也要安装以前下载了但没有安装的 _installationJob = _updateInstaller.BeginInstall(new InstallationProgressChangedFunc(this), new InstallCompletedFunc(this), null // new UpdateInstaller_state(this) ); }