Ejemplo n.º 1
0
        private void SetDataContext()
        {
            var context = new ObservableCollection <TrayStatus>();
            var apps    = CcmUtils.RequiredApps.Where(x => !x.InstallState.Equals("Installed") && x.Deadline > DateTime.Now).ToList();
            var updates = CcmUtils.GetUpdatesStatus();

            foreach (var obj in apps)
            {
                context.Add(new TrayStatus
                {
                    Name = obj.Name,
                    EvaluationStateText = "-",
                    ToolTipText         = obj.EvaluationStateText,
                    PercentComplete     = obj.PercentComplete,
                });
            }

            foreach (var obj in updates)
            {
                context.Add(new TrayStatus
                {
                    Name = obj.Name,
                    EvaluationStateText = obj.EvaluationStateText,
                    ToolTipText         = obj.EvaluationStateText,
                    PercentComplete     = obj.PercentComplete,
                });
            }

            SizeChanged           -= Window_SizeChanged;
            StatusGrid.ItemsSource = null;
            SizeChanged           += Window_SizeChanged;
            StatusGrid.ItemsSource = context;
        }
        private void BtInstall_Click(object sender, RoutedEventArgs e)
        {
            var ww = new WarningDialog
            {
                ShowActivated = true,
                Owner         = Application.Current.MainWindow,
            };

            ww.ShowDialog();

            if (ww.Abort)
            {
                return;
            }

            ScheduleGrid.IsEnabled     = false;
            BtInstall.IsEnabled        = false;
            DetailsExpander.IsExpanded = false;
            DetailsExpander.IsEnabled  = false;
            SetStatus(ScheduleStatus.Orange);

            SqlCe.SetAutoEnforceFlag(true);
            SqlCe.DeleteServiceSchedule();
            SqlCe.UpdateSupData("STD", string.Empty);

            CcmUtils.InstallAllAppsAndUpdates();

            if (_pipeClient == null)
            {
                _pipeClient = new PipeClient();
            }

            _pipeClient.Send("SetRed", "01DB94E3-90F1-43F4-8DDA-8AEAF6C08A8E");
            Globals.Log.Information("Sent icon switch command to tray.");
        }
        private void BtInstall_Click(object sender, RoutedEventArgs e)
        {
            BtInstall.IsEnabled = false;
            _isReschedule       = false;

            if (_app.IsIpuApplication)
            {
                try
                {
                    var pipeCmd = new PipeCommand {
                        Action = "InstallIpuApplication", AppId = _app.Id, AppRevision = _app.Revision
                    };
                    var jsonCmd = JsonConvert.SerializeObject(pipeCmd);
                    new PipeClient().Send(jsonCmd, "3A2CD127-D069-4CD5-994D-C481F4760748");
                }
                catch (Exception ex)
                {
                    Globals.Log.Error(ex.Message);
                }
            }
            else
            {
                CcmUtils.InstallApplication(_app);
            }
        }
Ejemplo n.º 4
0
        private void ApplyBranding()
        {
            var branding = CcmUtils.GetBranding();

            if (branding == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(branding.Logo))
            {
                Orglogo.Source = Utils.ToBitmapImage(branding.Logo);
                Globals.Log.Information("Loaded SC custom logo");
            }

            if (!string.IsNullOrEmpty(branding.Color))
            {
                BannerGrid.Background = (Brush) new BrushConverter().ConvertFrom(branding.Color);
                Globals.Log.Information("Loaded SC custom color");
            }

            if (!string.IsNullOrEmpty(branding.Orgname))
            {
                OrgName.Text = branding.Orgname;
                Globals.Log.Information("Loaded SC custom organization name");
            }
            else
            {
                OrgName.Text = string.Empty;
            }
        }
Ejemplo n.º 5
0
        private void BtRepair_Click(object sender, RoutedEventArgs e)
        {
            BtRepair.IsEnabled = false;
            _isReschedule      = false;
            var jobId = CcmUtils.RepairApplication(_app);

            Globals.Log.Information($"JobId Repair: '{jobId}' Application name: '{_app.Name}'");
        }
Ejemplo n.º 6
0
        private void WaitForCmClientOperational()
        {
            while (!CcmUtils.IsCmClientOperational())
            {
                Globals.Log.Information("Waiting 15 s for 'SMS_Client' to get operational.");
                System.Threading.Thread.Sleep(15000);
            }

            Globals.Log.Information("Detected 'SMS_Client' is operational continuing start.");
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RebootChecker"/> class.
        /// </summary>
        public static RebootReason RebootRequired(RestartChecks rebootChecks)
        {
            _pendingFileNameExclusions = rebootChecks.PendingFileNameExclusions;
            var rr      = new RebootReason();
            var logtext = new StringBuilder();

            if (rebootChecks.ConfigMgrClient)
            {
                if (CcmUtils.IsRebootPending().RebootPending)
                {
                    rr.ConfigMgrClient = true;
                    logtext.AppendLine("RebootWatcher detected SCCM Client RebootPending.");
                }
            }

            try
            {
                var rebootPendingKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending", false);
                if (rebootPendingKey != null && rebootChecks.ComponentBasedServicing)
                {
                    rr.ComponentBasedServicing = true;
                    logtext.AppendLine("RebootWatcher detected Component Based Servicing RebootPending.");
                }

                if (RegistryKeyExists(RegistryHive.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update", "RebootRequired") && rebootChecks.WindowsUpdate)
                {
                    rr.WindowsUpdate = true;
                    logtext.AppendLine("RebootWatcher detected Windows Update RebootPending.");
                }

                if (!IsRegKeyEmpty(RegistryHive.LocalMachine, @"SYSTEM\CurrentControlSet\Control\Session Manager", "PendingFileRenameOperations") && rebootChecks.PendingFileOperations)
                {
                    rr.PendingFileOperations = true;
                    logtext.AppendLine("RebootWatcher detected Pending File Name operations RebootPending.");
                }
            }
            catch (Exception ex)
            {
                _log.Error("RebootRequired", ex.Message);
            }

            if (!rr.Any)
            {
                logtext.AppendLine("RebootWatcher didn't detect any Pending Reboot operations.");
            }

            _log.Information(logtext.ToString());

            return(rr);
        }
Ejemplo n.º 8
0
        private void InstallIpuApplication(CMApplication cmApp)
        {
            if (_ipuRunning)
            {
                return;
            }

            _ipuRunning = true;

            Task.Run(() =>
            {
                _runningIpuApp = CcmUtils.GetSpecificApp(new ScheduledObject {
                    ObjectId = cmApp.Id, Revision = cmApp.Revision
                });

                if (_runningIpuApp == null)
                {
                    Globals.Log.Error($"Failed to get specific application, Id '{cmApp.Id}' Revision: '{cmApp.Revision}'");
                    _ipuRunning = false;
                    RegistryMethods.RemoveIpuIsRunning();
                    return;
                }

                var contentInfo = SqlCe.GetContentStatus(_runningIpuApp.DeploymentTypeId, _runningIpuApp.DeploymentTypeRevision);

                if (contentInfo != null)
                {
                    if (contentInfo.IsDownloaded && contentInfo.InstallTime < DateTime.Now.AddMinutes(-30))
                    {
                        Globals.Log.Information($"Detected request for upgrade, IpuApplication at '{contentInfo.Location}' - attempting upgrade.");
                        RegistryMethods.SetIpuIsRunning();
                        CcmUtils.InstallApplication(_runningIpuApp);
                    }
                    else
                    {
                        Globals.Log.Information($"Detected request for upgrade, IpuApplication at '{contentInfo.Location}' - content not yet downloaded or already installed, skipping.");
                        _ipuRunning = false;
                        RegistryMethods.RemoveIpuIsRunning();
                    }
                }
                else
                {
                    Globals.Log.Information($"Detected request for upgrade, IpuApplication DT Id '{_runningIpuApp.DeploymentTypeId}' Revision '{_runningIpuApp.DeploymentTypeRevision}' - content status returned Null, skipping.");
                    _ipuRunning = false;
                    RegistryMethods.RemoveIpuIsRunning();
                }
            });
        }
Ejemplo n.º 9
0
        private async Task EvaluateApplication()
        {
            BtInstall.IsEnabled   = false;
            BtUninstall.IsEnabled = false;
            BtRepair.IsEnabled    = false;
            BtSchedule.IsEnabled  = false;
            //TpPicker.Expanded = false;
            TpPicker.IsEnabled = false;
            ProgressbarEnforcement.Visibility = Visibility.Visible;

            CMApplication tmpApp = null;

            await Task.Run(() =>
            {
                try
                {
                    tmpApp = CcmUtils.GetSpecificApp(new ScheduledObject {
                        ObjectId = _app.Id, Revision = _app.Revision
                    }, false);
                    SetStatus(tmpApp);

                    do
                    {
                        System.Threading.Thread.Sleep(2500);
                        tmpApp = CcmUtils.GetSpecificApp(new ScheduledObject {
                            ObjectId = _app.Id, Revision = _app.Revision
                        }, false);
                        SetStatus(tmpApp);
                    }while (!(tmpApp.EvaluationState == 1 || tmpApp.EvaluationState == 3 || tmpApp.EvaluationState == 4 || tmpApp.EvaluationState == 16 || tmpApp.EvaluationState == 24 || tmpApp.EvaluationState == 25));
                }
                catch
                {
                    Globals.MainWnd.SpAvailableApps.Children.Remove(this);
                }
            });

            ProgressbarEnforcement.Visibility = Visibility.Hidden;
            BtInstall.IsEnabled   = !tmpApp.InstallState.Equals("Installed");
            BtUninstall.IsEnabled = tmpApp.InstallState.Equals("Installed");
            BtRepair.IsEnabled    = tmpApp.InstallState.Equals("Installed") && _app.AllowedActions.Contains("Repair");
            TpPicker.IsEnabled    = true;
            BtSchedule.IsEnabled  = true;
            _app = CcmUtils.GetSpecificApp(new ScheduledObject {
                ObjectId = _app.Id, Revision = _app.Revision
            });
        }
        private void BtInstall_Click(object sender, RoutedEventArgs e)
        {
            BtInstall.IsEnabled  = false;
            BtSchedule.IsEnabled = false;
            TpPicker.IsEnabled   = false;

            SqlCe.UpdateSupData("STD", string.Empty);

            if (_isReschedule)
            {
                SqlCe.SetEnforcedFlag(_scheduleId);
            }

            SqlCe.SetUpdatesInstallStatusFlag(true);
            CcmUtils.ExecuteInstallUpdates(true);
            SetStatus(ScheduleStatus.Green);
            StatusText.Text = "Installation has been initiated.";
        }
Ejemplo n.º 11
0
        private void LookForNewSettings()
        {
            var settingFile = string.Empty;

            var collVars = CcmUtils.GetSettingsVariables();

            if (collVars.Count() < 2)
            {
                return;
            }

            collVars = collVars.OrderBy(x => x.Name).ToList();

            foreach (var collVar in collVars)
            {
                var tmp = GetCDataFromString(collVar.Value);

                if (tmp == null)
                {
                    return;
                }

                settingFile += DecryptVariableValue(tmp).Trim().TrimEnd('\0');
            }

            if (!string.IsNullOrEmpty(settingFile))
            {
                settingFile = StringCompressor.DecompressString(settingFile);
            }

            if (settingFile.StartsWith("<?xml") && settingFile.EndsWith("</Settings>") && !settingFile.Equals(_oldSettings))
            {
                SettingsUtils.WriteStringToSettingsFile(settingFile);
                Globals.Log.Information("Wrote new settings to 'Settings.xml'");
                _oldSettings = settingFile;
            }
            else
            {
                Globals.Log.Information("No new settings found in Policy");
            }
        }
Ejemplo n.º 12
0
        private void EnforcePump()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        var scheduledobject = _objectsToEnforce.Take();
                        _allowFastReboot    = scheduledobject.IsAutoSchedule;

                        SqlCe.SetEnforcedFlag(scheduledobject.Id);

                        if (scheduledobject.EnforcementType.Equals("APP"))
                        {
                            var cmapp = CcmUtils.GetSpecificApp(scheduledobject);

                            if (cmapp == null)
                            {
                                Globals.Log.Warning($"A scheduled enforcement '{scheduledobject.ObjectId}/{scheduledobject.Revision}' could not be performed. Deployment has been removed or changed?");
                                continue;
                            }

                            if (scheduledobject.Action.Equals("I"))
                            {
                                if (cmapp.IsIpuApplication && _settings.IpuApplication.ShowDialog1 && UnsafeNativeMethods.IsUserLoggedOn())
                                {
                                    if (UnsafeNativeMethods.Run(_userApp, "/ShowIpuDialog1", true) == 0)
                                    {
                                        //RegistryMethods.SetIpuIsRunning();
                                        //CcmUtils.InstallApplication(cmapp);
                                        InstallIpuApplication(cmapp);
                                        Globals.Log.Information($"User pressed 'Install' feature updated '{cmapp.Name}'");
                                    }
                                    else
                                    {
                                        SqlCe.DeleteAppSchedule(cmapp.Id, cmapp.Revision);
                                        Globals.Log.Warning($"User aborted a scheduled Windows feature upgrade '{cmapp.Name}'");
                                    }
                                }
                                else if (cmapp.IsIpuApplication)
                                {
                                    //RegistryMethods.SetIpuIsRunning();
                                    InstallIpuApplication(cmapp);
                                    //CcmUtils.InstallApplication(cmapp);
                                }
                                else
                                {
                                    CcmUtils.InstallApplication(cmapp);
                                }
                            }
                            else if (scheduledobject.Action.Equals("R"))
                            {
                                CcmUtils.RepairApplication(cmapp);
                            }
                            else
                            {
                                CcmUtils.UninstallApplication(cmapp);
                            }
                        }
                        else if (scheduledobject.EnforcementType.Equals("SUP"))
                        {
                            Globals.Log.Information("Installing updates, disabling component servicing reboot detection until rebooted.");
                            _rebootServicingCheck = false;
                            Set_SupCheckBlocked();
                            SqlCe.UpdateSupData("STD", string.Empty);
                            CcmUtils.ExecuteInstallUpdates(true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Globals.Log.Error(ex.Message);
                    }
                }
            });
        }
Ejemplo n.º 13
0
        private void EnforcementTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _enforcementTimer.Stop();
            _enforcementTimer.Interval = AutoInterval();
            _enforcementTimer.Start();

            SaveAssignmentsToDB();

            if (SqlCe.GetAutoEnforceFlag())
            {
                Globals.Log.Information("Checking Service cycle status.");

                var reqApps        = CcmUtils.RequiredApps.Where(x => !x.InstallState.Equals("Installed") && x.EvaluationState == 3 && !x.IsIpuApplication).ToList();
                var pendingUpdates = CcmUtils.Updates.ToList();

                if (reqApps.Count() == 0 && pendingUpdates.Count() == 0 && !(CcmUtils.IsUpdatesEnforcing() || CcmUtils.IsAppsEnforcing()) && !RebootChecker.RebootRequired(new RestartChecks()
                {
                    PendingFileOperations = true
                }).Any)
                {
                    Globals.Log.Information("Service cycle - Resetting Auto Enforce Flag, nothing left to enforce and no reboot pending.");
                    SqlCe.SetAutoEnforceFlag(false);
                    _pipeClient.Send("SetBlue", "01DB94E3-90F1-43F4-8DDA-8AEAF6C08A8E");
                    _iEnforcementInterval = 5;

                    if (UnsafeNativeMethods.IsUserLoggedOn())
                    {
                        UnsafeNativeMethods.Run(_userApp, $"/ToastServiceEndNotification", false);
                    }

                    if (_settings.LegalNotice.UseLegalNotice)
                    {
                        Reg.RemoveLegalNotice();
                    }

                    return;
                }
                else if (CcmUtils.IsRebootPending().HardRebootPending&& !(CcmUtils.IsUpdatesEnforcing() || CcmUtils.IsAppsEnforcing()))
                {
                    Globals.Log.Information("Service cycle - Pending hard reboot detected - restarting computer.");

                    if (UnsafeNativeMethods.IsUserLoggedOn())
                    {
                        UnsafeNativeMethods.Run(_userApp, $"/ToastServiceRestartNotification", false);
                        RestartComputer();
                    }
                    else
                    {
                        RestartComputer(true);
                    }

                    return;
                }
                else if (!(CcmUtils.IsUpdatesEnforcing() || CcmUtils.IsAppsEnforcing()) && (reqApps.Count() != 0 || pendingUpdates.Count() != 0))
                {
                    Globals.Log.Information("Service cycle - Cycle running but required installations not enforcing - pushing enforcement.");
                    CcmUtils.InstallAllAppsAndUpdates();
                    return;
                }
                else if (reqApps.Count() == 0 && pendingUpdates.Count() == 0 && !(CcmUtils.IsUpdatesEnforcing() || CcmUtils.IsAppsEnforcing()) && RebootChecker.RebootRequired(new RestartChecks()
                {
                    PendingFileOperations = true
                }).Any)
                {
                    Globals.Log.Information("Service cycle - nothing left to enforce but a pending reboot (Any) was detected - restarting computer.");

                    if (UnsafeNativeMethods.IsUserLoggedOn())
                    {
                        UnsafeNativeMethods.Run(_userApp, $"/ToastServiceRestartNotification", false);
                        RestartComputer();
                    }
                    else
                    {
                        RestartComputer(true);
                    }

                    return;
                }

                Globals.Log.Information("Service cycle not yet finished.");

                return;
            }

            if (CcmUtils.IsUpdatesEnforcing())
            {
                return;
            }

            var rs = SqlCe.GetRestartSchedule();

            if (rs != null)
            {
                if (rs.RestartTime <= DateTime.Now)
                {
                    SqlCe.DeleteRestartSchedule();

                    if (UnsafeNativeMethods.IsUserLoggedOn())
                    {
                        UnsafeNativeMethods.Run(_userApp, $"/ShowRestartWindow", false);
                        Globals.Log.Information($"Launched Restart Window.");
                    }
                    else
                    {
                        RestartComputer(true);
                    }

                    return;
                }
            }

            RestartRequired();

            if (CcmUtils.IsRebootPending().HardRebootPending)
            {
                Globals.Log.Warning($"Detected pending hard reboot - postponing further enforcement(s)");
                return;
            }

            try
            {
                var serviceSchedule = CommonUtils.GetNextServiceCycleAsDateTime();

                if (serviceSchedule != null)
                {
                    if (serviceSchedule <= DateTime.Now)
                    {
                        SqlCe.SetAutoEnforceFlag(true);
                        _pipeClient.Send("SetRed", "01DB94E3-90F1-43F4-8DDA-8AEAF6C08A8E");
                        CcmUtils.InstallAllAppsAndUpdates();
                        _iEnforcementInterval = 1;
                        _enforcementTimer.Stop();
                        _enforcementTimer.Interval = AutoInterval();
                        _enforcementTimer.Start();

                        if (_settings.LegalNotice.UseLegalNotice)
                        {
                            Reg.SetLegalNotice(_settings.LegalNotice);
                        }

                        SqlCe.DeleteServiceSchedule();
                        SqlCe.UpdateSupData("STD", string.Empty);

                        if (UnsafeNativeMethods.IsUserLoggedOn())
                        {
                            UnsafeNativeMethods.Run(_userApp, $"/ToastServiceInitNotification", false);
                        }

                        Globals.Log.Information($"Found and triggered a Service Schedule (Install All)");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.Log.Error(ex.Message);
            }

            try
            {
                var sch = SqlCe.GetDueSchedules();

                if (sch.Count() > 0)
                {
                    Globals.Log.Information($"Found {sch.Count()} objects due for enforcement.");
                    sch.ForEach(x => _objectsToEnforce.Add(x));
                }
                else
                {
                    Globals.Log.Information($"No scheduled enforcements found at this time");
                }
            }
            catch (Exception ex)
            {
                Globals.Log.Error(ex.Message);
            }

            try
            {
                if (CcmUtils.IsApplicationEvaluationRequired())
                {
                    CcmUtils.EvaluateAllPolicies();
                }
            }
            catch (Exception ex)
            {
                Globals.Log.Error(ex.Message);
            }
        }
Ejemplo n.º 14
0
        protected override void OnStart(string[] args)
        {
            Globals.Log.Information("Service is starting");
            WaitForCcmExec();
            WaitForCmClientOperational();
            SqlCe.MaintainDatabase();
            _pipeServer = new PipeServer();
            _pipeServer.Listen("3A2CD127-D069-4CD5-994D-C481F4760748");
            _pipeServer.PipeMessage += PipeServer_PipeMessage;

            _settings = SettingsUtils.Settings;

            if (_settings.IsDefault)
            {
                SettingsUtils.WriteSettingsToFile();
                Globals.Log.Warning("Failed to load settings from file, created new 'Settings.xml'. If this is the first start after installation, it's expected.");
            }

            _serviceSettings = _settings.ServiceConfig;

            if (SqlCe.GetAutoEnforceFlag())
            {
                Globals.Log.Information("Auto Enforce Flag is true, enforcing all.");

                _iEnforcementInterval = 1;
                CcmUtils.InstallAllAppsAndUpdates();

                if (_settings.LegalNotice.UseLegalNotice)
                {
                    Reg.SetLegalNotice(_settings.LegalNotice);
                }
            }

            SqlCe.SetUpdatesInstallStatusFlag(false);
            SaveAssignmentsToDB();

            _enforcementTimer.AutoReset = false;
            _enforcementTimer.Elapsed  += EnforcementTimer_Elapsed;
            _enforcementTimer.Interval  = AutoInterval();
            _enforcementTimer.Start();

            _ccmWmiEventListener = new CcmWmiEventListener();
            _ccmWmiEventListener.OnNewApplication += CcmWmiEventListener_OnNewApplication;
            _ccmWmiEventListener.OnNewUpdate      += CcmWmiEventListener_OnNewUpdate;

            FeedEnforcementsPump();
            EnforcePump();
            ConfirmPump();

            if (_serviceSettings.HardSuppressSCNotifications)
            {
                RenameSCNotification();
            }

            if (UnsafeNativeMethods.IsUserLoggedOn())
            {
                UnsafeNativeMethods.Run(_trayApp, null, false);
            }

            Globals.Log.Information("Service sucessfully started.");
        }
 private void BtRepair_Click(object sender, RoutedEventArgs e)
 {
     BtRepair.IsEnabled = false;
     _isReschedule      = false;
     CcmUtils.RepairApplication(_app);
 }
        public override void OnActivated(string invokedArgs, NotificationUserInput userInput, string appUserModelId)
        {
            Application.Current.Dispatcher.Invoke(delegate
            {
                // Tapping on the top-level header launches with empty args
                if (invokedArgs.Length == 0)
                {
                    // Perform a normal launch
                    if (Application.Current.Windows.Count == 0)
                    {
                        Application.Current.Shutdown();
                    }
                    return;
                }

                // Parse the query string (using NuGet package QueryString.NET)
                var args = QueryString.Parse(invokedArgs);

                if (args["appidrevision"].Equals("close"))
                {
                    if (Application.Current.Windows.Count == 0)
                    {
                        Application.Current.Shutdown();
                    }

                    return;
                }
                else if (args["appidrevision"].Equals("reboot"))
                {
                    switch (args["action"])
                    {
                    case "restart":

                        Globals.Log.Information("User pressed Toast button 'Restart now' (Restart)");

                        try
                        {
                            var conf = Globals.Settings.RestartConfig;

                            Process.Start(new ProcessStartInfo
                            {
                                FileName  = _userApp,
                                Arguments = $"/ShowRestartWindow",
                            });
                        }
                        catch (Exception ex)
                        {
                            Globals.Log.Error(ex.Message);
                        }

                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }

                        break;

                    case "schedulerestart":

                        Globals.Log.Information("User pressed Toast button 'Schedule' (Restart)");

                        OpenWindowIfNeeded();
                        Globals.MainWnd.RebootScheduler();

                        break;

                    case "remind":

                        Globals.Log.Information("User pressed Toast button 'Remind me later' (Restart)");

                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }

                        break;
                    }
                }
                else if (args["appidrevision"].Equals("sup"))
                {
                    switch (args["action"])
                    {
                    // Open the image
                    case "install":
                        Globals.Log.Information("User pressed Toast button 'Install' (Sup)");

                        var jsonSup = SqlCe.GetSupData("STD");
                        var sups    = JsonConvert.DeserializeObject <List <Update> >(jsonSup);

                        //var sups = CcmUtils.GetUpdates();
                        if (sups.Count() > 0)
                        {
                            CustomToasts.NotifySupInstallationStart();
                            CcmUtils.ExecuteInstallUpdates(true);
                        }

                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }

                        break;

                    // Background: Quick reply to the conversation
                    case "schedule":

                        Globals.Log.Information("User pressed Toast button 'Schedule' (Sup)");
                        // Make sure we have a window open and in foreground
                        OpenWindowIfNeeded();

                        if (Globals.Settings.ToastNotifyNewSupSettings.OpenWizardTabOnSchedule)
                        {
                            Globals.MainWnd.OpenWizadTab();
                        }
                        else
                        {
                            Globals.MainWnd.AddSupScheduler();
                        }

                        break;

                    case "postpone":

                        Globals.Log.Information("User pressed Toast button 'Postpone' (Sup)");

                        // Make sure we have a window open and in foreground
                        //OpenWindowIfNeeded();
                        // And send this message

                        //(Application.Current.Windows[0] as MainWindow).ShowConversation("postpone" + args["appidrevision"]);
                        //Application.Current.Shutdown();
                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }
                        break;

                    default:
                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }
                        break;
                    }
                }
                else
                {
                    // See what action is being requested
                    switch (args["action"])
                    {
                    // Open the image

                    /*
                     * case "install":
                     *  Globals.Log.Information("User pressed Toast button 'Install' (App)");
                     *
                     *  var appdata = args["appidrevision"].Split(';');
                     *  var app = CcmUtils.GetSpecificApp(new ScheduledObject { ObjectId = appdata[0], Revision = appdata[1] });
                     *
                     *  if (app != null)
                     *  {
                     *      CustomToasts.NotifyAppInstallationStart(app);
                     *      CcmUtils.InstallApplication(app);
                     *  }
                     *
                     *  if (Application.Current.Windows.Count == 0)
                     *  {
                     *      Application.Current.Shutdown();
                     *  }
                     *
                     *  break;
                     */

                    // Background: Quick reply to the conversation
                    case "schedule":

                        Globals.Log.Information("User pressed Toast button 'Schedule' (App)");
                        // Make sure we have a window open and in foreground
                        OpenWindowIfNeeded();

                        if (Globals.Settings.ToastNotifyNewApplicationSettings.OpenWizardTabOnSchedule)
                        {
                            Globals.MainWnd.OpenWizadTab();
                        }
                        else
                        {
                            Globals.MainWnd.AddAppScheduler();
                        }

                        break;

                    case "scheduleipu":

                        Globals.Log.Information("User pressed Toast button 'Schedule' (IpuApp)");
                        // Make sure we have a window open and in foreground
                        OpenWindowIfNeeded();

                        Globals.MainWnd.AddIpuAppScheduler();

                        break;

                    case "postpone":

                        Globals.Log.Information("User pressed Toast button 'Postpone' (App)");

                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }

                        break;

                    default:

                        if (Application.Current.Windows.Count == 0)
                        {
                            Application.Current.Shutdown();
                        }

                        break;
                    }
                }
            });
        }
Ejemplo n.º 17
0
        private void SaveAssignmentsToDB()
        {
            var assignments = CcmUtils.GetAssignments();

            SqlCe.SaveAssignmentsToDB(assignments);
        }
Ejemplo n.º 18
0
        private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            var newEvent = e.NewEvent;

            if (newEvent == null)
            {
                return;
            }

            if (!(newEvent["ClassName"].ToString().Equals("CCM_Application") || newEvent["ClassName"].ToString().Equals("CCM_SoftwareUpdate")))
            {
                return;
            }

            try
            {
                var eventObject = (IResultObject) new WmiResultObject(newEvent);
                var target      = eventObject["TargetInstancePath"].StringValue;
                var targetparts = target.Split(',');

                switch (eventObject["ActionType"].IntegralValue)
                {
                case 23:

                    OnStatusChange?.Invoke(this, new CcmWmiEventargument
                    {
                        Id              = targetparts[0].Replace("CCM_Application.Id=", string.Empty).Replace("\"", string.Empty),
                        Revision        = targetparts[1].Replace("Revision=", string.Empty).Replace("\"", string.Empty),
                        IsMachineTarget = targetparts[2].Replace("IsMachineTarget=", string.Empty).Equals("1"),
                    });
                    break;

                case 12:

                    if (_dt12 > DateTime.Now)
                    {
                        return;
                    }

                    _dt12 = DateTime.Now.AddMinutes(4);

                    OnNewUpdate?.Invoke(this, new NewUpdateEventArg {
                        ActionId = eventObject["ActionType"].IntegralValue
                    });
                    break;

                case 21:
                case 28:

                    if (_dt21 > DateTime.Now || _isEvaluation)
                    {
                        return;
                    }

                    _isEvaluation = true;

                    if (!string.IsNullOrEmpty(eventObject["TargetInstancePath"].StringValue))
                    {
                        var app = CcmUtils.GetSpecificApp(new ScheduledObject
                        {
                            ObjectId = targetparts[0].Replace("CCM_Application.Id=", string.Empty).Replace("\"", string.Empty),
                            Revision = targetparts[1].Replace("Revision=", string.Empty).Replace("\"", string.Empty),
                        });

                        if (app != null)
                        {
                            if (app.Deadline > DateTime.Now.AddMinutes(30))
                            {
                                _dt21 = DateTime.Now.AddMinutes(4);
                                OnNewApplication?.Invoke(this, new NewApplicationEventArg {
                                    ActionId = eventObject["ActionType"].IntegralValue
                                });
                            }
                        }
                    }

                    _isEvaluation = false;
                    break;
                }

                eventObject.Dispose();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }
Ejemplo n.º 19
0
        private bool RestartRequired()
        {
            if (CcmUtils.IsUpdatesEnforcing() || CcmUtils.IsAppsEnforcing())
            {
                Globals.Log.Information("Detected ongoing installation, suppressing reboot checks.");
                return(false);
            }

            var checks = _settings.RestartChecks;

            var updatesStatus = _rebootServicingCheck && !SqlCe.GetUpdatesInstallStatusFlag();

            if (!updatesStatus)
            {
                checks.ComponentBasedServicing = updatesStatus;
                checks.PendingFileOperations   = updatesStatus;
                checks.WindowsUpdate           = updatesStatus;
            }

            var result = RebootChecker.RebootRequired(checks);
            var rs     = SqlCe.GetRestartSchedule();

            if (!result.Any)
            {
                SqlCe.DeleteRestartSchedule();
            }
            else if (rs != null)
            {
                if (rs.IsAcknowledged)
                {
                    return(false);
                }
            }

            if (result.ConfigMgrClient && (_allowFastReboot || !UnsafeNativeMethods.IsUserLoggedOn()))
            {
                SqlCe.DeleteRestartSchedule();

                SqlCe.SetRestartSchedule(new RestartSchedule
                {
                    DeadLine       = DateTime.Now.MinutePrecission().AddMinutes(5),
                    RestartTime    = DateTime.Now.MinutePrecission().AddMinutes(5),
                    IsAcknowledged = true,
                    IsExpress      = true,
                });

                return(result.Any);
            }

            if (result.Any && _rebootToastDelay-- <= 1)
            {
                if (rs == null)
                {
                    SqlCe.SetRestartSchedule(new RestartSchedule
                    {
                        DeadLine       = DateTime.Today.AddDays(_serviceSettings.RestartDeadlineAfterInstall.InDays).AddHours(_serviceSettings.RestartDeadlineAfterInstall.AtHour),
                        RestartTime    = DateTime.Today.AddDays(_serviceSettings.RestartDeadlineAfterInstall.InDays).AddHours(_serviceSettings.RestartDeadlineAfterInstall.AtHour),
                        IsAcknowledged = false,
                        IsExpress      = false,
                    });
                }

                if (SqlCe.GetAutoEnforceFlag())
                {
                    Globals.Log.Information($"Detected auto enforce flag 'true', skipping reboot toast.");
                }
                else if (!UnsafeNativeMethods.IsSessionLocked())
                {
                    UnsafeNativeMethods.Run(_userApp, $"/ToastReboot", false);
                }
                else
                {
                    Globals.Log.Information($"Detected a locked or non existing user session, a Toast notification was suppressed.");
                }

                _rebootToastDelay = _fiveMinuteIntervalsPerDay / _serviceSettings.NumberOfRestartToastsPerDay;
            }

            return(result.Any);
        }