I'm currently working on a project and one of the featured devices is a Windows Tablet. To "connect" it to other devices (like some Raspberry Pi) in the project environment UDP is used to send messages. The Windows Tablet is intended to be some controlling device with soem touch functionality. Therefore I'm writing an App (and the intention of the App is not to put it into the Windows Store). The UDP part in this work is quite painful because I had to do much research since I started with no experience in App programming. More painful than the programming is, that I practically finished the work only to start over again because the App didn't receive UDP anymore.
Here's my code (I removed elements not relevant to the actual problem). I apologize for the bad coding....
App.xaml.cs:
sealed partial class App : Application
{
NetworkInterface ni = new NetworkInterface();
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
ni.MessageReceived += OnMessageReceived;
ni.Connect(new HostName("127.0.0.1"), "5556");
}
private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
Debug.WriteLine("Processing");
Debug.WriteLine(e.Message.Data);
}
public static new App Current
{
get { return Application.Current as App; }
}
private DatagramSocket _socket;
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Update_Timer();
}
DispatcherTimer timer = new DispatcherTimer();
private void Update_Timer()
{
timer.Start();
timer.Interval = new TimeSpan(0,0,0,0,500);
timer.Tick += alive;
}
private void alive(object sender, object e)
{
if (start == 0) {
Debug.WriteLine("App-Startup");
ni.SendMessage("Startup...");
start++;
}
else
{
Debug.WriteLine("App-Alive");
ni.SendMessage("alive");
start++;
}
}
}
This part of code is to send and receive Messages in the backgrond in the whole App.
And a NetworkInterface class:
class NetworkInterface
{
private DatagramSocket _socket;
public bool IsConnected { get; set; }
public NetworkInterface()
{
IsConnected = false;
_socket = new DatagramSocket();
_socket.MessageReceived += OnSocketMessageReceived;
}
public async void Connect(HostName remoteHostName, string remoteServiceNameOrPort)
{
if (IsConnected != true)
{
await _socket.BindServiceNameAsync("5321");
await _socket.ConnectAsync(remoteHostName, remoteServiceNameOrPort);
}
IsConnected = true;
}
public void alive(object sender, object e)
{
Debug.WriteLine("alive");
}
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
var reader = args.GetDataReader();
var count = reader.UnconsumedBufferLength;
var data = reader.ReadString(count);
Debug.WriteLine(args);
if (MessageReceived != null)
{
var ea = new MessageReceivedEventArgs();
ea.Message = new Message() { Data = data };
ea.RemoteHostName = args.RemoteAddress;
ea.RemotePort = args.RemotePort;
MessageReceived(this, ea);
}
}
DataWriter _writer = null;
public async void SendMessage(string message)
{
if (_writer == null)
{
var stream = _socket.OutputStream;
_writer = new DataWriter(stream);
}
_writer.WriteString(message);
await _writer.StoreAsync();
}
}
The main problems are:
If I dont send something before receiving, I won't be able top get an message.
If I send before I have random Faults at this line:
var reader = args.GetDataReader();
If nothing fails, I'm not able to receive messages from a local Python script (which works) but I can send messages from a local program which the App receives.
Does anyone know how I can fix these problems?
Thanks in advance!
Related
so bascially i have a console application acting as a client software receiving data from a WCF feed. this works just fine when i want to do a console.writeline and print the data i'm getting in the console. I don't control the service end of the WCF feed so i have to use this console client software to access the data.
I'm trying to build an ASP.net web api application to pass this data to my own client via REST api. There are other complex reasons i have to do it this way but when it comes down to it i have to. I've built the basic web api for doing a GET to get the information. added the console application as a resource to the web api application but get an error message when I make the GET call.
This is the URL i'm using to make the GET call.
http://localhost:60421/api/CallData?skillNumber=92
After i make this call i get the below error message
[ERROR] System.InvalidOperationException occurred
HResult=0x80131509
Message=Could not find default endpoint element that references contract 'FeedService.IFeedService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
Source=
StackTrace:
The error occurs in this cs file. I've commented at the line it occurs in.
using ScoreBoardClientTest.FeedService;
namespace ScoreBoardClientTest
{
public class FeedServiceAgent : IFeedServiceAgent, IFeedServiceCallback
{
private static FeedServiceClient _feedServiceClient;
private ConnectionStats.ConnectionStatus _connectionStatus;
private bool _retrying;
private bool _disposed;
public FeedServiceAgent() //(IEventAggregator eventAggregator)
{
//Guard.ArgumentNotNull(eventAggregator, "eventAggregator");
//_eventAggregator = eventAggregator;
InitializeServiceClient();
}
public event MessageReceivedEventHandler MessageReceived;
public void InitializeServiceClient()
{
// The error message occurs at the line right below this
_feedServiceClient = new FeedServiceClient(new InstanceContext(this));
_feedServiceClient.InnerChannel.Opening += OnOpening;
_feedServiceClient.InnerChannel.Opened += OnOpened;
_feedServiceClient.InnerChannel.Closing += OnClosing;
_feedServiceClient.InnerChannel.Closed += OnClosed;
_feedServiceClient.InnerChannel.Faulted += OnFaulted;
}
private void DisposeServiceClient()
{
if (_feedServiceClient == null)
return;
try
{
_feedServiceClient.InnerChannel.Opening -= OnOpening;
_feedServiceClient.InnerChannel.Opened -= OnOpened;
_feedServiceClient.InnerChannel.Closing -= OnClosing;
_feedServiceClient.InnerChannel.Closed -= OnClosed;
_feedServiceClient.InnerChannel.Faulted -= OnFaulted;
_feedServiceClient.Abort();
}
catch
{
//Don't care.
}
finally
{
_feedServiceClient = null;
}
}
public ConnectionStats.ConnectionStatus ConnectionStatus
{
get { return _connectionStatus; }
set
{
_connectionStatus = value;
PublishConnectionStatus();
}
}
private void PublishConnectionStatus()
{
}
private void ProcessCmsData(A cmsData)
{
if (cmsData == null)
return;
var skill = new Skill();
var agents = new List<Agent>();
var cmLookupdata = new List<CmLookupData>();
// LookupData lookupdata = new LookupData();
if (cmsData.C != null && cmsData.C.Length > 0)
LookupDataTranslator.Translate(cmsData.C, cmLookupdata);
if (cmsData.AMember != null)
SkillTranslator.Translate(cmsData.AMember, skill, cmLookupdata);
if (cmsData.B != null && cmsData.B.Length > 0)
AgentTranslator.Translate(cmsData.B, agents, cmsData.AMember.A, cmsData.AMember.CmId); // passing skill params to validate the cmid to discard bad data
var mappedCmsData = new CmsData(skill, agents, cmLookupdata);
if (MessageReceived != null)
MessageReceived(this, new MessageReceivedEventArgs(mappedCmsData, null));
}
#region FeedServiceClient Channel Events
private void OnOpening(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Connecting;
}
private void OnOpened(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Connected;
}
private void OnClosing(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnecting;
}
private void OnClosed(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
}
private void OnFaulted(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
if (!_retrying)
ThreadPool.QueueUserWorkItem(delegate
{
Reconnect();
});
}
#endregion
private void Reconnect()
{
_retrying = true;
_connectionStatus = ConnectionStats.ConnectionStatus.Reconnecting;
// We don't want each client attempting the first reconnect all at the same time.
var random = new Random();
int randomWaitValue = random.Next(1, 10000);
Thread.Sleep(randomWaitValue);
// Try reconnecting 10 times.
for (int i = 1; i <= 10; i++)
{
try
{
DisposeServiceClient();
_feedServiceClient = new FeedServiceClient(new InstanceContext(this));
_feedServiceClient.Open();
_feedServiceClient.InnerChannel.Opening += OnOpening;
_feedServiceClient.InnerChannel.Opened += OnOpened;
_feedServiceClient.InnerChannel.Closing += OnClosing;
_feedServiceClient.InnerChannel.Closed += OnClosed;
_feedServiceClient.InnerChannel.Faulted += OnFaulted;
_connectionStatus = ConnectionStats.ConnectionStatus.Reconnected;
_retrying = false;
//_logger.Info(String.Format("The Scoreboard Client was able to reconnect after {0} retries.", i)) ;
return;
}
catch (Exception exception)
{
//_logger.Error(String.Format("The Scoreboard Client is unable to reconnect: {0}", exception)) ;
// Wait 30 seconds between retries to reduce network congestion.
Thread.Sleep(30000);
}
}
//_logger.Info("The Scoreboard Client was unable to reconnect after 10 retries.") ;
_connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
}
#region Implementation of IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
if (disposing)
{
// Dispose managed resources here.
DisposeServiceClient();
}
_disposed = true;
}
#endregion
public void NotifyCmsData(A cmsData)
{
ThreadPool.QueueUserWorkItem(delegate
{
ProcessCmsData(cmsData);
});
}
public void Subscribe(string eventTopic, int cmId)
{
if (String.IsNullOrEmpty(eventTopic))
return;
InvokeAction(x => x.Subscribe(eventTopic, cmId));
}
public void Unsubscribe(string eventTopic, int cmId)
{
if (String.IsNullOrEmpty(eventTopic))
return;
InvokeAction(x => x.Unsubscribe(eventTopic, cmId));
}
public void RefreshCmsData()
{
throw new NotImplementedException();
}
public LookupData GetLookupData()
{
LookupData lookupdata = new LookupData();
try
{
LookupDataTranslator.Translate(_feedServiceClient.GetLookupData(), lookupdata);
}
catch (Exception e)
{
//if (_logger != null)
// _logger.Error("Exception in finding the lookup data. Exception:" + e.Message);
throw e;
}
return lookupdata;
}
private void InvokeAction(Action<IFeedService> action)
{
try
{
action(_feedServiceClient);
}
catch (Exception exception)
{
//_logger.Error(" Exception in FeedService InvokeAction:" + exception.ToString());
_connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
}
}
}
}
The console application has a properly configured config file for the console application which is what the error message suggests does not exist. also, as i said above the console application functions fully by itself.
QUESTION
How do you use a WCF console application as a resource for a web api successfully?
I had to include the FeedService web URL inside of the web api service as long as the console application
I'm trying to fetch emails as soon as they arrive in my inbox using MailSystem.NET library. Everything works fine IMAP client gets connected but my NewMessageReceived event is never fired.
Please Help
Below is the code:
public static Imap4Client _imap = new Imap4Client();
public string SenderEmailAddress = System.Configuration.ConfigurationManager.AppSettings["EmailAddress"];
public string SenderEmailPassword = System.Configuration.ConfigurationManager.AppSettings["EmailPassword"];
public static Mailbox inbox = new Mailbox();
protected void Application_Start()
{
var worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(StartIdleProcess);
if (worker.IsBusy)
worker.CancelAsync();
worker.RunWorkerAsync();
}
private void StartIdleProcess(object sender, DoWorkEventArgs e)
{
try
{
if (_imap != null && _imap.IsConnected)
{
_imap.StopIdle();
_imap.Disconnect();
}
_imap = new Imap4Client();
_imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
_imap.ConnectSsl("imap.gmail.com", 993);
_imap.Login(SenderEmailAddress, SenderEmailPassword);
inbox = _imap.SelectMailbox("inbox");
int[] ids = inbox.Search("UNSEEN");
inbox.Subscribe();
_imap.StartIdle();
}
catch (Exception ex)
{
}
}
public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
{
int offset = e.MessageCount - 2;
Message message = inbox.Fetch.MessageObject(offset);
Debug.WriteLine("message subject: " + message.Subject);
// Do something with the source...
_imap.StopIdle();
}
I can't tell you the exact reason but it seems that interacting with the imapclient from the NewMessageReceived event just doesn't work.
In NewMessageReceived call _imap.StopIdle() then continue in your main execution flow and restart idle. Then use a boolean to drop out of the loop entirely.
private bool _stop = false;
private void StartIdle(object sender, DoWorkEventArgs e)
{
//Setup client
_imap = new Imap4Client();
_imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
StartRepeatExecution();
}
public void StartRepeatExecution()
{
_imap.StartIdle();
if(_stop) return;
//Handle your new messages here! dummy code
var mailBox = _imap.SelectMailBox("inbox");
var messages = mailBox.SearchParse("").Last();
StartRepeatExecution();
}
public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
{
//StopIdle will return to where _imap.StartIdle() was called.
_imap.StopIdle();
}
public void StopRepeatExecution()
{
_stop = true;
}
I am trying to send information from my windows phone to the computer. I read some where that the usb cable is treated like a Ethernet cable. I created a server and a client(Phone is client) to try to send information. The program sends a message every time it presses enter.
Client Side
public sealed partial class MainPage : Page
{
private bool Connected;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private DatagramSocket dataGramSocket = new DatagramSocket();
private DataWriter socketWriter;
private bool messageSent;
private static string port = "138";
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
dataGramSocket.MessageReceived += dataGramSocket_MessageReceived;
StartListener();
}
void dataGramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
}
private async void StartListener()
{
string IpHostname = "127.0.0.1";
var IpAdresses = NetworkInformation.GetHostNames();
for (int i = 0; i < IpAdresses.Count; i++)
{
if (IpAdresses[i].IPInformation != null)
{
if (IpAdresses[i].IPInformation.NetworkAdapter.IanaInterfaceType == 6 && IpAdresses[i].DisplayName != null)
{
IpHostname = IpAdresses[i].DisplayName;
break;
}
else if (IpAdresses[i].IPInformation.NetworkAdapter.IanaInterfaceType == 71 && IpAdresses[i].DisplayName != null)
{
IpHostname = IpAdresses[i].DisplayName;
break;
}
}
}
HostName host = new HostName(IpHostname);
//EndpointPair endpoint = new EndpointPair(localHostName,)
await dataGramSocket.BindServiceNameAsync(port);
await dataGramSocket.ConnectAsync(host, port);
socketWriter = new DataWriter(dataGramSocket.OutputStream);
Connected = true;
}
private async void SendPacket()
{
await socketWriter.StoreAsync();
messageSent = true;
}
private void TextBox1_KeyDown(object sender, KeyRoutedEventArgs e)
{
if(e.Key == Windows.System.VirtualKey.Enter)
{
SendMessage(textBox1.Text);
}
}
private void SendMessage(string message)
{
socketWriter.WriteString(message);
SendPacket();
textBox1.Text = "";
}
}
}
Server Side
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static int port = 138;
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Task.Factory.StartNew(() =>
{
var dataStream = new MemoryStream(1024);
var udpClient = new UdpClient(port);
while (true)
{
if (udpClient.Available > 0)
{
udpClient.BeginReceive(ar =>
{
var clientEndPoint = new IPEndPoint(IPAddress.Any, port);
var bytesReceived = udpClient.EndReceive(ar, ref clientEndPoint);
dataStream.Write(bytesReceived, 0, bytesReceived.Length);
if (bytesReceived.Length > 0)
{
UpdateUI(Encoding.UTF8.GetString(bytesReceived));
UpdateUI(Encoding.ASCII.GetString(bytesReceived));
}
}, null);
}
Thread.Sleep(1);
}
}, _cancellationTokenSource.Token);
}
private void UpdateUI(string message)
{
this.Invoke(new MethodInvoker(delegate
{
this.textBox1.Text += message + Environment.NewLine;
}));
}
private void button1_Click_1(object sender, EventArgs e)
{
byte[] message = Encoding.UTF8.GetBytes(textBox2.Text);
using (var udpClient = new UdpClient())
{
udpClient.Send(message, message.Length, new IPEndPoint(IPAddress.Loopback, port));
}
textBox2.Clear();
}
}
}
The information isn't connecting somewhere in the middle. On both sides nothing breaks. When I test the form by sending information to the loopback it works. I don't know why the information is not reaching the other side. Can you please tell me if I am doing this write and it is suppose to be done this way or can you tell me if this is not possible so I can stop working on it.
I saw a similar question and I answered there, Communicate to PC over USB.
It requires editing the registry, the server code running on the device and I am not sure if the code will run outside of a development environment (I only need this to speed up my workflow and debugging - so its not an issue).
Not possible.
TCP/IP over USB worked OK in Windows Phone 7. In Windows Phone 8 however they removed the functionality.
Seek for other alternatives.
You could use TCP/IP over WiFi, or use BT, or write data to "Documents" and read with MTP COM API, or write data to isolated storage and read it using isetool.exe (this one only works for dev.unlocked devices).
I have been searching for the code which will help me if the internet connection breaks in between.
I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.
I got good ans here
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
Console.WriteLine("Complete.");
writer.Close();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
{
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
}
else
{
ConnectToPUServer();
}
}
This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?
you can use the below mentioned code for it you have to use
using System.Net.NetworkInformation;
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}
I'm having the hardest time trying to get this to work, hoping one of you has done this before.
I have a C# console app that is running a child process which inherits its console. I want a ctrl-c caught by the outer app to be passed along to the inner app so that it can have a chance to shut down nicely.
I have some very simple code. I start a Process, then poll it with WaitForExit(10). I also have a CancelKeyPress handler registered, which sets a bool to true when it fires. The polling loop also checks this, and when it's true, it calls GenerateConsoleCtrlEvent() (which I have mapped through pinvoke).
I've tried a lot of combinations of params to GenerateConsoleCtrlEvent(). 0 or 1 for the first param, and either 0 or the child process's ID for the second param. Nothing seems to work. Sometimes I get a false back and Marshal.GetLastWin32Error() returns 0, and sometimes I get true back. But none cause the child app to receive a ctrl-c.
To be absolutely sure, I wrote a test C# app to be the child app which prints out what's going on with it and verified that manually typing ctrl-c when it runs does properly cause it to quit.
I've been banging my head against this for a couple hours. Can anyone give me some pointers on where to go with this?
Not so sure this is a good approach. This only works if the child process is created with the CREATE_NEW_PROCESS_GROUP flag for CreateProcess(). The System.Diagnostics.Process class however does not support this.
Consider using the return value from the Main() method. There is already a unique value defined in the Windows SDK for Ctrl+C aborts, STATUS_CONTROL_C_EXIT or 0xC000013A. The parent process can get that return code from the Process.ExitCode property.
Did you have any luck with this? My understanding is that when you press CTRL+C in a console, by default all the processes attached to the console receive it, not just the parent one. Here's an example:
Child.cs:
using System;
public class MyClass
{
public static void CtrlCHandler(object sender, ConsoleCancelEventArgs args)
{
Console.WriteLine("Child killed by CTRL+C.");
}
public static void Main()
{
Console.WriteLine("Child start.");
Console.CancelKeyPress += CtrlCHandler;
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Child finish.");
}
}
Parent.cs:
using System;
public class MyClass
{
public static void CtrlCHandler(object sender, ConsoleCancelEventArgs args)
{
Console.WriteLine("Parent killed by CTRL+C.");
}
public static void Main()
{
Console.CancelKeyPress += CtrlCHandler;
Console.WriteLine("Parent start.");
System.Diagnostics.Process child = new System.Diagnostics.Process();
child.StartInfo.UseShellExecute = false;
child.StartInfo.FileName = "child.exe";
child.Start();
child.WaitForExit();
Console.WriteLine("Parent finish.");
}
}
Output:
Y:\>parent
Parent start.
Child start.
Parent killed by CTRL+C.
Child killed by CTRL+C.
^C
Y:\>parent
Parent start.
Child start.
Child finish.
Parent finish.
So I wouldn't have thought you'd need to do anything special. However, if you really need to generate CTRL+C events yourself, things might not be so easy. I'm not sure about the problems you describe, but as far as I can tell you can only send CTRL+C events to all the processes attached to a console window. If you detach a process, you can't send it CTRL+C events. If you want to be selective in which processes to send the CTRL+C events, you seem to need to create new console windows for every one. I've no idea if there's some way to do it without visible windows or when you want to redirect I/O using pipes.
Here is my solution for sending ctrl-c to a process. FYI, I never got GenerateConsoleCtrlEvent to work.
Rather than using GenerateConsoleCtrlEvent, here is how I have found to send CTRL-C to a process. FYI, in this case, I didn't ever need to find the group process ID.
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class ConsoleAppManager
{
private readonly string appName;
private readonly Process process = new Process();
private readonly object theLock = new object();
private SynchronizationContext context;
private string pendingWriteData;
public ConsoleAppManager(string appName)
{
this.appName = appName;
this.process.StartInfo.FileName = this.appName;
this.process.StartInfo.RedirectStandardError = true;
this.process.StartInfo.StandardErrorEncoding = Encoding.UTF8;
this.process.StartInfo.RedirectStandardInput = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.EnableRaisingEvents = true;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
this.process.Exited += this.ProcessOnExited;
}
public event EventHandler<string> ErrorTextReceived;
public event EventHandler ProcessExited;
public event EventHandler<string> StandartTextReceived;
public int ExitCode
{
get { return this.process.ExitCode; }
}
public bool Running
{
get; private set;
}
public void ExecuteAsync(params string[] args)
{
if (this.Running)
{
throw new InvalidOperationException(
"Process is still Running. Please wait for the process to complete.");
}
string arguments = string.Join(" ", args);
this.process.StartInfo.Arguments = arguments;
this.context = SynchronizationContext.Current;
this.process.Start();
this.Running = true;
new Task(this.ReadOutputAsync).Start();
new Task(this.WriteInputTask).Start();
new Task(this.ReadOutputErrorAsync).Start();
}
public void Write(string data)
{
if (data == null)
{
return;
}
lock (this.theLock)
{
this.pendingWriteData = data;
}
}
public void WriteLine(string data)
{
this.Write(data + Environment.NewLine);
}
protected virtual void OnErrorTextReceived(string e)
{
EventHandler<string> handler = this.ErrorTextReceived;
if (handler != null)
{
if (this.context != null)
{
this.context.Post(delegate { handler(this, e); }, null);
}
else
{
handler(this, e);
}
}
}
protected virtual void OnProcessExited()
{
EventHandler handler = this.ProcessExited;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
protected virtual void OnStandartTextReceived(string e)
{
EventHandler<string> handler = this.StandartTextReceived;
if (handler != null)
{
if (this.context != null)
{
this.context.Post(delegate { handler(this, e); }, null);
}
else
{
handler(this, e);
}
}
}
private void ProcessOnExited(object sender, EventArgs eventArgs)
{
this.OnProcessExited();
}
private async void ReadOutputAsync()
{
var standart = new StringBuilder();
var buff = new char[1024];
int length;
while (this.process.HasExited == false)
{
standart.Clear();
length = await this.process.StandardOutput.ReadAsync(buff, 0, buff.Length);
standart.Append(buff.SubArray(0, length));
this.OnStandartTextReceived(standart.ToString());
Thread.Sleep(1);
}
this.Running = false;
}
private async void ReadOutputErrorAsync()
{
var sb = new StringBuilder();
do
{
sb.Clear();
var buff = new char[1024];
int length = await this.process.StandardError.ReadAsync(buff, 0, buff.Length);
sb.Append(buff.SubArray(0, length));
this.OnErrorTextReceived(sb.ToString());
Thread.Sleep(1);
}
while (this.process.HasExited == false);
}
private async void WriteInputTask()
{
while (this.process.HasExited == false)
{
Thread.Sleep(1);
if (this.pendingWriteData != null)
{
await this.process.StandardInput.WriteLineAsync(this.pendingWriteData);
await this.process.StandardInput.FlushAsync();
lock (this.theLock)
{
this.pendingWriteData = null;
}
}
}
}
}
Then, in actually running the process and sending the CTRL-C in my main app:
DateTime maxStartDateTime = //... some date time;
DateTime maxEndDateTime = //... some later date time
var duration = maxEndDateTime.Subtract(maxStartDateTime);
ConsoleAppManager appManager = new ConsoleAppManager("myapp.exe");
string[] args = new string[] { "args here" };
appManager.ExecuteAsync(args);
await Task.Delay(Convert.ToInt32(duration.TotalSeconds * 1000) + 20000);
if (appManager.Running)
{
// If stilll running, send CTRL-C
appManager.Write("\x3");
}
For details, please see Redirecting standard input of console application and Windows how to get the process group of a process that is already running?