How to keep streaming continuously - Tweetinvi - c#

I adapted the following code from one I found online. Works ok but is not running continuously and pulling in new tweets. What do I need to change? Help appreciated.
private static void Stream_FilteredStreamExample()
{
SqlConnection conn = new SqlConnection(#"Data Source=********************");
conn.Open();
for (; ; )
{
try
{
var stream = Stream.CreateFilteredStream();
//stream.AddLocation(Geo.GenerateLocation(-180, -90, 180, 90));
stream.AddTweetLanguageFilter(Language.English);
stream.AddTrack("#TubeStrike");
var timer = Stopwatch.StartNew();
stream.MatchingTweetReceived += (sender, args) =>
{
var tweet = args.Tweet;
if (timer.ElapsedMilliseconds > 1000)
{
Console.WriteLine("{0}, {1}", tweet.IdStr, tweet.Text);
timer.Restart();
}
};
stream.StartStreamMatchingAllConditions();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
}

You want to use the following code:
stream.StreamStopped += (sender, args) =>
{
stream.StartStreamMatchingAllConditions();
};

Related

Serial port continuous data reading

I've made and application using WPF and I have to implement serial communication.
Bellow i have the DataReceived function.
The main problem is that the function triggers only sometimes, does anybody have a better solution to DataReceived trigger in WPF?
Below is the connection Connection to ComPort
public static void connnect(string recPort)
{
System.Windows.Threading.DispatcherTimer MyTimer = null;
bool error = false;
String serialpname = recPort;
ComPort = new SerialPort();
if (ComPort.IsOpen == false)
{
ComPort.PortName = serialpname;
ComPort.BaudRate = 38400;
ComPort.Parity = Parity.None;
ComPort.DataBits = 8;
ComPort.StopBits = StopBits.One;
ComPort.DataReceived += new SerialDataReceivedEventHandler(OnSerialDataReceived);
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
try
{
if (ComPort.IsOpen == false)
{
//Open Port
ComPort.Open();
dispatcherTimer.Start();
}
}
catch (System.IO.IOException) { error = true; }
}
}
Below is the timer that interogates the port
private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
ComPort.Write(eot + "11" + STX + "2170" + ENQ); // get pos
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The datareceived event
public static void OnSerialDataReceived(object sender,
SerialDataReceivedEventArgs args)
{
bool isString = true;
try
{
Thread.Sleep(100);// this solves the problem
byte[] readBuffer = new byte[ComPort.ReadBufferSize];
int readLen = ComPort.Read(readBuffer, 0, readBuffer.Length);
string readStr = string.Empty;
if (isString)
{
readStr = Encoding.Default.GetString(readBuffer, 0, readLen);
if(readStr.Length > 10)
{
if (readStr.StartsWith("\u0002"))
{
Position = (Mid(readStr, 2, 5));
Messenger.Default.Send("NewPos");
}
else
{
Position = (Mid(readStr, 31, 4));
Messenger.Default.Send("NewPos");
}
}
}
else
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < readLen; i++)
{
stringBuilder.Append(readBuffer[i].ToString("X2") + " ");
}
readStr = stringBuilder.ToString();
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
Console.WriteLine(ex);
}
}
Problem solved, i have added a Thread.Sleep(100); in the datareceived function. The buffer was not filled with the incoming data and seems that was the cause.
Thank you.

signalr .net client reconnect error

I'm writing a program that makes remote desktop connection with signalr. I keep sending screenshots (in the .net client) for it. But when I reconnect to the server after a while, I get error: Connection started reconnecting before invocation result was received.
public void ImageMain()
{
var querstring = new Dictionary<string, string>();
querstring.Add("userid", "sessionlocal");
var hubConnectionMouse = new HubConnection("http://localhost:8089/", querstring);
Program p = new Program();
IHubProxy myHubProxyMouse = hubConnectionMouse.CreateHubProxy("MyHub");
string a = "";
try
{
hubConnectionMouse.Start().Wait();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
byte[] ekran;
while (true)
{
ekran = null;
ekran = EkranGoruntusu();
if (ekran.Length < 80000)
{
try
{
myHubProxy.Invoke("addMessage", "sessionlocal", ekran).ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("!!! image gönderilirken hata olıştu:{0} \n",
task.Exception.GetBaseException() + "tekrar bağlanılıyor....");
}
else
{
Console.WriteLine("Add messgae" + " gonderilecek ekran boyutu " + ekran.Length);
Console.WriteLine("hub durumu" + hubConnection.State);
}
}).Wait();
}
catch (Exception exception)
{
Console.WriteLine("bağlantı hatas tekrar bağlanılıyor" + exception.Message);
Console.ReadKey();
}
}
else
{
Console.WriteLine("gonderilcek goruntü cok büyük");
}
}
Console.ReadLine();
}

c# Read real time from windows event log

i can succesfully read events from event log. But polling all events has very bad performance. I wonder if there is an event or something that i can subscribe to catch log entries "as they happen"?
Is this possible?
EventLog log = new EventLog("Security");
var entries = log.Entries.Cast<EventLogEntry>().Where(x => x.InstanceId == 4624).Select(x => new
{
x.MachineName,
x.Site,
x.Source,
x.UserName,
x.Message
}).ToList();
Console.WriteLine(entries[0].UserName);
You can use EventLogWatcher for this purpose. You can subscribe to desired log filter(s) and implement a handler function to execute when you receive any events.
public static void eventLogSubscription()
{
using (EventLog eventLog = new EventLog("Application"))
{
String path = Path.GetTempPath();
eventLog.Source = "Event Log Reader Application";
eventLog.WriteEvent(new EventInstance(1003, 0, EventLogEntryType.Information), new object[] { "The event log watcher has started" , path});
//eventLog.WriteEntry(arg.EventRecord.ToXml(), EventLogEntryType.Information, 1001, 1);
eventLog.Dispose();
}
EventLogWatcher watcher = null;
try
{
string eventQueryString = "*[System/EventID=4688]" +
"and " +
"*[EventData[Data[#Name = 'NewProcessName'] = 'C:\\Windows\\explorer.exe']]";
EventLogQuery eventQuery = new EventLogQuery(
"Security", PathType.LogName, eventQueryString);
watcher = new EventLogWatcher(eventQuery);
watcher.EventRecordWritten +=
new EventHandler<EventRecordWrittenEventArgs>(
handlerExplorerLaunch);
watcher.Enabled = true;
}
catch (EventLogReadingException e)
{
Console.WriteLine("Error reading the log: {0}", e.Message);
}
Console.ReadKey();
}
public static void handlerExplorerLaunch(object obj,
EventRecordWrittenEventArgs arg)
{ if (arg.EventRecord != null)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Event Log Reader Application";
eventLog.WriteEvent(new EventInstance(1001, 0, EventLogEntryType.Information), new object[] {arg.EventRecord.FormatDescription() });
//eventLog.WriteEntry(arg.EventRecord.ToXml(), EventLogEntryType.Information, 1001, 1);
eventLog.Dispose();
}
}
else
{
Console.WriteLine("The event instance was null.");
}
}
I have found this to work more reliably.
using System;
using System.Diagnostics.Eventing.Reader;
static void Main(string[] args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
LoadEventLogs();
Console.ReadKey();
}
private static void LoadEventLogs()
{
EventLogSession session = new EventLogSession();
EventLogQuery query = new EventLogQuery("Security", PathType.LogName, "*[System/EventID=4688]")
{
TolerateQueryErrors = true,
Session = session
};
EventLogWatcher logWatcher = new EventLogWatcher(query);
logWatcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(LogWatcher_EventRecordWritten);
try
{
logWatcher.Enabled = true;
}
catch (EventLogException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private static void LogWatcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
var time = e.EventRecord.TimeCreated;
var id = e.EventRecord.Id;
var logname = e.EventRecord.LogName;
var level = e.EventRecord.Level;
var task = e.EventRecord.TaskDisplayName;
var opCode = e.EventRecord.OpcodeDisplayName;
var mname = e.EventRecord.MachineName;
Console.WriteLine($#"{time}, {id}, {logname}, {level}, {task}, {opCode}, {mname}");
}

C# multithreading code not hitting break point

Please look at the sample code below, When I place a break point inside "testmethod" and run the application, it is not hitting the breakpoint. Is this code good?
static void Main(string[] args)
{
Thread[] testthreads = new Thread[3];
List<int> testdata = new List<int>();
testdata.Add(1);
testdata.Add(2);
testdata.Add(3);
int i = 0;
foreach (int data in testdata)
{
testthreads[i] = new Thread(new ThreadStart(() => testmethod(data)));
testthreads[i].Name = string.Format("Working Thread: {0}", data);
i++;
}
}
static void testmethod(int i)
{
try
{
//DataTable dt = DB.GetData(i);
if (dt.Count > 0)
{
Console.WriteLine("Count: {0}", dt.Count);
}
}
catch (Exception ex)
{
throw ex;
}
}
I tried another method and it always returns the Name of first input.
Method 2:
static void Main(string[] args)
{
List testdata = new List();
testdata.Add(111111);
testdata.Add(222222);
testdata.Add(333333);
foreach (int data in testdata)
{
new Thread(delegate()
{
DataTable dt = DB.GetData(data);
if (dt.Count > 0)
{
Console.WriteLine("Name: {0}", dt.Rows[0]["Name"];);
}
// Signal the CountdownEvent.
countdownEvent.Signal();
}).Start();
}
// Wait for workers.
countdownEvent.Wait();
Console.WriteLine("Finished.");
}
Output:
Name: JULIE
Name: JULIE
Name: JULIE
Always returns the value(Name) of 111111
You need to start the thread.
testthreads[i] = new Thread(new ThreadStart(() => testmethod(data)));
testthreads[i].Name = string.Format("Working Thread: {0}", data);
testthreads[i].Start();

Threading in C# method with parameter using same variable

I'm a newb in programming and I'm trying to do my first thingy that would be for someone else and not just me (so shouldn't be that crappy ^^ )
It's a Online-Checker for clients in LAN network (so he can just paste a list of clients, and it returns the online or offline).
fyi: I'm using Try/Catch because ping.send to an offline host returns in an Error which crashed the application.
Currently it looks like this:
private void btn_check_Click(object sender, EventArgs e)
{
string[] hosts = txt_hosts.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (String host in hosts)
{
pinger(host);
}
}
public void pinger(string host)
{
var ping = new System.Net.NetworkInformation.Ping();
try
{
var result = ping.Send(host);
txt_result.Text += "true" + Environment.NewLine;
Application.DoEvents();
}
catch
{
txt_result.Text += "false"+Environment.NewLine;
Application.DoEvents();
}
}
Now, the interface is like frozen whenever a ping.send is processing (and that's quiet long cause of the timeout of pings).
Is there any way to do this threaded? Before I tried to start a thread, but that doesn't work either because both write in txt_result and that returns an error.
Thanks for any help!
If use acync/await:
// send request
foreach (string host in hosts)
pinger(host);
// async function
async void pinger(string host)
{
var ping = new System.Net.NetworkInformation.Ping();
bool bResp;
try
{
var result = await ping.SendPingAsync(host, 4000);
bResp = result.Status == System.Net.NetworkInformation.IPStatus.Success;
}
catch { bResp = false; }
txt_result.Text += bResp.ToString() + Environment.NewLine;
}
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
pinger(host);
});
It could throw an exception at the line : txt_result.Text = "...";
Because you are trying to modify a value in a thread from another thread.
So you could write:
System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
{
txt_result.Text = "...";
}));
Which will request the UI thread to modify the value.
Run on a background worker.
public void pinger(string host)
{
var bw = new BackgroundWorker();
bw.DoWork += delegate(object sender, DoWorkEventArgs e)
{
var ping = new System.Net.NetworkInformation.Ping();
try
{
var result = ping.Send(host);
e.Result = new object[] { result};
}
catch(Exception ex)
{
// Catch specific exceptions here as needed
}
};
bw.RunWorkerCompleted += (bw_txt_results);
bw.RunWorkerAsync();
}
private void bw_txt_results(object sender, RunWorkerCompletedEventArgs e)
{
txt_result = e.result[0].ToString();
}

Categories