public static Task StopProcessAsync(IProcess process)
        {
            if (process == null)
                return Task.FromResult<object>(null);

            return Task.Run(() => process.Kill());
        }
        void IProcessMonitor.Output(IProcess process, string line)
        {
            if (line == null)
                throw new ArgumentNullException(nameof(line));

            _Events.Add(new ProcessStandardOutputEvent(process.ExecutionDuration, DateTime.Now, line));
        }
예제 #3
0
 public ProcessInformation(IntPtr processHandle, int processId, IntPtr threadHandle, int threadId)
 {
     _process = new Process(new ProcessHandle(processHandle));
     _processId = processId;
     _thread = new Thread(new ThreadHandle(threadHandle));
     _threadId = threadId;
 }
        public void Init()
        {
            _createPositionMock = new Mock<IProcess<CreatePositionParams, PositionDisplayViewModel>>();
            _createPositionMock.Setup(x => x.Execute(It.IsAny<CreatePositionParams>())).Returns(new PositionDisplayViewModel());

            _verifyTokenMock = new Mock<IProcess<VerifyUserLinkedInAccessTokenParams, UserAccessTokenResultViewModel>>();
            _verifyTokenMock.Setup(x => x.Execute(It.IsAny<VerifyUserLinkedInAccessTokenParams>())).Returns(new UserAccessTokenResultViewModel { AccessTokenValid = true });

            _createCompanyCmdMock = CommandTestUtils.GenerateCreateCompanyCommandMock();
            _createCompanyCmdMock.Setup(x => x.Execute()).Returns(new Company { Id = NEW_COMPANY_ID });

            _companyQueryMock = QueryTestUtils.GenerateCompanyByIdQueryMock();
            _process = new LinkedInPositionSearchProcesses(_context, _verifyTokenMock.Object, _createCompanyCmdMock.Object, _createPositionMock.Object, _companyQueryMock.Object);

            // Initialize user with test (but valid) access token data
            _user = new User { LastVisitedJobSearch = new JobSearch() };
            var oauth = new OAuthData
            {
                Token = "bfcf3fe4-b4d4-4f37-9d32-292ae9d45347",
                Secret = "f66673b2-5877-4fbf-80e0-3826ca9f7eed",
                TokenProvider = TokenProvider.LinkedIn,
                TokenType = TokenType.AccessToken,
            };

            oauth.LinkedInUsers.Add(_user);
            _user.LinkedInOAuthData = oauth;
            _context.Users.Add(_user);
            _context.OAuthData.Add(oauth);
            _context.SaveChanges();
        }
 public PowerShellConsole(IPackage package, IProcess process, IFileSystem fileSystem, IPackageFile packageFile)
 {
     this.fileSystem = fileSystem;
     this.package = package;
     this.process = process;
     this.packageFile = packageFile;
 }
        public CommunicationViewModel(
            IProcess process, PacketListViewModel packetList, PacketDetailsViewModel packetDetails, IBus bus)
            : base(bus)
        {
            Contract.Requires<ArgumentNullException>(process != null);
            Contract.Requires<ArgumentNullException>(packetList != null);
            Contract.Requires<ArgumentNullException>(packetDetails != null);
            Contract.Requires<ArgumentNullException>(bus != null);

            this.process = process;
            this.packetList = packetList;
            this.packetDetails = packetDetails;

            Func<string> getTitle =
                () =>
                "Communication: " + (this.process.Player != null ? this.process.Player.Name : this.process.DisplayName);
            this.Title = getTitle();
            PropertyChangedEventManager.AddHandler(
                this.process, (sender, args) => this.Title = getTitle(), string.Empty);
            PropertyChangedEventManager.AddHandler(
                this.packetList,
                (sender, args) => this.packetDetails.Packet = this.packetList.SelectedPacket,
                "SelectedPacket");
            this.Bus.Subscribe(this.packetList);
        }
        public void Init()
        {
            _verifyTokenMock = new Mock<IProcess<VerifyUserLinkedInAccessTokenParams,UserAccessTokenResultViewModel>>();
            _verifyTokenMock.Setup(x => x.Execute(It.IsAny<VerifyUserLinkedInAccessTokenParams>())).Returns(new UserAccessTokenResultViewModel { AccessTokenValid = true });

            _createPositionMock = new Mock<IProcess<CreatePositionParams, PositionDisplayViewModel>>();
            var createCompanyCmd = new CreateCompanyCommand(_serviceFactory.Object);

            _process = new LinkedInPositionSearchProcesses(_context, _verifyTokenMock.Object, createCompanyCmd, _createPositionMock.Object, null);

            // Initialize user with test (but valid) access token data
            _user = new User();
            var oauth = new OAuthData
            {
                Token = "bfcf3fe4-b4d4-4f37-9d32-292ae9d45347",
                Secret = "f66673b2-5877-4fbf-80e0-3826ca9f7eed",
                TokenProvider = TokenProvider.LinkedIn,
                TokenType = TokenType.AccessToken,
            };

            oauth.LinkedInUsers.Add(_user);
            _user.LinkedInOAuthData = oauth;
            _context.Users.Add(_user);
            _context.OAuthData.Add(oauth);
            _context.SaveChanges();
        }
예제 #8
0
        public static Unit Restart()
        {
            ObservableRouter.Restart();

            ActorConfig config = ActorConfig.Default;

            if (system != null)
            {
                system.Shutdown();
            }

            Store = Map(Tuple("", (IProcess)new NullProcess()));

            // Root
            root        = new Actor<Unit, object>(new ProcessId(), config.RootProcessName, Process.pub);

            // Top tier
            system      = new Actor<Unit, object>(root.Id, config.SystemProcessName, Process.pub);
            self = user = new Actor<Unit, object>(root.Id, config.UserProcessName, Process.pub);

            // Second tier
            deadLetters = new Actor<Unit, object>(system.Id, config.DeadLettersProcessName, Process.pub);

            noSender    = new Actor<Unit, object>(system.Id, config.NoSenderProcessName, Process.pub);
            registered  = new Actor<Unit, object>(system.Id, config.RegisteredProcessName, Process.pub);

            return unit;
        }
        public void SpawnTrinket(IProcess targetProcess, TrinketSpawnConfiguration trinketSpawnConfiguration)
        {
            var components = new List<TrinketComponent>();
             if (trinketSpawnConfiguration.IsDebugEnabled) {
            components.Add(new DebugComponent());
             }
             if (trinketSpawnConfiguration.IsFileSystemHookingEnabled) {
            components.Add(new FilesystemComponent(trinketSpawnConfiguration.IsFileSystemOverridingEnabled));
             }
             if (trinketSpawnConfiguration.Name != null) {
            components.Add(new NameComponent(trinketSpawnConfiguration.Name));
             }
             if (trinketSpawnConfiguration.IsLoggingEnabled) {
            components.Add(new VerboseLoggerComponent());
             }
             if (trinketSpawnConfiguration.IsCommandingEnabled) {
            components.Add(new CommandListComponent(trinketSpawnConfiguration.CommandList));
             }
             if (trinketSpawnConfiguration.IsProcessSuspensionEnabled) {
            components.Add(new ProcessSuspensionComponent(trinketSpawnConfiguration.SuspendedProcessNames));
             }

             var targetProcessId = targetProcess.Id;
             var startupConfiguration = new TrinketStartupConfigurationImpl(targetProcessId, components);
             using (var ms = streamFactory.CreateMemoryStream()) {
            pofSerializer.Serialize(ms.Writer, startupConfiguration);
            exeggutorService.SpawnHatchling(
               kTrinketEggName,
               new SpawnConfiguration {
                  Arguments = ms.ToArray(),
                  InstanceName = kTrinketEggName + "_" + targetProcessId,
                  StartFlags = HatchlingStartFlags.StartAsynchronously
               });
             }
        }
예제 #10
0
 public async Task StopProcess(IProcess process)
 {
     string exePath = process.ExePath;
     try
     {
         if (!await StopGracefully(process))
         {
             Trace.TraceInformation(
                 "Process has not exited gracefully or is not listening to the stop event, let's try to close the main window");
             if (!await Close(process))
             {
                 Trace.TraceInformation("The host process would not close, attempting to kill");
                 await process.Kill();
                 Trace.TraceInformation("The host process was killed");
             }
             else
             {
                 Trace.TraceInformation("Process exited with CloseMainWindow");
             }
         }
         else
         {
             Trace.TraceInformation("Process exited gracefully");
         }
         await process.ReleaseResources();
         await Task.Delay(ReleaseResourcesDelayMilliseconds); // allowing the os some time to release resources
     }
     catch (Exception ex)
     {
         // there is nothing more we can do; we'll swallow the exception and log an error
         Trace.TraceError("{0} host process could not be killed. Exception was: {1}", exePath, ex);
     }
 }
        public void Can_Get_Decrypted_Credentials()
        {
            // Setup
            string decryptedString = "decrypted string";
            string username = "******";
            string encryptedString = "w6AnE3eWg1urf54jkTejCku+JT3gPT78e9MAkUa8fsI=";
            byte[] expectedKey = Convert.FromBase64String("LHRqdBadRUVh3cdMYoeuYVng/qQlgvBReEAg5JvO48E=");
            byte[] expectedIV = Convert.FromBase64String("CB7hOrmWxs2riRF26Imn7w==");
            byte[] expectedEncryptedPass = Convert.FromBase64String(encryptedString);

            var encryptionMock = new Mock<EncryptionUtils>();
            encryptionMock.Setup(x => x.DecryptStringFromBytes_AES(expectedEncryptedPass, expectedKey, expectedIV)).Returns(decryptedString);

            var user = new User();
            var jigsaw = new JigsawAccountDetails { AssociatedUser = user, Username = username, EncryptedPassword = encryptedString };
            _context.JigsawAccountDetails.Add(jigsaw);
            _context.SaveChanges();

            _process = new JigsawAuthProcesses(_context, encryptionMock.Object);

            // Act
            var result = _process.Execute(new GetUserJigsawCredentialsParams { RequestingUserId = user.Id });

            // Verify
            Assert.IsNotNull(result, "Process returned a null result");
            Assert.AreEqual(username, result.JigsawUsername, "An incorrect username was returned");
            Assert.AreEqual(decryptedString, result.JigsawPassword, "An incorrect password was returned");
        }
예제 #12
0
		public static void RemoveProcess(IProcess Proc)
		{
			lock (SyncObject)
			{
				ActiveProcesses.Remove(Proc);
			}
		}
        public void Can_Save_Jigsaw_Encrypted_Credentials_For_User()
        {
            // Setup
            string username = "******";
            string unencryptedPass = "******";
            byte[] expectedKey = Convert.FromBase64String("LHRqdBadRUVh3cdMYoeuYVng/qQlgvBReEAg5JvO48E=");
            byte[] expectedIV = Convert.FromBase64String("CB7hOrmWxs2riRF26Imn7w==");

            var encryptionMock = new Mock<EncryptionUtils>();
            encryptionMock.Setup(x => x.EncryptStringToBytes_AES(unencryptedPass, expectedKey, expectedIV)).Returns(new byte[] { Convert.ToByte(true) });

            var user = new User();
            _context.Users.Add(user);
            _context.SaveChanges();

            _process = new JigsawAuthProcesses(_context, encryptionMock.Object);

            // Act
            var result = _process.Execute(new SaveJigsawUserCredentialsParams
            {
                RequestingUserId = user.Id,
                JigsawUsername = username,
                JigsawPassword = unencryptedPass
            });

            // Verify
            Assert.IsNotNull(result, "Process returned a null result");
            Assert.IsTrue(result.WasSuccessful, "Process' result was not successful");

            var jigsaw = _context.JigsawAccountDetails.SingleOrDefault();
            Assert.IsNotNull(jigsaw, "No jigsaw credentials entity was created");
            Assert.AreEqual(username, jigsaw.Username, "Jigsaw username was incorrect");
            Assert.AreEqual(Convert.ToBase64String(new byte[] { Convert.ToByte(true) }), jigsaw.EncryptedPassword, "Jigsaw password was incorrect");
        }
 public TestController(IProcess _Process)
     : base(_Process)
 {
     ui = new UserInterface();
     reference = 2.5;
     ui.textBox1.Text = reference.ToString();
 }
        public void Jigsaw_Credentials_Gets_Updated_If_One_Exists_For_User()
        {
            // Setup
            var encryptionMock = new Mock<EncryptionUtils>();
            encryptionMock.Setup(x => x.EncryptStringToBytes_AES(It.IsAny<string>(), It.IsAny<byte[]>(), It.IsAny<byte[]>())).Returns(new byte[] { Convert.ToByte(true) });

            var user = new User { JigsawAccountDetails = new JigsawAccountDetails { Username = "******", EncryptedPassword = "******" } };
            _context.Users.Add(user);
            _context.SaveChanges();

            _process = new JigsawAuthProcesses(_context, encryptionMock.Object);

            // Act
            var result = _process.Execute(new SaveJigsawUserCredentialsParams
            {
                RequestingUserId = user.Id,
                JigsawUsername = "******",
                JigsawPassword = "******"
            });

            // Verify
            Assert.AreEqual(1, _context.JigsawAccountDetails.Count(), "Incorrect number of jigsaw records exist");
            Assert.AreEqual("a", user.JigsawAccountDetails.Username, "Jigsaw username was incorrect");
            Assert.AreEqual(Convert.ToBase64String(new byte[] { Convert.ToByte(true) }), user.JigsawAccountDetails.EncryptedPassword, "Jigsaw password was incorrect");
        }
        public IActionExecutionContext CreateContext(IProcess remoteProcess)
        {
            Contract.Requires<ArgumentNullException>(remoteProcess != null);
            Contract.Ensures(Contract.Result<IActionExecutionContext>() != null);

            throw new NotImplementedException();
        }
예제 #17
0
        public HeartContext()
        {
            worker.DoWork += worker_DoWork;
            worker.WorkerSupportsCancellation = true;

            Pump = new Com();
            //Pump = new RandomPump();
            //Pump = new FilePump();
            //Pump.Received += Pump_Received;

            Analyze = new ComDataAnalyze(Pump);
            Analyze.Analyzed += Analyze_Analyzed;

            Rate = new DifferenceHeartRate(this);
            Rate.RateAnalyzed += Rate_RateAnalyzed;

            AvgFilter = new AvgFilterProcess();
            //FirFilter = new MyFirFilterProcess();
            //FirFilter = new LowFirFilterProcess();
            FirFilter = new BandPassFirFilterProcess();
            BandStopFilter = new BandStopFirFilterProcess();
            MedianFilter = new MedianFilterProcess();

            Processes = new List<IProcess>()
            {
                AvgFilter,
                FirFilter,
                //BandStopFilter,
                MedianFilter,
            };
        }
예제 #18
0
 public ProcessTracker(IMessageTransport transport, JobObject jobObject, IProcess hostProcess, ProcessHelper processHelper)
 {
     this.transport = transport;
     this.jobObject = jobObject;
     this.hostProcess = hostProcess;
     this.processHelper = processHelper;
 }
 public BackupGitRepositoriesCommandProvider(IBackupGitRepositoriesConfigurationProvider backupGitRepositoriesConfigurationProvider, IGitRepositoryBackupFolderProvider gitRepositoryBackupFolderProvider, IProcess process, ILog logger)
 {
     _backupGitRepositoriesConfigurationProvider = backupGitRepositoriesConfigurationProvider;
     _gitRepositoryBackupFolderProvider = gitRepositoryBackupFolderProvider;
     _process = process;
     _logger = logger;
 }
예제 #20
0
 public DashboardController(IServiceFactory factory, 
                            IProcess<OrgMemberDocVisibilityByOrgAdminParams, GeneralSuccessResultViewModel> orgDocVisibilityProcess)
 {
     _serviceFactory = factory;
     _unitOfWork = factory.GetService<IUnitOfWork>();
     _orgDocVisibilityProcess = orgDocVisibilityProcess;
 }
예제 #21
0
		public static void AddProcess(IProcess Proc)
		{
			lock (SyncObject)
			{
				ActiveProcesses.Add(Proc);
			}
		}
예제 #22
0
 public override IEnumerable<TAVerb> DoNothing()
 {
     IProcess[] actions = new IProcess[_host.NumWords];
     for (int i = 0; i < _host.NumWords; i++)
         actions[i] = _host.Ops[i].Stick(StdLogicVector.DCs(_host.WordWidth));
     yield return Verb(ETVMode.Locked, actions);
 }
예제 #23
0
 void IProcessMonitor.Started(IProcess process)
 {
     lock (_Lock)
     {
         _Timer = new Timer(TimerCallback, null, _Timeout, _InfiniteTimeSpan);
         _Process = process;
     }
 }
예제 #24
0
        /// <summary>
        /// Creates a new <see cref="ExistingAcadProcess"/> instane.
        /// </summary>
        /// <param name="logger">A logger.</param>
        /// <param name="commandRunner">An AutoCAD command runner.</param>
        /// <param name="process">The existing AutoCAD process.</param>
        /// <param name="pluginLocator">An AutoCAD plugin locator.</param>
        public ExistingAcadProcess(ILogger logger, IAcadCommandRunner commandRunner, IProcess process, IAcadPluginLocator pluginLocator)
            : base(logger, commandRunner, pluginLocator)
        {
            if (process == null)
                throw new ArgumentNullException("process");

            this.process = process;
        }
예제 #25
0
 public IEnumerable<TAVerb> Concat(ISignalSource<StdLogicVector>[] ops, ISignalSink<StdLogicVector> r)
 {
     IProcess[] actions = new IProcess[_host.NumWords + 1];
     for (int i = 0; i < _host.NumWords; i++)
         actions[i] = _host.Ops[i].Drive(ops[i]);
     actions[_host.NumWords] = r.Comb.Connect(_host.R.Dual.AsSignalSource());
     yield return Verb(ETVMode.Locked, actions);
 }
예제 #26
0
        /// <inheritdoc/>
        protected override IProcess StartProcess(DebuggerSetup debuggerSetup)
        {
            if (process != null)
                throw new InvalidOperationException("Process already started.");

            process = StartProcessWithDebugger(debuggerSetup) ?? processCreator.Start(startInfo);
            return process;
        }
 public PowerShellPackageFile(
     IProcess process, IPackageManager manager, IFileSystem fileSystem, string configurationPath)
 {
     this.process = process;
     this.manager = manager;
     this.fileSystem = fileSystem;
     this.configurationPath = configurationPath;
 }
예제 #28
0
        internal void WaitForExit(IProcess process)
        {
            DateTime lastActivity = _lastActivity;
            DateTime lastCpuActivity = _lastActivity;
            TimeSpan previousCpuUsage = _initialCpuUsage;

            while (!process.WaitForExit(TimeSpan.FromSeconds(1)))
            {
                // there is IO activity, continue to wait.
                if (lastActivity != _lastActivity)
                {
                    // there is io activity, reset cpu to initial
                    previousCpuUsage = _initialCpuUsage;
                    lastActivity = _lastActivity;
                    continue;
                }

                // Check how long it's been since the last IO activity
                TimeSpan idleTime = DateTime.UtcNow - lastActivity;

                // If less than the timeout, do nothing
                if (idleTime < _idleTimeout) continue;

                // Write progress to prevent client timeouts
                WriteProgress();

                // There wasn't any IO activity. Check if we had any CPU activity

                // Check how long it's been since the last CPU activity
                TimeSpan cpuIdleTime = DateTime.UtcNow - lastCpuActivity;

                // If less than the timeout, do nothing
                if (cpuIdleTime < _idleTimeout) continue;

                TimeSpan currentCpuUsage = process.GetTotalProcessorTime(_tracer);

                _tracer.Trace("{0}: no io activity for {1:0}s, prev-cpu={2:0.000}s, current-cpu={3:0.000}s", 
                    process.Name, 
                    idleTime.TotalSeconds,
                    previousCpuUsage.TotalSeconds,
                    currentCpuUsage.TotalSeconds);

                if (currentCpuUsage != previousCpuUsage)
                {
                    // The process performed some compute bound operation.  We'll wait for it some more
                    lastCpuActivity = DateTime.UtcNow;
                    previousCpuUsage = currentCpuUsage;
                    continue;
                }

                // It's likely that the process is idling waiting for user input. Kill it
                process.Kill(_tracer);

                throw CreateIdleTimeoutException(process, cpuIdleTime);
            }

            process.WaitUntilEOF();
        }
예제 #29
0
        public void SetUp()
        {
            console = Substitute.For<IConsole>();
            translator = Substitute.For<ITranslator>();
            translator.Translate("GuiStartMessage").Returns("message");
            process = Substitute.For<IProcess>();

            routine = new GuiRoutine(console, translator, process);
        }
예제 #30
0
        public CommunicationModule(IProcess process, CommunicationFactory communicationFactory)
        {
            Contract.Requires<ArgumentNullException>(process != null);
            Contract.Requires<ArgumentNullException>(communicationFactory != null);

            this.iconSource = null;
            this.name = "Communication";
            this.communication = communicationFactory.CreateItem(process.Id);
        }
예제 #31
0
 public void AssignProcess(IProcess process)
 {
     _handle.AssignProcess(process.Handle);
 }
예제 #32
0
 public void Register(IProcess process)
 {
     _processes.Add(process);
 }
예제 #33
0
파일: Processor.cs 프로젝트: EGSP/Gooddland
 /// <summary>
 /// Добавляет процесс в конец списка.
 /// </summary>
 /// <param name="process"></param>
 public void AppendProcess(IProcess process)
 {
     OnDataReadAvailable += process.SearchData;
     Processes.Add(process);
 }
예제 #34
0
 public IProcess GetParentProcess(IProcess process)
 {
     return(WrapProcess(ParentProcessUtilities.GetParentProcess(process.Id)));
 }
예제 #35
0
파일: Context.cs 프로젝트: xdpcxq/HNXC_WCS
 /// <summary>
 /// 注册和Service没有联系的Process
 /// </summary>
 /// <param name="process"></param>
 public void RegisterProcess(IProcess process)
 {
     processes.Add(process);
 }
예제 #36
0
        private async Task <bool> Close(IProcess process)
        {
            await process.Close();

            return(await ProcessUtils.SpinWaitForExit(process, _waitForExitInSeconds));
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="MemoryPointer" /> class.
 /// </summary>
 /// <param name="process">The reference of the <see cref="IProcess"></see></param>
 /// <param name="address">The location where the pointer points in the remote process.</param>
 public MemoryPointer(IProcess process, IntPtr address)
 {
     // Save the parameters
     Process     = process;
     BaseAddress = address;
 }
예제 #38
0
파일: exec.cs 프로젝트: 0xCM/Meta.Core
 public static c exec(this IProcess broker, string commandText)
 => broker.Submit <c>(commandText);
예제 #39
0
 public VectorMemory(IProcess process, UIntPtr address)
     : base(process, address, 12)
 {
 }
예제 #40
0
파일: Evaluator.cs 프로젝트: lanicon/EtLast
 // caller is passed because process.InvocationInfo.Caller can not be used for this (it stores only the last caller)
 public Evaluator(IProcess caller, IEnumerable <IRow> input)
 {
     _caller = caller;
     _input  = input;
 }
 /// <summary>
 /// Create process context for process
 /// </summary>
 public ProcessContext(IProcess process)
 {
     Process = process;
 }
예제 #42
0
 public override void HandleRadsUserKernelLaunched(IProcess process) /* Occurs because ruk/patcher death order doesn't matter */ }
예제 #43
0
 /// <summary>Initializes a new instance of the <see cref="AssemblyFactory" /> class.</summary>
 /// <param name="process">The process.</param>
 /// <param name="assembler">The assembler.</param>
 public AssemblyFactory(IProcess process,
                        IAssembler assembler)
 {
     Process   = process;
     Assembler = assembler;
 }
예제 #44
0
        /// <summary>
        ///     Calls the script
        /// </summary>
        /// <param name="job">The current job</param>
        /// <returns>An ActionResult to determine the success and a list of errors</returns>
        public ActionResult ProcessJob(Job job)
        {
            _logger.Debug("Launched Script-Action");

            ApplyPreSpecifiedTokens(job);
            var actionResult = Check(job.Profile, job.Accounts, CheckLevel.Job);

            if (!actionResult)
            {
                return(actionResult);
            }

            var scriptFile = job.Profile.Scripting.ScriptFile;

            _logger.Debug("Script-File: " + scriptFile);

            IProcess process = _processStarter.CreateProcess(scriptFile);

            var parameters = ComposeScriptParameters(job.Profile.Scripting.ParameterString, job.OutputFiles, job.TokenReplacer);

            process.StartInfo.Arguments = parameters;
            if (job.Profile.Scripting.Visible == false)
            {
                process.StartInfo.ProcessStartInfoInstance.WindowStyle = ProcessWindowStyle.Hidden;
            }
            _logger.Debug("Script-Parameters: " + parameters);

            var scriptDir = PathSafe.GetDirectoryName(scriptFile);

            if (scriptDir != null)
            {
                process.StartInfo.WorkingDirectory = scriptDir;
            }

            _logger.Debug("Script-Working Directory: " + scriptDir);

            process.EnableRaisingEvents = true;
            process.Exited += (sender, args) => process.Close();

            try
            {
                _logger.Debug("Launching script...");
                process.Start();

                if (job.Profile.Scripting.WaitForScript)
                {
                    _logger.Debug("Waiting for script to end");
                    process.WaitForExit();
                    _logger.Debug("Script execution ended");
                }
                else
                {
                    _logger.Debug("The script is executed in the background");
                }

                return(new ActionResult());
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Exception while running the script file \"" + scriptFile);
                return(new ActionResult(ErrorCode.Script_GenericError));
            }
        }
예제 #45
0
        string sapviewmode = "I"; //interactive



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                idBR = int.Parse(Request.Params["idBR"]);
            }
            catch (Exception) { idBR = -432; }


            // Special viewing mode param added in May of 2010:
            //     sapview=interactive   or   html
            // The default is the former
            sapviewmode = "I";
            try
            {
                string mode = Request.Params["sapview"];
                sapviewmode = mode.ToUpper().Substring(0, 1);
            }
            catch (Exception) { }


            if (PANEL_tcodelistingmode_HtmlTable != null)
            {
                switch (sapviewmode)
                {
                case "I":
                    PANEL_tcodelistingmode_HtmlTable.Visible = false;
                    break;

                case "H":
                    PANEL_tcodelistingmode_interactive.Visible = false;
                    break;
                }
            }



            IProcess    engineProcess    = new IProcess(HELPERS.NewOdbcConn());
            ISubProcess engineSubProcess = new ISubProcess(HELPERS.NewOdbcConn());
            IBusRole    engineBR         = new IBusRole(HELPERS.NewOdbcConn());

            theBR         = engineBR.GetBusRole(idBR);
            theSubProcess = engineSubProcess.GetSubProcess(theBR.SubProcessID);
            theProcess    = engineProcess.GetProcess(theSubProcess.ProcessID);

            // Initialize dynamically-generated portions of the page
            if (PANELsapdesignnote != null)
            {
                IFuncApplNotes            engine   = new IFuncApplNotes(HELPERS.NewOdbcConn());
                returnListFuncApplNotes[] returned =
                    engine.ListFuncApplNotes
                        (null, "\"REFapplication\" = ?  AND  \"BusRole\" = ?" /* SAP application is ID 57 */,
                        new string[] { "57", idBR.ToString() }, "");
                if (returned.Length == 0)
                {
                    PANELsapdesignnote.Visible = false;
                }
                else
                {
                    STATICTXTsapfuncappdesignnote.Text =
                        returned[0].Comment;
                }
            }
        }
예제 #46
0
 public void Add(IProcess process) => ChildProcessTracker.AddProcess(process.Unwrap());
예제 #47
0
 public void SetProcess(IProcess process)
 {
     Process = process;
 }
예제 #48
0
 public GenerateCommissionPayment(IProcess nextStep = null)
 {
     this.nextStep = nextStep;
 }
예제 #49
0
        private Task <bool> StopGracefully(IProcess process)
        {
            process.StopGracefully();

            return(ProcessUtils.SpinWaitForExit(process, _waitForExitInSeconds));
        }
예제 #50
0
 internal ScriptManager(ISourceFileOpener sourceFileOpener, IProcess process)
 {
     this.sourceFileOpener = sourceFileOpener;
     this.process          = process;
 }
 public void Add(IProcess process)
 {
     _processes.Add(process);
     _watcher.AddFuture(new ProcessFuture(process).Run());
 }
예제 #52
0
        /// <summary>
        /// DoSetup setup up the working directory, returns an IProcess interface.
        /// </summary>
        /// <param name="job"></param>
        /// <param name="configFileName"></param>
        /// <returns></returns>
        private IProcess DoSetup(IJobConsumerContract job)
        {
            Debug.WriteLine("DoSetup Called on " + job.Id, "SinterConsumer");
            // NOTE: expect OptimisticConcurrencyException
            // to occur ONLY here when running multiple consumers
            IProcess process = null;

            try
            {
                process = job.Setup();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message, "SinterConsumer.DoSetup");
                throw;
            }

            //Sets the dir in the function to MyDocs, but doesn't actually chdir
            try
            {
                SetupWorkingDir(process);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to setup working directory", "SinterConsumer.Run");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
                job.Error(String.Format("Failed to setup working directory: {0}", ex.StackTrace));
                throw;
            }

            bool isCached = false;

            try
            {
                isCached = copyFromCache(job);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("copyFromCache Failed to copy files to working directory", "SinterConsumer.Run");
                Debug.WriteLine(ex.StackTrace, "SinterConsumer.Run");
                job.Error(String.Format("copyFromCache Failed to copy files to working directory: {0}", ex.StackTrace));
                throw;
            }

            if (isCached == false)
            {
                try
                {
                    copyFilesToDisk(job);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("copyFilesToDisk Failed to copy files to working directory", "SinterConsumer.Run");
                    Debug.WriteLine(ex.StackTrace, "SinterConsumer.Run");
                    job.Error(String.Format("copyFilesToDisk Failed to copy files to working directory: {0}", ex.StackTrace));
                    throw;
                }
            }
            job.Message("working directory setup finished");

            return(process);
        }
예제 #53
0
 public static void SetContext(IProcess self, ProcessId sender)
 {
     ActorContext.self   = self;
     ActorContext.sender = sender;
 }
예제 #54
0
        /// <summary>
        ///  DoConfigure starts up COM process server.  Occasionally readSetup fail, this
        ///  will attempt maxAttemptsReadSetup times to open the
        ///  simulation.  Also readSetup will hang in unmanaged code
        /// </summary>
        /// <param name="job"></param>
        /// <param name="process"></param>
        /// <param name="maxAttemptsReadSetup"></param>
        /// <returns></returns>
        private void DoConfigure(IJobConsumerContract job,
                                 IProcess process, int maxAttemptsReadSetup)
        {
            int    attempts    = 1;
            int    timeout     = 1000;
            string setupString = null;

            var configFilePath = Path.Combine(process.WorkingDirectory, configFileName);

            while (true)
            {
                Debug.WriteLine(String.Format("Attempt to Read {0}", configFilePath),
                                "SinterConsumer.DoConfigure");
                setupString = "";
                try
                {
                    StreamReader inFileStream = new StreamReader(configFilePath);
                    setupString = inFileStream.ReadToEnd();
                    inFileStream.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message, "SinterConsumer.DoConfigure");
                    Debug.WriteLine(ex.StackTrace, "SinterConsumer.DoConfigure");
                    job.Error(String.Format("Failed to read configuration file: {0}", ex.StackTrace));
                    throw;
                }

                try
                {
                    InitializeSinter(job, process.WorkingDirectory, setupString);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message, "SinterConsumer.DoConfigure.InitializeSinter");
                    Debug.WriteLine(ex.StackTrace, "SinterConsumer.DoConfigure.InitializeSinter");
                    job.Error(String.Format("Failed to InitializeSinter: {0}", ex.StackTrace));
                    throw;
                }

                Debug.WriteLine(String.Format("readSetup {0}", configFilePath),
                                "SinterConsumer.DoConfigure");
                Debug.WriteLine(String.Format("model {0}", sim.setupFile.aspenFilename),
                                "SinterConsumer.DoConfigure");

                try
                {
                    lock (this)
                    {
                        sim.openSim();
                        isSetup = true;
                        if (isTerminated)
                        {
                            throw new TerminateException(
                                      "APWN was terminated, try readSetup again");
                        }
                    }
                }
                catch (Exception ex)
                {
                    //System.Exception: Cannot create ActiveX component
                    var msg = String.Format("Failed to open Simulation ({0}: {1}", attempts, ex.Message);
                    Debug.WriteLine(msg, "SinterConsumer");
                    Debug.WriteLine(ex.StackTrace, "SinterConsumer");
                    try
                    {
                        sim.closeSim();
                    }
                    catch (NullReferenceException e2)
                    {
                        Debug.WriteLine(e2.Message, "SinterConsumer");
                        Debug.WriteLine(ex.StackTrace, "SinterConsumer");
                    }
                    if (job.IsTerminated())
                    {
                        throw new TerminateException("Job was terminated by producer");
                    }
                    else if (attempts >= maxAttemptsReadSetup)
                    {
                        job.Error(msg);
                        throw;
                    }
                    job.Message(msg);
                    isTerminated = false;
                    attempts    += 1;
                    System.Threading.Thread.Sleep(timeout);
                    timeout *= 2;
                    continue;
                }
                job.Message("sinter read setup finished");

                // One of these commands hangs infrequently..
                // However this job will not be retired as above, just abandoned and left in setup.
                Debug.WriteLine("set simulation layout", "SinterConsumer.DoConfigure");
                try
                {
                    sim.Vis = visible; // operates on Aspen instance
                }
                catch (Exception ex)
                {
                    sim.closeSim();
                    var msg = String.Format("Failed to Layout Simulation ({0}: {1}", attempts, ex.Message);
                    Debug.WriteLine(msg, "SinterConsumer.DoConfigure");
                    Debug.WriteLine(ex.StackTrace, "SinterConsumer.DoConfigure");
                    if (attempts >= maxAttemptsReadSetup)
                    {
                        job.Error(msg);
                        throw;
                    }
                    job.Message(msg);
                    attempts += 1;
                    System.Threading.Thread.Sleep(timeout);
                    timeout *= 2;
                    continue;
                }

                Debug.WriteLine("set simulation reset", "SinterConsumer.DoConfigure");
                try
                {
                    sim.dialogSuppress = true;  // operates on Aspen instance
                    //sim.resetSim(); // operates on Aspen instance
                }
                catch (Exception ex)
                {
                    sim.closeSim();
                    var msg = String.Format("Failed to Reset Simulation ({0}: {1}", attempts, ex.Message);
                    Debug.WriteLine(msg, "SinterConsumer.DoConfigure");
                    Debug.WriteLine(ex.StackTrace, "SinterConsumer.DoConfigure");
                    if (attempts >= maxAttemptsReadSetup)
                    {
                        job.Error(msg);
                        throw;
                    }
                    job.Message(msg);
                    attempts += 1;
                    System.Threading.Thread.Sleep(timeout);
                    timeout *= 2;
                    continue;
                }
                break;
            }
        }
예제 #55
0
        public void End(IProcess process)
        {
            IProcess toEnd = _processes.First(x => x.ProcessId == process.ProcessId);

            _processes.Remove(toEnd);
        }
예제 #56
0
        public static bool AuthenticateUser(ILogger <IAuthenticationService> logger, IProcessServices ps, string username, string password, string allowedGroup, out string profileDir)
        {
            bool     retval  = false;
            IProcess proc    = null;
            string   userDir = string.Empty;

            try {
                proc = CreateRunAsUserProcess(ps, false);
                using (BinaryWriter writer = new BinaryWriter(proc.StandardInput.BaseStream, Encoding.UTF8, true))
                    using (BinaryReader reader = new BinaryReader(proc.StandardOutput.BaseStream, Encoding.UTF8, true)) {
                        var message = new AuthenticationOnlyMessage()
                        {
                            Username = GetUnixUserName(username), Password = password, AllowedGroup = allowedGroup
                        };
                        string json      = JsonConvert.SerializeObject(message, GetJsonSettings());
                        var    jsonBytes = Encoding.UTF8.GetBytes(json);
                        writer.Write(jsonBytes.Length);
                        writer.Write(jsonBytes);
                        writer.Flush();

                        proc.WaitForExit(3000);

                        if (proc.HasExited && proc.ExitCode == 0)
                        {
                            int size  = reader.ReadInt32();
                            var bytes = reader.ReadBytes(size);
                            var arr   = JsonConvert.DeserializeObject <JArray>(Encoding.UTF8.GetString(bytes));
                            if (arr.Count > 1)
                            {
                                var respType = arr[0].Value <string>();
                                switch (respType)
                                {
                                case PamInfo:
                                case PamError:
                                    var pam = arr[1].Value <string>();
                                    logger.LogCritical(Resources.Error_PAMAuthenticationError.FormatInvariant(pam));
                                    break;

                                case JsonError:
                                    var jerror = arr[1].Value <string>();
                                    logger.LogCritical(Resources.Error_RunAsUserJsonError.FormatInvariant(jerror));
                                    break;

                                case RtvsResult:
                                    userDir = arr[1].Value <string>();
                                    retval  = true;
                                    if (userDir.Length == 0)
                                    {
                                        logger.LogError(Resources.Error_NoProfileDir);
                                    }
                                    break;

                                case RtvsError:
                                    var resource = arr[1].Value <string>();
                                    logger.LogCritical(Resources.Error_RunAsUserFailed.FormatInvariant(Resources.ResourceManager.GetString(resource)));
                                    break;
                                }
                            }
                            else
                            {
                                logger.LogCritical(Resources.Error_InvalidRunAsUserResponse);
                            }
                        }
                        else
                        {
                            logger.LogCritical(Resources.Error_AuthFailed, GetRLaunchExitCodeMessage(proc.ExitCode));
                        }
                    }
            } catch (Exception ex) {
                logger.LogCritical(Resources.Error_AuthFailed, ex.Message);
            } finally {
                if (proc != null && !proc.HasExited)
                {
                    try {
                        proc.Kill();
                    } catch (Exception ex) when(!ex.IsCriticalException())
                    {
                    }
                }
            }

            profileDir = userDir;
            return(retval);
        }
 public ActivateMemberShip(IProcess nextStep = null)
 {
     this.nextStep = nextStep;
 }
예제 #58
0
        /// <summary>
        /// Processes the exited.
        /// </summary>
        /// <param name="process">The process.</param>
        /// <param name="job">The job.</param>
        private void OnFfMpegProcessExited(IProcess process, EncodingJob job)
        {
            job.HasExited = true;

            Logger.Debug("Disposing stream resources");
            job.Dispose();

            var isSuccesful = false;

            try
            {
                var exitCode = process.ExitCode;
                Logger.Info("FFMpeg exited with code {0}", exitCode);

                isSuccesful = exitCode == 0;
            }
            catch
            {
                Logger.Error("FFMpeg exited with an error.");
            }

            if (isSuccesful && !job.IsCancelled)
            {
                job.TaskCompletionSource.TrySetResult(true);
            }
            else if (job.IsCancelled)
            {
                try
                {
                    DeleteFiles(job);
                }
                catch
                {
                }
                try
                {
                    job.TaskCompletionSource.TrySetException(new OperationCanceledException());
                }
                catch
                {
                }
            }
            else
            {
                try
                {
                    DeleteFiles(job);
                }
                catch
                {
                }
                try
                {
                    job.TaskCompletionSource.TrySetException(new Exception("Encoding failed"));
                }
                catch
                {
                }
            }

            // This causes on exited to be called twice:
            //try
            //{
            //    // Dispose the process
            //    process.Dispose();
            //}
            //catch (Exception ex)
            //{
            //    Logger.ErrorException("Error disposing ffmpeg.", ex);
            //}
        }
예제 #59
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SessionController"/> class.
        /// </summary>
        /// <param name="reattachInformation">The value of <see cref="reattachInformation"/>.</param>
        /// <param name="metadata">The owning <see cref="Instance"/>.</param>
        /// <param name="process">The value of <see cref="process"/>.</param>
        /// <param name="byondLock">The value of <see cref="byondLock"/>.</param>
        /// <param name="byondTopicSender">The value of <see cref="byondTopicSender"/>.</param>
        /// <param name="bridgeRegistrar">The <see cref="IBridgeRegistrar"/> used to populate <see cref="bridgeRegistration"/>.</param>
        /// <param name="chat">The value of <see cref="chat"/>.</param>
        /// <param name="chatTrackingContext">The value of <see cref="chatTrackingContext"/>.</param>
        /// <param name="assemblyInformationProvider">The <see cref="IAssemblyInformationProvider"/> for the <see cref="SessionController"/>.</param>
        /// <param name="logger">The value of <see cref="logger"/>.</param>
        /// <param name="postLifetimeCallback">The <see cref="Func{TResult}"/> returning a <see cref="Task"/> to be run after the <paramref name="process"/> ends.</param>
        /// <param name="startupTimeout">The optional time to wait before failing the <see cref="LaunchResult"/>.</param>
        /// <param name="reattached">If this is a reattached session.</param>
        /// <param name="apiValidate">If this is a DMAPI validation session.</param>
        public SessionController(
            ReattachInformation reattachInformation,
            Api.Models.Instance metadata,
            IProcess process,
            IByondExecutableLock byondLock,
            ITopicClient byondTopicSender,
            IChatTrackingContext chatTrackingContext,
            IBridgeRegistrar bridgeRegistrar,
            IChatManager chat,
            IAssemblyInformationProvider assemblyInformationProvider,
            ILogger <SessionController> logger,
            Func <Task> postLifetimeCallback,
            uint?startupTimeout,
            bool reattached,
            bool apiValidate)
        {
            this.reattachInformation = reattachInformation ?? throw new ArgumentNullException(nameof(reattachInformation));
            this.metadata            = metadata ?? throw new ArgumentNullException(nameof(metadata));
            this.process             = process ?? throw new ArgumentNullException(nameof(process));
            this.byondLock           = byondLock ?? throw new ArgumentNullException(nameof(byondLock));
            this.byondTopicSender    = byondTopicSender ?? throw new ArgumentNullException(nameof(byondTopicSender));
            this.chatTrackingContext = chatTrackingContext ?? throw new ArgumentNullException(nameof(chatTrackingContext));
            if (bridgeRegistrar == null)
            {
                throw new ArgumentNullException(nameof(bridgeRegistrar));
            }
            this.chat   = chat ?? throw new ArgumentNullException(nameof(chat));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            portClosedForReboot = false;
            disposed            = false;
            apiValidationStatus = ApiValidationStatus.NeverValidated;
            released            = false;

            rebootTcs = new TaskCompletionSource <object>();
            primeTcs  = new TaskCompletionSource <object>();
            initialBridgeRequestTcs = new TaskCompletionSource <object>();
            reattachTopicCts        = new CancellationTokenSource();
            synchronizationLock     = new object();

            if (apiValidate || DMApiAvailable)
            {
                bridgeRegistration = bridgeRegistrar.RegisterHandler(this);
                this.chatTrackingContext.SetChannelSink(this);
            }
            else
            {
                logger.LogTrace(
                    "Not registering session with {0} DMAPI version for interop!",
                    reattachInformation.Dmb.CompileJob.DMApiVersion == null
                                                ? "no"
                                                : $"incompatible ({reattachInformation.Dmb.CompileJob.DMApiVersion})");
            }

            async Task <int> WrapLifetime()
            {
                var exitCode = await process.Lifetime.ConfigureAwait(false);

                await postLifetimeCallback().ConfigureAwait(false);

                return(exitCode);
            }

            Lifetime = WrapLifetime();

            LaunchResult = GetLaunchResult(
                assemblyInformationProvider,
                startupTimeout,
                reattached,
                apiValidate);

            logger.LogDebug(
                "Created session controller. CommsKey: {0}, Port: {1}",
                reattachInformation.AccessIdentifier,
                reattachInformation.Port);
        }
예제 #60
0
 internal HttpDownloadToLocalFileException(IProcess process, string message, string url, string fileName)
     : base(process, message)
 {
     Data.Add("Url", url);
     Data.Add("FileName", fileName);
 }