I have code below to ping the IP address, but when I run this code, it's not running because there is no update into the database.
Here is the Start code:
protected void Start()
{
string ip_STCKL = "*.*.10.";
string ip_STCKCH = "*.*.128.";
for (int ipCount = ip_addr; ipCount < 195; ipCount++)
{
string ip = ip_STCKL + ipCount.ToString();
string loopIp = ip;
WaitCallback func = delegate(object state)
{
if (PingIP(loopIp))
{
UpdateStatusKL(loopIp, true);
Console.WriteLine("Ping Success");
}
else
{
loopIp = ip_STCKCH + ipCount.ToString();
if (PingIP(loopIp))
{
UpdateStatusKL(loopIp, true);
//Console.WriteLine("Ping Success");
}
else
{
UpdateStatusKL(loopIp, false);
//Console.WriteLine("Ping Failed");
}
}
};
ThreadPool.QueueUserWorkItem(func);
//ThreadPool.GetAvailableThreads;
}
//Console.ReadLine();
}
This is the ping function to get the status:
public static bool PingIP(string IP)
{
bool result = false;
try
{
Ping ping = new Ping();
PingReply pingReply = ping.Send(IP);
if (pingReply.Status == IPStatus.Success)
result = true;
}
catch(Exception)
{
result = false;
}
return result;
}
After get the status, update into the database:
public void UpdateStatusKL(string IP, bool Status)
{
string New_Status = "";
if (Status)
{
New_Status = "REACHABLE";
}
else
{
New_Status = "UNREACHABLEE";
}
//Declare the connection object
OracleConnection Conn = new OracleConnection("Data Source=COMMSERVERKL;User
Id=mt_mon;Password=butus123");
//Make the connection
Conn.Open();
//Define you query
string sql = "UPDATE BalaiConnectionStatus SET Balai_Status = :pstatus,
Timestamp = :pTime WHERE IP_STCKL = :pIP OR IP_STCKCH = :pIP";
//Declare the Command
OracleCommand cmd = new OracleCommand(sql, Conn);
//Add the parameters needed for the SQL query
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("pstatus", OracleType.VarChar).Value = New_Status;
cmd.Parameters.Add("pTime", OracleType.VarChar).Value =
DateTime.Now.ToString();
cmd.Parameters.Add("pIP", OracleType.VarChar).Value = IP;
//Execute the query
cmd.ExecuteNonQuery();
Conn.Close();
}
Every 15 minutes when the timer trigger, it will call the Start function to start pinging all the IP addresses again:
private void timer1_Tick(object sender, EventArgs e)
{
ip_addr = 10;
Start();
}
What is the problem with my code and how can I fix it?
Related
I have a method that check for records in a database and a timer that starts the method every 10 seconds. I check if a new record was inserted in a table and get these values to send emails.
The problem is, if has sended the email 1 time, it is no stop the timer and sends email every 10 seconds. To "solve" this i used an IF to check if the ID of the table was different, and partially i "resolved" the problem. And now, there is a new problem, because the result of the Select with joins query, returns much values and only the ID of that table is repeated, but the other fields are not, like this image:
As you can see, the ID of the table is 16, but the other ID are 2, 3, 4.
With my first solution, only sends email to the first row and ignore the others rows. Thats my problem, because i need to sends emails to the other rows. How can i do that?
This is my code (i use Windows Service):
public partial class GaxTankAlerts : ServiceBase
{
private string conn = "Data Source=.;Initial Catalog=DBCatalog;Integrated Security=false;User ID=GAX;Password=****;";
private Timer scheduleTimer = null;
private bool bandera;
private string id = "";
private string estatusAlerta = "";
private DateTime fechaAlerta;
public GaxTankAlerts()
{
InitializeComponent();
if (!EventLog.SourceExists("AlertService"))
{
EventLog.CreateEventSource("AlertService", "AlertLog");
}
eventLogEmail.Source = "AlertService";
eventLogEmail.Log = "AlertLog";
scheduleTimer = new Timer();
scheduleTimer.Interval = 10000;
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
bandera = true;
scheduleTimer.Start();
eventLogEmail.WriteEntry("El servicio ha iniciado");
//GetAlerts();
}
protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//if (bandera == true) {
// GetAlerts();
// //lastRun = DateTime.Now;
// bandera = false;
//}
eventLogEmail.WriteEntry("Comprobando si hay registros nuevos...");
if (bandera == true)
{
GetAlerts();
}
}
public void GetAlerts()
{
var path = AppDomain.CurrentDomain.BaseDirectory + "EmailTemplate\\Email.html";
string body = File.ReadAllText(path);
try
{
using (SqlConnection con = new SqlConnection(conn))
{
SqlCommand cmd = new SqlCommand("[General].[GetAlertas]", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
{
if (dr.HasRows)
{
while (dr.Read())
{
if (dr["ID"].ToString() != id)
{
id = dr["ID"].ToString();
if (dr["EstatusAlerta"].ToString() != estatusAlerta)
{
estatusAlerta = dr["EstatusAlerta"].ToString();
using (MailMessage mm = new MailMessage())
{
//Sends emails
}
}
}
//if (dr["EstatusAlerta"].ToString() != idReg)
//{
// idReg = dr["EstatusAlerta"].ToString();
// bandera = true;
//}
//else {
// bandera = false;
//}
}
}
}
dr.Close();
con.Close();
}
}
catch (Exception ex)
{
eventLogEmail.WriteEntry(ex.Message.ToString());
}
}
Thank you.
I have this code
private delegate void InvokeDelegate();
private void OpenFormNewNote(object sender, FileSystemEventArgs e)
{
if(loop == 2)
{
string service = null;
if (currentServiceName != null)
{
service = currentServiceName.Replace(" ", "");
}
NewNotePanel newNote = new NewNotePanel(e.FullPath, service, listOfService, Path, MyConn, ipAddress, imgFolder, Utente_id);
newNote.TopMost = true;
watcher.EnableRaisingEvents = false;
var result = newNote.ShowDialog();
if(result == DialogResult.OK || result == DialogResult.Cancel)
{
watcher.EnableRaisingEvents = true;
if(result == DialogResult.OK)
{
this.BeginInvoke(new InvokeDelegate(Refresh));
}
}
loop = 0;
}
else
{
loop++;
}
}
And this is the Refresh() Function:
public void Refresh()
{
noteContainer.Controls.Clear();
page = 0;
try
{
string Query = "SELECT a, v, b, cFROM note Where Servizio_ID = " + asd+ " AND Visibile = 1 order by ID desc limit 15 OFFSET " + (pageIndex * page) + " ;";
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MySqlDataReader MyReader;
if (MyConn.State == ConnectionState.Open)
{
MyReader = MyCommand.ExecuteReader();// Here our query will be executed and data saved into the database.
while (MyReader.Read())
{
CreateNotePreview(MyReader.GetString("a"), MyReader.GetString("b"), MyReader.GetString("c"), MyReader.GetString("d"));
}
MyReader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Since OpenFormNewNote is called when the "Change" event of FileSystemWatcher is triggered.. of course it runs on a separated thread. Instead Refresh() does some UI stuff and it can't be called directly from OpenFormNewNote() otherwise it gives a Cross-Thread exception. So I tried with delegate but when the codeflow arrives on the BeginInvoke part.. Nothing happens and the Refresh function is not called.
What should I do?
I have a problem in using ProgressBar while my program does PING. Error says that "This BackgroundWorker is currently busy and cannot run multiple tasks concurrently". Can anyone help me ? These are what I have done
private void ProsesSemuaKamera()
{
Stopwatch watch = Stopwatch.StartNew();
Ping ping = new Ping();
PingReply pingreply;
BackgroundWorker BWKamera = new BackgroundWorker();
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
kon.Open();
string selecturl = "select * from datakamera";
command.CommandText = selecturl;
OleDbDataReader bacadata = command.ExecuteReader();
/* PING Kamera IP */
while (bacadata.Read())
{
pingreply = ping.Send(bacadata["ipadd"].ToString());
BWKamera.WorkerReportsProgress = true;
BWKamera.DoWork += BWKamera_DoWork;
BWKamera.ProgressChanged += BWKamera_ProgressChanged;
BWKamera.RunWorkerAsync(); //error exists here
if (pingreply.Status == IPStatus.Success)
{
listBox1.Items.Add(bacadata["namakamera"].ToString());
if (CaptureSemuaKamera == null)
{
try
{
CaptureSemuaKamera = new Capture(bacadata["urlkamera"].ToString());
}
catch (NullReferenceException ex)
{
MessageBox.Show(ex.Message);
}
}
if (CaptureSemuaKamera != null)
{
Application.Idle += new EventHandler(ProcessFrameSemuaKamera);
}
}
else if (pingreply.Status != IPStatus.Success)
{
listBox2.Items.Add(bacadata["namakamera"].ToString());
}
watch.Stop();
File.AppendAllText(#"D:\Dokumen\Alfon\TA Alfon\Waktu Eksekusi Ping.txt", "Waktu eksekusi ping " + DateTime.Now + " :" + " " + watch.Elapsed.TotalMilliseconds.ToString() + Environment.NewLine);
}
kon.Close();
}
private void BWKamera_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 1000; i++)
{
BWKamera.ReportProgress(i);
Thread.Sleep(1000);
}
}
private void BWKamera_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBarKamera.Value = e.ProgressPercentage;
StatusKamera.Text = "Please Wait...";
}
private void BWKamera_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
StatusKamera.Text = "Done !";
}
Since it is in a while loop. I will assume that the first background worker has not completed and you are telling it to run again on the same instance.
OleDbDataReader bacadata = command.ExecuteReader();
BWKamera.WorkerReportsProgress = true;
BWKamera.DoWork += BWKamera_DoWork;
BWKamera.ProgressChanged += BWKamera_ProgressChanged;
BWKamera.RunWorkerAsync(bacadata);
then the background worker code would look like this:
private void BWKamera_DoWork(object sender, DoWorkEventArgs e)
{
OleDbDataReader bacadata = (OleDbDataReader)e.Argument;
while (bacadata.Read())
{
pingreply = ping.Send(bacadata["ipadd"].ToString());
I want to retrieve mail attachments and store them into bytes[] so that I can insert them into table where a column attachment is of varbinary type. In windows form I am using OpenFileDialog and I don't know how to get the file's bytes in a byte[] type so that I can insert that into table in SQLServer.
Here is the code:
namespace fyp8
{
public partial class ComposeMail : Form1
{
ArrayList alAttachments;
MailMessage mmsg;
string conn = #"Data source=(local);Initial Catalog=fyp;Integrated Security=true";
public ComposeMail()
{
InitializeComponent();
}
private void ComposeMail_Load(object sender, EventArgs e)
{
}
private void btnAttachment_Click(object sender, EventArgs e)
{
OpenFileDialog odflg = new OpenFileDialog();
odflg.ShowDialog();
if (odflg.ShowDialog() == DialogResult.OK)
{
try
{
txtAttachments.Text = odflg.FileName;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
if (txtEmid.Text != null && txtPass.Text != null)
{
mmsg = new MailMessage(txtEmid.Text, txtTo.Text);
mmsg.Subject = txtSub.Text;
mmsg.Body = txtBody.Text;
mmsg.IsBodyHtml = true;
/* Set the SMTP server and send the email with attachment */
SmtpClient smtpClient = new SmtpClient();
// smtpClient.Host = emailServerInfo.MailServerIP;
//this will be the host in case of gamil and it varies from the service provider
smtpClient.Host = "smtp.gmail.com";
//smtpClient.Port = Convert.ToInt32(emailServerInfo.MailServerPortNumber);
//this will be the port in case of gamil for dotnet and it varies from the service provider
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
//smtpClient.Credentials = new System.Net.NetworkCredential(emailServerInfo.MailServerUserName, emailServerInfo.MailServerPassword);
smtpClient.Credentials = new NetworkCredential(txtEmid.Text, txtPass.Text);
//Attachment
Attachment attachment = new Attachment(txtAttachments.Text);
if (attachment != null)
{
mmsg.Attachments.Add(attachment);
}
//this will be the true in case of gamil and it varies from the service provider
smtpClient.EnableSsl = true;
smtpClient.Send(mmsg);
}
string msg = "Message Send Successfully:";
msg += "\n To :" + txtTo.Text;
SqlConnection con = new SqlConnection(conn);
string query = "insert into sentmail values(#from,#to,#sub,#body,#status)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#from", txtFrom.Text);
cmd.Parameters.AddWithValue("#to", txtTo.Text);
cmd.Parameters.AddWithValue("#sub", txtSub.Text);
cmd.Parameters.AddWithValue("#body",txtBody.Text);
cmd.Parameters.AddWithValue("#status","sent" );
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(msg.ToString());
/* clear the controls */
txtEmid.Text = string.Empty;
txtPass.Text = string.Empty;
txtFrom.Text = string.Empty;
txtTo.Text = string.Empty;
txtSub.Text = string.Empty;
txtBody.Text = string.Empty;
txtAttachments.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
}
Use the FileDialog.FileName property to get the selected file name.
Use File.ReadAllBytes to easily read the entire file into a byte array.
void Test() {
var dialog = new OpenFileDialog();
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
byte[] buffer = File.ReadAllBytes(dialog.FileName);
// Do whatever you want here with buffer
}
You're currently calling ShowDialog() twice. Just call it once and save the result.
I got a tab container which has 4 tabs in it. In one of the tab named ADD TASK I got few fields like
(Task Name: --txtbox
Client Name:--drpdwn
Begin Date:--txtbox wid calendar
Due Date:--txtbox wid calendar
Description:--txtbox
Assign To:--drpdown
Status:--drpdown
% Complete:--drpdown)
and an ADD and CANCEL button in the end.
On running the project and inserting the values to those above mentioned fields i will click the add button and after clicking the button the values should store in my DATABASE. i have table named TASK in my DB already.
Please help me with the back end code.
here is my code
protected void BtnAdd_Click(object sender, EventArgs e)
{
MTMSDTO objc = new MTMSDTO();
int Flag = 0;
objc.TaskName = Session["TaskName"].ToString();
objc.ClientName = DrpClientName.SelectedItem.Text;
objc.BeginDate = Convert.ToDateTime(TxtBeginDate.Text);
objc.DueDate = Convert.ToDateTime(TxtDueDate.Text);
objc.Description = Session["Description"].ToString();
objc.AssignTo = DrpAssignTo.SelectedItem.Text;
objc.Status = DrpStatus.SelectedItem.Text;
objc.PercentageComplete = Convert.ToInt32(DrpPercentageComplete.Text);
int X = obj.InsertTask(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Data Added Successfully";
Panel2.Visible = false;
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Add Data!!!";
}
}
im using layered architecture and i have this code on my ACCESS file of DAL CLASS
public int InsertTask(MTMSDTO M)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#TaskID", M.TaskID);
objParam.Direction = ParameterDirection.Output;
db.Parameters.Add(new SqlParameter("#TaskName", M.TaskName));
db.Parameters.Add(new SqlParameter("#ClientName", M.ClientName));
db.Parameters.Add(new SqlParameter("#BeginDate", M.BeginDate));
db.Parameters.Add(new SqlParameter("#DueDate", M.DueDate));
db.Parameters.Add(new SqlParameter("#Description", M.Description));
db.Parameters.Add(new SqlParameter("#AssignTo", M.AssignTo));
db.Parameters.Add(new SqlParameter("#Status", M.Status));
db.Parameters.Add(new SqlParameter("#PercentageComplete", M.PercentageComplete));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("InsertTask");
if (retval >= 1)
{
return int.Parse(objParam.Value.ToString());
}
else
{
return -1;
}
}
the code is edited now but im getting error as "object reference not set to an instance of an object. " for the line (objc.TaskName = Session["TaskName"].ToString();) which is in BtnAdd_Cick.
Shouldn't your BtnAdd_Click function be something like this instead? You don't currently seem to be calling the InsertTask() function.
protected void BtnAdd_Click(object sender, EventArgs e) {
MTMSDTO m = new MTMSDTO();
m.TaskName = TxtTaskName.Text;
m.ClientName = DrpClientName.Text;
m.BeginDate = TxtBeginDate.Text;
m.DueDate = TxtDueDate.Text;
m.Description = TxtDescription.Text;
m.AssignTo = DrpAssignTo.Text;
m.Status = DrpStatus.Text;
m.PercentageComplete = DrpPercentageComplete.Text;
InsertTask(m);
}
get all values in back end and pass to this function
public bool InsertRecord(string strTableName, string strColumn_Name, string strValues)
{
SqlConnection OBJCONNECTION;
StringBuilder strbQuery;
SqlCommand cmd;
try
{
OBJCONNECTION= new SqlConnection();
OBJCONNECTION.ConnectionString = ConfigurationManager.ConnectionStrings["Basic_ADO"].ConnectionString;//get connection string from web.config file
OBJCONNECTION=
strbQuery = new StringBuilder();
strbQuery.Append("INSERT INTO ");
strbQuery.Append(strTableName);
strbQuery.Append("(" + strColumn_Name + ")");
//strbQuery.Append(" VALUES");
strbQuery.Append("(" + strValues + ")");
cmd = new SqlCommand(strbQuery.ToString(), OBJCONNECTION);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex) { throw ex; }
finally { strbQuery = null; cmd = null;OBJCONNECTION.close();}
}