Exemplo n.º 1
0
        internal static void WsusDownloadFromWsus(ISearchResult search)
        {
            UpdateDownloader udownloader = new UpdateDownloader();

            udownloader.Updates = search.Updates;
            udownloader.Download();
            UpdateCollection updatesToInstall = new UpdateCollection();

            foreach (IUpdate update in search.Updates)
            {
                if (update.IsDownloaded)
                {
                    updatesToInstall.Add(update);
                }
            }
            WsusInstaller(updatesToInstall);
        }
Exemplo n.º 2
0
        // Method for using WUAPI to download the named update - "Windows Update" service needs turning on before calling this method
        public void downloadUpdate()
        {
            try
            {
                Logger.instance.Debug("Downloading update");
                IUpdateSession uSession = new UpdateSession();

                Logger.instance.Debug("Creating searcher");
                IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher(); // Search for available Updates

                Logger.instance.Debug("Creating downloader");
                UpdateDownloader downloader = uSession.CreateUpdateDownloader(); //Create a downloader

                Logger.instance.Debug("Creating holder for updates");
                UpdateCollection updatesToDownload = new UpdateCollection();

                Logger.instance.Debug("Searcing for updates");
                ISearchResult uResult = uSearcher.Search("Type='Software' And IsAssigned = 1"); //Save the result of the search

                for (int i = 0; i < uResult.Updates.Count; i++)
                {
                    if (uResult.Updates[i].Title.ToString().Equals(this.Name))
                    {
                        updatesToDownload.Add(uResult.Updates[i]);   //save all the queued updates to the downloader queue
                        break;
                    }
                }

                if (updatesToDownload.Count > 0)
                {
                    downloader.Updates = updatesToDownload;
                    downloader.Download(); //download queued updates (should be just one)

                    // If fails, will need to check here
                    this.isDownloaded       = true;
                    this.DateTimeDownloaded = DateTime.UtcNow;

                    Logger.instance.Debug("Saving update");
                    save();   // Save the latest information
                }
            }
            catch (Exception e)
            {
                Logger.instance.Error(e);
            }
        }
Exemplo n.º 3
0
        private void DownloadPatches(UpdateSession session, List <IUpdate5> updates)
        {
            Log($"Downloading {updates.Count} patches...");

            foreach (IUpdate5 update in updates.OrderBy(u => u.Title))
            {
                if (update.IsDownloaded)
                {
                    Log($"Patch is already downloaded: {update.Title}");
                    continue;
                }


                UpdateCollection updateCollection = new UpdateCollection();
                updateCollection.Add(update);

                UpdateDownloader downloader = session.CreateUpdateDownloader();
                downloader.Updates = updateCollection;

                bool downloaded = false;

                for (int tries = 0; tries < 3 && !downloaded; tries++)
                {
                    try
                    {
                        string printtry = tries > 0 ? $" (try {(tries + 1)})" : string.Empty;

                        Log($"Downloading {printtry}: {update.Title}: {GetPrintSize(update.MaxDownloadSize)} MB.");

                        IDownloadResult downloadresult = downloader.Download();
                        if (downloadresult.ResultCode == OperationResultCode.orcSucceeded)
                        {
                            downloaded = true;
                        }
                        else
                        {
                            Log($"Couldn't download patch: {downloadresult.ResultCode}: 0x{downloadresult.HResult:X)}");
                        }
                    }
                    catch (COMException ex)
                    {
                        Log($"Couldn't download patch: 0x{ex.HResult:X)}");
                    }
                }
            }
        }
        public async Task Test()
        {
            await UpdateDownloader.DownloadAsync(CancellationToken.None);

            Assert.Equal(2, Downloads.Count);
            Assert.Contains(Hash.Parse("7324c19ad06ea51117d7ffdd01f7d030ac03651f6ea57472de1765b3dfa3a9e0"), Downloads);
            Assert.Contains(Hash.Parse("ac6cb635c58754672d0e576442db9ecadd8043829916ca85330cf00bd7359df9"), Downloads);

            Assert.Equal(2, TempFiles.Count);

            Assert.True(TempFiles.TryGetValue("7324c19ad06ea51117d7ffdd01f7d030ac03651f6ea57472de1765b3dfa3a9e0",
                                              out var tempFile));
            Assert.Equal("NORA2", Encoding.ASCII.GetString(tempFile.DataStream.ToArray()));

            Assert.True(TempFiles.TryGetValue("ac6cb635c58754672d0e576442db9ecadd8043829916ca85330cf00bd7359df9",
                                              out tempFile));
            Assert.Equal("NORA3", Encoding.ASCII.GetString(tempFile.DataStream.ToArray()));
        }
Exemplo n.º 5
0
        private static void CheckUpdate(UpdateOptions options)
        {
            var update = new UpdateDownloader(options);

            // Exit if check only is true
            if (options.CheckOnly)
            {
                Environment.Exit(update.IsUpToDate() ? 201 : 200);
            }

            if (update.IsUpToDate())
            {
                Environment.Exit(5);                      // Download only if new version is available. 5 means no updates
            }
            // Download files
            update.DownloadPackage(new Uri(update.LatestRelease.Assets[0].BrowserDownloadUrl));

            // Writes Json package info
            update.WritePackageJson();
        }
        public static DownloadSession BeginDownload(this PSCmdlet cmdlet, ISearchResult searchResult)
        {
            UpdateSession    session    = new UpdateSession();
            UpdateDownloader downloader = session.CreateDownloader();

            downloader.Updates  = searchResult.Updates;
            downloader.Priority = DownloadPriority.dpExtraHigh;

            ProgressAdapter adapter = new ProgressAdapter(cmdlet, downloader);

            DownloadProgressChangedCallback progressCallback = new DownloadProgressChangedCallback(adapter);

            DownloadCompletedCallback completedCallback = new DownloadCompletedCallback(downloader);

            object state = new object();

            downloader.BeginDownload(progressCallback, completedCallback, state);

            return(DownloadSession.From(completedCallback));
        }
Exemplo n.º 7
0
        public GspUpdater()
        {
            InitializeComponent();

            this.m_lvwColumnSorter = new ListViewColumnSorter();
            this.lsvInstalls.ListViewItemSorter = this.m_lvwColumnSorter;

            this.m_latestVersion       = null;
            this.m_gspUpdatesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GspLatestVersion");

            this.m_updateDownloader = new UpdateDownloader("GspLatestVersion");
            this.m_updateDownloader.UpdateDownloading += new UpdateDownloader.UpdateDownloadingHandler(m_updateDownloader_UpdateDownloading);

            this.m_updateDownloader.DownloadUnzipComplete += new UpdateDownloader.DownloadUnzipCompleteHandler(m_updateDownloader_DownloadUnzipComplete);
            this.m_updateDownloader.DownloadLatest();

            this.m_lstIgnoreDirectories = new List <string>()
            {
                "updates", "gsplatestversion", "localization", "plugins", "configs", "updates", "logs", "media"
            };
        }
         public static UpdateCollection DownloadUpdates()
         {
             UpdateSession UpdateSession = new UpdateSession();
             IUpdateSearcher SearchUpdates = UpdateSession.CreateUpdateSearcher();
             ISearchResult UpdateSearchResult = SearchUpdates.Search("IsInstalled=0 and IsPresent=0");
             UpdateCollection UpdateCollection = new UpdateCollection();
             //Accept Eula code for each update
             for (int i = 0; i < UpdateSearchResult.Updates.Count; i++)
             {
                 IUpdate Updates = UpdateSearchResult.Updates[i];
                 if (Updates.EulaAccepted == false)
                 {
                     Updates.AcceptEula();
                 }
                 UpdateCollection.Add(Updates);
             }
             //Accept Eula ends here
             //if it is zero i am not sure if it will trow an exception -- I havent tested it.
  
                 UpdateCollection DownloadCollection = new UpdateCollection();
                 UpdateDownloader Downloader = UpdateSession.CreateUpdateDownloader();
                
                 for (int i = 0; i < UpdateCollection.Count; i++)
                 {
                     DownloadCollection.Add(UpdateCollection[i]);
                 }
 
                 Downloader.Updates = DownloadCollection;
                 Console.WriteLine("Downloading Updates");
                 IDownloadResult DownloadResult = Downloader.Download();
                 UpdateCollection InstallCollection = new UpdateCollection();
                 for (int i = 0; i < UpdateCollection.Count; i++)
                 {
                     if (DownloadCollection[i].IsDownloaded)
                     {
                         InstallCollection.Add(DownloadCollection[i]);
                     }
                 }
                 return InstallCollection;
         }
Exemplo n.º 9
0
        private void UpdateCheck(bool isManualCheck = false)
        {
            UpdatePackage update = _updater.UpdateCheck();

            // Determine is target version is > current version
            if (_updater.IsNewVersion(Program.APP_VERSION, update.version))
            {
                if (MessageBox.Show($"A newer version of FastFileTransfer has been found. Would you like to download version: {update.version}?", "Checking For Updates", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    // SHOW GATE UNTIL DOWNLOAD COMPELTED
                    string targetFile = System.IO.Path.Combine(Application.StartupPath, update.package.Replace("apps/", ""));
                    string message    = $"Current Version: {Program.APP_VERSION}\nTarget Version: {update.version}\n\nDestination:\n{targetFile}";

                    using (dlgLoadingGate dlg = new dlgLoadingGate("Downloading Update", message))
                    {
                        using (UpdateDownloader ud = new UpdateDownloader(targetFile, update))
                        {
                            dlg.Show();
                            ud.Download();
                            while (!ud.DownloadComplete)
                            {
                                Application.DoEvents();
                            }

                            dlg.CloseDialog();

                            // TODO: It would be nice to extract and auto install the updates
                            // However, we will need to write or utilize an installation wizard
                            MessageBox.Show($"The updated package has been downloaded to:\n\n{targetFile}\n\nPlease extract it to complete the update!", "Update Downloaded", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            else if (isManualCheck)
            {
                MessageBox.Show($"FastFileTransfer is up to date with version {Program.APP_VERSION}.", "Checking For Updates", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 10
0
        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);
            }
        }
Exemplo n.º 11
0
        private async Task <bool> ValidateOrGetUpdate(IrdFile irdFile, CancellationToken cancellation)
        {
            // All zeroes, then no update is available (release date games only!)
            if (irdFile.UpdateVersion != "0000")
            {
                // Check the PS3Update version
                string ps3updatePath = System.IO.Path.Combine(Path, "PS3_UPDATE", "PS3UPDAT.PUP");
                bool   invalidUpdate = false, downloadUpdate = false;
                if (!File.Exists(ps3updatePath))
                {
                    invalidUpdate  = true;
                    downloadUpdate = await Interaction.Instance.DownloadUpdate(
                        string.Format(
                            "The file PS3UPDAT.PUP is missing from your JB rip. Automatically try and download version {0}?",
                            irdFile.UpdateVersion));
                }
                else
                {
                    using (FileStream fs = new FileStream(ps3updatePath, FileMode.Open, FileAccess.Read))
                    {
                        string version = Utilities.FindUpdateVersion(fs, 0);
                        if (version == null || version != irdFile.UpdateVersion)
                        {
                            invalidUpdate = true;
                            string msg = version != null
                                             ? string.Format(
                                "The file PS3UPDAT.PUP is version {0}, while the original disc contains version {1}. Either continue (and accept the invalid hash), or replace the PS3UPDAT.PUP with the correct version.\nAutomatically try to download the correct update file?",
                                version, irdFile.UpdateVersion)
                                             : string.Format(
                                "The file PS3UPDAT.PUP is either empty, or not a valid file. The original disc contains version {0}. Automatically try to download the correct update file?",
                                irdFile.UpdateVersion);

                            downloadUpdate = await Interaction.Instance.DownloadUpdate(msg);
                        }
                    }
                }

                if (invalidUpdate)
                {
                    if (!downloadUpdate)
                    {
                        Interaction.Instance.ReportMessage(
                            "The PS3UPDAT.PUP file is missing or incorrect, and you've choosen to not download the correct file. Download the file manually. The required version is " +
                            irdFile.UpdateVersion,
                            ReportType.Fail);
                        Interaction.Instance.ReportMessage("Create ISO aborted.", ReportType.Fail);
                        return(false);
                    }

                    // Download the correct update
                    Interaction.Instance.TaskBegin(true);
                    Interaction.Instance.ReportMessage("Download update file...");
                    bool success =
                        await
                        UpdateDownloader.Download(irdFile.UpdateVersion, irdFile.GameID, ps3updatePath, cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(false);
                    }

                    if (success)
                    {
                        Interaction.Instance.ReportMessage("Updatefile successfully downloaded.", ReportType.Success);
                    }
                    else
                    {
                        Interaction.Instance.ReportMessage(
                            "Failed to download the update file. You should try to locate the update file yourself.",
                            ReportType.Fail);
                        return(false);
                    }
                }
            }
            return(true);
        }
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     updateDownloader = Globals.updateSession.CreateUpdateDownloader();
 }
 public Task Test()
 {
     return(Assert.ThrowsAsync <InvalidOperationException>(() =>
                                                           UpdateDownloader.DownloadAsync(CancellationToken.None)));
 }
 protected override void BeginProcessing()
 {
     base.BeginProcessing();
     updateDownloader = updateSession.CreateUpdateDownloader();
 }
Exemplo n.º 15
0
        /// <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);
        }
Exemplo n.º 16
0
 // 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 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));
            }
        }
        private OperationResultCode DownloadUpdatesUtil(CancellationToken cancellationToken)
        {
            try
            {
                UpdateDownloader uDownloader       = this._uSession.CreateUpdateDownloader();
                UpdateCollection updatesToDownload = new UpdateCollection();

                foreach (WUUpdateWrapper item in this._wuCollectionWrapper.Collection.Values)
                {
                    if (!item.IsDownloaded)
                    {
                        if (item.Update.EulaAccepted == false)
                        {
                            if (this._serviceSettings.AcceptWindowsUpdateEula)
                            {
                                try
                                {
                                    item.Update.AcceptEula();
                                }
                                catch (Exception e)
                                {
                                    _eventSource.WarningMessage(string.Format("Error occurred while accepting Eula for {0} . Exception : {1}",
                                                                              item, e));
                                }
                                updatesToDownload.Add(item.Update);
                            }
                        }
                        else
                        {
                            updatesToDownload.Add(item.Update);
                        }
                    }
                }

                uDownloader.Updates = updatesToDownload;

                DownloadCompletedCallback downloadCompletedCallback = new DownloadCompletedCallback();
                IDownloadJob downloadJob = uDownloader.BeginDownload(new DownloadProgressChangedCallback(),
                                                                     downloadCompletedCallback, null);

                TimeSpan operationTimeOut = TimeSpan.FromMinutes(this._serviceSettings.WUOperationTimeOutInMinutes);
                if (
                    !this._helper.WaitOnTask(downloadCompletedCallback.Task, (int)operationTimeOut.TotalMilliseconds,
                                             cancellationToken))
                {
                    _eventSource.Message("downloadJob : Requested Abort");
                    downloadJob.RequestAbort();
                }

                IDownloadResult uResult = uDownloader.EndDownload(downloadJob);
                for (int i = 0; i < updatesToDownload.Count; i++)
                {
                    var hResult  = uResult.GetUpdateResult(i).HResult;
                    var updateID = updatesToDownload[i].Identity.UpdateID;
                    this._wuCollectionWrapper.Collection[updateID].IsDownloaded = (hResult == 0);
                    if (hResult != 0)
                    {
                        _eventSource.WarningMessage(string.Format("Download for update ID {0} returned hResult {1}", updateID, hResult));
                    }
                }

                return(uResult.ResultCode);
            }
            catch (Exception e)
            {
                if ((uint)e.HResult == WUErrorCodes.WU_E_NO_UPDATE)
                {
                    return(OperationResultCode.orcSucceeded); // no updates found.
                }
                _eventSource.InfoMessage("Exception while downloading Windows-Updates: {0}", e);
                return(OperationResultCode.orcFailed);
            }
        }
 public ProgressAdapter(PSCmdlet cmdlet, UpdateDownloader updateDownloader)
 {
     _cmdlet           = cmdlet;
     _updateDownloader = updateDownloader;
 }
        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 DownloadCompletedCallback(UpdateDownloader downloader)
 {
     Downloader = downloader;
 }
Exemplo n.º 22
0
        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
            }
        }