コード例 #1
0
        protected override void RunJournalCommand()
        {
            var journal   = OpenJournal();
            var entryDate = Date == null?Today.PlusDays(DateOffset) : LocalDate.FromDateTime(Date.Value).PlusDays(DateOffset);

            var hour = Now.Time().Hour;

            if (hour >= 0 && hour <= 4)
            {
                var dayPrior = entryDate.Minus(Period.FromDays(1));
                var question = $"Did you mean to create an entry for '{dayPrior}' or '{entryDate}'?";
                var result   = Choice("It's after midnight!", question, 0, dayPrior.DayOfWeek.ToChoiceString(), entryDate.DayOfWeek.ToChoiceString());
                if (result == 0)
                {
                    entryDate = dayPrior;
                }
            }

            Commit(GitCommitType.PreNewJournalEntry);

            try
            {
                journal.CreateNewEntry(entryDate, Tags, Readme);
                Commit(GitCommitType.PostNewJournalEntry);
            }
            catch (JournalEntryAlreadyExistsException e)
            {
                var question = $"An entry for {entryDate} already exists. Do you want to open it instead?";
                if (YesOrNo(question))
                {
                    SystemProcess.Start(e.EntryFilePath);
                }
            }
        }
コード例 #2
0
        public DataTransfer <GetOutput> Get(string id)
        {
            DataTransfer <GetOutput> tranfer = new DataTransfer <GetOutput>();

            System.Int32 systemprocessid = 0;
            if (!string.IsNullOrEmpty(id) && System.Int32.TryParse(id, out systemprocessid))
            {
                SystemProcess systemprocess = _iSystemProcessRepository.GetSystemProcess(systemprocessid);
                if (systemprocess != null)
                {
                    tranfer.IsSuccess = true;
                    GetOutput output = new GetOutput();
                    output.CopyFrom(systemprocess);
                    tranfer.Data = output;
                }
                else
                {
                    tranfer.IsSuccess = false;
                    tranfer.Errors    = new string[1];
                    tranfer.Errors[0] = "Error: No record found.";
                }
            }
            else
            {
                tranfer.IsSuccess = false;
                tranfer.Errors    = new string[1];
                tranfer.Errors[0] = "Error: Invalid request.";
            }
            return(tranfer);
        }
コード例 #3
0
        private static void ShowDotNetFrameworkVersions()
        {
            var process = new SystemProcess();

            WriteOutput("Report at: ", process.Report.TimeStamp.ToString(), ConsoleColor.Green);
            WriteOutput("User Domain Name: ", process.Report.UserDomainName, ConsoleColor.Green);
            WriteOutput("Machine Name: ", process.Report.MachineName, ConsoleColor.Green);
            WriteOutput("OS Version: ", process.Report.OSVersion, ConsoleColor.Green);
            WriteOutput("OS Version Caption: ", process.Report.OSVersionCaption, ConsoleColor.Green);
            WriteOutput("OS Version Datailed: ", process.Report.OSVersionDetailed, ConsoleColor.Green);
            WriteOutput("Platform: ", process.Report.OperatingSystemVersionPlatform, ConsoleColor.Green);
            WriteOutput("OS Server: ", process.Report.IsServer.ToString(), ConsoleColor.Green);
            WriteOutput("x64 OS: ", process.Report.Is64BitOperatingSystem.ToString(), ConsoleColor.Green);
            WriteWithForeColor(Environment.NewLine);

            foreach (var item in process.Report.ReportDetails)
            {
                WriteOutput("Version: ", item.Version, ConsoleColor.Cyan);
                WriteOutput("Framework Version: ", item.FrameworkVersion, ConsoleColor.Cyan);
                WriteOutput("Service Pack: ", item.ServicePack, ConsoleColor.Cyan);
                WriteOutput("Release: ", item.Release.ToString(), ConsoleColor.Cyan);
                WriteOutput("Release Name: ", item.ReleaseName, ConsoleColor.Cyan);
                WriteOutput("Install Path: ", item.InstallPath, ConsoleColor.Cyan);
                WriteOutput("Is Deprecated: ", item.IsDeprecated.ToString(), ConsoleColor.Cyan);
                WriteWithForeColor(Environment.NewLine);
            }
        }
コード例 #4
0
 public override void Close()
 {
     base.Close();
     if (this.receivePack != null)
     {
         try
         {
             this.receivePack.WaitFor();
         }
         catch (Exception)
         {
         }
         finally
         {
             // Stop waiting and return anyway.
             this.receivePack = null;
         }
     }
     if (this.errorReaderThread != null)
     {
         try
         {
             this.errorReaderThread.Join();
         }
         catch (Exception)
         {
         }
         finally
         {
             // Stop waiting and return anyway.
             this.errorReaderThread = null;
         }
     }
 }
コード例 #5
0
        public virtual void TestProxyUserFromEnvironment()
        {
            string proxyUser = "******";

            Runtime.SetProperty(UserGroupInformation.HadoopProxyUser, proxyUser);
            UserGroupInformation ugi = UserGroupInformation.GetLoginUser();

            Assert.Equal(proxyUser, ugi.GetUserName());
            UserGroupInformation realUgi = ugi.GetRealUser();

            NUnit.Framework.Assert.IsNotNull(realUgi);
            // get the expected real user name
            SystemProcess  pp = Runtime.GetRuntime().Exec("whoami");
            BufferedReader br = new BufferedReader(new InputStreamReader(pp.GetInputStream())
                                                   );
            string realUser = br.ReadLine().Trim();
            // On Windows domain joined machine, whoami returns the username
            // in the DOMAIN\\username format, so we trim the domain part before
            // the comparison. We don't have to special case for Windows
            // given that Unix systems do not allow slashes in usernames.
            int backslashIndex = realUser.IndexOf('\\');

            if (backslashIndex != -1)
            {
                realUser = Runtime.Substring(realUser, backslashIndex + 1);
            }
            Assert.Equal(realUser, realUgi.GetUserName());
        }
コード例 #6
0
        private void OpenToCurrent()
        {
            var    fileSystem = new FileSystem();
            string path;
            var    year  = Journal.YearDirectoryPattern.Format(Today.Date());
            var    month = Journal.MonthDirectoryPattern.Format(Today.Date());

            switch (To)
            {
            case "CurrentMonth":
                path = fileSystem.Path.Combine(Location, year, month);
                break;

            case "CurrentYear":
                path = fileSystem.Path.Combine(Location, year);
                break;

            default:
                path = fileSystem.Path.Combine(Location);
                break;
            }

            if (!fileSystem.Directory.Exists(path))
            {
                throw new PSInvalidOperationException("No directory currently exists for the selected period.");
            }

            SystemProcess.Start(path);
        }
コード例 #7
0
        public virtual SystemProcess UpdateSystemProcess(SystemProcess entity)
        {
            if (entity.IsTransient())
            {
                return(entity);
            }
            SystemProcess other = GetSystemProcess(entity.SystemProcessId);

            if (entity.Equals(other))
            {
                return(entity);
            }
            string sql = @"Update SystemProcess set  [Name]=@Name
							, [Description]=@Description
							, [Enabled]=@Enabled
							, [DisplayOrder]=@DisplayOrder
							, [Ip]=@Ip
							, [Port]=@Port 
							 where SystemProcessID=@SystemProcessID"                            ;

            SqlParameter[] parameterArray = new SqlParameter[] {
                new SqlParameter("@Name", entity.Name)
                , new SqlParameter("@Description", entity.Description ?? (object)DBNull.Value)
                , new SqlParameter("@Enabled", entity.Enabled)
                , new SqlParameter("@DisplayOrder", entity.DisplayOrder)
                , new SqlParameter("@Ip", entity.Ip ?? (object)DBNull.Value)
                , new SqlParameter("@Port", entity.Port ?? (object)DBNull.Value)
                , new SqlParameter("@SystemProcessID", entity.SystemProcessId)
            };
            SqlHelper.ExecuteNonQuery(this.ConnectionString, CommandType.Text, sql, parameterArray);
            return(GetSystemProcess(entity.SystemProcessId));
        }
コード例 #8
0
ファイル: Instance.cs プロジェクト: khalilcharfi/winp
        public async Task Stop(ApplicationConfig application)
        {
            if (_process != null)
            {
                // Stop running process
                var duration = TimeSpan.FromSeconds(5);
                var tasks    = new List <Task <int?> >(2)
                {
                    _process.Stop(duration)
                };

                // Execute "stop" command
                var stopStartInfo = Package.CreateProcessStop(application, _process.Id);
                var stopProcess   = SystemProcess.Start(stopStartInfo);

                if (stopProcess != null)
                {
                    tasks.Add(stopProcess.Stop(duration));
                }

                // Wait for both processes to end
                await Task.WhenAll(tasks);
            }

            _process = null;
        }
コード例 #9
0
ファイル: Shell.cs プロジェクト: bbyars/CM.NET
        private static void ThrowIfFailed(SystemProcess process)
        {
            if (process.WasSuccessful)
                return;

            throw new ApplicationException(process.ToString());
        }
        public async Task Update_Operation_AddsToDb()
        {
            var connFactory      = new ConnectionStringFactory(this._config);
            var parentRepository = new SystemProcessRepository(connFactory, this._processLogger);
            var repository       = new SystemProcessOperationRepository(connFactory, this._operationLogger);

            var systemProcess = new SystemProcess
            {
                MachineId         = Environment.MachineName,
                ProcessId         = Process.GetCurrentProcess().Id.ToString(),
                InstanceInitiated = DateTime.UtcNow,
                Heartbeat         = DateTime.UtcNow,
                SystemProcessType = SystemProcessType.DataImportService
            };

            systemProcess.Id = systemProcess.GenerateInstanceId();

            await parentRepository.Create(systemProcess);

            var systemProcessOperation = new SystemProcessOperation
            {
                SystemProcessId = systemProcess.Id,
                OperationStart  = DateTime.UtcNow,
                OperationState  = OperationState.InProcess
            };

            await repository.Create(systemProcessOperation);

            systemProcessOperation.OperationEnd = DateTime.UtcNow;

            await repository.Update(systemProcessOperation);

            Assert.IsTrue(true);
        }
コード例 #11
0
        public DataTransfer <PutOutput> Update(PutInput Input)
        {
            DataTransfer <PutOutput> transer             = new DataTransfer <PutOutput>();
            SystemProcess            systemprocessinput  = new SystemProcess();
            SystemProcess            systemprocessoutput = new SystemProcess();
            PutOutput output = new PutOutput();

            systemprocessinput.CopyFrom(Input);
            SystemProcess systemprocess = _iSystemProcessRepository.GetSystemProcess(systemprocessinput.SystemProcessId);

            if (systemprocess != null)
            {
                systemprocessoutput = _iSystemProcessRepository.UpdateSystemProcess(systemprocessinput);
                if (systemprocessoutput != null)
                {
                    output.CopyFrom(systemprocessoutput);
                    transer.IsSuccess = true;
                    transer.Data      = output;
                }
                else
                {
                    transer.IsSuccess = false;
                    transer.Errors    = new string[1];
                    transer.Errors[0] = "Error: Could not update.";
                }
            }
            else
            {
                transer.IsSuccess = false;
                transer.Errors    = new string[1];
                transer.Errors[0] = "Error: Record not found.";
            }
            return(transer);
        }
コード例 #12
0
        protected override void EndProcessing()
        {
            base.EndProcessing();

            var journal = OpenJournal();

            var hour = Now.Time().Hour;

            if (hour >= 0 && hour <= 4)
            {
                var dayPrior = Date.Minus(Period.FromDays(1));
                var question = $"Did you mean to create an entry for '{dayPrior}' or '{Date}'?";
                var result   = Choice("It's after midnight!", question, 0, dayPrior.DayOfWeek.ToChoiceString(), Date.DayOfWeek.ToChoiceString());
                if (result == 0)
                {
                    Date = dayPrior;
                }
            }

            try
            {
                journal.CreateNewEntry(Date, Tags, Readme);
                new JournalTagCache().Invalidate();
            }
            catch (JournalEntryAlreadyExistsException e)
            {
                var question = $"An entry for {Date} already exists. Do you want to open it instead?";
                if (YesOrNo(question))
                {
                    SystemProcess.Start(e.EntryFilePath);
                }
            }
        }
コード例 #13
0
        public ProcessStartInfo CreateProcessStart(ApplicationConfig application)
        {
            var installDirectory = application.Environment.InstallDirectoryOrDefault;

            return(CreateProcessStartInfo(installDirectory, "mysqld.exe",
                                          SystemProcess.EscapeArgument("--defaults-file=config/" + ConfigurationMysqld)));
        }
コード例 #14
0
        protected override void ProcessRecord()
        {
            var fileSystem = new FileSystem();
            var store      = new FileStore <UserSettings>(fileSystem);

            SystemProcess.Start(store.FilePath);
        }
コード例 #15
0
        public List <SystemProcessThread> GetSystemProcessThreadsByProcessName(string name)
        {
            SystemProcess process = GetSystemProcessByName(name);
            //ISystemProcessThreadRepository systemProcessThreadRepository = IoC.Resolve<ISystemProcessThreadRepository>("SystemProcessThreadRepository");
            SystemProcessThreadRepository systemProcessThreadRepository = new SystemProcessThreadRepository();

            return(systemProcessThreadRepository.GetSystemProcessThreadBySystemProcessId(process.SystemProcessId));
        }
コード例 #16
0
 public void TestMethod1andabit()
 {
     using (var notepad = new SystemProcess(Environment.SystemDirectory + "\\notepad.exe", x => x.Kill()))
     {
         Thread.Sleep(500);
         notepad.Start();
     }
 }
コード例 #17
0
 public void TestMethod1andabit()
 {
     using (var notepad = new SystemProcess(Environment.SystemDirectory + "\\notepad.exe", x => x.Kill()))
     {
         Thread.Sleep(500);
         notepad.Start();
     }
 }
コード例 #18
0
        public ServiceManager(bool autoRun, List <IMachineInfo> machineInfos, List <IProcessInfo> processInfos, List <IComplexEventAction> complexEventActions, List <IViewModelInfo> viewModelInfos)
        {
            try
            {
                var ctx         = Context;
                var machineInfo =
                    machineInfos.FirstOrDefault(
                        x => x.MachineName == Environment.MachineName && x.Processors == Environment.ProcessorCount);
                if (machineInfo == null)
                {
                    return;
                }
                var processInfo = processInfos.FirstOrDefault(x => x.ParentProcessId == 0);
                if (processInfo == null)
                {
                    return;
                }
                var systemProcess = new SystemProcess(new RevolutionEntities.Process.Process(processInfo, new Agent("System")), machineInfo);
                Source = new Source(Guid.NewGuid(), "ServiceManager", new SourceType(typeof(IServiceManager)), systemProcess, machineInfo);
                var systemStartedMsg = new SystemStarted(new StateEventInfo(systemProcess.Id, RevolutionData.Context.Process.Events.ProcessStarted), systemProcess, Source);



                EventMessageBus.Current.GetEvent <IServiceStarted <IProcessService> >(Source).Where(x => x.Process.Id == 1)//only start up process
                .Subscribe(async x =>
                {
                    var child = Context.Child("ViewModelSupervisor");
                    if (!Equals(child, ActorRefs.Nobody))
                    {
                        return;
                    }

                    await Task.Run(() => ctx.ActorOf(Props.Create <ViewModelSupervisor>(viewModelInfos, systemProcess, systemStartedMsg), "ViewModelSupervisor")).ConfigureAwait(false);

                    await Task.Run(() => ctx.ActorOf(Props.Create <EntityDataServiceManager>(systemProcess), "EntityDataServiceManager")).ConfigureAwait(false);
                    await Task.Run(() => ctx.ActorOf(Props.Create <EntityViewDataServiceManager>(systemProcess), "EntityViewDataServiceManager")).ConfigureAwait(false);


                    EventMessageBus.Current.Publish(
                        new ServiceStarted <IServiceManager>(this,
                                                             new StateEventInfo(systemProcess.Id, RevolutionData.Context.Actor.Events.ActorStarted),
                                                             systemProcess, Source), Source);
                });

                Task.Run(() => ctx.ActorOf(Props.Create <ProcessSupervisor>(autoRun, systemStartedMsg, processInfos, complexEventActions), "ProcessSupervisor")).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Debugger.Break();
                EventMessageBus.Current.Publish(new ProcessEventFailure(failedEventType: typeof(ServiceStarted <IServiceManager>),
                                                                        failedEventMessage: null,
                                                                        expectedEventType: typeof(ServiceStarted <IServiceManager>),
                                                                        exception: ex,
                                                                        source: Source, processInfo: new StateEventInfo(1, RevolutionData.Context.Process.Events.Error)), Source);
            }
        }
コード例 #19
0
        protected override void RunJournalCommand()
        {
            if (Last)
            {
                var journal   = OpenJournal();
                var lastEntry = journal.CreateIndex <JournalEntryFile>().SelectMany(x => x.Entries).OrderByDescending(x => x.EntryDate).First();
                SystemProcess.Start(lastEntry.FilePath);
                return;
            }

            var       fileSystem    = new FileSystem();
            var       journalWriter = new JournalWriter(fileSystem, Location);
            string    path;
            LocalDate entryDate;

            switch (ParameterSetName)
            {
            case "Name":
            {
                entryDate = EntryName.EndsWith(".md") ? Journal.FileNameWithExtensionPattern.Parse(EntryName).Value : Journal.FileNamePattern.Parse(EntryName).Value;
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "Date":
            {
                entryDate = LocalDate.FromDateTime(Date);
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "DateOffset":
            {
                entryDate = Today.PlusDays(DateOffset);
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            case "Entry":
            {
                entryDate = Journal.FileNamePattern.Parse(Entry.EntryName).Value;
                path      = journalWriter.GetJournalEntryFilePath(entryDate);
                break;
            }

            default:
                throw new NotSupportedException();
            }

            if (!fileSystem.File.Exists(path))
            {
                throw new PSInvalidOperationException($"An entry does not exist for '{entryDate}'.");
            }

            SystemProcess.Start(path);
        }
コード例 #20
0
    public static void Start(string filename, string arguments)
    {
        ProcessStartInfo startInfo = SystemProcess.Prepare(filename, arguments);

        using (Process process = Process.Start(startInfo)) {
            SystemProcess.output = process.StandardOutput.ReadToEnd();
            SystemProcess.error  = process.StandardError.ReadToEnd();
            process.WaitForExit();
        }
    }
コード例 #21
0
        protected override void ProcessRecord()
        {
            if (!Directory.Exists(LogsDirectory))
            {
                WriteHostInverted("No logs have been created yet.");
                return;
            }

            SystemProcess.Start(LogsDirectory);
        }
コード例 #22
0
 public void TestMethod1()
 {
     var process = new Process { StartInfo = new ProcessStartInfo(Environment.SystemDirectory + "\\notepad.exe") };
     process.Start();
     using (var notepad = new SystemProcess(process))
     {
         Thread.Sleep(500);
         notepad.Kill();
     }
 }
コード例 #23
0
        /// <summary>given user name - get all the groups.</summary>
        /// <remarks>
        /// given user name - get all the groups.
        /// Needs to happen before creating the test users
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.Exception"/>
        public virtual void TestGetServerSideGroups()
        {
            // get the user name
            SystemProcess  pp = Runtime.GetRuntime().Exec("whoami");
            BufferedReader br = new BufferedReader(new InputStreamReader(pp.GetInputStream())
                                                   );
            string userName = br.ReadLine().Trim();

            // If on windows domain, token format is DOMAIN\\user and we want to
            // extract only the user name
            if (Shell.Windows)
            {
                int sp = userName.LastIndexOf('\\');
                if (sp != -1)
                {
                    userName = Runtime.Substring(userName, sp + 1);
                }
                // user names are case insensitive on Windows. Make consistent
                userName = StringUtils.ToLowerCase(userName);
            }
            // get the groups
            pp = Runtime.GetRuntime().Exec(Shell.Windows ? Shell.Winutils + " groups -F" : "id -Gn"
                                           );
            br = new BufferedReader(new InputStreamReader(pp.GetInputStream()));
            string line = br.ReadLine();

            System.Console.Out.WriteLine(userName + ":" + line);
            ICollection <string> groups = new LinkedHashSet <string>();

            string[] tokens = line.Split(Shell.TokenSeparatorRegex);
            foreach (string s in tokens)
            {
                groups.AddItem(s);
            }
            UserGroupInformation login = UserGroupInformation.GetCurrentUser();
            string loginUserName       = login.GetShortUserName();

            if (Shell.Windows)
            {
                // user names are case insensitive on Windows. Make consistent
                loginUserName = StringUtils.ToLowerCase(loginUserName);
            }
            Assert.Equal(userName, loginUserName);
            string[] gi = login.GetGroupNames();
            Assert.Equal(groups.Count, gi.Length);
            for (int i = 0; i < gi.Length; i++)
            {
                Assert.True(groups.Contains(gi[i]));
            }
            UserGroupInformation fakeUser = UserGroupInformation.CreateRemoteUser("foo.bar");

            fakeUser.DoAs(new _PrivilegedExceptionAction_248(login, fakeUser));
        }
コード例 #24
0
ファイル: Subversion.cs プロジェクト: L-proger/Subville
        public string Cat(string repoName, string path)
        {
            var repoPath = RepositoriesRoot + "/" + repoName;
            var subPath =  "/" + path;

            var result = SystemProcess.Execute("svnlook", false, $"cat {repoPath} {subPath}");
            if (result.exitCode != 0)
            {
                throw new Exception(string.Join("\r\n", result.errBuffer));
            }
            return  string.Join("\r\n", result.outBuffer);
        }
コード例 #25
0
ファイル: Subversion.cs プロジェクト: L-proger/Subville
        public SvnList List(string repoName, string path)
        {
            var listPath = FileSchemeRepositoriesRoot + "/" + repoName + "/" + path;

            var result = SystemProcess.Execute("svn", false, $"list  --xml \"{listPath}\"");
            var combinedResult = string.Join("\r\n", result.outBuffer);


            var lists = DeserializeXml<SvnLists>(combinedResult);
            return lists.Lists[0];

        }
コード例 #26
0
ファイル: DeployLog.cs プロジェクト: bbyars/CM.NET
        public DeployLog(SystemProcess process)
        {
            this.process = process;

            InitializeComponent();

            Load += (sender, e) => Initialize();
            process.OutputUpdated += (sender, e) => AppendOutput(e.Data);
            process.ErrorUpdated += (sender, e) => AppendError(e.Data);
            uxShowWorkingDirectory.Click += (sender, e) => ShowWorkingDirectory();
            uxKill.Click += (sender, e) => Kill();
            uxSave.Click += (sender, e) => SelectFile(Save);
        }
コード例 #27
0
        public void TestMethod1()
        {
            var process = new Process {
                StartInfo = new ProcessStartInfo(Environment.SystemDirectory + "\\notepad.exe")
            };

            process.Start();
            using (var notepad = new SystemProcess(process))
            {
                Thread.Sleep(500);
                notepad.Kill();
            }
        }
コード例 #28
0
        /// <summary>
        /// Run a given command in a subprocess, including threads to copy its stdout
        /// and stderr to our stdout and stderr.
        /// </summary>
        /// <param name="command">the command and its arguments</param>
        /// <param name="env">the environment to run the process in</param>
        /// <returns>a handle on the process</returns>
        /// <exception cref="System.IO.IOException"/>
        internal static SystemProcess RunClient(IList <string> command, IDictionary <string
                                                                                     , string> env)
        {
            ProcessStartInfo builder = new ProcessStartInfo(command);

            if (env != null)
            {
                builder.EnvironmentVariables.PutAll(env);
            }
            SystemProcess result = builder.Start();

            return(result);
        }
コード例 #29
0
        public SystemProcess GetSystemProcessByName(string processName)
        {
            //ISystemProcessService systemProcessService = IoC.Resolve<ISystemProcessService>("SystemProcessService");
            SystemProcessService systemProcessService = new SystemProcessService();
            DataTransfer <ControlPanel.Core.DataTransfer.SystemProcess.GetOutput> dt = systemProcessService.GetSystemProcessByName(processName);

            if (dt != null && dt.IsSuccess)
            {
                SystemProcess process = new SystemProcess();
                process.CopyFrom(dt.Data);
                return(process);
            }
            return(null);
        }
コード例 #30
0
        private void OpenToDate()
        {
            var year       = Journal.YearDirectoryPattern.Format(LocalDate.FromDateTime(Date));
            var month      = Journal.MonthDirectoryPattern.Format(LocalDate.FromDateTime(Date));
            var fileSystem = new FileSystem();
            var path       = fileSystem.Path.Combine(Location, year, month);

            if (!fileSystem.Directory.Exists(path))
            {
                throw new PSInvalidOperationException("No directory currently exists for the selected period.");
            }

            SystemProcess.Start(path);
        }
        public async Task Get_RuleRun_UpdatesInDb()
        {
            var connFactory         = new ConnectionStringFactory(this._config);
            var processRepository   = new SystemProcessRepository(connFactory, this._processLogger);
            var operationRepository = new SystemProcessOperationRepository(connFactory, this._operationLogger);
            var ruleRunRepository   = new SystemProcessOperationRuleRunRepository(connFactory, this._logger);

            var systemProcess = new SystemProcess
            {
                MachineId         = Environment.MachineName,
                ProcessId         = Process.GetCurrentProcess().Id.ToString(),
                InstanceInitiated = DateTime.UtcNow,
                Heartbeat         = DateTime.UtcNow,
                SystemProcessType = SystemProcessType.DataImportService
            };

            systemProcess.Id = systemProcess.GenerateInstanceId();

            await processRepository.Create(systemProcess);

            var systemProcessOperation = new SystemProcessOperation
            {
                SystemProcessId = systemProcess.Id,
                OperationStart  = DateTime.UtcNow,
                OperationState  = OperationState.InProcess
            };

            await operationRepository.Create(systemProcessOperation);

            var systemProcessOperationRuleRun = new SystemProcessOperationRuleRun
            {
                SystemProcessOperationId = systemProcessOperation.Id,
                RuleDescription          = "High Profits",
                RuleVersion       = "1.0",
                ScheduleRuleStart = DateTime.UtcNow,
                ScheduleRuleEnd   = DateTime.UtcNow.AddMinutes(1),
                RuleParameterId   = "1",
                IsBackTest        = true,
                RuleTypeId        = (int)Rules.HighVolume
            };

            await ruleRunRepository.Create(systemProcessOperationRuleRun);

            await ruleRunRepository.Update(systemProcessOperationRuleRun);

            var etc = await ruleRunRepository.Get(new[] { systemProcessOperationRuleRun.Id.ToString() });

            Assert.IsTrue(true);
        }
コード例 #32
0
        protected override void ProcessRecord()
        {
            var fileSystem     = new FileSystem();
            var encryptedStore = EncryptedStoreFactory.Create <UserSettings>();
            var path           = UserSettings.Load(encryptedStore).BackupLocation;

            if (!string.IsNullOrEmpty(path) && fileSystem.Directory.Exists(path))
            {
                SystemProcess.Start(path);
            }
            else
            {
                throw new PSInvalidOperationException("Backup location not found");
            }
        }
コード例 #33
0
 /// <summary>Execute a command and return a single line of output as a String</summary>
 /// <param name="dir">Working directory for the command</param>
 /// <param name="command">as component array</param>
 /// <param name="encoding"></param>
 /// <returns>the one-line output of the command</returns>
 protected internal static string ReadPipe(FilePath dir, string[] command, string
                                           encoding)
 {
     try
     {
         SystemProcess  p        = Runtime.GetRuntime().Exec(command, null, dir);
         BufferedReader lineRead = new BufferedReader(new InputStreamReader(p.GetInputStream
                                                                                (), encoding));
         string r = null;
         try
         {
             r = lineRead.ReadLine();
         }
         finally
         {
             p.GetOutputStream().Close();
             p.GetErrorStream().Close();
             lineRead.Close();
         }
         for (; ;)
         {
             try
             {
                 if (p.WaitFor() == 0 && r != null && r.Length > 0)
                 {
                     return(r);
                 }
                 break;
             }
             catch (Exception)
             {
             }
         }
     }
     catch (IOException e)
     {
         // Stop bothering me, I have a zombie to reap.
         if (SystemReader.GetInstance().GetProperty("jgit.fs.debug") != null)
         {
             System.Console.Error.WriteLine(e);
         }
     }
     // Ignore error (but report)
     return(null);
 }
コード例 #34
0
        public async Task Update_UpdatesADistributedRuleEntity_AsExpected()
        {
            var connFactory          = new ConnectionStringFactory(this._config);
            var processRepository    = new SystemProcessRepository(connFactory, this._processLogger);
            var operationRepository  = new SystemProcessOperationRepository(connFactory, this._operationLogger);
            var distributeRepository = new SystemProcessOperationDistributeRuleRepository(connFactory, this._logger);

            var systemProcess = new SystemProcess
            {
                MachineId         = Environment.MachineName,
                ProcessId         = Process.GetCurrentProcess().Id.ToString(),
                InstanceInitiated = DateTime.UtcNow,
                Heartbeat         = DateTime.UtcNow,
                SystemProcessType = SystemProcessType.DataImportService
            };

            systemProcess.Id = systemProcess.GenerateInstanceId();

            await processRepository.Create(systemProcess);

            var systemProcessOperation = new SystemProcessOperation
            {
                SystemProcessId = systemProcess.Id,
                OperationStart  = DateTime.UtcNow,
                OperationState  = OperationState.InProcess
            };

            await operationRepository.Create(systemProcessOperation);

            var systemProcessOperationRuleRun = new SystemProcessOperationDistributeRule
            {
                SystemProcessOperationId = systemProcessOperation.Id,
                ScheduleRuleInitialStart = DateTime.UtcNow,
                ScheduleRuleInitialEnd   = DateTime.UtcNow.AddMinutes(30),
                RulesDistributed         = "High Profits, Marking The Close"
            };

            await distributeRepository.Create(systemProcessOperationRuleRun);

            systemProcessOperationRuleRun.RulesDistributed = "Spoofing";

            await distributeRepository.Update(systemProcessOperationRuleRun);

            Assert.IsTrue(true);
        }
コード例 #35
0
ファイル: SvnProvider.cs プロジェクト: bbyars/CM.NET
 private void LogFailure(SystemProcess process)
 {
     log.Error(process.ToString());
     throw new Exception("svn command failed");
 }
コード例 #36
0
        /// <summary>
        /// Starts the process.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Cannot Start Running Process.</exception>
        /// <exception cref="ProcessHelpers.PsExecCommandException">PSTools command did not successfully complete</exception>
        public void Start()
        {
            if (this.IsProcessRunning)
            {
                throw new InvalidOperationException("Cannot Start Running Process.");
            }

            /* Command: Use PsExec http://ss64.com/nt/psexec.html
             * - i : Interactive - Run the program so that it interacts with the desktop on the remote system.
             * - d : Don’t wait for the application to terminate.
             * - accepteula: Suppress the display of the license dialog.
             */
            const string Args = @" -accepteula -i -d \\{0}{1} ""{2}""";

            using (
                var psExecProcess = new Process()
                {
                    StartInfo =
                        new ProcessStartInfo()
                        {
                            UseShellExecute = false,
                            RedirectStandardOutput = false,
                            RedirectStandardError = true,
                            RedirectStandardInput = true,
                            FileName = this.config.ExecPath,
                            Arguments = string.Format(Args, this.hostname, this.GetCredentialPowershellArgs(), this.exePath)
                        }
                })
            using (var psExec = new SystemProcess(psExecProcess, x => x.Kill()))
            {
                psExec.Start();
                var standardError = ReadWithTimeout(psExecProcess.StandardError);

                if (!standardError.Contains(string.Format("started on {0} with process ID", this.hostname)))
                {
                    throw new PsExecCommandException(string.Format("Failure running PsExec: {0}", standardError));
                }

                this.processId = this.GetPid(standardError);
            }

            this.IsProcessRunning = true;
        }
コード例 #37
0
        /// <summary>
        /// Immediately stops the associated process.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Cannot Terminate Non-Running Process.</exception>
        /// <exception cref="PsExecCommandException">PSTools command did not successfully complete</exception>
        public void Kill()
        {
            if (!this.IsProcessRunning)
            {
                throw new InvalidOperationException("Cannot Terminate Non-Running Process.");
            }

            /* Command: Use PsKill http://ss64.com/nt/pskill.html
             * - accepteula: Suppress the display of the license dialog.
             */
            const string Args = @" -accepteula \\{0} ""{1}""";

            using (
                var psKillProcess = new Process()
                {
                    StartInfo =
                        new ProcessStartInfo()
                        {
                            UseShellExecute = false,
                            RedirectStandardOutput = true,
                            RedirectStandardError = false,
                            RedirectStandardInput = true,
                            FileName = this.config.KillPath,
                            Arguments = string.Format(Args, this.hostname, this.processId) // -t treekill seems to regularly cause PsKill to crash
                        }
                })
            using (var psKill = new SystemProcess(psKillProcess, x => x.Kill()))
            {
                psKill.Start();

                var standardOutput = ReadWithTimeout(psKillProcess.StandardOutput);

                if (
                    !(standardOutput.Contains(string.Format("Process {0} killed", this.processId))
                      || standardOutput.Contains(string.Format("Process {0} on {1} killed", this.processId, this.hostname))))
                {
                    throw new PsExecCommandException(string.Format("Failure running PsExec: {0}", standardOutput));
                }
            }

            this.IsProcessRunning = false;
        }
コード例 #38
0
ファイル: DeployForm.cs プロジェクト: bbyars/CM.NET
 private static void ShowDeployLog(SystemProcess process)
 {
     var logForm = new DeployLog(process);
     logForm.Show();
 }