Windows Service sends request twice within for loop - c#

I'm using a windows service for my online recharge website.
I'm selecting requested numbers from table and send it through api and get response. But some times its send request twice for same number while my table contains only one entry for that number.
My full page code is given below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
using System.Net;
namespace bulkRechargeService
{
public partial class bulkRecharge : ServiceBase
{
System.Timers.Timer timer;
SqlConnection conn;
public bulkRecharge()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
proccessQue();
}
protected override void OnStop()
{
timer.Stop();
timer.Enabled = false;
}
protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
proccessQue();
}
public void proccessQue()
{
try
{
timer = new System.Timers.Timer();
timer.Interval = (1000) * 10;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
conn = new SqlConnection(ConfigurationManager.AppSettings["ConnString1"]);
SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM recharge_request WHERE is_done=0 AND rdate>DATEADD(minute,-5,GETDATE())", conn);
DataTable dt = new DataTable();
adap.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
string rId = dt.Rows[i]["id"] + "";
string operators = dt.Rows[i]["operator"] + "";
string mobileNo = dt.Rows[i]["mobile_no"] + "";
string amount = dt.Rows[i]["amount"] + "";
string rechargeType = dt.Rows[i]["recharge_type"] + "";
string referenceId = dt.Rows[i]["user_reference_id"] + "";
string api = "http://*******************************************";
HttpWebRequest httpreq = (HttpWebRequest)WebRequest.Create(api);
HttpWebResponse httpres = (HttpWebResponse)httpreq.GetResponse();
StreamReader sr = new StreamReader(httpres.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
SqlCommand cmd = new SqlCommand("UPDATE recharge_request SET is_done=1,rdate=GETDATE(),udate=GETDATE() WHERE id=" + rId, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
timer.Enabled = true;
timer.Start();
}
catch(Exception ex)
{
}
}
}
}
Any ideas on where I'm going wrong?

I think your for loop it self runs more than one time even if you have one record in the table.
you started i =0 so put a minus (-1)
for (int i = 0; i < dt.Rows.Count - 1; i++)
instead of
for (int i = 0; i < dt.Rows.Count; i++)

protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(10000D);
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.proccessQue();
}
I have place timer constructor in onStart method and remove from processQue method and now its works fine

Related

SQL Dependency queries the whole table

I have a console app that monitors a database using SqlDependency. The app is to monitor the database table and send an email once a new record is added in the table.
Everything works fine, just that each time a new record is added the whole query is executed again and all the records in the table are returned. What I actually want is to return only the newly added record in the table.
Here is my code below:
SQLWatcher class:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestApp
{
public enum SqlWatcherNotificationType
{
Blocking,
Threaded // Launch in another thread so SqlWatcher can immediately start monitoring again.
}
public class SqlWatcher : IDisposable
{
private string ConnectionString;
private SqlConnection Connection;
private SqlCommand Command;
private SqlDataAdapter Adapter;
private DataSet Result;
private SqlWatcherNotificationType NotificationType;
public SqlWatcher(string ConnectionString, SqlCommand Command, SqlWatcherNotificationType NotificationType)
{
this.NotificationType = NotificationType;
this.ConnectionString = ConnectionString;
SqlDependency.Start(this.ConnectionString);
this.Connection = new SqlConnection(this.ConnectionString);
this.Connection.Open();
this.Command = Command;
this.Command.Connection = this.Connection;
Adapter = new SqlDataAdapter(this.Command);
}
public void Start()
{
RegisterForChanges();
}
public void Stop()
{
SqlDependency.Stop(this.ConnectionString);
}
public delegate void SqlWatcherEventHandler(DataSet Result);
public event SqlWatcherEventHandler OnChange;
public DataSet DataSet
{
get { return Result; }
}
private void RegisterForChanges()
{
// Remove old dependency object
this.Command.Notification = null;
// Create new dependency object
SqlDependency dep = new SqlDependency(this.Command);
dep.OnChange += new OnChangeEventHandler(Handle_OnChange);
// Save data
Result = new DataSet();
Adapter.Fill(Result);
// Notify client of change to DataSet
switch (NotificationType)
{
case SqlWatcherNotificationType.Blocking:
OnChange(Result);
break;
case SqlWatcherNotificationType.Threaded:
ThreadPool.QueueUserWorkItem(ChangeEventWrapper, Result);
break;
}
}
public void ChangeEventWrapper(object state)
{
DataSet Result = (DataSet)state;
OnChange(Result);
}
private void Handle_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type != SqlNotificationType.Change)
throw new ApplicationException("Failed to create queue notification subscription!");
//Clean up the old notification
SqlDependency dep = (SqlDependency)sender;
dep.OnChange -= Handle_OnChange;
//Register for the new notification
RegisterForChanges();
}
public void Dispose()
{
Stop();
}
}
}
Implementation:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
private static SqlWatcher SqlQueueWatcher;
// string pin = string.Empty;
string siteURL = "http://docapp/sites/nlpc";
public string benefitCheck()
{
DataContext db = new DataContext("Data Source=;Initial Catalog=ServiceTest;User ID=;password = ;Integrated Security=true");
BenefitDocModel RSAName = new BenefitDocModel();
CustomerCareContextDataContext LandingDb = new CustomerCareContextDataContext(siteURL);
IEnumerable<BenefitDocModel> r = db.GetTable<BenefitDocModel>().ToList<BenefitDocModel>();
var query = r.ToList();
var rsa = from rr in query
select ( new { rr.PIN , rr.Document_Name, rr.Firstname, rr.Surname, rr.URL});
foreach (var rsapin in rsa)
{
Console.WriteLine(rsapin);
// sendEmail(rsapin.PIN);
}
/*pin = RSAName.PIN;
RSAsLibraryDocument test = new RSAsLibraryDocument();
BenefitDocModel RSAName1 = db.GetTable<BenefitDocModel>().FirstOrDefault(x => x.PIN == pin);
if (pin == RSAName1.PIN)
{
test.PIN = RSAName.PIN;
test.UserID = RSAName.UserID;
test.Firstname = RSAName.Firstname;
test.Surname = RSAName.Surname;
test.Document_Name = RSAName.Document_Name;
test.Document_URL = RSAName.URL;
test.UserType = RSAName.UserType;
test.Name = RSAName.PIN + RSAName.Document_Name;
}*/
return "success";
}//
public void SQLServiceStartForLog()
{
//BenefitDocModel rsapin = db.GetTable<BenefitDocModel>().FirstOrDefault(x => x.PIN == pin);
//cmd.Notification = null;
string connS = "Data Source=;Initial Catalog=ServiceTest;User ID=;password = ;Integrated Security=true";
SqlCommand cmd = new SqlCommand();
//cmd.Notification = null;
cmd = new SqlCommand("SELECT UserID, Surname, Firstname, PIN, URL, Document_Name FROM dbo.BenefitDoc");
cmd.CommandType = CommandType.Text;
SqlQueueWatcher = new SqlWatcher(connS, cmd, SqlWatcherNotificationType.Blocking);
SqlQueueWatcher.OnChange += new SqlWatcher.SqlWatcherEventHandler(QueueSQLWatcher_OnChangeForLog);
cmd.Notification = null;
SqlQueueWatcher.Start();
}
private void QueueSQLWatcher_OnChangeForLog(DataSet Result)
{
try
{
Console.WriteLine("Database monitoring is starting....");
benefitCheck();
Console.WriteLine("Database monitoring completed.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void sendEmail(string pin)
{
MailMessage mail = new MailMessage("", "");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("", "");
mail.Subject = "New Record added for RSA with " + pin;
mail.Body = "The benefit application for user has been created.";
client.Send(mail);
}
public static void Stop()
{
SqlQueueWatcher.Dispose();
}
static void Main(string[] args)
{
Program n = new Program();
n.SQLServiceStartForLog();
Console.ReadLine();
}
}
}
That is not how SqlDependency works. Basically the way it works is you give it a query and if the query results change, it triggers a notification. But when you execute the datareader, it will not only return the changes. It returns data as if it was a regular query.
If you want to get only the changes, then you need to have a column in your table with something like LastModifiedDateTime and then query those records where LastModifiedDateTime is bigger than when you retrieved records the last time.
Alternatively, there is this NuGet package that will do this sort of thing for you if you are interested in using it.

How do i loop for the next 25 results next page using facebook api?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Facebook;
using System.Net;
using System.IO;
namespace WebSite_Login_And_Browsing
{
class Posts
{
public string PostId { get; set; }
public string PostStory { get; set; }
public string PostMessage { get; set; }
public string PostPicture { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
class FacebookPosts
{
static string accesstoken;
//static string token = "2f89d691b5f39";
static string token = "1186840401345424|GoJRCpM";
static string mytoken = "CAACEdEose0cBACPu39NSSalHCGFGDGRKZAvwiTuzG8PHlNRJwbyMVugovDxgL7CT3a1QbRuVDZALXxWU0ntwSrDyq75LIIuzFpBtx47cJYCY2OiA21lpTRKt2bB0t5HrsQYIXHXhmU7GnavWZCzqN8yeuv5NWXxTIOfVCZAZArjYNiPWhZBqZAZAO03s6FKNIulm4kjzXvp4QKiahAlcyaZBg";
static string mytokenaslip = "CAACEdEose0cBABmWuBI9p9dpPxEsMJoFZAG3kScx61kZAImNBgt52kVrd8WWPRpwjWP8nCPX69zdLuFyVQHzxYfMk85ZBZC4BIajVWXNLo7OI7yaCbNIwqkcdwpabQVFZBRWt0rzTQrQr6ZBij45XnrQyEUqFKP4gADeO4Fl9yRaZAZCOFtV3b84sWUFEgwaKbZAPY4BCljVjWQZDZD";
public static void RetrievePosts()
{
try
{
var client = new FacebookClient(mytokenaslip);
dynamic result = client.Get("/me/posts");
List<Posts> postsList = new List<Posts>();
//all the posts and their information (like pictures and links) is strored in result.data not in result
for (int i = 0; i < result.data.Count; i++)
{
Posts posts = new Posts();
posts.PostId = result.data[i].id;
if (object.ReferenceEquals(result.data[i].story, null))
posts.PostStory = "this story is null";
else
posts.PostStory = result.data[i].story;
if (object.ReferenceEquals(result.data[i].message, null))
posts.PostMessage = "this message is null";
else
posts.PostMessage = result.data[i].message;
posts.PostPicture = result.data[i].picture;
posts.UserId = result.data[i].from.id;
posts.UserName = result.data[i].from.name;
postsList.Add(posts);
}
}
catch (Exception err)
{
//throw;
string myerr = err.ToString();
}
}
}
}
I'm getting 25 results in the List postsList
How do i loop now asgain to get the next page with the next 25 results and add it to postsList and loop over and over again untill there are no more results ?
What i want to do is to delete automatic every 50 minutes the last old 25 posts.
In my other class in my project i'm posting automatic to my wall a post every minute. After 50 minutes i want to delete the last old 25 posts so on my wall will be all the time with 25 posts only.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using mshtml;
using HtmlAgilityPack;
using System.Net;
using System.IO;
namespace WebSite_Login_And_Browsing
{
public partial class Facebook_Post : Form
{
WebBrowser wb = new WebBrowser();
int postsCounter = 0;
StreamWriter w = new StreamWriter(#"e:\posts.txt");
WebBrowser webBrowser1;
public Facebook_Post()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("https://www.facebook.com/");
label4.Text = DateTime.Now.ToString();
w.WriteLine(label4.Text.ToString());
w.WriteLine(Environment.NewLine);
label5.Visible = false;
label2.Visible = false;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (e.Url.AbsoluteUri != webBrowser1.Url.AbsoluteUri)
{
return;
}
wb = webBrowser1;
foreach (HtmlElement he in wb.Document.All.GetElementsByName("xhpc_message"))
{
he.SetAttribute("value", RandomString(10));
}
var elems = wb.Document.GetElementsByTagName("button");
foreach (HtmlElement elem in elems)
{
if (elem.InnerText == "Post")
{
elem.InvokeMember("click");
}
}
sent = true;
postsCounter += 1;
label2.Text = postsCounter.ToString();
label2.Visible = true;
timer1.Enabled = true;
webBrowser1.Dispose();
if (postsCounter == 720)
{
w.WriteLine(postsCounter.ToString());
w.WriteLine(Environment.NewLine);
label5.Text = DateTime.Now.ToString();
label5.Visible = true;
w.WriteLine(label5.Text.ToString());
w.Close();
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> results = new List<string>();
HtmlElementCollection elems = wb.Document.GetElementsByTagName("INPUT");
foreach (HtmlElement elem in elems)
{
String nameStr = elem.GetAttribute("value");
results.Add(nameStr);
}
}
bool sent = false;
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
try
{
count += 1;
if (sent == true && count >= 60)
{
count = 0;
timer1.Enabled = false;
webBrowser1 = new WebBrowser();
if (webBrowser1.IsBusy == false)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.Navigate("https://www.facebook.com/");
}
sent = false;
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
}
private StringBuilder builder;
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
try
{
builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
return builder.ToString();
}
}
}
I believe this is what you're looking for:
var client = new FacebookClient(mytokenaslip);
//1-25
dynamic result = client.Get("/me/posts", new { limit = "25", offset = "0"});
//26-50
dynamic result = client.Get("/me/posts", new { limit = "25", offset = "25"});
You can also chose to get more than 25 posts at once.
//51-100
dynamic result = client.Get("/me/posts", new { limit = "50", offset = "50"});
You can use a "recursive function" to get all entries, and the "next" parameter in the API result includes the API call for the next batch of results: https://developers.facebook.com/docs/graph-api/using-graph-api#paging
Be careful though, you may hit an API limit if you try to do this too fast and if there are too many results. Also, since you want to delete old entries and deleting one entry is one API call, you should try with a timeout after each call just to make sure not to hit a limit.
Make sure you learn and understand how recursive functions work, hereĀ“s one of countless threads about that: Help with Creating a Recursive Function C#

How to send data using tcpclient on button click event as many times as i want without reestablishing connection?

I have c# server-client app..client sends its two ids to server.It works fine one time.But if the same client want to send another request..it does not work.
Because if i remove 'tcpclient.close' command,my server execution suspends.
Here is code..
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data;
namespace newserver
{
public partial class Form1 : Form
{
Socket sck;
// EndPoint epLocal, epRemote;
IPAddress ipAdress;
TcpListener myList;
string serverIP;
private PerformanceCounter cpuCounter;
int cpuLoad;
public Form1()
{
InitializeComponent();
InitialiseCPUCounter();
timer1.Start();
serverIP = "127.0.0.1";
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void InitialiseCPUCounter()
{
cpuCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
ipAdress = IPAddress.Parse(serverIP);
myList = new TcpListener(ipAdress, Convert.ToInt32("8000"));
myList.Start();
byte[] bytes = new byte[2560];
string data = "";
//sck = myList.AcceptSocket();
TcpClient client = myList.AcceptTcpClient();
btnStart.Text = "Connected";
lblCAFrom.Visible = true;
IPEndPoint ipep = (IPEndPoint)client.Client.RemoteEndPoint;
IPAddress ipa = ipep.Address;
txtCIP.Text = ipa.ToString();
NetworkStream stream = client.GetStream();
int i;
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
i = stream.Read(bytes, 0, bytes.Length);
}
string[] arr = data.Split(new char[] { ';' });
int length = arr.Length;
int no_of_req = length / 2;
// ..............server register....................//
string constr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Ayne\Documents\db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
int j = 0;
while (j < no_of_req)
{
string insert_register = "INSERT INTO Register(IP,IMPU,IMPI) Values('" + ipa.ToString() + "','" + arr[0] + "','" + arr[1] + "')";
SqlCommand cmd = new SqlCommand(insert_register, con);
cmd.ExecuteNonQuery();
j++;
}
con.Close();
txtCIP.Visible = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
this.txtCPUusage.Text =
cpuLoad.ToString() +
"%";
}
}
}
Client:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data;
namespace newserver
{
public partial class Form1 : Form
{
Socket sck;
// EndPoint epLocal, epRemote;
IPAddress ipAdress;
TcpListener myList;
string serverIP;
private PerformanceCounter cpuCounter;
int cpuLoad;
public Form1()
{
InitializeComponent();
InitialiseCPUCounter();
timer1.Start();
serverIP = "127.0.0.1";
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void InitialiseCPUCounter()
{
cpuCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
ipAdress = IPAddress.Parse(serverIP);
myList = new TcpListener(ipAdress, Convert.ToInt32("8000"));
myList.Start();
byte[] bytes = new byte[2560];
string data = "";
//sck = myList.AcceptSocket();
TcpClient client = myList.AcceptTcpClient();
btnStart.Text = "Connected";
lblCAFrom.Visible = true;
IPEndPoint ipep = (IPEndPoint)client.Client.RemoteEndPoint;
IPAddress ipa = ipep.Address;
txtCIP.Text = ipa.ToString();
NetworkStream stream = client.GetStream();
int i;
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
i = stream.Read(bytes, 0, bytes.Length);
}
string[] arr = data.Split(new char[] { ';' });
int length = arr.Length;
int no_of_req = length / 2;
// ..............server register....................//
string constr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Ayne\Documents\db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
int j = 0;
while (j < no_of_req)
{
string insert_register = "INSERT INTO Register(IP,IMPU,IMPI) Values('" + ipa.ToString() + "','" + arr[0] + "','" + arr[1] + "')";
SqlCommand cmd = new SqlCommand(insert_register, con);
cmd.ExecuteNonQuery();
j++;
}
con.Close();
txtCIP.Visible = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
this.txtCPUusage.Text =
cpuLoad.ToString() +
"%";
}
}
}
I was asking myself this very question today ,
I came Across a YouTube video that explains it nicely.
It should not be too hard to convert this code to a form application.
The Main Trick Seems to be to multi-thread the incoming connections
And Use asynchronous socket rather than TcpListener(TcpListener may be easier how ever)
I hope This Helps

Why does my Outlook becomes slow and sometimes unresponsive after starting an app to clear the clipboard?

I had a requirement to disable Copy Paste and even the print screen key while a website is running. So I wrote a WPF application to keep clearing the clipboard when Open Website link is clicked and stop clearing as soon as Close website button. But the problem is that when I press Open Website button the outlook client becomes very slow and sometimes unresponsive. I know that it has something to do with the clipboard only. Is there a way to disable Outlooks clipboard until the button is pressed.
However the code is not required but is included bleow, or can be downloaded from Dropbox:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Security.Cryptography;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Net.NetworkInformation;
namespace ccb
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string docNum,qs;
int status = 0;
static string connectionstring = "SERVER=abcd.com;port=3306;DATABASE=abcd_secure;UID=abcd_sec;PASSWORD=abcd_sec";
MySqlConnection conn = new MySqlConnection(connectionstring);
private static Random random = new Random((int)DateTime.Now.Ticks);
public MainWindow()
{
InitializeComponent();
}
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
status = 1;
Thread backgroundThread = new Thread(clear);
backgroundThread.IsBackground = true;
backgroundThread.SetApartmentState(ApartmentState.STA);
backgroundThread.Start();
qs=generaterandomnumber();
insert(qs);
System.Diagnostics.Process.Start("http://abcd/login.php?osid=win&id="+qs);
}
private void clear()
{
while (status == 1)
System.Windows.Clipboard.Clear();
}
//Genrate random number and encrypt it to MD5
private string generaterandomnumber()
{
string Rand1 = RandomString(8);
string Rand2 = RandomString(8);
docNum = Rand1 + "-" + Rand2;
MD5 md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(docNum));
//get hash result after compute it
byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
//Insert the generated value to the database
protected void insert(string q)
{
try
{
conn.Open();
string ins = "insert into mgen_validation_check(md5values) values(#m)";
MySqlCommand cmd = new MySqlCommand(ins, conn);
cmd.Parameters.AddWithValue("#m", q);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://abcd/include/LogoutPage.php");
this.Close();
status = 0;
try
{
conn.Open();
string del = "delete from mgen_validation_check where md5values=#m";
MySqlCommand cmd2 = new MySqlCommand(del, conn);
cmd2.Parameters.AddWithValue("#m", qs);
cmd2.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
private void Window_Closed(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://abcd/include/LogoutPage.php");
try
{
conn.Open();
string delconf = "delete from mgen_validation_check where md5values=#m";
MySqlCommand cmd3 = new MySqlCommand(delconf, conn);
cmd3.Parameters.AddWithValue("#m", docNum);
cmd3.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
}
}
The app is working properly except when running outlook becomes very slow. Other ms office apps are working properly.
Any help would be helpful.
Thanks in advance

C# passing serial to class

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.

Categories

Resources