Esempio n. 1
1
        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)
                );
        }
Esempio n. 2
0
        private static UpdateCollection BundleRecursion(IUpdate bundle, Operations.SavedOpData updateData)
        {
            var collection   = new UpdateCollection();
            var index        = 0;
            var updateFolder = Path.Combine(UpdateDirectory, updateData.filedata_app_id);

            if (!Directory.Exists(updateFolder))
            {
                return(collection);
            }
            IList <string> updateFiles = Directory.GetFiles(updateFolder);

            foreach (IUpdate insideBundle in bundle.BundledUpdates)
            {
                //Recursive Call if there are more bundles inside this bundle.
                if (insideBundle.BundledUpdates.Count > 0)
                {
                    Logger.Log("    Found bundles inside {0}", LogLevel.Debug, insideBundle.Title);
                    var totalBundles = BundleRecursion(insideBundle, updateData);
                    Logger.Log("          - Loading {0} bundles for {1}", LogLevel.Debug, totalBundles.Count, insideBundle.Title);
                    foreach (IUpdate item in totalBundles)
                    {
                        Logger.Log("Adding {0}", LogLevel.Info, item.Title);
                        collection.Add(item);
                    }
                }

                if (insideBundle.IsInstalled != true)
                {
                    var finalFileCollection = new StringCollection();

                    List <DownloadUri> nodes = GrabLocalUpdateBundle(bundle.Identity.UpdateID, insideBundle.Title);

                    foreach (var iteration in nodes)
                    {
                        var fileCollection = new StringCollection();

                        foreach (var item in updateFiles)
                        {
                            var strip         = item.Split(new[] { '\\' });
                            var localFilename = strip[strip.Length - 1];

                            if (Operations.StringToFileName(localFilename).ToLower() == Operations.StringToFileName(iteration.FileName).ToLower())
                            {
                                fileCollection.Add(item);
                                finalFileCollection = fileCollection;
                                break;
                            }
                        }
                    }

                    ((IUpdate2)bundle.BundledUpdates[index]).CopyToCache(finalFileCollection);
                    collection.Add(bundle);
                }
                index++;
            }
            return(collection);
        }
Esempio n. 3
0
        private void metaGroupItem_Click(object sender, EventArgs e)
        {
            Logger.EnteringMethod();
            string    metaGroupName     = sender.ToString();
            MetaGroup selectedMetaGroup = null;

            mnuStripUpdateListViewer.Hide();
            this.Cursor = Cursors.WaitCursor;

            foreach (MetaGroup metaGroup in _metaGroups)
            {
                if (metaGroup.Name == metaGroupName)
                {
                    selectedMetaGroup = metaGroup;
                    break;
                }
            }
            if (dgvUpdateList.SelectedRows.Count != 0)
            {
                UpdateCollection updates = new UpdateCollection();

                foreach (DataGridViewRow row in dgvUpdateList.SelectedRows)
                {
                    updates.Add((IUpdate)row.Cells["UpdateId"].Value);
                }
                if (QuicklyApproveUpdate != null)
                {
                    QuicklyApproveUpdate(updates, selectedMetaGroup);
                }
            }
        }
Esempio n. 4
0
        public void Updates(UpdateCollection updates)
        {
            string        t       = template;
            List <String> changes = new List <String>();

            foreach (string key in updates.Keys)
            {
                if (!currentValues.ContainsKey(key))
                {
                    currentValues.Add(key, updates[key]);
                    changes.Add(key);
                }
                {
                    if (currentValues[key] != updates[key])
                    {
                        changes.Add(key);
                        currentValues[key] = updates[key];
                    }
                }
            }

            if (changes.Count > 0)
            {
                RefreshDeviceData();
            }
        }
Esempio n. 5
0
        private void iUpdateSearchComplete(Form1 mainform)
        {
            Form1 formRef = mainform;

            // Declare a new UpdateCollection and populate the result...
            NewUpdatesCollection   = new UpdateCollection();
            NewUpdatesSearchResult = iUpdateSearcher.EndSearch(iSearchJob);

            Count = NewUpdatesSearchResult.Updates.Count;
            formRef.Invoke(formRef.sendNotification);

            // Accept Eula code for each update
            for (int i = 0; i < NewUpdatesSearchResult.Updates.Count; i++)
            {
                IUpdate iUpdate = NewUpdatesSearchResult.Updates[i];

                if (iUpdate.EulaAccepted == false)
                {
                    iUpdate.AcceptEula();
                }

                NewUpdatesCollection.Add(iUpdate);
            }

            foreach (IUpdate update in NewUpdatesSearchResult.Updates)
            {
                textBox1.AppendText(update.Title + Environment.NewLine);
            }

            if (NewUpdatesSearchResult.Updates.Count > 0)
            {
                iUpdateDownload();
            }
        }
Esempio n. 6
0
        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)
                                                             );
        }
        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);
            }
        }
Esempio n. 8
0
        static bool InstallUpdates_WUApiLib()
        {
            UpdateSession updateSession = new UpdateSession(); //  Activator.CreateInstance(updateSessionType);
            IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher();
            Console.WriteLine("Searching for available updates...");
            ISearchResult searchResult;
            try
            {
                searchResult = updateSearcher.Search(query);
            }
            catch (COMException e)
            {
                Console.WriteLine(WUError.GetHRMessage(e.HResult));
                return false;
            }

            UpdateCollection updatesToInstall = new UpdateCollection();
            for (int i = 0; i < searchResult.Updates.Count; ++i)
            {
                IUpdate update = searchResult.Updates[i];
                Console.WriteLine(update.Title);
                updatesToInstall.Add(update);
            }

            if (searchResult.Updates.Count == 0)
            {
                Console.WriteLine("No updates found.");
                return false;
            }

            if (listUpdates)
            {
                return false;
            }

            if (updatesToInstall.Count > 0)
            {
                IUpdateInstaller installer = updateSession.CreateUpdateInstaller();
                installer.Updates = updatesToInstall;
                IInstallationResult installResult;
                try
                {
                    installResult = installer.Install();
                }
                catch (COMException e)
                {
                    Console.WriteLine(WUError.GetHRMessage(e.HResult));
                    return false;
                }
                Console.WriteLine("Installation result code: " + installResult.ResultCode);
                Console.WriteLine("Reboot required: " + installResult.RebootRequired);
                return installResult.RebootRequired;
            }

            return false;
        }
Esempio n. 9
0
        public UpdateCollection GetUpdates()
        {
            UpdateCollection updates = new UpdateCollection();

            foreach (Update item in updateView.CheckedObjects)
            {
                updates.Add(item.Entry);
            }
            return(updates);
        }
Esempio n. 10
0
        protected void OnUpdatesFound(ISearchJob searchJob)
        {
            if (searchJob != mSearchJob)
            {
                return;
            }
            mSearchJob = null;
            mCallback  = null;

            ISearchResult SearchResults = null;

            try
            {
                SearchResults = mUpdateSearcher.EndSearch(searchJob);

                if (mOfflineService != null)
                {
                    mUpdateServiceManager.RemoveService(mOfflineService.ServiceID);
                    mOfflineService = null;
                }
            }
            catch (Exception err)
            {
                AppLog.Line(Program.fmt("Search for updats failed, Error: {0}", err.Message));
                return;
            }

            mPendingUpdates   = new UpdateCollection();
            mInstalledUpdates = new UpdateCollection();
            mHiddenUpdates    = new UpdateCollection();

            foreach (IUpdate update in SearchResults.Updates)
            {
                if (safe_IsHidden(update))
                {
                    mHiddenUpdates.Add(update);
                }
                else if (update.IsInstalled)
                {
                    mInstalledUpdates.Add(update);
                }
                else
                {
                    mPendingUpdates.Add(update);
                }

                Console.WriteLine("\r\n");
            }

            AppLog.Line(Program.fmt("Found {0} pending updates.", mPendingUpdates.Count));

            Progress(this, new ProgressArgs(0, 0, 0, "", 0));

            Found(this, new FoundUpdatesArgs());
        }
Esempio n. 11
0
        static UpdateCollection getAutoUpdates(ISearchResult found)
        {
            Console.WriteLine("Accepting EULAs");
            UpdateCollection toInstallAutomatically = new UpdateCollection();
            foreach (IUpdate update in found.Updates)
            {
                if (update.AutoSelectOnWebSites == true)
                {

                    if (!update.EulaAccepted)
                    {
                        try
                        {
                            update.AcceptEula();
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unable to accept EULA on update " + update.Title);
                        }
                    }

                    //if (update.EulaAccepted && !update.InstallationBehavior.CanRequestUserInput)
                     if (update.EulaAccepted)
                    {
                        toInstallAutomatically.Add(update);
                    }

                    // works for service packs, even though CanRequestUserInput is true. however, IE9 blocks progress.
                    // This currently will try to install anything wtih "service pack" in the name. No bueno.
                    // if (update.EulaAccepted && update.Title.Contains("Service Pack"))
                    // {
                    //     toInstallAutomatically.Add(update);
                    //    Console.WriteLine("Service pack found!");
                    //    Console.WriteLine(update.Title);
                    // }
                }

            }
            if (toInstallAutomatically.Count == 1)
            {
                Console.WriteLine(String.Format("{0,5} update out of {0} can be installed automatically.", toInstallAutomatically.Count, found.Updates.Count));
            }
            else
            {
                Console.WriteLine(String.Format("{0,5} updates out of {0} can be installed automatically.", toInstallAutomatically.Count, found.Updates.Count));
            }
            foreach (IUpdate update in toInstallAutomatically)
            {
                Console.WriteLine(update.Title);
            }
            return toInstallAutomatically;
        }
Esempio n. 12
0
        private void btnClose_Click(object sender, EventArgs e)
        {
            Logger.EnteringMethod();
            subscribers.Clear();

            foreach (DataGridViewRow row in dgvUpdates.Rows)
            {
                IUpdate update = (IUpdate)row.Cells["Update"].Value;
                subscribers.Add(update);
                Logger.Write(update.Title);
            }
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
Esempio n. 13
0
        /// <summary>
        /// Get a collection of updates displayed by the control.
        /// </summary>
        /// <returns>Collection of IUpdate. May be empty if no update are displayed.</returns>
        internal UpdateCollection GetDisplayedUpdates()
        {
            Logger.EnteringMethod();
            UpdateCollection updates = new UpdateCollection();

            foreach (DataGridViewRow row in dgvUpdateList.Rows)
            {
                IUpdate update = (IUpdate)row.Cells["UpdateId"].Value;
                Logger.Write("Adding " + update.Title);
                updates.Add(update);
            }

            return(updates);
        }
Esempio n. 14
0
 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 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.
            if (UpdateSearchResult.Updates.Count > 0)
            {
                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... This may take several minutes.");


                IDownloadResult  DownloadResult    = Downloader.Download();
                UpdateCollection InstallCollection = new UpdateCollection();
                for (int i = 0; i < UpdateCollection.Count; i++)
                {
                    if (DownloadCollection[i].IsDownloaded)
                    {
                        InstallCollection.Add(DownloadCollection[i]);
                    }
                }
                Console.WriteLine("Download Finished");
                return(InstallCollection);
            }
            else
            {
                return(UpdateCollection);
            }
        }
Esempio n. 16
0
        static int Main(string[] args)
        {
            var session  = new UpdateSession();
            var searcher = session.CreateUpdateSearcher();

            Log("Searching...");
            var searchResult    = searcher.Search("IsInstalled=0 And IsHidden=0");
            var defenderUpdates = searchResult.Updates.Cast <IUpdate>()
                                  .Where(u => u.Title.IndexOf("Definition Update for Windows Defender", StringComparison.Ordinal) >= 0)
                                  .ToArray();

            if (defenderUpdates.Any())
            {
                Log("Going to install:");
                var updates = new UpdateCollection();
                foreach (var item in defenderUpdates)
                {
                    updates.Add(item);
                    Log("\t" + item.Title);
                }

                var downloader = session.CreateUpdateDownloader();
                downloader.Updates = updates;
                Log("Downloading...");
                var downloadResult = downloader.Download();
                Log("Result: {0} [0x{1}]", downloadResult.ResultCode, downloadResult.HResult.ToString("X"));
                if (downloadResult.ResultCode != OperationResultCode.orcSucceeded)
                {
                    return(-1 * (int)downloadResult.ResultCode);
                }

                var updater = session.CreateUpdateInstaller();
                updater.Updates = updates;
                Log("Installing...");
                var updateResult = updater.Install();
                Log("Result: {0} [0x{1}]", updateResult.ResultCode, updateResult.HResult.ToString("X"));
                if (updateResult.ResultCode != OperationResultCode.orcSucceeded)
                {
                    return(-1 * (int)updateResult.ResultCode);
                }

                return(0);
            }
            else
            {
                Log("Nothing to install.");
                return(0);
            }
        }
Esempio n. 17
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);
        }
Esempio n. 18
0
        private void DownloadPatches(UpdateSession session, List <IUpdate5> updates, Stream output)
        {
            Bender.WriteLine("Downloading " + updates.Count + " patches...", output);

            foreach (IUpdate5 update in updates.OrderBy(u => u.Title))
            {
                if (update.IsDownloaded)
                {
                    Bender.WriteLine("Patch is already downloaded: " + update.Title, output);
                    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;

                        Bender.WriteLine("Downloading" + printtry + ": " + update.Title + ": " + GetPrintSize(update.MaxDownloadSize) + " MB.", output);

                        IDownloadResult downloadresult = downloader.Download();
                        if (downloadresult.ResultCode == OperationResultCode.orcSucceeded)
                        {
                            downloaded = true;
                        }
                        else
                        {
                            Bender.WriteLine("Couldn't download patch: " + downloadresult.ResultCode + ": 0x" + downloadresult.HResult.ToString("X"), output);
                        }
                    }
                    catch (COMException ex)
                    {
                        Bender.WriteLine("Couldn't download patch: 0x" + ex.HResult.ToString("X"), output);
                    }
                }
            }
        }
Esempio n. 19
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)}");
                    }
                }
            }
        }
        private UpdateCollection _GetUpdatesToInstall(string[] kbIdsToInstall, UpdateCollection updates)
        {
            var updatesToInstall = new UpdateCollection();

            foreach (IUpdate update in updates)
            {
                foreach (var id in update.KBArticleIDs)
                {
                    if (kbIdsToInstall.Any(x => Equals(id, x)))
                    {
                        updatesToInstall.Add(update);
                    }
                }
            }

            return(updatesToInstall);
        }
Esempio n. 21
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);
            }
        }
Esempio n. 22
0
        public static UpdateCollection DownloadUpdates()
        {
            var UpdateSession      = new UpdateSession();
            var SearchUpdates      = UpdateSession.CreateUpdateSearcher();
            var UpdateSearchResult = SearchUpdates.Search("IsInstalled=0");
            var UpdateCollection   = new UpdateCollection();

            //Accept Eula code for each update

            for (int i = 0; i < UpdateSearchResult.Updates.Count; i++)
            {
                var 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.

            var DownloadCollection = new UpdateCollection();
            var Downloader         = UpdateSession.CreateUpdateDownloader();

            for (int i = 0; i < UpdateCollection.Count; i++)
            {
                DownloadCollection.Add(UpdateCollection[i]);
            }

            Downloader.Updates = DownloadCollection;

            var DownloadResult = Downloader.Download();

            var InstallCollection = new UpdateCollection();

            for (int i = 0; i < UpdateCollection.Count; i++)
            {
                if (DownloadCollection[i].IsDownloaded)
                {
                    InstallCollection.Add(DownloadCollection[i]);
                }
            }
            return(InstallCollection);
        }
Esempio n. 23
0
        private void processUpdate(IUpdate update, List <String> updateList, UpdateCollection uDownloadList, UpdateCollection uInstallList)
        {
            Program.Dash.storeUpdateInDashboard(update);

            Program.Dash.updateUpdateInDashboardForThisServer(update);

            if (!update.IsDownloaded)
            {
                uDownloadList.Add(update);
            }

            if (Program.Dash.isUpdateApproved(update))
            {
                uInstallList.Add(update);
            }

            updateList.Add(update.Title.ToString());
        }
        private int _InstallUpdates(UpdateSession session, UpdateCollection updates)
        {
            if (updates.Count < 1 || UacHelper.IsRunningAsAdmin() == false)
            {
                return(0);
            }

            try
            {
                var downloader = session.CreateUpdateDownloader();
                downloader.Updates = updates;
                downloader.Download();

                var updatesToInstall = new UpdateCollection();
                foreach (IUpdate update in updates)
                {
                    if (update.IsDownloaded)
                    {
                        updatesToInstall.Add(update);
                    }
                }

                var installer = session.CreateUpdateInstaller();
                installer.Updates = updatesToInstall;

                var result = installer.Install();
                var numberOfInstalledUpdates = 0;

                for (var i = 0; i < updatesToInstall.Count; i++)
                {
                    if (result.GetUpdateResult(i).HResult == 0)
                    {
                        numberOfInstalledUpdates++;
                    }
                }

                return(numberOfInstalledUpdates);
            }
            catch (Exception)
            {
                return(0);
            }
        }
Esempio n. 25
0
        public async void DownloadUpdates()
        {
            try
            {
                UpdateCollection toDwnload = new UpdateCollection();
                foreach (IUpdate update in updateCollection)
                {
                    if (!update.IsDownloaded && !update.IsInstalled)
                    {
                        toDwnload.Add(update);
                    }
                }

                if (toDwnload.Count > 0)
                {
                    //updateSession = new UpdateSession();
                    //todo what if I:
                    //1. crete  new session?
                    //2. create the Downlaoder with new keywoard
                    updateDownloader = updateSession.CreateUpdateDownloader();

                    updateDownloader.Updates = updateCollection;
                    DebugLog("Update downloader params are: " + Dump(updateDownloader));

                    downloadJob_ = updateDownloader.BeginDownload(this, this, null);
                }
                else if (updateCollection.Count > 0)
                {
                    //ReadyToInstall?.Invoke();
                    DownloadCompleted?.Invoke(true);
                }
            }
            catch (Exception ex)
            {
                VMManagementTool.Log.Error("WinUpdatesManager.DownloadUpdates", ex.ToString());
                //this will allow the caller UI method to finish and
                //the event will be handled like expected asyncronously
                await Task.Yield();

                DownloadCompleted?.Invoke(false);
            }
        }
Esempio n. 26
0
        private void dgvUpdateList_SelectionChanged(object sender, EventArgs e)
        {
            Logger.EnteringMethod();
            UpdateCollection selectedUpdates = new UpdateCollection();

            foreach (DataGridViewRow row in dgvUpdateList.SelectedRows)
            {
                selectedUpdates.Add((IUpdate)row.Cells["UpdateId"].Value);
            }

            mnuStripUpdateListViewer.Items[resMan.GetString("Revise")].Enabled                  = ((dgvUpdateList.SelectedRows.Count == 1) && (!_wsus.IsReplica));
            mnuStripUpdateListViewer.Items[resMan.GetString("Delete")].Enabled                  = !HasSomeApprove(selectedUpdates);
            mnuStripUpdateListViewer.Items[resMan.GetString("Expire")].Enabled                  = !HasSomeExpired(selectedUpdates);
            mnuStripUpdateListViewer.Items[resMan.GetString("ExportThisUpdate")].Enabled        = ((dgvUpdateList.SelectedRows.Count == 1) && (!_wsus.IsReplica));
            mnuStripUpdateListViewer.Items[resMan.GetString("CreateSupersedingUpdate")].Enabled = ((dgvUpdateList.SelectedRows.Count == 1) && (!_wsus.IsReplica));

            dgvUpdateList.Refresh();
            if (UpdateSelectionChanged != null && !_populateDGV)
            {
                UpdateSelectionChanged(dgvUpdateList.SelectedRows);
            }
        }
        /// <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);
        }
Esempio n. 28
0
        private static UpdateCollection SearchUpdates()
        {
            Logger.Write("Starting to search for Pending Updates.");
            UpdateCollection installableUpdates = new UpdateCollection();
            UpdateCollection pendingUpdates     = new UpdateCollection();

            try
            {
                UpdateSession   uSession  = new UpdateSession();
                IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();

                uSearcher.ServerSelection = ServerSelection.ssManagedServer;
                uSearcher.IncludePotentiallySupersededUpdates = false;
                uSearcher.Online = false;

                ISearchResult sResult = uSearcher.Search(_arguments.SearchString);
                if (sResult.ResultCode == OperationResultCode.orcSucceeded && sResult.Updates.Count != 0)
                {
                    pendingUpdates = sResult.Updates;
                }

                Logger.Write("Found " + pendingUpdates.Count + " Pending Updates.");
                foreach (IUpdate update in pendingUpdates)
                {
                    if (update.InstallationBehavior.RebootBehavior == InstallationRebootBehavior.irbNeverReboots || _arguments.IncludeUpdatesWithRebootRequire == true)
                    {
                        Logger.Write("Selecting : " + update.Title);
                        installableUpdates.Add(update);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write("Problem when seraching for Pending Updates. " + ex.Message);
            }
            Logger.Write("Found " + installableUpdates.Count + " Installable update(s).");
            return(installableUpdates);
        }
Esempio n. 29
0
        public static void Test3()
        {
            // http://www.nullskull.com/a/1592/install-windows-updates-using-c--wuapi.aspx
            var uSession  = new UpdateSessionClass();
            var uSearcher = uSession.CreateUpdateSearcher();
            var uResult   = uSearcher.Search("IsInstalled=0 and Type = 'Software'");

            foreach (IUpdate update in uResult.Updates)
            {
                Console.WriteLine(update.Title);
            }
            var updatesToInstall = new UpdateCollection();

            foreach (IUpdate update in uResult.Updates)
            {
                if (update.IsDownloaded)
                {
                    updatesToInstall.Add(update);
                }
            }
            var installer = uSession.CreateUpdateInstaller();

            installer.Updates = updatesToInstall;
            var 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);
                }
            }
        }
Esempio n. 30
0
        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);
        }
Esempio n. 31
0
 public void HideUpdates(UpdateCollection Updates, bool Hide)
 {
     foreach (IUpdate update in Updates)
     {
         try
         {
             update.IsHidden = Hide;
             if (Hide)
             {
                 mHiddenUpdates.Add(update);
                 RemoveFrom(mPendingUpdates, update);
             }
             else
             {
                 mPendingUpdates.Add(update);
                 RemoveFrom(mHiddenUpdates, update);
             }
         }
         catch (Exception err)
         {
             // Hide update may throw an exception, if the user has hidden the update manually while the search was in progress.
         }
     }
 }
        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 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);
            }
        }
Esempio n. 34
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists("Backup"))
            {
                Directory.CreateDirectory("Backup");
                if (Directory.Exists("Rads"))
                {
                    DirectoryInfo airinfo = new DirectoryInfo(airr);
                    DirectoryInfo air = airinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo slninfo = new DirectoryInfo(slnr);
                    DirectoryInfo sln = slninfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo launchinfo = new DirectoryInfo(launchr);
                    DirectoryInfo launch = launchinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo gameinfo = new DirectoryInfo(gamer);
                    DirectoryInfo game = gameinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    string gamez = @"RADS\projects\lol_game_client\releases\" + game + @"\deploy";
                    string airz = @"RADS\projects\lol_air_client\releases\" + air + @"\deploy\Adobe AIR\Versions\1.0";

                    File.Copy(gamez + @"\cg.dll", @"Backup\cg.dll", true);
                    File.Copy(gamez + @"\cgd3d9.dll", @"Backup\cgd3d9.dll", true);
                    File.Copy(gamez + @"\cggl.dll", @"Backup\cggl.dll", true);
                    File.Copy(gamez + @"\tbb.dll", @"Backup\tbb.dll", true);
                    File.Copy(airz + @"\Resources\NPSWF32.dll", @"Backup\NPSWF32.dll", true);
                    File.Copy(airz + @"\Adobe Air.dll", @"Backup\Adobe Air.dll", true);
                    if (File.Exists(@"Config\game.cfg"))
                    {
                        File.Copy(@"Config\game.cfg", @"Backup\game.cfg", true);
                    }
                }
                else if (Directory.Exists("Game"))
                {
                    Directory.CreateDirectory("Backup");
                    File.Copy(@"game\cg.dll", @"Backup\cg.dll", true);
                    File.Copy(@"game\cgd3d9.dll", @"Backup\cgd3d9.dll", true);
                    File.Copy(@"game\cggl.dll", @"Backup\cggl.dll", true);
                    File.Copy(@"game\tbb.dll", @"Backup\tbb.dll", true);
                    File.Copy(@"Air\Adobe Air\Versions\1.0\Resources\NPSWF32.dll", @"Backup\NPSWF32.dll", true);
                    File.Copy(@"Air\Adobe Air\Versions\1.0\Adobe Air.dll", @"Backup\Adobe Air.dll", true);
                    if (File.Exists(@"Game\DATA\CFG\defaults\game.cfg"))
                    {
                        File.Copy(@"Game\DATA\CFG\defaults\game.cfg", @"Backup\game.cfg", true);
                        File.Copy(@"Game\DATA\CFG\defaults\gamepermanent.cfg", @"Backup\gamepermanent.cfg", true);
                        if (File.Exists(@"Game\DATA\CFG\defaults\GamePermanent_zh_MY.cfg"))
                        {
                            File.Copy(@"Game\DATA\CFG\defaults\GamePermanent_zh_MY.cfg", @"Backup\GamePermanent_zh_MY.cfg", true);
                        }
                        if (File.Exists(@"Game\DATA\CFG\defaults\GamePermanent_en_SG.cfg"))
                        {
                            File.Copy(@"Game\DATA\CFG\defaults\GamePermanent_en_SG.cfg", @"Backup\GamePermanent_en_SG.cfg", true);
                        }

                    }
                }
            }

            var windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            string root = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
            RegistryKey keycg = Registry.LocalMachine;
            RegistryKey subKeycg = keycg.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Cg Toolkit_is1");
            var CG = subKeycg.GetValue("InstallLocation") + @"bin\";
            if (Cleantemp.Checked)
            {
                var cm = new ProcessStartInfo();
                cm.FileName = "cleanmgr";
                cm.Arguments = "sagerun:1";
                cm.Verb = "runas";
                var process = new Process();
                process.StartInfo = cm;
                process.Start();
                process.WaitForExit();
            }
            if (Cleanupdatecache.Checked)
            {
                ServiceController updateservice = new ServiceController("wuauserv");
                switch (updateservice.Status)
                {
                    case ServiceControllerStatus.Running:
                        updateservice.Stop();
                        updateservice.WaitForStatus(ServiceControllerStatus.Stopped);
                        Directory.Delete(windir + @"\SoftwareDistribution", true);
                        updateservice.Start();
                        updateservice.WaitForStatus(ServiceControllerStatus.Running);
                        break;
                    case ServiceControllerStatus.Stopped:
                        Directory.Delete(windir + @"\SoftwareDistribution", true);
                        updateservice.Start();
                        updateservice.WaitForStatus(ServiceControllerStatus.Running);
                        break;
                }
            }
            if (UninstallPMB.Checked)
            {
                using (RegistryKey Key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Pando Networks\\PMB"))
                    if (Key != null)
                    {
                        RegistryKey key = Registry.LocalMachine;
                        RegistryKey subKey = key.OpenSubKey("SOFTWARE\\Wow6432Node\\Pando Networks\\PMB");
                        var PMB = subKey.GetValue("Program Directory").ToString();
                        var psi2 = new ProcessStartInfo();
                        psi2.FileName = PMB + @"\uninst.exe";
                        psi2.Verb = "runas";
                        var PMBUninstallProc = new Process();
                        PMBUninstallProc.StartInfo = psi2;
                        PMBUninstallProc.Start();
                        PMBUninstallProc.WaitForExit();
                    }
                    else
                    {
                        MessageBox.Show("Pando Media Booster is already Uninstalled");
                    }
            }
            var allServices = new Dictionary<string, string[]>
            {
            { "6.3", new[] { "Appmgmt", "bthserv", "PeerDistSvc", "NfsClnt", "TrkWks", "WPCSvc", "vmickvpexchange", "vmicguestinterface", "vmicshutdown", "vmicheartbeat", "vmicrdv", "vmictimesync", "vmicvss", "IEEtwCollectorService", "iphlpsvc", "Netlogon", "CscService", "RpcLocator", "MSiSCSI", "SensrSvc", "ScDeviceEnum", "SCPolicySvc", "SNMPTRAP", "StorSvc", "WbioSrvc", "wcncsvc", "fsvc", "WMPNetworkSvc" } },
            { "6.2", new[] { "WMPNetworkSvc", "wcncsvc", "WbioSrvc", "StorSvc", "SNMPTRAP", "SCPolicySvc", "SensrSvc", "RpcLocator", "CscService", "Netlogon", "MSiSCSI", "iphlpsvc", "vmicvss", "vmictimesync", "vmicrdv", "vmicheartbeat", "vmicshutdown", "vmickvpexchange", "WPCSvc", "TrkWks", "NfsClnt", "CertPropSvc", "PeerDistSvc", "bthserv", "Appmgmt" } },
            { "6.1", new[] {"WSearch", "WMPNetworkSvc", "wcncsvc", "StorSvc", "SNMPTRAP", "SCPolicySvc", "SCardSvr", "RemoteRegistry", "RpcLocator", "WPCSvc", "CscService", "napagent", "Netlogon", "MSiSCSI", "iphlpsvc", "TrkWks", "CertPropSvc", "bthserv", "AppMgmt" } },
            { "6.0", new[] { "TrkWks", "WinHttpAutoProxySvc", "WSearch", "WinRM", "WebClient", "UmRdpService", "TabletInputService", "SNMPTRAP", "SCPolicySvc", "SCardSvr", "RemoteRegistry", "CscService", "Netlogon", "MSiSCSI", "iphlpsvc", "Fax", "CertPropSvc" } },
            { "5.1", new[] { "WmiApSrv", "W32Time", "WebClient", "UPS", "Netlogon", "SCardSvr", "TlntSvr", "seclogon", "RemoteRegistry", "RDSessMgr", "RSVP", "WmdmPmSN", "xmlprov", "mnmsrvc", "cisvc", "ERSvc" } }
            };
            string[] services;
            if (WindowsServices.Checked && allServices.TryGetValue(Environment.OSVersion.Version.ToString(), out services))
            {
                services.ToList().ForEach(service => ServiceHelper.ChangeStartMode(new ServiceController(service), ServiceStartMode.Manual));
            }
            if (Mousepollingrate.Checked)
            {
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers");
                RegistryKey mousehz = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers", true);
                mousehz.SetValue("C:\\Windows\\Explorer.exe", "NoDTToDITMouseBatch");
                System.Diagnostics.Process applymouseHz = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "cmd.exe";
                startInfo.Verb = "runas";
                startInfo.Arguments = @"/C Rundll32 apphelp.dll , ShimFlushCache";
                applymouseHz.StartInfo = startInfo;
                applymouseHz.Start();
                applymouseHz.WaitForExit();
            }
            if (Defrag.Checked)
            {
                System.Diagnostics.Process defrag = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = "dfrgui.exe";
                startInfo.Verb = "runas";
                defrag.StartInfo = startInfo;
                defrag.Start();
                defrag.WaitForExit();
            }
            if (WindowsUpdate.Checked)
            {
                UpdateSessionClass uSession = new UpdateSessionClass();
                IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
                ISearchResult uResult = uSearcher.Search(@"IsInstalled=0 and
            Type='Software' and IsHidden=0 and BrowseOnly=1 and AutoSelectOnWebSites=1 and RebootRequired=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();
            }
            if (Deleteoldlogs.Checked)
            {
                if (Directory.Exists("Logs"))
                {
                    string[] files = Directory.GetFiles("Logs");
                    foreach (string file in files)
                    {
                        FileInfo fi = new FileInfo(file);
                        if (fi.LastAccessTime < DateTime.Now.AddDays(-7))
                            fi.Delete();
                    }
                }
            }
            if (Patcher.Checked)
            {
                int coreCount = 0;
                foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
                {
                    coreCount += int.Parse(item["NumberOfCores"].ToString());
                }
                if (coreCount >= 2)
                {

                    if (File.Exists(@"Config\game.cfg"))
                    {
                        File.AppendAllText(@"Config\game.cfg", Environment.NewLine + "DefaultParticleMultithreading=1");
                    }

                    else if (File.Exists(@"Game\DATA\CFG\defaults\game.cfg"))
                    {
                        File.AppendAllText(@"Game\DATA\CFG\defaults\game.cfg", Environment.NewLine + "DefaultParticleMultithreading=1");
                        File.AppendAllText(@"Game\DATA\CFG\defaults\GamePermanent.cfg", Environment.NewLine + "DefaultParticleMultithreading=1");
                        File.AppendAllText(@"Game\DATA\CFG\defaults\GamePermanent_zh_MY.cfg", Environment.NewLine + "DefaultParticleMultithreading=1");
                        File.AppendAllText(@"Game\DATA\CFG\defaults\GamePermanent_en_SG.cfg", Environment.NewLine + "DefaultParticleMultithreading=1");

                    }

                }
                if (Directory.Exists("Rads"))
                {
                    DirectoryInfo airinfo = new DirectoryInfo(airr);
                    DirectoryInfo air = airinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo slninfo = new DirectoryInfo(slnr);
                    DirectoryInfo sln = slninfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo launchinfo = new DirectoryInfo(launchr);
                    DirectoryInfo launch = launchinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo gameinfo = new DirectoryInfo(gamer);
                    DirectoryInfo game = gameinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    string gamez = @"RADS\projects\lol_game_client\releases\" + game + @"\deploy";
                    string airz = @"RADS\projects\lol_air_client\releases\" + air + @"\deploy\Adobe AIR\Versions\1.0";
                    string slnz = @"RADS\solutions\lol_game_client_sln\releases\" + sln + @"\deploy";
                    string launchz = @"RADS\projects\lol_launcher\releases\" + launch + @"\deploy";
                    System.IO.File.WriteAllBytes(gamez + @"\tbb.dll", LoLUpdater.Properties.Resources.tbb);
                    File.Copy(CG + @"\cg.dll", gamez + @"\cg.dll", true);
                    File.Copy(CG + @"\cgd3d9.dll", gamez + @"\cgd3d9.dll", true);
                    File.Copy(CG + @"\cggl.dll", gamez + @"\cggl.dll", true);
                    File.Copy(CG + @"\cg.dll", launchz + @"\cg.dll", true);
                    File.Copy(CG + @"\cgd3d9.dll", launchz + @"\cgd3d9.dll", true);
                    File.Copy(CG + @"\cggl.dll", launchz + @"\cggl.dll", true);
                    System.IO.File.WriteAllBytes(slnz + @"\tbb.dll", LoLUpdater.Properties.Resources.tbb);
                    File.Copy(CG + @"\cg.dll", slnz + @"\cg.dll", true);
                    File.Copy(CG + @"\cgd3d9.dll", slnz + @"\cgd3d9.dll", true);
                    File.Copy(CG + @"\cggl.dll", slnz + @"\cggl.dll", true);
                    System.IO.File.WriteAllBytes(airz + @"\Resources\NPSWF32.dll", LoLUpdater.Properties.Resources.NPSWF32);
                    System.IO.File.WriteAllBytes(airz + @"\Adobe Air.dll", LoLUpdater.Properties.Resources.Adobe_AIR);
                }
                else if (Directory.Exists("Game"))
                {
                    System.IO.File.WriteAllBytes(@"game\tbb.dll", LoLUpdater.Properties.Resources.tbb);
                    File.Copy(CG + @"\cg.dll", @"game\cg.dll", true);
                    File.Copy(CG + @"\cgd3d9.dll", @"game\cgd3d9.dll", true);
                    File.Copy(CG + @"\cggl.dll", @"game\cggl.dll", true);
                    System.IO.File.WriteAllBytes(@"Air\Adobe Air\Versions\1.0\Resources\NPSWF32.dll", LoLUpdater.Properties.Resources.NPSWF32);
                    System.IO.File.WriteAllBytes(@"Air\Adobe Air\Versions\1.0\Adobe Air.dll", LoLUpdater.Properties.Resources.Adobe_AIR);
                }
                System.Windows.Forms.MessageBox.Show("Finished!");
            }
            else if (Restorebackups.Checked)
            {
                if (Directory.Exists("Rads"))
                {
                    DirectoryInfo airinfo = new DirectoryInfo(airr);
                    DirectoryInfo air = airinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo slninfo = new DirectoryInfo(slnr);
                    DirectoryInfo sln = slninfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo launchinfo = new DirectoryInfo(launchr);
                    DirectoryInfo launch = launchinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    DirectoryInfo gameinfo = new DirectoryInfo(gamer);
                    DirectoryInfo game = gameinfo.GetDirectories()
                    .OrderByDescending(d => d.CreationTime)
                    .FirstOrDefault();
                    string gamez = @"RADS\projects\lol_game_client\releases\" + game + @"\deploy";
                    string airz = @"RADS\projects\lol_air_client\releases\" + air + @"\deploy\Adobe AIR\Versions\1.0";
                    string slnz = @"RADS\solutions\lol_game_client_sln\releases\" + sln + @"\deploy";
                    string launchz = @"RADS\projects\lol_launcher\releases\" + launch + @"\deploy";
                    File.Copy(@"Backup\cg.dll", gamez + @"\cg.dll", true);
                    File.Copy(@"Backup\cgd3d9.dll", gamez + @"\cgd3d9.dll", true);
                    File.Copy(@"Backup\cggl.dll", gamez + @"\cggl.dll", true);
                    File.Copy(@"Backup\tbb.dll", gamez + @"\tbb.dll", true);
                    File.Copy(@"Backup\cg.dll", slnz + @"\cg.dll", true);
                    File.Copy(@"Backup\cgd3d9.dll", slnz + @"\cgd3d9.dll", true);
                    File.Copy(@"Backup\cggl.dll", slnz + @"\cggl.dll", true);
                    File.Copy(@"Backup\tbb.dll", slnz + @"\tbb.dll", true);
                    File.Copy(@"Backup\cg.dll", launchz + @"\cg.dll", true);
                    File.Copy(@"Backup\cgd3d9.dll", launchz + @"\cgd3d9.dll", true);
                    File.Copy(@"Backup\cggl.dll", launchz + @"\cggl.dll", true);
                    File.Copy(@"Backup\NPSWF32.dll", airz + @"\Resources\NPSWF32.dll", true);
                    File.Copy(@"Backup\Adobe Air.dll", airz + @"\Adobe Air.dll", true);
                    if (File.Exists(@"Backup\game.cfg"))
                    {
                        File.Copy(@"Backup\game.cfg", @"Config\game.cfg", true);
                    }
                }
                else if (Directory.Exists("Game"))
                {
                    File.Copy(@"Backup\cg.dll", @"game\cg.dll", true);
                    File.Copy(@"Backup\cgd3d9.dll", @"game\cgd3d9.dll", true);
                    File.Copy(@"Backup\cggl.dll", @"game\cggl.dll", true);
                    File.Copy(@"Backup\tbb.dll", @"game\tbb.dll", true);
                    File.Copy(@"Backup\NPSWF32.dll", @"AIR\Adobe Air\Versions\1.0\Resources\NPSWF32.dll", true);
                    File.Copy(@"Backup\Adobe Air.dll", @"AIR\Adobe Air\Versions\1.0\Adobe Air.dll", true);
                    if (File.Exists(@"Game\DATA\CFG\defaults\game.cfg"))
                    {
                        File.Copy(@"Backup\game.cfg", @"Game\DATA\CFG\defaults\game.cfg", true);
                        File.Copy(@"Backup\gamepermanent.cfg", @"Game\DATA\CFG\defaults\gamepermanent.cfg", true);
                        if (File.Exists(@"Backup\GamePermanent_zh_MY.cfg"))
                        {
                            File.Copy(@"Backup\GamePermanent_zh_MY.cfg", @"Game\DATA\CFG\defaults\GamePermanent_zh_MY.cfg", true);

                            if (File.Exists(@"Backup\GamePermanent_en_SG.cfg"))
                            {
                                File.Copy(@"Game\DATA\CFG\defaults\GamePermanent_en_SG.cfg", @"Game\DATA\CFG\defaults\GamePermanent_en_SG.cfg", true);
                            }

                        }
                    }
                    System.Windows.Forms.MessageBox.Show("Finished!");
                }

                else if (onlycheckboxes.Checked)
                {
                    System.Windows.Forms.MessageBox.Show("Finished!");

                }
            }
        }
Esempio n. 35
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);
                }
            }
        }
        /// <summary>
        /// uninstall and hide the updates that match the given KB numbers
        /// </summary>
        /// <param name="numbersKB">knowledge base (KB) article numbers</param>
        /// <returns>Returns true, if uinstallation was successful.
        /// Returns false, if uninstallation failed.</returns>
        public bool uninstallAndHide(HashSet<uint> numbersKB, dlgtChangeStatusBarMessage ChangeStatusBarMessage)
        {
            if (null == numbersKB)
                return false;
            if (numbersKB.Count <= 0)
                return false;
            if (m_Busy)
                return false;

            m_Busy = true;
            UpdateSession session = new UpdateSession();

            IUpdateSearcher updateSearcher = session.CreateUpdateSearcher();
            //Do not go online to search for updates. We want to be fast(er).
            updateSearcher.Online = false;

            UpdateSearchCompleteCallback callback = new UpdateSearchCompleteCallback();

            ChangeStatusBarMessage("Searching through installed updates... (This may take several minutes.)");

            var searchJob = updateSearcher.BeginSearch("IsInstalled=1 or IsInstalled=0", callback, null);

            while (!searchJob.IsCompleted)
            {
                //Process application events.
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(200);
            } //while

            var searchResult = updateSearcher.EndSearch(searchJob);
            int count = searchResult.Updates.Count;

            ChangeStatusBarMessage("Hiding/blocking telemetry updates...");
            System.Windows.Forms.Application.DoEvents();
            System.Threading.Thread.Sleep(200);

            List<IUpdate> toBeRemoved = new List<IUpdate>();

            int i = 0;
            for (i = 0; i < count; ++i)
            {
                if (containsKB(searchResult.Updates[i].KBArticleIDs, numbersKB))
                {
                    /* Hide update from future installations. This way we avoid
                     * that the update might get installed again by an
                     * automatic update. */
                    try
                    {
                        /* Hide update. This may throw an exception, if the
                         * user has hidden the update manually while the search
                         * was in progress. */
                        searchResult.Updates[i].IsHidden = true;
                    }
                    catch (Exception)
                    {
                        /* Ignore exception, there's not much we can
                         * (or need to) do about it anyway. */
                    } //try-catch

                    // If update is installed, but can be uninstalled, add it to the list.
                    if (searchResult.Updates[i].IsInstalled && searchResult.Updates[i].IsUninstallable)
                    {
                        toBeRemoved.Add(searchResult.Updates[i]);
                    } //if installed
                } //if KB matches
            } //for

            try
            {
                searchJob.RequestAbort();
                searchJob.CleanUp();
            }
            catch (Exception)
            {
                // Do nothing.
            }
            searchJob = null;
            searchResult = null;

            updateSearcher = null;
            session = null;

            //Finish, if there is nothing more to do.
            if (toBeRemoved.Count <= 0)
            {
                m_Busy = false;
                return true;
            }

            ChangeStatusBarMessage("Removing " + toBeRemoved.Count.ToString()
                + " installed telemetry update(s)...");
            System.Windows.Forms.Application.DoEvents();
            System.Threading.Thread.Sleep(200);

            UpdateCollection collection = new UpdateCollection();
            foreach (var item in toBeRemoved)
            {
                collection.Add(item);
            }

            bool reboot = false;
            bool success = Updates.uninstallUpdates(collection, ref reboot);
            m_Busy = false;
            ChangeStatusBarMessage("Removal of telemetry update(s) is finished.");
            return success;
        }
        private static UpdateCollection BundleRecursion(IUpdate bundle, Operations.SavedOpData updateData)
        {
            var collection = new UpdateCollection();
               var index = 0;
               var updateFolder = Path.Combine(UpdateDirectory, updateData.filedata_app_id);

               if (!Directory.Exists(updateFolder))
                   return collection;
               IList<string> updateFiles = Directory.GetFiles(updateFolder);

               foreach (IUpdate insideBundle in bundle.BundledUpdates)
               {
                   //Recursive Call if there are more bundles inside this bundle.
                   if (insideBundle.BundledUpdates.Count > 0)
                   {
                       Logger.Log("    Found bundles inside {0}", LogLevel.Debug, insideBundle.Title);
                       var totalBundles = BundleRecursion(insideBundle, updateData);
                       Logger.Log("          - Loading {0} bundles for {1}", LogLevel.Debug, totalBundles.Count, insideBundle.Title);
                       foreach (IUpdate item in totalBundles)
                       {
                           Logger.Log("Adding {0}", LogLevel.Info, item.Title);
                           collection.Add(item);
                       }
                   }

                   if (insideBundle.IsInstalled != true)
                   {
                       var finalFileCollection = new StringCollection();

                       List<DownloadUri> nodes = GrabLocalUpdateBundle(bundle.Identity.UpdateID, insideBundle.Title);

                       foreach (var iteration in nodes)
                       {
                           var fileCollection = new StringCollection();

                           foreach (var item in updateFiles)
                           {
                               var strip = item.Split(new[] {'\\'});
                               var localFilename = strip[strip.Length - 1];

                               if (Operations.StringToFileName(localFilename).ToLower() == Operations.StringToFileName(iteration.FileName).ToLower())
                               {
                                   fileCollection.Add(item);
                                   finalFileCollection = fileCollection;
                                   break;
                               }
                           }
                       }

                       ((IUpdate2)bundle.BundledUpdates[index]).CopyToCache(finalFileCollection);
                       collection.Add(bundle);
                   }
                   index++;
               }
               return collection;
        }
        private UpdateCollection RetrieveUpdates(List<Update> updateList, string type = OperationValue.Unknown)
        {
            // For other options when it comes to searching for updates:
            // http://msdn.microsoft.com/en-us/library/aa386526(v=vs.85)
            string searchIdCriteria = "";
            UpdateCollection updateCollection = new UpdateCollection();
            IUpdateSearcher searcher = session.CreateUpdateSearcher();

            // Since we can't AND the searchIdCriteria string for searcher, we send it one UpdateID at a time.
            // Then we add the IUpdate searcher found to our updateCollection.
            if ((type == OperationValue.Hide) || (type == OperationValue.Show))
            {
                foreach (Update update in updateList)
                {
                    //searchIdCriteria = String.Format("IsInstalled = 0 and UpdateID ='{0}'", update.VendorId);
                    searchIdCriteria = String.Format("UpdateID ='{0}'", update.VendorId);
                    searchResults = searcher.Search(searchIdCriteria.ToString());
                    updateCollection.Add(searchResults.Updates[0]);
                    AgentSettings.Log("Search (hide/show) result code: " + searchResults.ResultCode.ToString(), AgentLogLevel.Debug);
                }

            }
            else if (type == OperationValue.Install)
            {
                foreach (Update update in updateList)
                {
                    if (update != null)
                    {
                        searchIdCriteria = String.Format("UpdateID ='{0}'", update.VendorId);
                        searchResults = searcher.Search(searchIdCriteria.ToString());
                        updateCollection.Add(searchResults.Updates[0]);
                        AgentSettings.Log("Search (install) result code: " + searchResults.ResultCode.ToString(), AgentLogLevel.Debug);
                    }
                }
            }
            return updateCollection;
        }
Esempio n. 39
0
        public static UpdateItem ProcessCheck(string branch, string flightLevel, Guid updateId)
        {
            UpdateSession uSession;
            IUpdateSearcher uSearcher;
            List<IUpdate> uCollection, uInCollection;
            ISearchResult sResult, ssResult;
            string updTitle = "";

            Debug.PrintMessage(string.Format("Current Branch: {0}", branch));
            Debug.PrintMessage(string.Format("Current Flight Level = \"{0}\"", flightLevel));
            if (branch != null)
            {
                FlightRegistry.Branch = branch;
                Program.consoleWrite("Checking now: " + branch);
            }

            FlightRegistry.FlightLevel = flightLevel;

            uSession = new UpdateSession();
            uSearcher = uSession.CreateUpdateSearcher();

            if (Debug.IsDebug)
            {
                Console.WriteLine("");
                Debug.PrintMessage("Created new IUpdateSession and IUpdateSearcher sessions.");
            }

            uSearcher.Online = true;
            uSearcher.ServiceID = _serviceGuid.ToString();
            uSearcher.ServerSelection = ServerSelection.ssOthers;
            uSearcher.IncludePotentiallySupersededUpdates = true;
            uSearcher.ClientApplicationID = _userAgent;
            Debug.PrintMessage("IUpdateSearcher configuring is done.");

            StringBuilder ssSearch = new StringBuilder();
            Debug.PrintMessage("Executing IUpdateSearcher::Search()...");
            try
            {
                sResult = (updateId == Guid.Empty) ?
                    uSearcher.Search(string.Join(" OR ", _categoryGuids.Select(s => string.Format("AppCategoryIDs contains '{0}' AND IsInstalled = 0 OR AppCategoryIDs contains '{0}' AND IsInstalled = 1", s)))) :
                    uSearcher.Search(string.Format("IsInstalled = 0 And UpdateID = '{0}' And RevisionNumber = 2", updateId));

                Debug.PrintMessage(string.Format("IUpdateSearcher::Search() done, returned {0} updates count.", sResult.Updates.Count));
            }
            catch (Exception seException)
            {
                Console.WriteLine("An error occured while performing searching - {0}", seException.Message);
                Debug.PrintMessage("ERROR: Exception in IUpdateSearcher::Search(). " +
                                   string.Format("HResult = {0}, ", seException.HResult.ToString("X")) +
                                   string.Format("Message = '{0}'", seException.Message));
                return null;
            }

            uCollection = new List<IUpdate>();

            foreach (IUpdate update in sResult.Updates)
            {
                //Filters results which are related to given branch only. Space was added incase some results
                //contained same beginning (e.g. fbl_hyp and fbl_hyp_dev).
                if (update != null & update.Title.ToLower().Contains(FlightRegistry.Branch.ToLower() + " "))
                    uCollection.Add(update);
            }
            if (uCollection.Count == 0) { Console.WriteLine("No updates were found using given criteria(s)."); return null; }

            Console.WriteLine("Found {0} update(s).", uCollection.Count);

            // Sorting results
            //Array.Sort(uCollection, delegate (IUpdate up1, IUpdate up2) { return up1.Title.CompareTo(up2.Title); });
            uCollection.Sort(delegate (IUpdate up1, IUpdate up2) { return up1.Title.CompareTo(up2.Title); });
            Debug.PrintMessage("Results from IUpdateSearcher were saved in ISearchResult and were sorted.");

            UpdateCollection updCollection = new UpdateCollection();

            foreach (IUpdate update in uCollection)
            {
                updCollection.Add(update);
                Console.WriteLine("    {0,-48} {1,-35}    {2:#,###,###,###} bytes", update.Title, update.Identity.UpdateID, update.MaxDownloadSize);
                update.AcceptEula();

                if (!Program.CheckAllBundledUpdates) continue;

                //Save array and sort
                if (update.SupersededUpdateIDs.Count != 0)
                {
                    Debug.PrintMessage(string.Format("List of bundled updates ({0}):", update.SupersededUpdateIDs.Count));
                    foreach (string dbgSsUID in update.SupersededUpdateIDs)
                    { Debug.PrintMessage(string.Format(" {0}", dbgSsUID)); }

                    foreach (string ssUID in update.SupersededUpdateIDs)
                        ssSearch.Append(string.Join(" Or ", _categoryGuids.Select(s => string.Format("(AppCategoryIds contains '{0}' and UpdateID = '{1}')", s, ssUID))));

                    ssSearch = ssSearch.Remove(ssSearch.Length - 3, 3);
                    ssResult = uSearcher.Search(ssSearch.ToString());

                    Console.WriteLine(" Distinguished bundled updates count: {0}/{1}", ssResult.Updates.Count, update.SupersededUpdateIDs.Count);

                    if (ssResult.Updates.Count != 0)
                    {
                        uInCollection = new List<IUpdate>();
                        foreach (IUpdate sUpdate in ssResult.Updates) { uInCollection.Add(sUpdate); }
                        if (ssResult.Updates.Count != 1) uInCollection.Sort(delegate (IUpdate up1, IUpdate up2) { return up1.Title.CompareTo(up2.Title); });

                        foreach (IUpdate sUpdate in uInCollection)
                        {
                            if (sUpdate.Title.Length <= 23) updTitle = sUpdate.Title + "\t\t\t\t";
                            if (sUpdate.Title.Length > 23 && sUpdate.Title.Length <= 31) updTitle = sUpdate.Title + "\t\t\t";
                            if (sUpdate.Title.Length > 33 && sUpdate.Title.Length <= 40) updTitle = sUpdate.Title + "\t\t";
                            if (sUpdate.Title.Length > 40) updTitle = sUpdate.Title + "\t";

                            Console.WriteLine("  {0}\t{1}\t{2}", sUpdate.Identity.UpdateID, updTitle, sUpdate.MaxDownloadSize.ToString("0,000,000,000 bytes"));
                        }
                    }

                }
                else
                    Console.WriteLine(" Distinguished bundled updates count: 0");

                Console.WriteLine("");
                ssSearch = new StringBuilder();
            }

            Console.WriteLine("");

            //Used to get only single result than showing other architecture/SKUs of a single build in results.
            UpdateItem updateObj = new UpdateItem();
            updateObj.updateID = uCollection.ElementAt(uCollection.Count - 1).Identity.UpdateID;
            updateObj.updateTitle = uCollection.ElementAt(uCollection.Count - 1).Title;
            updateObj.updateSize = uCollection.ElementAt(uCollection.Count - 1).MaxDownloadSize;
            return updateObj;
        }
Esempio n. 40
0
        private static IInstallationResult installUpdates(UpdateSession session, UpdateCollection toInstallAutomatically)
        {
            Console.WriteLine("Downloading {0} updates", toInstallAutomatically.Count);
            UpdateDownloader downloader = session.CreateUpdateDownloader();

            downloader.Updates = toInstallAutomatically;
            downloader.Download();
            UpdateCollection updatesToInstall = new UpdateCollection();
            foreach (IUpdate update in toInstallAutomatically)
            {

                if (update.IsDownloaded)
                {
                    updatesToInstall.Add(update);
                }

            }
            Console.WriteLine("Installing {0} updates", updatesToInstall.Count);
            IUpdateInstaller installer = session.CreateUpdateInstaller();
            // don't let the updater prompt for CDs/DVDs.
            installer.AllowSourcePrompts = false;
            IUpdateInstaller2 quietinstall;
            quietinstall = (IUpdateInstaller2)session.CreateUpdateInstaller();
            quietinstall.Updates = updatesToInstall;
            quietinstall.ForceQuiet = true;
            IInstallationResult installtionRes = quietinstall.Install();
            Console.WriteLine("Updates complete!");
            return installtionRes;
        }
Esempio n. 41
0
        private void InstallPatches(UpdateSession session, List<IUpdate5> updates)
        {
            Log("Installing " + updates.Count + " patches...");

            bool reboot = false;

            foreach (IUpdate5 update in updates.OrderBy(u => u.Title))
            {
                if (update.IsInstalled)
                {
                    Log("Patch is already installed: " + update.Title);
                    continue;
                }
                else if (!update.IsDownloaded)
                {
                    Log("Patch isn't downloaded yet: " + update.Title);
                }
                else
                {
                    try
                    {
                        Log("Installing: " + update.Title);

                        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
                        {
                            Log("Couldn't install patch: " + installresult.ResultCode + ": 0x" + installresult.HResult.ToString("X"));
                        }
                    }
                    catch (COMException ex)
                    {
                        Log("Couldn't download patch: 0x" + ex.HResult.ToString("X"));
                    }
                }
            }

            string regpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired";
            if (reboot || CheckIfLocalMachineKeyExists(regpath))
            {
                Log("Rebooting");

                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))
                {
                    Log("Couldn't reboot.");
                }
            }
        }
Esempio n. 42
0
        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);
            }
        }
Esempio n. 43
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.ToString("X"));
                        }
                    }
                    catch (COMException ex)
                    {
                        Log("Couldn't download patch: 0x" + ex.HResult.ToString("X"));
                    }
                }
            }
        }
Esempio n. 44
0
        static void Main(string[] args)
        {
            bool addthisupdate, rebootMayBeRequired;
            UpdateSession uSession = new UpdateSession();
            IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
            uSession.ClientApplicationID = "ABS WUA";
            uSearcher.Online = true;

            try
            {
                //processamento de updates - Scan
                ISearchResult sResult = uSearcher.Search("(IsInstalled=0 and Type='Software' and CategoryIDs contains '0FA1201D-4330-4FA8-8AE9-B877473B6441') or (IsInstalled=0 and Type='Software' and CategoryIDs contains 'E6CF1350-C01B-414D-A61F-263D14D133B4')");
                Console.Write(sResult.Updates.Count + Environment.NewLine);
                foreach (IUpdate update in sResult.Updates)
                {
                    Console.WriteLine(update.Title);
                }
                UpdateCollection updatesToDownload = new UpdateCollection();
                foreach (IUpdate update in sResult.Updates)
                {
                    addthisupdate = false;
                    if (update.InstallationBehavior.CanRequestUserInput == true)
                    {
                        Console.WriteLine("skipping interactive update: " + update.Title);
                    }
                    else
                    {
                        if (update.EulaAccepted == false)
                        {
                            update.AcceptEula();
                            addthisupdate = true;
                        }
                        else
                        {
                            addthisupdate = true;
                        }
                    }
                    if (addthisupdate == true)
                    {
                        updatesToDownload.Add(update);
                    }
                }
                if (updatesToDownload.Count == 0)
                {
                    Console.Write("All applicable updates were skipped.");
                }
                else
                {

                    //processamento de updates - Download
                    UpdateDownloader downloader = uSession.CreateUpdateDownloader();
                    downloader.Updates = updatesToDownload;
                    downloader.Download();

                    //processamento de updates - Install
                    UpdateCollection updatesToInstall = new UpdateCollection();
                    //UpdateInstaller updatesToInstall = uSession.CreateUpdateInstaller();
                    rebootMayBeRequired = false;
                    foreach (IUpdate update in sResult.Updates)
                    {
                        if (update.IsDownloaded==true)
                        {
                            updatesToInstall.Add(update);
                            if (update.InstallationBehavior.RebootBehavior > 0)
                            {
                                rebootMayBeRequired = true;
                            }
                        }
                    }
                    if (updatesToInstall.Count == 0) Console.Write("No updates were successfully downloaded.");
                    if (rebootMayBeRequired == true) Console.Write("Reboot will be required.");
                    //UpdateInstaller installer = uSession.CreateUpdateInstaller();
                    IUpdateInstaller installer = uSession.CreateUpdateInstaller();
                    installer.Updates = updatesToInstall;
                    installer.Install();

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Something went wrong: " + ex.Message);
            }
        }
        /// <summary>
        /// Downloads and installs updates using the Windows Update Agent
        /// from a list of given titles received from the site.
        /// </summary>
        /// <param name="titles"></param>
        public static void Install(List<string> titles)
        {
            UpdateCollection collection = new UpdateCollection();
            IUpdateSearcher searcher = session.CreateUpdateSearcher();

            try
            {
                // Build a collection from the titles received.
                ISearchResult result = searcher.Search("IsInstalled=0 And IsHidden=0");
                foreach (IUpdate update in result.Updates)
                {
                    // Go through each title and see if this update matches
                    // one of the titles. If it does, add it to the collection.
                    foreach (string title in titles)
                        if (update.Title.ToUpper() == title.ToUpper())
                            collection.Add(update);
                }

                // Download the updates.
                UpdateDownloader downloader = session.CreateUpdateDownloader();
                downloader.Updates = collection;
                downloader.Download();

                // Install the updates.
                IUpdateInstaller installer = session.CreateUpdateInstaller();
                installer.Updates = collection;
                IInstallationResult installResults = installer.Install();
            }
            catch (Exception exception)
            {
                EventLog.WriteEntry("LiberatioAgent", exception.ToString(), EventLogEntryType.Error);
            }
        }
Esempio n. 46
0
        private void SearchUpdateComplete(WindowsUpdateDialog mainform)
        {
            WindowsUpdateDialog formRef = mainform;

            // Declare a new UpdateCollection and populate the result...
            _updateCollection = new UpdateCollection();
            _updateSearchResult = _updateSearcher.EndSearch(_searchJob);

            _searchJob = null;

            //Count = NewUpdatesSearchResult.Updates.Count;
            //formRef.Invoke(formRef.sendNotification);

            // Accept Eula code for each update
            for (int i = 0; i < _updateSearchResult.Updates.Count; i++)
            {
                IUpdate iUpdate = _updateSearchResult.Updates[i];

                if (iUpdate.EulaAccepted == false)
                {
                    iUpdate.AcceptEula();
                }

                _updateCollection.Add(iUpdate);
            }



            if (_updateSearchResult.Updates.Count > 0)
            {
                {
                    this.AppendString("\r\n发现 " + _updateSearchResult.Updates.Count + " 个更新:\r\n");

                    int i = 0;
                    foreach (IUpdate update in _updateSearchResult.Updates)
                    {
                        this.AppendString((i + 1).ToString() + ") " + update.Title + "\r\n");
                        // textBox1.AppendText(update.Title + Environment.NewLine);
                        i++;
                    }
                    this.AppendString("\r\n");
                }
#if NO
                DialogResult result = MessageBox.Show(this,
"要下载这 " + _updateSearchResult.Updates.Count + " 个更新么?",
"WindowsUpdateDialog",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
                if (result == System.Windows.Forms.DialogResult.No)
                {
                    OnAllComplete();
                    return;
                }
#endif

                BeginDownloadUpdate();
            }
            else
            {
                this.AppendString("当前没有发现任何更新");
                // 全部结束
                OnAllComplete();
            }
        }