Skip to content

Instantly share code, notes, and snippets.

@ralfw
Last active August 29, 2015 14:15
Show Gist options
  • Save ralfw/dcf73a10856667b3fb4b to your computer and use it in GitHub Desktop.
Save ralfw/dcf73a10856667b3fb4b to your computer and use it in GitHub Desktop.
CLI µService Adapters
using System;
using System.Collections.Generic;
using System.Diagnostics;
public class ConsoleServiceProvider : IDisposable
{
private readonly string serviceFilepath;
private readonly string commandlineParams;
public ConsoleServiceProvider(string serviceFilepath) : this(serviceFilepath, "") { }
public ConsoleServiceProvider(string serviceFilepath, string commandlineParams)
{
this.commandlineParams = commandlineParams;
this.serviceFilepath = serviceFilepath;
}
public string Process(string input) { return Process(this.commandlineParams, input); }
public string Process(string commandlineParams, string input)
{
var p = new Process
{
StartInfo = new ProcessStartInfo(this.serviceFilepath, commandlineParams)
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
p.Start();
p.StandardInput.Write(input);
p.StandardInput.Close();
var output = new List<string>();
p.OutputDataReceived += (sender, e) => output.Add(e.Data);
p.BeginOutputReadLine();
p.WaitForExit();
return string.Join("\n", output);
}
#region IDisposable implementation
public void Dispose() { }
#endregion
}
public class ConsoleServicePortal : IDisposable {
public string Receive() {
var message = "";
var l = "";
while ((l = Console.ReadLine()) != null) {
if (message != "") message += "\n";
message += l;
}
return message;
}
public void Send(string message) {
Console.Write(message);
}
#region IDisposable implementation
public void Dispose () {}
#endregion
}
class Program
{
static void Main(string[] args)
{
using (var p = new servicewrappers.ConsoleServicePortal ()) {
var input = p.Receive ();
p.Send (string.Format("<<<{0}, {1}>>>", args[0], input.ToUpper ()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment