/// <summary>
        /// Callback for completed download operations.
        /// </summary>
        private void EndDownloadUpdates(IDownloadResult result, IUpdateCollection updates)
        {
            Log.Debug("Download result callback received: " + result.ResultCode.ToString("G"));
            using (ll.Lock(StateLock))
            {
                switch (result.ResultCode)
                {
                case OperationResultCode.orcSucceeded:
                    EnterStateWhenAllowed(new WuStateDownloadCompleted(updates, result.HResult));
                    break;

                case OperationResultCode.orcSucceededWithErrors:
                    EnterStateWhenAllowed(new WuStateDownloadPartiallyFailed(null, "Could not download all updates: HResult " + result.HResult));
                    break;

                default:
                    if (_currentState is WuStateDownloadFailed)
                    {
                        return;
                    }
                    EnterStateWhenAllowed(new WuStateDownloadFailed(null, "Could not download updates: HResult" + result.HResult));
                    break;
                }
            }
        }
Beispiel #2
0
 public WuStateCompleted(WuStateId id, string DisplayName, IUpdateCollection updates, int hResult) : base(id, DisplayName)
 {
     if (updates == null)
     {
         throw new ArgumentNullException(nameof(updates));
     }
     Updates = updates;
     HResult = hResult;
 }
Beispiel #3
0
        public static ISearchResult GetSearchResult(IUpdateCollection updates, OperationResultCode resultcode = OperationResultCode.orcSucceeded)
        {
            var mock = new Mock <ISearchResult>();

            mock.Setup(m => m.ResultCode).Returns(resultcode);
            mock.Setup(m => m.Updates).Returns(((UpdateCollection)updates));
            mock.Setup(m => m.RootCategories).Throws(new NotImplementedException("Not supported by this mock."));
            mock.Setup(m => m.Warnings).Returns((IUpdateExceptionCollection)null);
            return(mock.Object);
        }
        public void Should_CreateNewObjects_When_RequestInstance()
        {
            UpdateCollectionFactory factory = new UpdateCollectionFactory();

            IUpdateCollection coll1 = factory.GetInstance();
            IUpdateCollection coll2 = factory.GetInstance();

            Assert.IsNotNull(coll1);
            Assert.IsNotNull(coll2);
            Assert.AreNotSame(coll1, coll2);
        }
Beispiel #5
0
        private static IEnumerable <IUpdate> ToArray(IUpdateCollection updates)
        {
            var updatesArray = new IUpdate[updates.Count];

            for (var i = 0; i < updates.Count; i++)
            {
                updatesArray[i] = updates[i];
            }

            return(updatesArray);
        }
        /// <summary>
        /// Converts <see cref="IUpdate"/> enumerations to <see cref="IUpdateCollection"/>.
        /// </summary>
        private IUpdateCollection ToUpdateCollection(IEnumerable <IUpdate> updateList)
        {
            IUpdateCollection collection = UpdateCollectionFactory.GetInstance();

            if (updateList.Any())
            {
                foreach (IUpdate update in updateList)
                {
                    collection.Add(update);
                }
            }
            return(collection);
        }
 /// <summary>
 /// Callback for completed installation operations.
 /// </summary>
 private void EndInstallUpdates(IInstallationResult result, IUpdateCollection updates)
 {
     Log.Debug("Installation result callback received: " + result.ResultCode.ToString("G"));
     using (ll.Lock(StateLock))
     {
         if (result.ResultCode == OperationResultCode.orcSucceeded)
         {
             IEnumerable <IUpdate> notInstalledUpdates;
             using (ll.Lock(UpdateHolderLock))
             {
                 notInstalledUpdates = UpdateHolder.GetSelectedUpdates((u) => !u.IsInstalled);
             }
             if (result.RebootRequired || SystemInfo.IsRebootRequired())
             {
                 EnterStateWhenAllowed(new WuStateRebootRequired());
             }
             else if (notInstalledUpdates.Any(u => !u.EulaAccepted || u.InstallationBehavior.CanRequestUserInput))
             {
                 if (IsValidTransition <WuStateUserInputRequired>())
                 {
                     string reason = (notInstalledUpdates.Any(u => !u.EulaAccepted))
                         ? "Some selected updates were not installed. Please accept the eulas for these updates."
                         : "Some updates were not installed because they can request user input.";
                     EnterState(new WuStateUserInputRequired(reason));
                 }
             }
             else
             {
                 EnterStateWhenAllowed(new WuStateInstallCompleted(updates, result.HResult));
             }
         }
         else if (result.ResultCode == OperationResultCode.orcSucceededWithErrors)
         {
             EnterStateWhenAllowed(new WuStateInstallPartiallyFailed(null, "Could not install all updates: HResult " + result.HResult));
         }
         else
         {
             if (_currentState is WuStateInstallFailed)
             {
                 return;
             }
             EnterStateWhenAllowed(new WuStateInstallFailed(null, "Could not install updates: HResult " + result.HResult.ToString()));
         }
     }
 }
Beispiel #8
0
        public void Should_SkipInstalledUpdates_When_SearchCompleted()
        {
            UpdateFake update = new UpdateFake("update1");

            update.IsInstalled = true;
            IUpdateCollection updateCollection = ToUpdateCollection(update);

            var session = new UpdateSessionFake(true);

            session.SearcherMock.FakeSearchResult = CommonMocks.GetSearchResult(updateCollection);

            using (WuApiController wu = new WuApiController(session, UpdateCollectionFactory, SystemInfo))
            {
                wu.BeginSearchUpdates();
                WaitForStateChange(wu, WuStateId.SearchCompleted);
                Assert.IsTrue(wu.GetAvailableUpdates().Count == 0);
            }
        }
        public void Should_NotEnterDownloadingState_When_NotEnoughFreeSpaceAvailable()
        {
            var system    = MoqFactory.Create <ISystemInfo>(MockBehavior.Loose);
            int freespace = 100;

            system.Setup(s => s.GetFreeSpace()).Returns(freespace);
            system.Setup(s => s.GetFQDN()).Returns("fqdn");
            system.Setup(s => s.GetOperatingSystemName()).Returns("osname");
            system.Setup(s => s.GetWuServer()).Returns("update server");
            system.Setup(s => s.GetTargetGroup()).Returns("target group");

            UpdateFake update = new UpdateFake("update1");

            update.IsMandatory     = true;
            update.EulaAccepted    = true;
            update.MaxDownloadSize = freespace;
            UpdateFake update2 = new UpdateFake("update2");

            update2.IsMandatory              = true;
            update2.EulaAccepted             = true;
            update2.RecommendedHardDiskSpace = 10;

            IUpdateCollection updateCollection = ToUpdateCollection(update, update2);

            var session = new UpdateSessionFake(true);

            session.SearcherMock.FakeSearchResult = CommonMocks.GetSearchResult(updateCollection);

            WuApiController wu = new WuApiController(session, UpdateCollectionFactory, system.Object);

            wu.BeginSearchUpdates();
            WaitForStateChange(wu, WuStateId.SearchCompleted);

            try
            {
                wu.BeginDownloadUpdates();
                Assert.Fail("exception expected");
            }
            catch (InvalidStateTransitionException e)
            {
                Assert.IsTrue(e.Message.Contains("free space"));
                Assert.IsTrue(wu.GetWuStatus().Equals(WuStateId.SearchCompleted));
            }
        }
        public void Should_EnterDownloadFailedState_When_DownloadTimeRunsOut()
        {
            UpdateFake        update           = new UpdateFake("update1", true);
            IUpdateCollection updateCollection = ToUpdateCollection(update);

            var session = new UpdateSessionFake(true);

            session.SearcherMock.FakeSearchResult     = CommonMocks.GetSearchResult(updateCollection);
            session.DownloaderMock.FakeDownloadTimeMs = 10000;

            using (WuApiController wu = new WuApiController(session, UpdateCollectionFactory, SystemInfo))
            {
                wu.AutoAcceptEulas = true;
                wu.BeginSearchUpdates();
                WaitForStateChange(wu, WuStateId.SearchCompleted);
                wu.BeginDownloadUpdates(1);
                WaitForStateChange(wu, WuStateId.DownloadFailed, 2000);
                Assert.IsTrue(wu.GetWuStatus().Description.Contains("Timeout"));
            }
        }
        /// <summary>
        /// Sets the windows update search result with updates that are applicable to this maschine.
        /// </summary>
        /// <param name="applicableUpdates">The windows update search result.</param>
        /// <exception cref="ArgumentNullException" />
        public void SetApplicableUpdates(IUpdateCollection applicableUpdates)
        {
            if (applicableUpdates == null)
            {
                throw new ArgumentNullException(nameof(applicableUpdates));
            }

            lock (_updateLock)
            {
                _applicableUpdates = applicableUpdates;
                _selectedUpdates.Clear();
                if (AutoSelectUpdates)
                {
                    foreach (var update in _applicableUpdates.OfType <IUpdate>().Where(u => IsImportant(u)))
                    {
                        _selectedUpdates.Add(update.Identity.UpdateID);
                    }
                }
            }
        }
        public WuStateInstalling(IUpdateInstaller uInstaller, IUpdateCollection updates,
                                 InstallCompletedCallback completedCallback, TimeoutCallback timeoutCallback, ProgressChangedCallback progressCallback,
                                 int timeoutSec) : base(WuStateId.Installing, "Installing Updates", timeoutSec, timeoutCallback, progressCallback)
        {
            if (uInstaller == null)
            {
                throw new ArgumentNullException(nameof(uInstaller));
            }
            if (updates == null)
            {
                throw new ArgumentNullException(nameof(updates));
            }
            if (completedCallback == null)
            {
                throw new ArgumentNullException(nameof(completedCallback));
            }

            _uInstaller        = uInstaller;
            _updates           = updates;
            _completedCallback = completedCallback;
        }
Beispiel #13
0
        public void Should_ConvertValues_When_ConvertUpdateToTransferObject()
        {
            Update3Fake update = new Update3Fake("update1", false);

            update.IsInstalled     = false;
            update.Identity        = CommonMocks.GetUpdateIdentity("update");
            update.Description     = "some text about me";
            update.IsDownloaded    = false;
            update.MaxDownloadSize = 5;
            update.MinDownloadSize = 1;
            update.Title           = "i am the update";
            update.EulaAccepted    = true;

            IUpdateCollection updateCollection = ToUpdateCollection(update);

            var session = new UpdateSessionFake(true);

            session.SearcherMock.FakeSearchResult = CommonMocks.GetSearchResult(updateCollection);
            using (WuApiController wu = new WuApiController(session, UpdateCollectionFactory, SystemInfo))
            {
                wu.AutoSelectUpdates = true;
                wu.BeginSearchUpdates();
                WaitForStateChange(wu, WuStateId.SearchCompleted);

                UpdateDescription ud = wu.GetAvailableUpdates().Single();

                Assert.AreEqual(ud.IsImportant, !update.BrowseOnly);
                Assert.AreEqual(ud.Description, update.Description);
                Assert.AreEqual(ud.ID, update.Identity.UpdateID);
                Assert.AreEqual(ud.IsDownloaded, update.IsDownloaded);
                Assert.AreEqual(ud.IsInstalled, update.IsInstalled);
                Assert.AreEqual(ud.MaxByteSize, update.MaxDownloadSize);
                Assert.AreEqual(ud.MinByteSize, update.MinDownloadSize);
                Assert.AreEqual(ud.Title, update.Title);
                Assert.AreEqual(ud.EulaAccepted, update.EulaAccepted);
                Assert.AreEqual(ud.SelectedForInstallation, !update.BrowseOnly);
            }
        }
Beispiel #14
0
        public Result InstallUpdates(IUpdateCollection updates)
        {
            //TODO: use NetBIOS name (until first .)

            Logger.Debug("START InstallUpdates");

            var updateLog = new UpdateInstallationLog();

            var uSession   = new UpdateSessionClass();
            var downloader = uSession.CreateUpdateDownloader();

            downloader.Updates = (UpdateCollection)updates;

            Logger.Debug("Downloading the following updates:");
            foreach (IUpdate update in updates)
            {
                Logger.DebugFormat("  KB = '{0}', Title = '{1}'", update.KBArticleIDs[0], update.Title);
            }

            downloader.Download();

            var updatesToInstall = new UpdateCollectionClass();

            foreach (IUpdate update in updates)
            {
                if (update.IsDownloaded)
                {
                    bool addUpdate = true;

                    if (!update.EulaAccepted)
                    {
                        update.AcceptEula();
                    }

                    string message = string.Empty;

                    if (update.InstallationBehavior.CanRequestUserInput)
                    {
                        addUpdate = false;
                        message   = Constants.CMessageUpdateCanRequestUserInput;
                        Logger.DebugFormat("KB='{0}', Title='{1}' can request user input and it will not be installed.", update.KBArticleIDs[0], update.Title);
                    }

                    if (addUpdate)
                    {
                        updatesToInstall.Add(update);
                    }
                    else
                    {
                        Logger.DebugFormat("KB='{0}', Title='{1}' was not installed because: {2}", update.KBArticleIDs[0], update.Title, message);
                        updateLog.Add(new UpdateInstallationLogEntry(update.KBArticleIDs[0], InstallationStatus.NotAttempted, message, DateTime.UtcNow));
                    }
                }
                else
                {
                    Logger.DebugFormat("KB='{0}', Title='{1}' was in the list of available updates but it was not downloaded.", update.KBArticleIDs[0], update.Title);
                    updateLog.Add(new UpdateInstallationLogEntry(update.KBArticleIDs[0], InstallationStatus.NotAttempted, Constants.CMessageUpdateNotDownloaded, DateTime.UtcNow));
                }
            }

            Logger.Debug("Installing the following updates:");
            foreach (IUpdate update in updatesToInstall)
            {
                var sb = new StringBuilder();
                foreach (var id in update.KBArticleIDs)
                {
                    sb.Append(id + ", ");
                }
                string kbArticleIds = sb.ToString();
                kbArticleIds = kbArticleIds.Remove(kbArticleIds.Length - 2);

                Logger.DebugFormat("  KB = '{0}', Title = '{1}', KB_Articles = '{2}'", update.KBArticleIDs[0], update.Title, kbArticleIds);
            }

            IInstallationResult installationResult;

            if (updatesToInstall.Count == 0)
            {
                Logger.Debug("No updates to install.");
                installationResult = new EmptyInstallationResult();
            }
            else
            {
                IUpdateInstaller installer = uSession.CreateUpdateInstaller();
                installer.Updates = updatesToInstall;

                installationResult = installer.Install();

                for (int i = 0; i < updatesToInstall.Count; i++)
                {
                    var result = installationResult.GetUpdateResult(i);
                    if (result.ResultCode == OperationResultCode.orcSucceeded)
                    {
                        updateLog.Add(new UpdateInstallationLogEntry(updatesToInstall[i].KBArticleIDs[0], InstallationStatus.Success, "", DateTime.UtcNow));
                    }
                    else
                    {
                        updateLog.Add(new UpdateInstallationLogEntry(updatesToInstall[i].KBArticleIDs[0], InstallationStatus.Failure
                                                                     , "Operation result: " + result.ResultCode
                                                                     , DateTime.UtcNow));
                    }
                }
            }

            Logger.Debug("END InstallUpdates");

            var processResult = new Result
            {
                InstallationResult    = installationResult,
                UpdateInstallationLog = updateLog
            };

            return(processResult);
        }
        private static IResult ConvertToResult(IInstallationResult result, IUpdateCollection updates)
        {
            if (result.ResultCode == OperationResultCode.orcAborted)
                return new UpdateOperationCancelled();

            if (result.ResultCode == OperationResultCode.orcSucceeded)
                return new NextResult();

            if (result.ResultCode == OperationResultCode.orcSucceededWithErrors)
                return new NextResult();

            if (updates.Count != 1)
                return new UpdateInstallFailed(result);

            var update = updates[0];
            return new UpdateInstallFailed(string.Format("{0} installation failed", update.Title), result.GetUpdateResult(0));
        }
Beispiel #16
0
        private void runUpdateProcedure()
        {
            lock (mSyncObject)
            {
                try
                {
                    Logger.Debug("START runUpdateProcedure");

                    mInactivated = false;

                    mStopServiceEvent.Reset();

                    logSystemInfo();

                    readLocalConfiguration();
                    readCentralConfiguration();
                    getExcludedUpdates();

                    if (mCentralConfiguration == null)
                    {
                        Logger.DebugFormat("Going idle - Customer name '{0}' was not found in the CustomerConfigurations section.", LocalConfig.CustomerName);
                        inactivate();
                        return;
                    }

                    if (isServerInExclusionList())
                    {
                        Logger.Debug("Going idle - Server is present in exclusion list.");
                        inactivate();
                        return;
                    }

                    if (!isWithinMaintenanceTimeFrame())
                    {
                        Logger.Debug("Going idle - Not within maintenance timeframe.");
                        inactivate();
                        return;
                    }

                    trySendSavedReports();

                    Logger.Debug("Fetching available updates.");
                    IUpdateCollection updates = WindowsUpdateClient.GetAvailableUpdates();

                    if (updates == null || updates.Count == 0)
                    {
                        Logger.Debug("Going idle - No updates retrieved from WUA.");
                        inactivate();
                        return;
                    }

                    var updatesToInstall = new UpdateCollectionClass();
                    var excludedUpdates  = new UpdateCollectionClass();

                    for (int i = 0; i < updates.Count; i++)
                    {
                        IUpdate update = updates[i];
                        if (!isUpdateExcluded(update))
                        {
                            updatesToInstall.Add(update);
                        }
                        else
                        {
                            excludedUpdates.Add(update);
                        }
                    }

                    if (updatesToInstall.Count == 0)
                    {
                        if (excludedUpdates.Count > 0)
                        {
                            var entries = UpdateInstallationLog.CreateExcludedLogEntries(excludedUpdates);
                            var log     = UpdateInstallationLog.Create(entries);
                            reportUpdateInstallationStatus(log, true);
                        }
                        Logger.Debug("Going idle - No new updates found.");
                        inactivate();
                        return;
                    }

                    Logger.Debug("Writing event log and monitoring API call.");
                    WindowsTaskHandler.WriteEventLog(Constants.CEventLogId, Constants.CEventLogDescription);
                    WindowsTaskHandler.CallMonitoringApi();

                    Logger.Debug("Installing updates.");
                    Result result = WindowsUpdateClient.InstallUpdates(updatesToInstall);

                    // add excluded updates to result
                    var excludedEntries = UpdateInstallationLog.CreateExcludedLogEntries(excludedUpdates);
                    result.UpdateInstallationLog.AddRange(excludedEntries);

                    reportStatus(result);

                    if (result.InstallationResult.RebootRequired)
                    {
                        Logger.Debug("Rebooting system.");
                        WindowsTaskHandler.RebootSystem();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
                finally
                {
                    if (!mInactivated)
                    {
                        inactivate();
                    }

                    Logger.Debug("FINISH runUpdateProcedure");
                    mStopServiceEvent.Set();
                }
            }
        }
Beispiel #17
0
 public WuStateInstallCompleted(IUpdateCollection updates, int hResult = 0) : base(WuStateId.InstallCompleted, "Installation Completed", updates, hResult)
 {
 }
Beispiel #18
0
 public WuStateDownloadCompleted(IUpdateCollection updates, int hResult = 0) : base(WuStateId.DownloadCompleted, "Download Completed", updates, hResult)
 {
 }
Beispiel #19
0
 public WuStateSearchCompleted(IUpdateCollection updates, int hResult = 0) : base(WuStateId.SearchCompleted, "Search Completed", updates, hResult)
 {
 }