I wrote a code to update DDNS which works fine. I now need to run this code every n minutes: how would I go doing that?
I tried using:
while (true)
{
this.DoMyMethod();
Thread.Sleep(TimeSpan.FromMinutes(1));
}
and I am still having some trouble. What is the best way to run this task every n minutes?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
}
}
}
Why not using System.Threading.Timer to do so?
From the Microsoft documentation, say you have the following sample class:
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if (invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
Then you can create a Timer to run CheckStatus every n seconds, like:
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(5);
// creates a Timer to call CheckStatus() with autoEvent as argument,
// starting with 1 second delay and calling every 2 seconds.
var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 2000);
autoEvent.WaitOne();
i use timer,
the code is
using System;
using System.Net;
using System.Timers;
static void Main(string[] args)
{
Console.WriteLine("The system is start at {0}", DateTime.Now);
Timer t = new Timer(10000);
t.Enabled = true;
t.Elapsed += T_Elapsed;
Console.ReadKey();
}
private static void T_Elapsed(object sender, ElapsedEventArgs e)
{
//write your code
}
This is what fixed for me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows.Forms;
using System.Timers;
namespace GoogleDDNS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (username.Text == "")
{
System.Windows.MessageBox.Show("Please enter the username");
username.Focus();
return;
}
if (password.Text == "")
{
System.Windows.MessageBox.Show("Please enter the password");
password.Focus();
return;
}
if (subdomain.Text == "")
{
System.Windows.MessageBox.Show("Please enter the subdomain");
subdomain.Focus();
return;
}
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
Properties.Settings.Default.usernamesave = username.Text;
Properties.Settings.Default.passwordsave = password.Text;
Properties.Settings.Default.subdomainsave = subdomain.Text;
//Properties.Settings.Default.intervalsave = interval.Text;
Properties.Settings.Default.Save();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
username.Text = Properties.Settings.Default.usernamesave;
password.Text = Properties.Settings.Default.passwordsave;
subdomain.Text = Properties.Settings.Default.subdomainsave;
//interval.Text = Properties.Settings.Default.intervalsave;
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
var client = new WebClient { Credentials = new NetworkCredential(username.Text, password.Text) };
var response = client.DownloadString("https://domains.google.com/nic/update?hostname=" + subdomain.Text);
//MessageBox.Show(response);
responseddns.Content = response;
//this.Close();
}
}
}
Have a look at this. I recall a colleague using it a while ago:
FluentScheduler - [Project Site]
Usage:
// Schedule an IJob to run at an interval
Schedule<MyJob>().ToRunNow().AndEvery(2).Minutes();
Will fulfill your need.
somwhere met this code
class Program
{
static void Main(string[] args)
{
int Interval = 5;
CancellationTokenSource cancellation = new CancellationTokenSource();
Console.WriteLine("Start Loop...");
RepeatActionEvery(() => Console.WriteLine("Hi time {0}",DateTime.Now), TimeSpan.FromMinutes(Interval), cancellation.Token).Wait();
Console.WriteLine("Finish loop!!!");
}
public static async Task RepeatActionEvery(Action action, TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
action();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
}
Related
so I'm very new to Visual Studio and C# but I'm having trouble making a Ping cmd in my app. I have included the code and images. Basically, when I run the app and try to make the ping request it just takes me to the App.g.i.cs file and highlights this code
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
}
}
}
So I don't know where I'm really going wrong. I know this might be a really dumb question but I'm just not familiar with Visual Studio yet. Would love any suggestions :)
Here is the code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.ComponentModel;
using System.Threading;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace Ping_IP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Ping pingsender = new Ping();
PingReply reply = pingsender.Send(ip_address.ToString());
if (reply.Status == IPStatus.Success)
{
status_info.Text = "Sucess! - " + DateTime.Now.ToLocalTime(); //reply.Status.ToString();
} else
{
status_info.Text = "Failed... - " + DateTime.Now.ToLocalTime();
}
}
}
}
I referred to Klaus Gütter's opinion and successfully returned the data.
PingReply reply = pingsender.Send(ip_address.Text);
Complete code
private void Button_Click(object sender, RoutedEventArgs e) {
Ping pingsender = new Ping();
PingReply reply = pingsender.Send(ip_address.Text);
if (reply.Status == IPStatus.Success) {
status_info.Text = "Sucess! - " + DateTime.Now.ToLocalTime(); //reply.Status.ToString();
} else {
status_info.Text = "Failed... - " + DateTime.Now.ToLocalTime();
}
}
Try catch
private void Button_Click(object sender, RoutedEventArgs e) {
Ping pingsender = new Ping();
try {
PingReply reply = pingsender.Send(ip_address.Text);
if (reply.Status == IPStatus.Success) {
status_info.Text = "Sucess! - " + DateTime.Now.ToLocalTime(); //reply.Status.ToString();
} else {
status_info.Text = "Failed... - " + DateTime.Now.ToLocalTime();
}
} catch (Exception) {
MessageBox.Show("something wrong");
}
}
}
Prompt when try fails.
I tried everything I could, but nothing works. My IP address 3 first digits changed from 192.168.1 to 192.168.0. The program has to accept data from address 192.168.0.255 then in reaction, it has to open a window and play video from a folder and is set to listen to every IP address there shouldn't be a problem before the change of router everything worked as expected.
For sending data I use my own android app I tested that app with Wireshark everything works as it should.
The window doesn't open everything works, but it seems that the socket just doesn't get any data.=>condition checking for available data socket available>0 returns false.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Timers;
using System.Net.Sockets;
using System.Net;
namespace SysConf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Timer timer1;
System.Windows.Threading.DispatcherTimer dispatcherTimer;
Encoding coding = Encoding.GetEncoding("ISO-8859-2");
int ByteC;
Byte[] bytes = new byte[1024];
EndPoint rE = new IPEndPoint(IPAddress.Any, 2200);
int order = 0;
public MainWindow()
{
InitializeComponent();
Clipboard.SetText(GetLocalIPAddress());
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (ip.ToString().Split('.')[0] == "192")
{
return ip.ToString();
}
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void MainWindow1_StateChanged(object sender, EventArgs e)
{
if (MainWindow1.WindowState == WindowState.Maximized) { MainWindow1.WindowStyle = WindowStyle.None; }
else { MainWindow1.WindowStyle= WindowStyle.SingleBorderWindow; }
}
private void MainWindow1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.F11)
{
if (MainWindow1.WindowState == WindowState.Maximized)
{
MainWindow1.WindowState = WindowState.Normal;
MainWindow1.Topmost = false;
}
else
{
MainWindow1.WindowState = WindowState.Maximized;
MainWindow1.Topmost = true;
}
}
}
private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
{
// win = (SysConf.MainWindow)Application.Current.MainWindow;
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(10);
dispatcherTimer.Start();
// MainWindow1.Visibility = Visibility.Collapsed;
MainWindow1.Visibility = Visibility.Collapsed;
if (GetLocalIPAddress() != "No network adapters with an IPv4 address in the system!")
{
sck.Bind(new IPEndPoint(IPAddress.Parse(GetLocalIPAddress()), 2200));
}
else
{
MessageBox.Show("No Internet connection!");
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (player1.Position == player1.NaturalDuration & MainWindow1.Visibility == Visibility.Visible)
{
MainWindow1.Topmost = false;
MainWindow1.Visibility = Visibility.Collapsed;
}
Task.Run(() =>
{
if (sck.Available > 0)
{
MessageBox.Show("Data arrived");
ByteC = sck.ReceiveFrom(bytes, ref rE);
order = 1;
}
});
if (order == 1)
{
this.Close();
String cmd = coding.GetString(bytes);
MainWindow1.Visibility = Visibility.Visible;
MainWindow1.Topmost = true;
player1.Source = new Uri("Resources/" + (cmd.Substring(0,12)).Split('_')[1] + ".mp4", UriKind.Relative); //+ (#"\Resources\" ), UriKind.Relative);
player1.Position = TimeSpan.Zero;
MainWindow1.WindowState = WindowState.Maximized;
player1.Play();
order = 0;
bytes = null;
bytes = new byte[9024];
cmd = "";
}
dispatcherTimer.Start();
}
private void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//win.Visibility = Visibility.Visible;
timer1.Start();
}
private void player1_BufferingEnded(object sender, RoutedEventArgs e)
{
}
}
}
What I have is a medical record database that is accessed via PuTTY (SSH client). The cards themselves will only have Client name, record number in a barcode format (still determining the barcode type to be used), and client registration date.
1) We can get the data output as .zpl for Zebra Barcode label printers or formats compatible with laser printers like HP or Brother in a RAW format.
2) What output WILL the ZXP 3 SDK accept?
3) Can the SDK be set up to wait for and accept data coming at it using a command line from something like RedMon?
The cards themselves will only have the printed data, no mag stripe, smart chips, laminates or anything like that.
Mahalo in advance.
I would not recommend using either RedMon nor the SDK, as neither are required for what you are trying to do, and they both are time-vampires. Instead, I would write a small Windows Forms application which listens on a TCP port to receive the print job and send it to the standard printer which uses the Zebra driver.
Have the MUMPS application send an XML document via the Remote Print support in VT100. The example I have been using is below:
^[[5i
<patient>
<name first="John" last="Smith" />
<mrn>A04390503</mrn>
<dob>1991-03-12</dob>
</patient>
^[[4i
Configure a printer on the windows client to redirect to TCP/IP:
Add Printer
Local printer
Create a new port
Standard TCP/IP Port
Hostname: 127.0.0.1
Port name: CardFormatter
Uncheck "Query the printer and automatically select the driver to use"
Device type: Custom
Protocol: Raw
Port: 9101
Driver: Generic / Text Only
Start the application at logon, and print from the server. The MUMPS application will send back the XML, which Putty prints to the Text printer, which gets sent to the C# application on localhost. The C# application interprets the XML and prints to the actual printer via the Zebra driver or SDK.
Note: This only assumes one interactive session per workstation. If you are using fast-user-switching or terminal services, further care must be taken to ensure things work properly.
Example App:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassThroughPrinterTest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TrayApplicationContext());
}
}
}
TrayApplicationContext.cs
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassThroughPrinterTest
{
class TrayApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
private PrintListener listener;
private PrintHandler handler;
public TrayApplicationContext()
{
this.trayIcon = new NotifyIcon()
{
Text = "Card Formatter",
Icon = Properties.Resources.AppIcon,
ContextMenu = new ContextMenu()
{
MenuItems =
{
new MenuItem("Print Options...", miPrintOptions_Click),
new MenuItem("Exit", miExit_Click)
}
},
Visible = true
};
this.handler = new PrintHandler();
this.listener = new PrintListener(9101);
this.listener.PrintDataReceived += this.handler.HandlePrintData;
}
private void miPrintOptions_Click(object sender, EventArgs args)
{
// TODO: add configuration and options to avoid having to hard code
// the printer name in PrintHandler.cs
MessageBox.Show("Options");
}
private void miExit_Click(object sender, EventArgs args)
{
Application.Exit();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
trayIcon.Dispose();
}
}
}
}
PrintHandler.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
namespace PassThroughPrinterTest
{
partial class PrintHandler : Form
{
public PrintHandler()
{
InitializeComponent();
}
public void HandlePrintData(object sender, PrintDataReceivedEventArgs args)
{
if (this.InvokeRequired)
{
this.Invoke(new EventHandler<PrintDataReceivedEventArgs>(HandlePrintData), sender, args);
return;
}
this.Show();
var sXml = Encoding.UTF8.GetString(args.PrintData);
this.PrintCard(XDocument.Parse(sXml));
this.Hide();
}
private void PrintCard(XDocument xDocument)
{
var nameElement = xDocument.Root.Element("name");
var lastName = nameElement.Attribute("last").Value;
var firstName = nameElement.Attribute("first").Value;
var mrn = xDocument.Root.Element("mrn").Value;
var printDoc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
PrinterName = "Adobe PDF"
},
DocumentName = "Patient ID Card"
};
var cardPaperSize = new PaperSize("Card", 337, 213) { RawKind = (int)PaperKind.Custom };
printDoc.DefaultPageSettings.PaperSize = cardPaperSize;
printDoc.PrinterSettings.DefaultPageSettings.PaperSize = cardPaperSize;
printDoc.PrintPage += (s, e) =>
{
var gfx = e.Graphics;
// print the text information
var fArial12 = new Font("Arial", 12);
gfx.DrawString(lastName, fArial12, Brushes.Black, new RectangleF(25, 25, 200, 75));
gfx.DrawString(firstName, fArial12, Brushes.Black, new RectangleF(25, 100, 200, 75));
// add a code39 barcode using a barcode font
// http://www.idautomation.com/free-barcode-products/code39-font/
// var fCode39 = new Font("IDAutomationHC39M", 12);
// gfx.DrawString("(" + mrn + ")", fArial12, Brushes.Black, new RectangleF(25, 200, 200, 75));
// or by using a barcode library
// https://barcoderender.codeplex.com/
// var barcode = BarcodeDrawFactory.Code128WithChecksum.Draw(mrn, 20, 2);
// gfx.DrawImage(barcode, 50, 200);
e.HasMorePages = false;
};
printDoc.Print();
}
}
}
PrintListener.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace PassThroughPrinterTest
{
sealed class PrintListener : IDisposable
{
private TcpListener listener;
public event EventHandler<PrintDataReceivedEventArgs> PrintDataReceived;
public PrintListener(int port)
{
this.listener = new TcpListener(IPAddress.Loopback, port);
this.listener.Start();
this.listener.BeginAcceptTcpClient(listener_AcceptClient, null);
}
public void Dispose()
{
this.listener.Stop();
}
private void listener_AcceptClient(IAsyncResult iar)
{
TcpClient client = null;
bool isStopped = false;
try
{
client = this.listener.EndAcceptTcpClient(iar);
}
catch (ObjectDisposedException)
{
// this will occur in graceful shutdown
isStopped = true;
return;
}
finally
{
if (!isStopped)
{
this.listener.BeginAcceptTcpClient(listener_AcceptClient, null);
}
}
Debug.Assert(client != null);
try
{
byte[] printData;
using (var clientStream = client.GetStream())
using (var buffer = new MemoryStream())
{
clientStream.CopyTo(buffer);
printData = buffer.ToArray();
}
OnPrintDataReceived(printData);
}
catch
{
// TODO: add logging and error handling for network issues or processing issues
throw;
}
finally
{
client.Close();
}
}
private void OnPrintDataReceived(byte[] printData)
{
var handler = PrintDataReceived;
if (handler != null)
{
handler(this, new PrintDataReceivedEventArgs(printData));
}
}
}
}
TrayApplicationContext.cs
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PassThroughPrinterTest
{
class TrayApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
private PrintListener listener;
private PrintHandler handler;
public TrayApplicationContext()
{
this.trayIcon = new NotifyIcon()
{
Text = "Card Formatter",
Icon = Properties.Resources.AppIcon,
ContextMenu = new ContextMenu()
{
MenuItems =
{
new MenuItem("Print Options...", miPrintOptions_Click),
new MenuItem("Exit", miExit_Click)
}
},
Visible = true
};
this.handler = new PrintHandler();
this.listener = new PrintListener(9101);
this.listener.PrintDataReceived += this.handler.HandlePrintData;
}
private void miPrintOptions_Click(object sender, EventArgs args)
{
// TODO: add configuration and options to avoid having to hard code
// the printer name in PrintHandler.cs
MessageBox.Show("Options");
}
private void miExit_Click(object sender, EventArgs args)
{
Application.Exit();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
listener.Dispose();
trayIcon.Dispose();
}
}
}
}
PrintDataReceivedEventArgs.cs
using System;
namespace PassThroughPrinterTest
{
class PrintDataReceivedEventArgs : EventArgs
{
public byte[] PrintData { get; set; }
public PrintDataReceivedEventArgs(byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
this.PrintData = data;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
namespace Datalogging
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public class ThreadExample
{
public static void ThreadJob(MainWindow mainWindow)
{
string dBConnectionString = #"Data Source = C:\Users\johnmark\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
//open connection to database
try
{
sqliteCon.Open();
SQLiteCommand createCommand = new SQLiteCommand("Select empID from EmployeeList", sqliteCon);
SQLiteDataReader reader;
reader = createCommand.ExecuteReader();
//richtextbox2.Document.Blocks.Clear();
while (reader.Read())
{
string Text = (String.Format("{0}", Object.Equals(definition.buffering, reader.GetValue(0))));
if (Convert.ToBoolean(Text))
{
mainWindow.SerialWrite('s');
Console.WriteLine(Text);
//richtextbox1.Document.Blocks.Add(new Paragraph(new Run(Text)));
}
}
sqliteCon.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public partial class MainWindow : Window
{
//string received_data;
//Thread readThread = new Thread(Read);
FlowDocument mcFlowDoc = new FlowDocument();
Paragraph para = new Paragraph();
SerialPort serial = new SerialPort();
public MainWindow()
{
InitializeComponent();
combobox1.Items.Insert(0, "Select Port");
combobox1.SelectedIndex = 0;
string[] ports = null;
ports = SerialPort.GetPortNames();
// Display each port name to the console.
int c = ports.Count();
for (int i = 1; i <= c; i++)
{
if (!combobox1.Items.Contains(ports[i - 1]))
{
combobox1.Items.Add(ports[i - 1]);
}
}
}
private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
if ((string)button2.Content == "Connect")
{
string myItem = combobox1.SelectedItem.ToString();
if (myItem == "Select Port")
{
MessageBox.Show("Select Port");
}
else
{
serial.PortName = myItem;
serial.Open();
button2.Content = "Disconnect";
textbox2.Text = "Serial Port Opened";
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
}
}
else
{
serial.Close();
button2.Content = "Connect";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#region Receiving
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytes = serial.BytesToRead;
byte[] buffer = new byte[bytes];
serial.Read(buffer, 0, bytes);
foreach (var item in buffer)
{
Console.Write(item.ToString());
}
definition.buffering = BitConverter.ToInt64(buffer, 0);
Console.WriteLine();
Console.WriteLine(definition.buffering);
Console.WriteLine();
Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));
thread.Start();
thread.Join();
}
#endregion
public void WriteSerial(string text)
{
serial.Write(text);
}
}
}
Hi guys. Can anyone help me what went wrong in this code? It is displaying this error:
Error 2 'Datalogging.MainWindow' does not contain a definition for 'SerialWrite' and no extension method 'SerialWrite' accepting a first argument of type 'Datalogging.MainWindow' could be found (are you missing a using directive or an assembly reference?)
Error 3 Method name expected
how can I fix that? Please edit the code and post it here as your answer thanks.
Change your method call mainWindow.SerialWrite('s'); to mainWindow.WriteSerial('s'); to fit the method name declared here :
public void WriteSerial(string text)
You inverted both words.
For your "Method name expected", I guess it's in port_DataReceived. You need to pass a delegate to the thread, but you're not doing it correctly.
Instead of
Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));
(you can't directly pass a method as a parameter, you can only use function pointers) you can use this syntax to pass a delegate :
Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
Please note that new TreadStart is redundant, new Thread(() => ThreadExample.ThreadJob(this)); will do the job.
How could i update the windows audio playback agent properties like title and artist, live ,when it is playing. I want to update the title every 20 seconds without stopping the music which is playing? please help. I tried this but its stopping and replaying at every 20 seconds which is annoying. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundAudio;
using System.Threading;
using System.Windows.Threading;
namespace PhoneApp2
{
public partial class MainPage : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer();
string Artist;
string Song;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
timer.Interval = TimeSpan.FromSeconds(20);
timer.Start();
timer.Tick += timer_Tick;
}
void timer_Tick(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
client.DownloadStringAsync(new Uri("http://air-online2.hitfm.md/status_hitfm.xsl"));
client.DownloadStringCompleted += client_DownloadStringCompleted;
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string[] FullTitle = e.Result.Substring(166).Split('-');
Artist= FullTitle[0];
if(Artist.Contains(":"))
{
Artist=FullTitle[0].Replace(":",string.Empty);
}
Song = FullTitle[1].Replace(" ", string.Empty);
if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Playing)
{
BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri("http://air-online2.hitfm.md/hitfm.mp3"), Artist, Song, null, null);
BackgroundAudioPlayer.Instance.Play();
}
else
{
BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri("http://air-online2.hitfm.md/hitfm.mp3"), Artist, Song, null, null);
}
}
}
}