static void Main(string[] args) { Console.WriteLine("Hello World!"); var factory = new ProcessFactory(); var process = factory.Create("INSERT"); }
public void LaunchUrl(string url) { if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows && EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.OSX) { throw new NotImplementedException(); } var process = ProcessFactory.Create(new ProcessOptions { FileName = url, //EnableRaisingEvents = true, UseShellExecute = true, ErrorDialog = false }); process.Exited += ProcessExited; try { process.Start(); } catch (Exception ex) { Console.WriteLine("Error launching url: {0}", url); Logger.ErrorException("Error launching url: {0}", ex, url); throw; } }
public void test2() { var e1 = new DeveloperCreated { Name = "Vasya" }; var e2 = new DeveloperCreated { Name = "Dima" }; var state = new DeveloperState(); state.Apply(e2); state.Apply(e1); state.Apply(e2); state.Apply(e1); var factory = new ProcessFactory(); var agr = factory.Create <DeveloperAR>(); var result = agr.Execute(new ChangeDeveloperName() { NewName = "Cohen" }, new CommandMetadata(), state); Assert.That(((DeveloperNameChanged)result.First().Message).NewName, Is.EqualTo("Cohen")); }
public TransformalizeResponse Run(TransformalizeRequest request) { var moduleVersion = _extensionManager.GetExtension("Transformalize.Orchard").Version; var logger = new TransformalizeLogger(request.Part.Title(), request.Part.LogLevel, Logger, OrchardVersion, moduleVersion); var processes = new List <Process>(); //transitioning to using TflRoot instead of string configuration if (request.Root != null) { processes.AddRange(ProcessFactory.Create(request.Root, logger, request.Options)); } else //legacy { processes.AddRange(ProcessFactory.Create(request.Configuration, logger, request.Options, request.Query)); } for (var i = 0; i < processes.Count; i++) { var process = processes[i]; CreateInputOperation(process, request); process.ExecuteScaler(); } return(new TransformalizeResponse() { Processes = processes.ToArray(), Log = logger.Dump().ToList() }); }
public void TestPrimaryOutput() { var input = new RowsBuilder() .Row("id", 1).Field("name", "one") .Row("id", 2).Field("name", "two") .Row("id", 3).Field("name", "three") .ToOperation(); var xml = @"<tfl><processes> <add name='process'> <connections> <add name='input' provider='internal' /> <add name='output' provider='internal' /> </connections> <entities> <add name='entity'> <fields> <add name='id' type='int' primary-key='true' /> <add name='name' /> </fields> </add> </entities> </add> </processes></tfl>".Replace('\'', '"'); var process = ProcessFactory.Create(xml, new TestLogger())[0]; process.Entities[0].InputOperation = input; var output = process.Execute(); Assert.IsInstanceOf <IEnumerable <Row> >(output); Assert.AreEqual(3, output.Count()); }
/// <summary> /// Specify process to invoke /// </summary> /// <typeparam name="TProcess"></typeparam> /// <returns></returns> public TProcess For <TProcess>() where TProcess : class, IBaseProcess <VoidResult>, new() { var processType = typeof(TProcess); var instance = ProcessFactory.Create <VoidResult>(processType); return(instance as TProcess); }
/// <summary> /// Load an existing windows process configuration from disk. /// </summary> /// <param name="name">display name for process</param> /// <param name="config">windows process configuration</param> public static void Load(string name, out IProcessConfig config) { config = null; using (FileStream stream = ReadStream(name)) { config = (IProcessConfig)ProcessFactory.Create(stream); } }
public void TestBase() { var northWind = ProcessFactory.Create("NorthWind.xml", new TestLogger())[0]; Assert.AreEqual("int16", northWind.Entities[0].Fields["OrderDetailsQuantity"].Type); Assert.AreEqual(8, northWind.Entities.Count); Assert.AreEqual(3, northWind.Entities[1].CalculatedFields.Count); Assert.AreEqual(2, northWind.FileInspectionRequest.DataTypes.Count); }
private async Task <RefLoadResult> TryRegularBranchCheckoutAsync(string branchName) { var checkoutProcess = ProcessFactory.Create("git", $"checkout -b {branchName}-branch origin/{branchName}"); var(succeeded, _, _, branchLoadError) = await ProcessExecutor.ExecuteAsync(checkoutProcess); if (!succeeded) { _logger.LogError("Failed to load branch. Error:{newLine}{error}}", Environment.NewLine, branchLoadError); } return(new RefLoadResult(succeeded, succeeded ? null : branchLoadError)); }
/// <summary> /// 创建一个分析请求 /// </summary> /// <param name="uri">分析的Uri</param> /// <returns>返回Html对象</returns> public static Html CreatHtml(Uri uri) { try { if (_processors == null) { InitProcessors(new HtmlProcessor()); } var request = CreateRequest(uri); request.UserAgent = "[Iveely Computing]-Create By [email protected], Share in Open Source Community!"; //request.Credentials = new NetworkCredential("spidertest", "iveely123456"); //获取响应 using (var response = (HttpWebResponse)request.GetResponse()) { // 只取文本数据 if (response.ContentType.Contains("text/html")) { //处理获取到得响应结果 using (var crawlerContent = ProcessFactory.Create(uri, response)) { Html html = new Html(); html.Title = crawlerContent.GetTitle(); // response.Headers[] for (int i = 0; i < response.Headers.Count; ++i) { if (response.Headers.Keys[i] == "Expires") { html.Timestamp = response.Headers[i]; break; } } html.Content = crawlerContent.GetContent(); html.SourceCode = crawlerContent.Text; html.ChildrenLink = new List <Uri>(ProcessContent(crawlerContent, uri)); return(html); } } return(null); } } catch (Exception exception) { Logger.Error(uri + "->" + exception); return(null); } }
/// <summary> /// Handle the request /// </summary> /// <returns></returns> public TResponse Dispatch <T1, T2, T3, TResponse>(Type processType, T1 obj1, T2 obj2, T3 obj3) where TResponse : VoidResult, new() { // create instance var process = ProcessFactory.Create <TResponse>(processType); if (process.IsNull()) { return(VoidResult.FaultedResult <TResponse>()); } // execute process var response = ProcessExecutor.Execute(process, obj1, obj2, obj3); return(response); }
public void TestSecondaryOutputs() { var file1 = Path.GetTempFileName(); var file2 = Path.GetTempFileName(); var input = new RowsBuilder() .Row("id", 1).Field("name", "one") .Row("id", 2).Field("name", "two") .Row("id", 3).Field("name", "three") .ToOperation(); var xml = string.Format(@"<tfl><processes> <add name='process'> <connections> <add name='input' provider='internal' /> <add name='output' provider='internal' /> <add name='c1' provider='file' file='{0}' /> <add name='c2' provider='file' file='{1}' /> </connections> <entities> <add name='name'> <output> <add name='o1' connection='c1' run-field='name' run-value='two' /> <add name='o2' connection='c2' run-field='id' run-operator='GreaterThan' run-type='int' run-value='1' /> </output> <fields> <add name='id' type='int' primary-key='true' /> <add name='name' /> </fields> </add> </entities> </add> </processes></tfl>", file1, file2).Replace('\'', '"'); var process = ProcessFactory.Create(xml, new TestLogger())[0]; process.Entities[0].InputOperation = input; var rows = process.Execute(); Assert.IsNotNull(rows); Assert.AreEqual(3, rows.Count()); const int header = 1; Assert.AreEqual(1, File.ReadAllLines(file1).Length - header); Assert.AreEqual(2, File.ReadAllLines(file2).Length - header); }
/// <summary> /// Creates the lsp server process object /// </summary> /// <returns></returns> public System.Diagnostics.Process Create(TraceLevel?traceLevel = TraceLevel.Info) { var assembly = Assembly.GetAssembly(typeof(LanguageServerClientProcess)); string arguments = null; var exe = @"node.exe"; var logPath = $"{Application.LogPath}{Application.LogNameAgent}"; #if DEBUG var path = Path.GetDirectoryName(assembly.Location) + @"\dist\agent.js"; arguments = $@"--nolazy --inspect=6010 ""{path}"" --stdio --log={logPath}"; Node.EnsureVersion(exe); #else exe = Path.GetDirectoryName(assembly.Location) + @"\dist\agent.exe"; arguments = $@"--stdio --nolazy --log={logPath}"; #endif return(ProcessFactory.Create(exe, arguments, false)); }
/// <summary> /// Handle the request /// </summary> /// <returns></returns> public TResponse Dispatch <TProcess, T1, T2, TResponse>(T1 obj1, T2 obj2) where TProcess : IBaseProcess <TResponse>, new() where TResponse : VoidResult, new() { // create instance var process = ProcessFactory.Create <TResponse>(typeof(TProcess)); if (process.IsNull()) { return(VoidResult.FaultedResult <TResponse>()); } // execute process var response = ProcessExecutor.Execute(process, obj1, obj2); return(response); }
public async Task <ProjectPublishResult> PublishAsync(Uri projectUri, Uri cloneBasePath) { var publishPath = Path.Combine(cloneBasePath.LocalPath, "publish"); var process = ProcessFactory.Create("dotnet", $"publish -c Release {projectUri.LocalPath} -o {publishPath}"); var(succeeded, _, _, publishError) = await ProcessExecutor.ExecuteAsync(process); if (!succeeded) { _logger.LogError("Failed to load branch. Error:{newLine}{error}}", Environment.NewLine, publishError); } return(succeeded ? new ProjectPublishResult(true, new Uri(publishPath)) : new ProjectPublishResult(false, publishError)); }
public void Report() { var matches = ((TransformalizeConfiguration)ConfigurationManager.GetSection("transformalize")).Processes.Cast <ProcessConfigurationElement>().Where(p => p.Name.Equals(JUNK_SUMMARY, StringComparison.OrdinalIgnoreCase)).ToArray(); if (matches.Length <= 0) { return; } try { ProcessFactory.Create(JUNK_SUMMARY, new Options() { Mode = "init" })[0].ExecuteScaler(); ProcessFactory.Create(JUNK_SUMMARY)[0].ExecuteScaler(); } catch (Exception e) { _log.Warn("Sorry. I couldn't produce the junk summary {0}. {1}.", matches[0].Connections["output"].File, e.Message); } }
public void DomainReturningIsValid() { var input = new RowsBuilder() .Row("in", 2) .Row("in", 4).ToOperation(); var xml = @" <cfg> <processes> <add name='process'> <connections> <add name='input' provider='internal' /> <add name='output' provider='internal' /> </connections> <entities> <add name='entity'> <fields> <add name='in' type='int' /> </fields> <calculated-fields> <add name='out' type='bool'> <transforms> <add method='domain' domain='1,2,3' parameter='in' /> </transforms> </add> </calculated-fields> </add> </entities> </add> </processes> </cfg> ".Replace('\'', '"'); var process = ProcessFactory.Create(xml, new TestLogger())[0]; process.Entities[0].InputOperation = input; var output = process.Execute().ToArray(); Assert.AreEqual(true, output[0]["out"]); Assert.AreEqual(false, output[1]["out"]); }
public async Task <string> RunAsync(Uri benchmarkBinariesUri, string assemblyName, string benchmarkName) { var currentDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(benchmarkBinariesUri.LocalPath); var benchmarkProcess = ProcessFactory.Create("dotnet", $"{assemblyName} -i --filter *{benchmarkName}*"); var(succeeded, _, benchmarkOutput, benchmarkError) = await ProcessExecutor.ExecuteAsync(benchmarkProcess); Directory.SetCurrentDirectory(currentDirectory); if (!succeeded) { _logger.LogError("Failed to execute Benchmark. Error:{newLine}{error}}", Environment.NewLine, benchmarkError); } return(succeeded ? benchmarkOutput : benchmarkError); }
public static void Main(string[] args) { string filepath = Path.Combine(typeof(TestProgramWhileTrue.Program).Assembly.Location); var factory = new ProcessFactory(); using (var processInfo = factory.Create(null, filepath, true, ProcessCreationFlags.NewConsole, (IEnvironmentBlock)null, null, new ProcessStartInfo())) { Thread.Sleep(20000); var memoryCounters = processInfo.Process.GetProcessMemoryCounters(); Console.WriteLine("Memory Counters:"); Console.WriteLine("----------------"); Console.WriteLine("- PageFaultCount: {0}", memoryCounters.PageFaultCount); Console.WriteLine("- PagefileUsage: {0}", memoryCounters.PagefileUsage); Console.WriteLine("- PeakPagefileUsage: {0}", memoryCounters.PeakPagefileUsage); Console.WriteLine("- PeakWorkingSetSize: {0}", memoryCounters.PeakWorkingSetSize); Console.WriteLine("- PrivateUsage: {0}", memoryCounters.PrivateUsage); Console.WriteLine("- QuotaNonPagedPoolUsage: {0}", memoryCounters.QuotaNonPagedPoolUsage); Console.WriteLine("- QuotaPagedPoolUsage: {0}", memoryCounters.QuotaPagedPoolUsage); Console.WriteLine("- QuotaPeakNonPagedPoolUsage: {0}", memoryCounters.QuotaPeakNonPagedPoolUsage); Console.WriteLine("- QuotaPeakPagedPoolUsage: {0}", memoryCounters.QuotaPeakPagedPoolUsage); Console.WriteLine("- WorkingSetSize: {0}", memoryCounters.WorkingSetSize); processInfo.Process.Terminate(0); var processTimes = processInfo.Process.GetProcessTimes(); Console.WriteLine(); Console.WriteLine("Process times:"); Console.WriteLine("--------------"); Console.WriteLine("- CreationTime: {0}", processTimes.CreationTime); Console.WriteLine("- ExitTime: {0}", processTimes.ExitTime); Console.WriteLine("- KernelTime: {0}", processTimes.KernelTime); Console.WriteLine("- UserTime: {0}", processTimes.UserTime); } Console.WriteLine("Press any key to quit..."); Console.ReadKey(intercept: true); }
public async Task <RepositoryCloneResult> CloneAync(Uri repositoryUri, string target, string traceIdentifier) { var cloneBasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), ".autofacbot", traceIdentifier, target.ToString()); var clonePath = Path.Combine(cloneBasePath, "src"); var cloneProcess = ProcessFactory.Create("git", $"clone {repositoryUri} {clonePath}"); var(succeeded, _, _, cloneError) = await ProcessExecutor.ExecuteAsync(cloneProcess); if (!succeeded) { _logger.LogError("Failed to clone repository. Error:{newLine}{error}}", Environment.NewLine, cloneError); } return(succeeded ? new RepositoryCloneResult(true, new Uri(cloneBasePath), new Uri(clonePath)) : new RepositoryCloneResult(false, cloneError)); }
private static void Main(string[] args) { var processes = new List <Process>(); if (args.Length == 0) { Console.WriteLine("Please provide the process(es) name, file, or address."); Console.WriteLine(@"Usage:"); Console.WriteLine(@" tfl fancy - looks in tfl.exe.config for fancy process."); Console.WriteLine(@" tfl c:\fancy.xml - looks for processes in c:\fancy.xml file."); Console.WriteLine(@" tfl http://localhost/fancy.xml - makes web request for processes in http://localhost/fancy.xml."); return; } var resource = args[0]; _options = new Options(CombineArguments(args)); var listener = new ObservableEventListener(); listener.EnableEvents(TflEventSource.Log, _options.LogLevel); var subscription = listener.LogToConsole(new LegacyLogFormatter()); try { if (OptionsMayExist(args)) { if (_options.Valid()) { if (_options.Mode == "rebuild") { _options.Mode = "init"; processes.AddRange(ProcessFactory.Create(resource, new RunLogger(), _options)); _options.Mode = "first"; processes.AddRange(ProcessFactory.Create(resource, new RunLogger(), _options)); } else { processes.AddRange(ProcessFactory.Create(resource, new RunLogger(), _options)); } } else { foreach (var problem in _options.Problems) { Console.WriteLine(resource + " | " + problem); } Console.WriteLine(resource + " | Aborting process."); Environment.Exit(1); } } else { processes.AddRange(ProcessFactory.Create(resource, new RunLogger())); } } catch (Exception e) { Console.WriteLine(e.Message); listener.DisableEvents(TflEventSource.Log); listener.Dispose(); return; } foreach (var process in processes) { try { process.ExecuteScaler(); } catch (TransformalizeException e) { Console.WriteLine(e.Message); break; } } listener.DisableEvents(TflEventSource.Log); listener.Dispose(); subscription.Dispose(); }
/// <summary> /// Creates an ActiveProcess within the TQF /// </summary> /// <param name="name">Unique name for the ActiveProcess</param> public static void Create(string name) { Create(ProcessFactory.Create(name)); }
/// <summary> /// Create a new windows process configuration filled with default values. /// </summary> /// <param name="name">display name for process</param> /// <param name="config">windows process configuration</param> public static void Create(string name, out IProcessConfig config) { config = (IProcessConfig)ProcessFactory.Create(name); }
/// <summary> /// Creates an ActiveProcess within the TQF /// </summary> /// <param name="stream">Configuration stream compatible with the WindowsProcess class</param> public static void Create(Stream stream) { Create(ProcessFactory.Create(stream)); }
/// <summary> /// Handle the request /// </summary> /// <param name="context">For testing</param> /// <returns></returns> public MiddlewareResult Dispatch(IHttpContextWrapper context = null) { var httpContext = context ?? SystemBootstrapper.GetInstance <IHttpContextWrapper>(); // execute custom url handlers foreach (var handler in CustomUrlHandlers) { var result = handler.RenderContent(httpContext); // check if url maches if (result != MiddlewareResult.DoNothing) { return(result); } } // get valid process type var validType = ProcessRepository.All(type => Filters.All(filter => filter.IsCorrectProcessType(type, httpContext))).FirstOrDefault(); if (validType.IsNull()) { return(MiddlewareResult.StopExecutionAndInvokeNextMiddleware); } // create instance var process = ProcessFactory.Create <VoidResult>(validType); if (process.IsNull()) { return(MiddlewareResult.StopExecutionAndInvokeNextMiddleware); } // execute factory filters foreach (var createEvent in FactoryFilters) { var result = createEvent.IsValidInstance(process, validType, httpContext); if (result != MiddlewareResult.DoNothing) { return(result); } } var method = EnumExtensions.FromString <SignalsApiMethod>(httpContext.HttpMethod?.ToUpper()); // determine the parameter binding method var parameterBindingAttribute = validType? .GetCustomAttributes(typeof(SignalsParameterBindingAttribute), false) .Cast <SignalsParameterBindingAttribute>() .FirstOrDefault(); // resolve default if not provided if (parameterBindingAttribute.IsNull()) { DefaultModelBinders.TryGetValue(method, out var modelBinder); parameterBindingAttribute = new SignalsParameterBindingAttribute(modelBinder); } var requestInput = parameterBindingAttribute.Binder.Bind(httpContext); // execute process var response = new VoidResult(); // decide if we need to execute switch (method) { case SignalsApiMethod.OPTIONS: case SignalsApiMethod.HEAD: break; default: response = ProcessExecutor.Execute(process, requestInput); break; } // post execution events foreach (var executeEvent in ResultHandlers) { var result = executeEvent.HandleAfterExecution(process, validType, response, httpContext); if (result != MiddlewareResult.DoNothing) { // flag to stop pipe execution return(result); } } // flag to stop pipe execution return(MiddlewareResult.StopExecutionAndStopMiddlewarePipe); }