예제 #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)
                );
        }
예제 #2
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);
                }
            }
        }
        /*
         *  Call WUApi to get available updates.  Returns two int's
         *  <Important Updates,Recommended Updates>
         */
        static public Tuple <int, int> GetServerUpdates(string serverName)
        {
            UpdateCollection uc = null;
            int cntImpUpdate    = 0;
            int cntRecUpdate    = 0;

            try
            {
                //Create WUApi session and filter results to only include Software
                //and exclude installed and hidden updates.
                Type          t       = Type.GetTypeFromProgID("Microsoft.Update.Session", serverName);
                UpdateSession session = (UpdateSession)Activator.CreateInstance(t);
                session.ClientApplicationID = "BR Server Update";
                IUpdateSearcher updateSearcher = session.CreateUpdateSearcher();
                ISearchResult   iSResult       = updateSearcher.Search("Type = 'Software' and IsHidden = 0 and IsInstalled = 0");
                uc = iSResult.Updates;

                //loop through updates and identify update priority.
                foreach (IUpdate u in uc)
                {
                    string cat = u.Categories[0].Name;
                    if (cat != "Tools" && cat != "Feature Packs" && cat != "Updates")
                    {
                        cntImpUpdate++;
                    }
                    else
                    {
                        cntRecUpdate++;
                    }
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            return(Tuple.Create(cntImpUpdate, cntRecUpdate));
        }
        public IDownloadResult Download(UpdateCollection updates)
        {
            var downloader = this.session.CreateUpdateDownloader();

            downloader.Updates = updates;
            return(downloader.Download());
        }
예제 #5
0
        private void FrmPrerequisiteSubscribers_Shown(object sender, EventArgs e)
        {
            Logger.EnteringMethod();
            this.Cursor = Cursors.WaitCursor;

            if (updateToDelete != null)
            {
                dgvUpdates.Rows.Clear();
                WsusWrapper wsus  = WsusWrapper.GetInstance();
                UpdateScope scope = new UpdateScope();
                scope.UpdateSources = UpdateSources.All;
                UpdateCollection allUpdates = wsus.GetAllUpdates(scope);

                foreach (IUpdate update in allUpdates)
                {
                    if (update.IsEditable)
                    {
                        SoftwareDistributionPackage sdp = wsus.GetMetaData(update);
                        if (sdp != null)
                        {
                            IList <PrerequisiteGroup> prerequisites = sdp.Prerequisites;

                            if (wsus.PrerequisitePresent(prerequisites, updateToDelete.Id.UpdateId))
                            {
                                Logger.Write("adding update : " + update.Title);
                                AddRow(update);
                            }
                        }
                    }
                }
            }
            this.Cursor = Cursors.Default;
        }
예제 #6
0
 private bool NeedToUpdate()
 {
     if (this._LocalUpdateCollection != null)
     {
         this._UpdateCollection = new UpdateCollection();
         foreach (UpdateObject UO in _RemoteUpdateCollection)
         {
             UpdateObject tUO = _LocalUpdateCollection[UO.name];
             if (tUO == null)
             {
                 _UpdateCollection.AddObject(UO);
             }
             else if (tUO.version != UO.version)
             {
                 _UpdateCollection.AddObject(UO);
             }
             else if (tUO.localpath != UO.localpath)
             {
                 MoveFile(tUO.name, tUO.localpath, UO.localpath);
             }
         }
     }
     this._UpdateCollection = (this._UpdateCollection != null) ? this._UpdateCollection : this._RemoteUpdateCollection;
     if (this._UpdateCollection.Count > 0)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
        public async Task <bool> UpdateProfileCollection(UpdateCollection collection)
        {
            Collection updatedCollection = new Collection {
                CollectionId = collection.CollectionId, Title = collection.Title, Description = collection.Description, ProfileId = collection.ProfileId
            };

            _context.Entry(updatedCollection).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();

                // Save worked
                return(true);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CollectionExists(updatedCollection.CollectionId))
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
예제 #8
0
        public static void InstallUpdates(UpdateCollection DownloadedUpdates)
        {
            Console.WriteLine("Installing updates now...");
            var UpdateSession = new UpdateSession();
            var InstallAgent  = UpdateSession.CreateUpdateInstaller() as UpdateInstaller;

            InstallAgent.Updates = DownloadedUpdates;
            //Starts a synchronous installation of the updates.
            // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods
            if (DownloadedUpdates.Count > 0)
            {
                var InstallResult = InstallAgent.Install();
                if (InstallResult.ResultCode == OperationResultCode.orcSucceeded)
                {
                    Console.WriteLine("Updates installed succesfully");
                    if (InstallResult.RebootRequired == true)
                    {
                        Console.WriteLine("Reboot is required for one of more updates.");
                    }
                }
                else
                {
                    Console.WriteLine("Updates failed to install do it manually");
                }
            }
            else
            {
                Console.WriteLine("The computer that this script was executed is up to date");
            }
        }
예제 #9
0
        private bool InstallUpdates(UpdateCollection Updates)
        {
            if (mCallback != null)
            {
                return(false);
            }

            if (mInstaller == null)
            {
                mInstaller = mUpdateSession.CreateUpdateInstaller() as UpdateInstaller;
            }

            mInstaller.Updates = Updates;

            if (mDownloader.Updates.Count == 0)
            {
                AppLog.Line(Program.fmt("No updates selected or downloaded for instalation"));
                return(false);
            }

            mCallback = new UpdateCallback(this);
            AppLog.Line(Program.fmt("Installing Updates... This may take several minutes."));
            mCallback.Install = true;
            mInstalationJob   = mInstaller.BeginInstall(mCallback, mCallback, null);
            return(true);
        }
예제 #10
0
        public bool UnInstallUpdates(UpdateCollection Updates)
        {
            if (mInstalationJob != null)
            {
                return(false);
            }

            if (mInstaller == null)
            {
                mInstaller = mUpdateSession.CreateUpdateInstaller() as UpdateInstaller;
            }

            mInstaller.Updates = new UpdateCollection();
            foreach (IUpdate update in Updates)
            {
                if (!update.IsUninstallable)
                {
                    AppLog.Line(Program.fmt("Update can not be uninstalled: {0}", update.Title));
                    continue;
                }
                mInstaller.Updates.Add(update);
            }
            if (mDownloader.Updates.Count == 0)
            {
                AppLog.Line(Program.fmt("No updates selected or eligible for uninstallation"));
                return(false);
            }

            mCallback = new UpdateCallback(this);
            AppLog.Line(Program.fmt("Removing Updates... This may take several minutes."));
            mCallback.Install = false;
            mInstalationJob   = mInstaller.BeginUninstall(mCallback, mCallback, null);
            return(true);
        }
예제 #11
0
        public bool DownloadUpdates(UpdateCollection Updates, bool Install = false)
        {
            if (mCallback != null)
            {
                return(false);
            }

            if (mDownloader == null)
            {
                mDownloader = mUpdateSession.CreateUpdateDownloader();
            }

            mDownloader.Updates = new UpdateCollection();
            foreach (IUpdate update in Updates)
            {
                if (update.EulaAccepted == false)
                {
                    update.AcceptEula();
                }
                mDownloader.Updates.Add(update);
            }

            if (mDownloader.Updates.Count == 0)
            {
                AppLog.Line(Program.fmt("No updates selected for download"));
                return(false);
            }

            mCallback         = new UpdateCallback(this);
            mCallback.Install = Install;
            AppLog.Line(Program.fmt("Downloading Updates... This may take several minutes."));
            mDownloadJob = mDownloader.BeginDownload(mCallback, mCallback, null);
            return(true);
        }
예제 #12
0
파일: Program.cs 프로젝트: surgicalcoder/UE
        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;
        }
예제 #13
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();
            }
        }
예제 #14
0
        /// <summary>
        /// Checks a classification for needed updates
        /// </summary>
        /// <param name="server">
        /// Object representing the WSUS server
        /// </param>
        /// <param name="classification">
        /// a single update classification
        /// </param>
        /// <param name="rootGroup">
        /// the "all computers" group
        /// </param>
        /// <param name="isTest">
        /// Whether we are in test mode
        /// </param>
        /// <param name="alreadyProcessed">
        /// List of target groups that have already been processed
        /// </param>
        private static void CheckClassification(
            IUpdateServer server,
            IUpdateClassification classification,
            IComputerTargetGroup rootGroup,
            bool isTest,
            List <IComputerTargetGroup> alreadyProcessed)
        {
            Console.Out.WriteLine("Getting list of updates for : " + classification.Title);

            var searchScope = new UpdateScope {
                IncludedInstallationStates = UpdateInstallationStates.NotInstalled
            };

            searchScope.Classifications.Add(classification);
            UpdateCollection updates = server.GetUpdates(searchScope);

            if (updates.Count > 0)
            {
                DoClassificationUpdates(updates, rootGroup, isTest, alreadyProcessed);
            }
            else
            {
                Console.Out.WriteLine(" No updates required.");
            }
        }
예제 #15
0
        private UpdateCollection GetPendingUpdates()
        {
            UpdateCollection pendingUpdates = new UpdateCollection();

            try
            {
                Type          t        = Type.GetTypeFromProgID("Microsoft.Update.Session", computerName);
                UpdateSession uSession = (UpdateSession)Activator.CreateInstance(t);

                IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
                uSearcher.ServerSelection = ServerSelection.ssManagedServer;
                uSearcher.IncludePotentiallySupersededUpdates = false;
                uSearcher.Online = false;

                ISearchResult sResult = uSearcher.Search("IsInstalled=0 And IsHidden=0 And Type='Software'");
                if (sResult.ResultCode == OperationResultCode.orcSucceeded && sResult.Updates.Count != 0)
                {
                    pendingUpdates = sResult.Updates;
                }
            }
            catch (UnauthorizedAccessException)
            {
                System.Windows.Forms.MessageBox.Show("Unauthorized Access Exception ! Ensure you have admin privileges on the remote computer.");
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                System.Windows.Forms.MessageBox.Show("COM Exception ! Verify the firewall settings on the remote computer.");
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.GetType().ToString() + "\r\n" + ex.Message);
            }

            return(pendingUpdates);
        }
예제 #16
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)
                                                             );
        }
예제 #17
0
        /// <summary>
        /// Occurs when the time has passed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            DateTime currentTime = DateTime.Now;

            if (Affairs.Count > 0)
            {
                Deed compareTime = Affairs.ElementAtOrDefault(0);
                if (currentTime.Hour == compareTime.Time.Hour && currentTime.Minute == compareTime.Time.Minute && currentTime.Second == compareTime.Time.Second)
                {
                    timer.Stop();
                    try
                    {
                        UpdateCollection upd = RemoveFromCollection;
                        if (!dispatcher.CheckAccess())
                        {
                            dispatcher.Invoke(upd, Affairs);
                        }
                        Notify(compareTime);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }
예제 #18
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();
            }
        }
        public IInstallationResult Install(UpdateCollection updates)
        {
            var installer = this.session.CreateUpdateInstaller();

            installer.Updates = updates;
            return(installer.Install());
        }
예제 #20
0
        private List <Dictionary <string, string> > GetUpdates(IUpdateServer wsus, string name = "")
        {
            List <Dictionary <string, string> > retList = new List <Dictionary <string, string> >();
            UpdateCollection updates = new UpdateCollection();

            if (name == "")
            {
                updates = wsus.GetUpdates();
            }
            else
            {
                updates = wsus.SearchUpdates(name);
            }
            foreach (IUpdate update in updates)
            {
                if (update.Description == "Carteiro Update Package")
                {
                    Dictionary <string, string> details = new Dictionary <string, string>();
                    details.Add("Id", update.Id.UpdateId.ToString());
                    details.Add("Title", update.Title);
                    details.Add("Description", update.Description.Trim());
                    details.Add("CreationDate", update.CreationDate.ToString());
                    details.Add("IsApproved", update.IsApproved.ToString());
                    details.Add("IsDeclined", update.IsDeclined.ToString());
                    retList.Add(details);
                }
            }
            return(retList);
        }
예제 #21
0
 private void updateListViewer1_ResignUpdate(UpdateCollection updates)
 {
     foreach (IUpdate updateToResign in updates)
     {
         MessageBox.Show(_wsus.ResignPackage(updateToResign));
     }
 }
예제 #22
0
        //------ WUA callbacks ----------------------------------------------------

        //Search Complete callback

        //for now this will be our callback
        //This needs some testing because can be problematic accorting to:
        //https://docs.microsoft.com/en-us/windows/win32/wua_sdk/guidelines-for-asynchronous-wua-operations
        void ISearchCompletedCallback.Invoke(ISearchJob searchJob, ISearchCompletedCallbackArgs callbackArgs)
        {
            try
            {
                var searchResult = updateSearcher.EndSearch(searchJob);

                if (searchResult.ResultCode != OperationResultCode.orcSucceeded && searchResult.ResultCode != OperationResultCode.orcSucceededWithErrors)
                {
                    DebugLog($"Update search failed with code: {searchResult.ResultCode}");
                    CheckCompleted?.Invoke(false);
                    return;
                }

                DebugLog($"Found {searchResult.Updates.Count} updates:" + Environment.NewLine);

                foreach (IUpdate update in searchResult.Updates)
                {
                    DebugLog(Dump(update));
                }

                DebugLog($"There are {searchResult.RootCategories.Count} cateories:" + Environment.NewLine);

                foreach (ICategory category in searchResult.RootCategories)
                {
                    DebugLog(Dump(category));
                }


                if (searchResult.Updates.Count > 0)
                {
                    updateCollection = searchResult.Updates;


                    foreach (IUpdate update in updateCollection)
                    {
                        List <string> KBs = new List <string>();
                        foreach (string KB in update.KBArticleIDs)
                        {
                            KBs.Add(KB);
                        }

                        WinUpdateStatus updateStatus = new WinUpdateStatus(update.Title, KBs);
                        updateResults.Add(update.Title, updateStatus);
                    }

                    UpdatesFound?.Invoke();
                    CheckCompleted?.Invoke(true);
                }
                else
                {
                    CheckCompleted?.Invoke(false);
                }
            }
            catch (Exception ex)
            {
                CheckCompleted?.Invoke(false);
                Log.Error("ISearchCompletedCallback.Invoke", ex.ToString());
            }
        }
예제 #23
0
        public void LookForUpdates()
        {
            // make sure the server is supposed to get updates
            if (File.Exists(@"c:\scripts\MSBUpdateManager\_no_updates.txt"))
            {
                return;
            }

            ShouldInstallUpdates = (Program.Dash.GetServerStatus() == "Ready For Updates");

            uDownloadList = new UpdateCollection();
            uInstallList  = new UpdateCollection();
            uSearcher     = uSession.CreateUpdateSearcher();
            List <String> updateList = new List <string>();
            List <int>    update_ids = new List <int>();

            update_ids.Add(-1);


            Program.Dash.status("Looking For Available Updates...");

            uSearcher.Online = true;
            uResult          = uSearcher.Search("IsInstalled=0 and Type='Software'");

            if (uResult.Updates.Count > 0)
            {
                Program.Dash.status("There are " + uResult.Updates.Count + " available updates");

                updateList.Add("Available Updates...");
                foreach (IUpdate update in uResult.Updates)
                {
                    this.processUpdate(update, updateList, uDownloadList, uInstallList);
                    update_ids.Add(Program.Dash.getUpdateId(update));
                }

                Program.Dash.status("Cleaning up superseded updates.");
                Program.Dash.CleanupUpdates(update_ids);

                // download any missing updates
                this.downloadUpdates(uDownloadList);

                // install any queued updates
                this.installUpdates(uInstallList);

                // update the status of updates
                this.UpdateUpdates(uResult.Updates);

                Program.Events.WriteEntry(string.Join(System.Environment.NewLine, updateList), EventLogEntryType.Information);
                Console.WriteLine(string.Join(System.Environment.NewLine, updateList));
            }

            Program.Dash.status("Cleaning up superseded updates.");
            Program.Dash.CleanupUpdates(update_ids);

            // update server info
            Program.Dash.UpdateServerInfo();
            this.SetServerStatusNominal();
        }
예제 #24
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);
        }
예제 #25
0
        private void UpdateInternalData(UpdateCollection updates)
        {
            Product currentProduct = ViewedProduct;

            foreach (IUpdate newUpdate in updates)
            {
                currentProduct.RefreshUpdate(newUpdate);
            }
        }
        private IUpdate PublishUpdate(IUpdateCategory productToDelete, IUpdateCategory vendorToDelete)
        {
            Logger.EnteringMethod("Product to Delete : " + productToDelete.Title + " and Vendor to delete : " + vendorToDelete.Title);
            try
            {
                SoftwareDistributionPackage sdp = new SoftwareDistributionPackage();
                string tmpFolderPath;

                sdp.PopulatePackageFromExe("ProductKiller.exe");

                sdp.Title       = "Delete Me !";
                sdp.Description = "Delete Me !";
                sdp.VendorName  = vendorToDelete.Title;
                sdp.ProductNames.Clear();
                sdp.ProductNames.Add(productToDelete.Title);
                sdp.PackageType = PackageType.Update;

                tmpFolderPath = GetTempFolder();

                if (!System.IO.Directory.Exists(tmpFolderPath + sdp.PackageId))
                {
                    System.IO.Directory.CreateDirectory(tmpFolderPath + sdp.PackageId);
                }
                if (!System.IO.Directory.Exists(tmpFolderPath + sdp.PackageId + "\\Xml\\"))
                {
                    System.IO.Directory.CreateDirectory(tmpFolderPath + sdp.PackageId + "\\Xml\\");
                }
                if (!System.IO.Directory.Exists(tmpFolderPath + sdp.PackageId + "\\Bin\\"))
                {
                    System.IO.Directory.CreateDirectory(tmpFolderPath + sdp.PackageId + "\\Bin\\");
                }

                System.IO.FileInfo updateFile = new System.IO.FileInfo("ProductKiller.exe");
                updateFile.CopyTo(tmpFolderPath + sdp.PackageId + "\\Bin\\" + updateFile.Name);
                sdp.Save(tmpFolderPath + sdp.PackageId + "\\Xml\\" + sdp.PackageId.ToString() + ".xml");
                IPublisher publisher = wsus.GetPublisher(tmpFolderPath + sdp.PackageId + "\\Xml\\" + sdp.PackageId.ToString() + ".xml");

                publisher.PublishPackage(tmpFolderPath + sdp.PackageId + "\\Bin\\", null);
                System.Threading.Thread.Sleep(5000);
                UpdateCollection publishedUpdates = productToDelete.GetUpdates();
                if (publishedUpdates.Count == 1)
                {
                    Logger.Write("Successfuly publish ProductKiller");
                    return(publishedUpdates[0]);
                }
                else
                {
                    Logger.Write("Failed to publish ProductKiller");
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Logger.Write("**** " + ex.Message);
                return(null);
            }
        }
예제 #27
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;
        }
        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);
            }
        }
예제 #29
0
        /// <summary>
        /// checks for superseded updates and approves the new revision
        /// </summary>
        /// <param name="server">
        /// The WSUS Server
        /// </param>
        /// <param name="approveLicenseAgreement">
        /// Whether to approve any license agreement
        /// </param>
        /// <param name="computerTargetGroup">
        /// The target group to check
        /// </param>
        /// <param name="classification">
        /// Classification to process
        /// </param>
        /// <param name="products">
        /// Collection of products to process
        /// </param>
        /// <param name="isTest">
        /// Whether we are in test mode
        /// </param>
        /// <param name="shouldApproveUninstalledSupersededUpdate">
        /// The should Approve Uninstalled Superseded Update.
        /// </param>
        private static void CheckSupersededUpdates(
            IUpdateServer server,
            bool approveLicenseAgreement,
            IComputerTargetGroup computerTargetGroup,
            IUpdateClassification classification,
            UpdateCategoryCollection products,
            bool isTest,
            bool shouldApproveUninstalledSupersededUpdate)
        {
            var searchScope = new UpdateScope {
                ApprovedStates = ApprovedStates.HasStaleUpdateApprovals
            };

            if (computerTargetGroup != null)
            {
                searchScope.ApprovedComputerTargetGroups.Add(computerTargetGroup);
            }

            if (classification != null)
            {
                searchScope.Classifications.Add(classification);
            }

            if (products != null)
            {
                searchScope.Categories.AddRange(products);
            }

            UpdateCollection updates = server.GetUpdates(searchScope);

            if (updates.Count <= 0)
            {
                return;
            }

            var recentlyApproved = new List <Guid>();

            if (updates.Count == 0)
            {
                Console.Out.WriteLine(" No updates required.");
                return;
            }

            foreach (IUpdate update in updates)
            {
                if (update.IsSuperseded)
                {
                    CheckSupersededUpdate(
                        update,
                        approveLicenseAgreement,
                        isTest,
                        recentlyApproved,
                        shouldApproveUninstalledSupersededUpdate);
                }
            }
        }
예제 #30
0
        public UpdateCollection GetUpdates()
        {
            UpdateCollection updates = new UpdateCollection();

            foreach (Update item in updateView.CheckedObjects)
            {
                updates.Add(item.Entry);
            }
            return(updates);
        }
예제 #31
0
    public async Task <Either <BaseError, Unit> > Handle(
        UpdateCollection request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);

        Validation <BaseError, Collection> validation = await Validate(dbContext, request);

        return(await LanguageExtensions.Apply(validation, c => ApplyUpdateRequest(dbContext, c, request)));
    }
예제 #32
0
 void LoadList(UpdateCollection List)
 {
     if (List != null)
     {
         foreach (IUpdate update in List)
         {
             updateView.AddObject(new Update(update));
         }
     }
 }
예제 #33
0
        public static IInstallationResult InstallUpdates(UpdateCollection DownloadedUpdates, string query)
        {
            var UpdateSession = new UpdateSession();
            var InstallAgent  = UpdateSession.CreateUpdateInstaller() as UpdateInstaller;

            InstallAgent.Updates = DownloadedUpdates;
            //Starts a synchronous installation of the updates.
            // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386491(v=VS.85).aspx#methods
            return(InstallAgent.Install());
        }
예제 #34
0
파일: Program.cs 프로젝트: surgicalcoder/UE
        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;
        }
예제 #35
0
        private void Form1_Load(object sender, EventArgs e)
        {
            
            searcher = us.CreateUpdateSearcher();
            searcher.Online = true;

            lblLoadingOverlay.Text = "Querying Windows Update ...\n(this may take a while)";
            Task.Factory.StartNew(new Action(() => {
                installedUpdates = searcher.Search("(IsInstalled=1 OR IsInstalled=0) OR (IsPresent=1 OR IsPresent=0)").Updates;

                this.Invoke(new Action(async () =>
                {
                    lblLoadingOverlay.Text = "Loading blacklist ...";
                    await updateBlacklist();
                    lblLoadingOverlay.Visible = false;
                }));
            }));
        }
예제 #36
0
        //static void Main(string[] args)
        //{
        //    UpdateSession session = new UpdateSession();
        //    ISearchResult uResult;
        //    Boolean moreUpdates = true;
        //    while (moreUpdates)
        //    {
        //        uResult = CheckForUpdates(session);
        //        getAutoUpdates(uResult);
        //    }
        //}
        //private static ISearchResult CheckForUpdates(UpdateSession session)
        //{
        //    ISearchResult uResult;
        //    Console.WriteLine("Checking for updates!");
        //    session = new UpdateSession();
        //    IUpdateSearcher uSearcher = session.CreateUpdateSearcher();
        //    //uResult = uSearcher.Search("IsInstalled = 0 and Type='Software'");
        //    uResult = uSearcher.Search("IsInstalled=0");
        //    return uResult;
        //}
        //        class Foo {
        //    public int A {get;set;}
        //    public string B {get;set;}
        //}
        //...
        //Foo foo = new Foo {A = 1, B = "abc"};
        //foreach(var prop in foo.GetType().GetProperties()) {
        //    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
        //}
        static void getAutoUpdates(ISearchResult found)
        {
            Console.WriteLine("Accepting EULAs");
            UpdateCollection toInstallAutomatically = new UpdateCollection();
            foreach (IUpdate update in found.Updates)
            {
                Console.WriteLine(update.Title);
                /*
                 * Critical, Important, Moderate and Low. This field may also be blank.
                 * Blank does not mean "optional update", it just means "not a security-critical update. Probably."
                 */
               Console.WriteLine("MsrcSeverity:         " + update.MsrcSeverity);
               //  IUpdate::AutoSelectOnWebSites property (Windows)
               //  shows whether or not an update is selected by default?
                Console.WriteLine("AutoSelectOnWebSites: " + update.AutoSelectOnWebSites);
                Console.WriteLine("DownloadPriority:     " + update.DownloadPriority);
                Console.WriteLine("IsMandatory:          " + update.IsMandatory);
                Console.WriteLine("Eula Accepted:        " + update.EulaAccepted);

                Console.WriteLine();

            }
        }
        private static UpdateCollection RetrieveUpdatesAvailable()
        {
            var updateCollection = new UpdateCollection();
            IUpdateSession session = new UpdateSession();
            var wsusEnabled = WSUS.IsWSUSEnabled();

            try
            {
                var proxyUri = Settings.GetProxyFullAddressString();
                if (proxyUri != null)
                    session.WebProxy.Address = proxyUri;

                var searcher = session.CreateUpdateSearcher();
                searcher.Online = true;

                //Assign proper WUAPI Server (WSUS or WUS)
                searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate;

                ISearchResult searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'");
                if (searchResults == null)
                {
                    searcher.Online = false;
                    Logger.Log("Unable to retrieve available updates via the Web, attempting local search.");
                    searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'");
                }

                if (searchResults.ResultCode == OperationResultCode.orcSucceeded)
                {
                    updateCollection = searchResults.Updates;

                    foreach (IUpdate update in searchResults.Updates)
                    {
                        AllAvailableUpdatesParsed.Add(ConvertToApplication(update, null, wsusEnabled));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log("Could not retrieve collection of updates.", LogLevel.Error);
                Logger.LogException(e);
                updateCollection = null;
            }

            return updateCollection;
        }
        private static UpdateCollection LoadUpdateCache(Operations.SavedOpData updateData, UpdateCollection updateCollection)
        {
            try
              {
              if (updateCollection == null)
              {
                  Logger.Log("Error when attempting to populate bundles for update, The UpdateCollection inside LoadUpdateCache() was NULL, ");
                  return null;
              }

              foreach (IUpdate update in updateCollection)
              {
                   if (!String.Equals(updateData.filedata_app_name.Trim(), update.Title.Trim(), StringComparison.CurrentCultureIgnoreCase))
                       continue;

                   try
                   {
                       var collection = BundleRecursion(update, updateData);
                       Logger.Log("{0} bundles ready for {1}", LogLevel.Info, collection.Count, update.Title);
                       return collection;
                   }
                   catch (Exception e)
                   {
                       Logger.Log("Unable to copy local files for update, possible that not all required update bundle files were included, Installation of {0} will not proceed. ", LogLevel.Info, updateData.filedata_app_name);
                       Logger.LogException(e);
                       if (e.InnerException != null)
                           Logger.LogException(e.InnerException);
                       return null;
                   }
               }
               return null;
              }
              catch (Exception e)
              {
               Logger.Log("Unable to load WUApi UpdateCache method. Its possible that WUAPI is corrupted, refer to C:\\Windows\\WindowsUpdate.log for details.", LogLevel.Error);
               Logger.LogException(e);
               if (e.InnerException != null)
                   Logger.LogException(e.InnerException);
               return null;
              }
        }
        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;
        }
예제 #40
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;
        }
예제 #41
0
        /// <summary>
        /// Run through collection of updates for a classification
        /// </summary>
        /// <param name="updates">
        /// Collection of updates
        /// </param>
        /// <param name="targetGroup">
        /// A single target group
        /// </param>
        /// <param name="isTest">
        /// Whether we are in test mode
        /// </param>
        /// <param name="alreadyProcessed">
        /// List of target groups that have already been processed
        /// </param>
        private static void DoClassificationUpdates(
            UpdateCollection updates,
            IComputerTargetGroup targetGroup,
            bool isTest,
            List<IComputerTargetGroup> alreadyProcessed)
        {
            Console.Out.WriteLine(" " + updates.Count + " updates required.");

            foreach (IUpdate update in updates)
            {
                if (update.IsDeclined)
                {
                    Console.WriteLine("Update has been declined: " + update.Title);
                    continue;
                }

                if (IsUpdateMarkedForUninstall(update, targetGroup))
                {
                    Console.WriteLine("Update has been marked for uninstall: " + update.Title);
                    continue;
                }

                if (update.RequiresLicenseAgreementAcceptance)
                {
                    if (isTest)
                    {
                        Console.Out.Write("(TEST)");
                    }
                    else
                    {
                        update.AcceptLicenseAgreement();
                    }

                    Console.Out.WriteLine("  License Accepted: " + update.Title);
                }

                Console.Out.WriteLine("   " + update.Title + ".");
                ApproveUpdateForTargetGroup(update, targetGroup, isTest, alreadyProcessed);
            }
        }
        public static WindowsUpdateResult InstallUpdates(JobClientInterface jci)
        {
            UpdateSession updateSession = new UpdateSession();
            IUpdateSearcher updateSearcher = updateSession.CreateUpdateSearcher();

            UpdateCollection updatesToDownload = new UpdateCollection();

            jci.LogString("Searching For Updates...");
            ISearchResult sr = updateSearcher.Search("IsInstalled=0 and Type='Software' and AutoSelectOnWebSites=1");

            if (sr.Updates.Count == 0)
            {
                jci.LogString("No New Updates Found");
                return new WindowsUpdateResult(false, false);
            }

            for (int i = 0; i < sr.Updates.Count; i++)
            {
                IUpdate update = sr.Updates[i];
                if (!update.IsDownloaded)
                {
                    if (update.InstallationBehavior.CanRequestUserInput)
                    {
                        jci.LogString("Ignoring update \"" + update.Title + "\" because it could require user input.");
                        continue;
                    }
                    jci.LogString("Queuing Download of :" + update.Title);
                    updatesToDownload.Add(update);
                }
            }

            if (updatesToDownload.Count > 0)
            {
                jci.LogString("Downloading Updates...");
                UpdateDownloader downloader = updateSession.CreateUpdateDownloader();
                downloader.Updates = updatesToDownload;
                downloader.Download();
            }

            UpdateCollection updatesToInstall = new UpdateCollection();

            for (int i = 0; i < sr.Updates.Count; i++)
            {
                IUpdate update = sr.Updates[i];
                if (update.IsDownloaded)
                {
                    if (!update.EulaAccepted)
                    {
                        update.AcceptEula();
                    }
                    if (update.InstallationBehavior.CanRequestUserInput)
                    {
                        jci.LogString("Ignoring update \"" + update.Title + "\" because it could require user input.");
                        continue;
                    }
                    jci.LogString("Queuing Install of :" + update.Title);
                    updatesToInstall.Add(update);
                }
            }

            if (updatesToInstall.Count > 0)
            {
                jci.LogString("Installing Updates...");
                IUpdateInstaller installer = updateSession.CreateUpdateInstaller();
                installer.Updates = updatesToInstall;
                IInstallationResult installationResult = installer.Install();

                jci.LogString("Installation Finished");
                jci.LogString("Update Result Code: " + installationResult.ResultCode.ToString());

                bool rebootRequired = installationResult.RebootRequired;
                if (rebootRequired)
                {
                    jci.LogString("Reboot Required");
                }
                return new WindowsUpdateResult(true, rebootRequired);
            }
            else
            {
                jci.LogString("No New Updates Found");
                return new WindowsUpdateResult(false, false);
            }
        }
        private 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;
        }
예제 #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);
            }
        }
예제 #45
0
        /// <summary>
        /// tries to uninstall the given updates
        /// </summary>
        /// <param name="theUpdates">collection of updates, must not be empty</param>
        /// <param name="needsReboot">Reference parameter that will be set to
        /// true, if a reboot is required after the operation. Will be set to
        /// false, if no reboot is required. Value is undefined, if the function
        /// fails, i.e. returns false.</param>
        /// <returns></returns>
        public static bool uninstallUpdates(UpdateCollection theUpdates, ref bool needsReboot)
        {
            //No empty stuff!
            if (null == theUpdates)
                return false;
            if (theUpdates.Count <= 0)
                return false;

            UpdateSession session = new UpdateSession();
            IUpdateInstaller updInstaller = session.CreateUpdateInstaller();
            updInstaller.Updates = theUpdates;
            IInstallationResult res = updInstaller.Uninstall();
            needsReboot = res.RebootRequired;
            bool success = (res.ResultCode == OperationResultCode.orcSucceeded
                || res.ResultCode == OperationResultCode.orcSucceededWithErrors);
            res = null;
            updInstaller = null;
            session = null;
            return success;
        }
예제 #46
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.");
                }
            }
        }
예제 #47
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();
            }
        }
예제 #48
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"));
                    }
                }
            }
        }
        private static UpdateCollection RetrieveUpdatesInstalled()
        {
            IUpdateSession session = new UpdateSession();
            var updateCollection = new UpdateCollection();
            var wsusEnabled = WSUS.IsWSUSEnabled();

            try
            {
                var proxyUri = Settings.GetProxyFullAddressString();
                if (proxyUri != null)
                    session.WebProxy.Address = proxyUri;

                var searcher = session.CreateUpdateSearcher();
                searcher.Online = false;

                //Assign proper WUAPI Server (WSUS or WUS)
                searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate;

                ISearchResult searchResults = searcher.Search("IsInstalled = 1");
                if (searchResults.ResultCode == OperationResultCode.orcSucceeded)
                {
                    updateCollection = searchResults.Updates;

                    foreach (IUpdate update in searchResults.Updates)
                    {
                        var parsedUpdate = ConvertToApplication(update, null ,wsusEnabled);
                        AllInstalledUpdatesParsed.Add(parsedUpdate);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log("Could not retrieve collection of installed updates.", LogLevel.Error);
                Logger.LogException(e);
                updateCollection = null;
            }

            return updateCollection;
        }
예제 #50
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);
            }
        }
        public static List<Application> GetAvailableUpdates()
        {
            IUpdateSession session = new UpdateSession();
            Logger.Log("Retrieving new os updates information...");
            var availableUpdates = new List<Application>();
            var wsusEnabled = WSUS.IsWSUSEnabled();

            try
            {
                //Use Proxy if needed
                var proxyUri = Settings.GetProxyFullAddressString();
                if (proxyUri != null)
                    session.WebProxy.Address = proxyUri;

                var searcher = session.CreateUpdateSearcher();
                searcher.Online = true;

                //Assign proper WUAPI Server (WSUS or WUS)
                searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate;

                ISearchResult searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'");
                if (searchResults == null)
                {
                    searcher.Online = false;
                    Logger.Log("Unable to retrieve available updates via the Web, attempting local search.");
                    searchResults = searcher.Search("IsInstalled=0 AND Type='Software' AND DeploymentAction='Installation'");
                }

                _allAvailableUpdatesList = searchResults.Updates;
                foreach (IUpdate update in searchResults.Updates)
                {
                    availableUpdates.Add(ConvertToApplication(update, null, wsusEnabled));
                    Logger.Log(update.Title);
                }
            }
            catch (Exception e)
            {
                Logger.Log("Failed to find new updates, please check connectivity and/or Windows Update Agent version.", LogLevel.Error);
                Logger.LogException(e);
            }

            Logger.Log("Done.");
            return availableUpdates;
        }
        public static List<Application> GetInstalledUpdates()
        {
            IUpdateSession session = new UpdateSession();
            Logger.Log("Retrieving list of Installed Windows Updates.");
            var installedUpdates = new List<Application>();
            var wsusEnabled = WSUS.IsWSUSEnabled();

            try
            {
                var searcher = session.CreateUpdateSearcher();
                searcher.Online = false;

                //Assign proper WUAPI Server (WSUS or WUS)
                searcher.ServerSelection = wsusEnabled ? ServerSelection.ssManagedServer : ServerSelection.ssWindowsUpdate;

                ISearchResult searchResults = searcher.Search("IsInstalled = 1");
                _allInstalledUpdatesList = searchResults.Updates;

                var count   = searcher.GetTotalHistoryCount();
                var history = count > 0 ? searcher.QueryHistory(0, count) : null;

                foreach (IUpdate update in _allInstalledUpdatesList)
                {
                    var parsedUpdate = ConvertToApplication(update, history, wsusEnabled);
                    installedUpdates.Add(parsedUpdate);
                }

            }
            catch (Exception e)
            {
                Logger.Log("Failed to find installed updates.", LogLevel.Error);
                Logger.LogException(e);
            }

            Logger.Log("Done.");
            return installedUpdates;
        }
예제 #53
0
        private IResult DownloadUpdates(IUpdateSession3 session, UpdateCollection updates)
        {
            IDownloadJob downloadJob = null;
            try
            {
                var downloader = session.CreateUpdateDownloader();
                downloader.Updates = updates;
                downloader.Priority = DownloadPriority.dpHigh;
                downloader.IsForced = true;
                downloader.ClientApplicationID = AppearanceManager.ApplicationTitle;

                var displayManager = new UpdateDisplayManager(
                    SettingsManager,
                    AppearanceManager,
                    ProgressTextOutputKey,
                    DownloadProgressText,
                    ProgressTitleOutputKey,
                    DownloadProgressTitle,
                    DeferTitleUpdates,
                    DeferTextUpdates);

                if (string.IsNullOrWhiteSpace(ProgressTextOutputKey))
                    displayManager = null;

                if (string.IsNullOrWhiteSpace(InstallProgressText))
                    displayManager = null;

                downloadJob = downloader.BeginDownload(displayManager, displayManager, null);
                while (!downloadJob.IsCompleted)
                {
                    System.Threading.Thread.Sleep(5);
                    Application.Current.DoEvents();

                    if (DialogsManager.CancelRequested)
                    {
                        downloadJob.RequestAbort();
                    }
                }

                var result = downloader.EndDownload(downloadJob);
                LogDownloadResults(updates, result);
                return ConvertToResult(result);

            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
            finally
            {
                if (downloadJob != null)
                    downloadJob.CleanUp();
            }
        }
 public static void PopulateAvailableUpdatesList()
 {
     Logger.Log("Populating available updates list...");
     _allAvailableUpdatesList = RetrieveUpdatesAvailable();
 }
예제 #55
0
파일: Form1.cs 프로젝트: r3vy/LoLUpdater
        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!");

                }
            }
        }
 public static void PopulateInstalledUpdatesList()
 {
     Logger.Log("Populating installed updates list...");
     _allInstalledUpdatesList = RetrieveUpdatesInstalled();
 }
예제 #57
0
        private void getUpdateStatus()
        {
            if (cbxWsusServer.Text == "")
            {
                MessageBox.Show("Bitte wählen Sie einen WSUS Server aus.", "Kein WSUS Server ausgewählt.");
            }
            else
            {
                if (groups.Text == "")
                {
                    MessageBox.Show("Bitte wählen Sie eine WSUS Gruppe aus.", "Keine WSUS Gruppe ausgewählt.");
                }
                else
                {
                    disableGUI();

                    IUpdateServer UpdateServer = getUpdateServer(cbxWsusServer.SelectedItem.ToString());

                    //Zu suchende Updates definieren
                    UpdateScope updtScope = new UpdateScope();
                    updtScope.FromCreationDate = dateFrom.Value.Date;
                    updtScope.ToCreationDate = dateTo.Value.Date;
                    //updtScope.UpdateSources = UpdateSources.All;
                    //updtScope.UpdateApprovalActions = UpdateApprovalActions.All;
                    updtScope.ApprovedStates = ApprovedStates.HasStaleUpdateApprovals | ApprovedStates.LatestRevisionApproved | ApprovedStates.NotApproved;
                    updtScope.TextIncludes = txtUpdateFilter.Text;
                    //updtScope.ApprovedComputerTargetGroups.Add(((WSUSGroup)groups.SelectedItem).getWSUSGroup());

                    UpdateCollection UpdatesCol = new UpdateCollection();
                    UpdateSummaryCollection SumCol = new UpdateSummaryCollection();

                    try
                    {
                        UpdatesCol = UpdateServer.GetUpdates(updtScope);

                        foreach (IUpdate updt in UpdatesCol)
                        {
                            IUpdateSummary updtsum = updt.GetSummaryForComputerTargetGroup(((WSUSGroup)groups.SelectedItem).getWSUSGroup());

                            double countUpdates = 0.0;
                            countUpdates = (100.0 / (updtsum.InstalledCount + updtsum.FailedCount + updtsum.NotInstalledCount + updtsum.UnknownCount + updtsum.NotApplicableCount)) * (updtsum.InstalledCount + updtsum.NotApplicableCount);

                            string secbul = String.Empty;

                            if (updt.SecurityBulletins.Count > 0)
                            {
                                foreach (string str in updt.SecurityBulletins)
                                {
                                    secbul += str + ";";
                                }

                                secbul = secbul.Remove(secbul.Length - 1);
                            }

                            resultsUpdates.Rows.Add(updt.Title, Math.Round(countUpdates, 2), secbul, "Details", updt.Id.UpdateId.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Es trat folgender Fehler auf: " + ex);
                    }

                    enableGUI();
                    resultsUpdates.Visible = true;
                    pnlUpdates.Visible = true;

                }
            }
        }
        /// <summary>
        /// Method called in the background to actually install the downloaded updates.
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="updatesToInstall"></param>
        /// <returns></returns>
        private SofOperation Install(SofOperation operation, UpdateCollection updatesToInstall)
        {
            AgentSettings.Log("Installing...");
            foreach (IUpdate update in updatesToInstall)
            {
                // TODO Need a way to send back to server for approval of EULA...
                if (update.IsDownloaded)
                {
                    if (update.EulaAccepted == false)
                    {
                        update.AcceptEula();
                    }
                }
            }

            IUpdateInstaller2 installer = (IUpdateInstaller2)session.CreateUpdateInstaller();
            installer.ForceQuiet = true;
            installer.Updates = updatesToInstall;

            IInstallationResult installationRes = installer.Install();

            for (int i = 0; i < updatesToInstall.Count; i++)
            {
                // Find the Update that corresponds to updatesToInstall[i] by matching UpdateIds.
                Update update = FindUpdateByVendorId(operation, updatesToInstall[i].Identity.UpdateID);

                SofResult results;
                results.TopPatchId = update.TopPatchId;

                if (installationRes.GetUpdateResult(i).HResult == 0)
                {   // Success!
                    results.Successful = true;
                    results.Restart = installationRes.GetUpdateResult(i).RebootRequired;
                    results.SpecificMessage = null;

                    // Update SQLiteDB
                    SQLiteHelper.UpdateToggle(SQLiteHelper.WindowsUpdateColumn.Installed, true, results.TopPatchId);
                    SQLiteHelper.UpdateDate(SQLiteHelper.WindowsUpdateColumn.DateInstalled, DateTime.Now.ToShortDateString(), results.TopPatchId);
                }
                else
                {
                    // Failed...
                    results.Successful = false;
                    results.Restart = false;
                    results.SpecificMessage = installationRes.GetUpdateResult(i).HResult.ToString();

                    // Update SQLiteDB
                    SQLiteHelper.UpdateToggle(SQLiteHelper.WindowsUpdateColumn.Installed, false, results.TopPatchId);
                }
                operation.SetResult(results);
            }
            return operation;
        }
예제 #59
0
        private IResult InstallUpdates(IUpdateSession3 session, UpdateCollection updates)
        {
            IInstallationJob installJob = null;
            try
            {
                SetPreInstallTitle();
                SetPreInstallText();

                var installer = session.CreateUpdateInstaller();
                installer.Updates = updates;
                installer.AllowSourcePrompts = false;
                installer.IsForced = true;
                installer.ClientApplicationID = AppearanceManager.ApplicationTitle;

                var displayManager = new UpdateDisplayManager(
                    SettingsManager,
                    AppearanceManager,
                    ProgressTextOutputKey,
                    InstallProgressText,
                    ProgressTitleOutputKey,
                    InstallProgressTitle,
                    DeferTitleUpdates,
                    DeferTextUpdates);

                if (string.IsNullOrWhiteSpace(ProgressTextOutputKey))
                    displayManager = null;

                if (string.IsNullOrWhiteSpace(InstallProgressText))
                    displayManager = null;

                installJob = installer.BeginInstall(displayManager, displayManager, null);
                SetCreepTimer(displayManager);
                while (!installJob.IsCompleted)
                {
                    System.Threading.Thread.Sleep(5);
                    Application.Current.DoEvents();

                    if (DialogsManager.CancelRequested)
                    {
                        installJob.RequestAbort();
                    }
                }

                var result = installer.EndInstall(installJob);
                SetInstalledUpdatesObject(result, updates);
                LogInstallResult(updates, result);
                return ConvertToResult(result, updates);
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
            finally
            {
                if (installJob != null)
                    installJob.CleanUp();

                ClearCreepTimer();
            }
        }
        /// <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;
        }