Windows Services (error 1053) event log trigger - c#

I am new to programming and I have this project due on coming Tuesday. What I am trying to do is if a user enters a wrong password on the logon screen the cam takes the picture. I tried to implement my code in services but it gives me error 1053. I was wondering if somebody could fix this code for me or if file watcher is of use in my code. Please help!
namespace SampleWS
{
public partial class Service1 : ServiceBase
{
private WebCam camera;
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected virtual void OnPause(string[] args)
{
bool infinite = false;
LogonChecker(infinite);
}
protected virtual void OnContinue(string[] args)
{
bool infinite = true;
LogonChecker(infinite);
}
protected override void OnStart(string[] args)
{
bool infinite = true;
LogonChecker(infinite);
}
protected override void OnStop()
{
bool infinite = false;
LogonChecker(infinite);
}
DateTime mytime = DateTime.MinValue;
public void LogonChecker(bool infinity)
{
string queryString =
"<QueryList>" +
" <Query Id=\"\" Path=\"Security\">" +
" <Select Path=\"Security\">" +
" *[System[(Level <= 0) and" +
" TimeCreated[timediff(#SystemTime) <= 86400000]]]" +
" </Select>" +
" <Suppress Path=\"Application\">" +
" *[System[(Level = 0)]]" +
" </Suppress>" +
" <Select Path=\"System\">" +
" *[System[(Level=1 or Level=2 or Level=3) and" +
" TimeCreated[timediff(#SystemTime) <= 86400000]]]" +
" </Select>" +
" </Query>" +
"</QueryList>";
camera = new WebCam();
while (infinity)
{
EventLogQuery eventsQuery = new EventLogQuery("Security", PathType.LogName, queryString);
eventsQuery.ReverseDirection = true;
EventLogReader logReader = new EventLogReader(eventsQuery);
EventRecord eventInstance;
Int32 eventexists3 = new Int32();
EventLog mylog = new EventLog();
for (eventInstance = logReader.ReadEvent(); null != eventInstance; eventInstance = logReader.ReadEvent())
{
eventexists3 = eventInstance.Id.CompareTo(4625);
if (eventexists3 == 0)
{
if (eventInstance.TimeCreated.Value > mytime)
{
mytime = eventInstance.TimeCreated.Value;
camera.Connect();
Image image = camera.GetBitmap();
image.Save(#"D:\Audio\testimage3.jpg");
camera.Disconnect();
eventInstance = null;
break;
}
}
EventLogRecord logRecord = (EventLogRecord)eventInstance;
LogonChecker(infinity);
}
}
}
}
}

Despite my comment, this is easy. Check what the error 1053 means:
ERROR_SERVICE_REQUEST_TIMEOUT
1053 (0x41D)
The service did not respond to the start or control request in a timely fashion.
Your overrides of ServiceBase methods like OnStart need to return as soon as possible. If you want to perform any ongoing work either subscribe to events or spin up a worker thread.
The .NET documentation on MSDN doesn't really cover much about the execution model of services, for this you need to look at the Win32 documentation: About Services.

Related

C# WUApiLib: Failing to Install Updates with 0x80240024 Even Though Updates are Found

I have followed instructions found on this site, which was found when I researched Stack Overflow and found this question. However, I can't seem to figure out why my code is hitting the catch block. I have a break at the IInstallationResult line, which the code hits but then goes to the catch, stating 0x80240024 (There are no updates), even though there are certainly updates available and I list them in the text box.
What am I missing here?
using System;
using System.Windows.Forms;
using WUApiLib;
namespace TEST.DetectWindowsUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetUpdates(bool downloadUpdates, bool installUpdates)
{
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
UpdateCollection updatesToInstall = new UpdateCollection();
UpdateDownloader downloader = uSession.CreateUpdateDownloader();
IUpdateInstaller installer = uSession.CreateUpdateInstaller();
uSearcher.Online = true;
try
{
ISearchResult sResult = uSearcher.Search("IsInstalled=0 And Type='Software'");
lblUpdateCount.Text = sResult.Updates.Count.ToString();
foreach (IUpdate update in sResult.Updates)
{
txtUpdatesList.AppendText("Title: " + update.Title + Environment.NewLine);
txtUpdatesList.AppendText("IsInstalled: " + update.IsInstalled.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("Downloaded: " + update.IsDownloaded.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("IsMandatory: " + update.IsMandatory.ToString() + Environment.NewLine);
txtUpdatesList.AppendText(Environment.NewLine);
if (downloadUpdates)
{
if (update.IsDownloaded == false)
{
do
{
downloader.Updates.Add(update);
downloader.Download();
}
while (update.IsDownloaded == false);
if (update.IsDownloaded == true)
{
updatesToInstall.Add(update);
}
}
else
{
updatesToInstall.Add(update);
}
}
if (installUpdates)
{
installer.Updates = updatesToInstall;
IInstallationResult installationRes = installer.Install();
for (int i = 0; i < updatesToInstall.Count; i++)
{
txtUpdatesList.AppendText("Installing " + updatesToInstall[i].Title + "...");
if (installationRes.GetUpdateResult(i).HResult == 0)
{
txtUpdatesList.AppendText("INSTALL SUCCESS FOR " + updatesToInstall[i].Title);
}
else
{
txtUpdatesList.AppendText("INSTALL FAIL FOR " + updatesToInstall[i].Title);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message + ": " + ex.HelpLink);
}
}
private void btnGetUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(false, false);
}
private void btnInstallUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(true, true );
}
}
}
Turns out it was an issue with privileges. I ran as administrator and it functioned appropriately.

How to fix issue of zkemkeeper.dll realtime events inside windows service?

i'm setting up windows service and want it to sync the device attendance to SQL Server database using zkemkeeper real time event. i have successfully created service as well as tested the service on my local system which run windows 10 and another one window 8 service work fine and sync the attendance record to DB server at real time. Now after successful testing on local system i deployed service over production server where service successfully established the connection with device but it didn't respond to Real time event for testing purpose i have created winform app and run it over the server and find out it is working and listening to real time event but i need service to work properly not win form application any help will be appreciated thanks below is my code !
public partial class AttendanceSyncService_405 : ServiceBase
{
public AttendanceSyncService_405()
{
InitializeComponent();
}
System.Timers.Timer timer = new System.Timers.Timer();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
protected override void OnStart(string[] args)
{
//var thread = new Thread();
//thread.SetApartmentState(ApartmentState.STA);
//thread.Start();
WriteToFile("Service is started at " + DateTime.Now);
Connect();
// LoadCurrentMonthAtt();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 900000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
if (bIsConnected == true)
{
WriteToFile("Service recall at " + DateTime.Now);
WriteToFile("Device Status Connected at " + DateTime.Now);
}
else
{
WriteToFile("Device Status DisConnected at " + DateTime.Now);
WriteToFile("Service recall at " + DateTime.Now);
Connect();
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
private void Connect()
{
try
{
int idwErrorCode = 0;
bIsConnected = axCZKEM1.Connect_Net("192.168.0.177", 4370);
if (bIsConnected == true)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
iMachineNumber = 1;
if (axCZKEM1.RegEvent(iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
else
{
WriteToFile("RT Events didn't registered at " + DateTime.Now);
}
axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
WriteToFile("Device Connection Established Successfully at " + DateTime.Now);
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
WriteToFile("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString() + " at " + DateTime.Now);
}
}
catch(Exception ex)
{
WriteToFile("Exception :" + ex.Message + " at " + DateTime.Now);
}
}
private void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
{
DateTime Attendancedate = new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond);
string row = sEnrollNumber + "," + Attendancedate.ToString();
WriteToFile("Attendane :" + row + " Marked At: " + DateTime.Now);
if (bIsConnected == false)
{
Connect();
return;
}
decimal empserial = decimal.Parse(sEnrollNumber);
attInsert(empserial, Attendancedate);
}
private void attInsert(decimal empserial, DateTime Attendancedate)
{
try
{
WriteToFile("Attendance Entry Arrived for EMP-Serial :" + empserial + " At: " + DateTime.Now + " for Insertion");
DBAccess db = new DBAccess();
DataSet attCount = db.GetDataSetFromQuery("select Count(att.[todayCount]) as attCount from tblAttendance att where (att.attDate = Convert(date,GETDATE()) AND att.fkSerial ='" + empserial.ToString() + "')");
int count = int.Parse(attCount.Tables[0].Rows[0]["attCount"].ToString());
Boolean INOUT = (count % 2 == 0) ? true : false;
WriteToFile("Attendane Count :" + count + " & In/Out : " + INOUT + " Marked At: " + DateTime.Now);
db.Parameters.AddWithValue("fkSerial", empserial);
db.Parameters.AddWithValue("attTerminalId", "Time1");
db.Parameters.AddWithValue("attDateTime", Attendancedate);
db.Parameters.AddWithValue("attTgId", 3);
db.Parameters.AddWithValue("attINOUT", INOUT);
db.Parameters.AddWithValue("attEmpCode", "no need");
db.ExecuteNonQuery("spInsertAttendance");
WriteToFile("Attendance Inserted of EMP-Serial :" + empserial + " At: " + DateTime.Now);
}
catch (Exception ex)
{
WriteToFile("Exception in insert method :" + ex.Message + " At: " + DateTime.Now);
}
}
}
Type This Code in Your IntializeComponent and it will respond to realtime events
private void InitializeComponent()
{
Thread createComAndMessagePumpThread = new Thread(() =>
{
axCZKEM1 = new zkemkeeper.CZKEMClass();
bool connSatus = axCZKEM1.Connect_Net(192.168.0.177, 4370);
if (connSatus == true)
{
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}

C# process output redirection with plink (putty)

This one is driving me nuts... I want to write a simple C# application (with GUI) that logs into our Cisco Wireless Lan Controller (short WLC) via SSH and creates guest users. This would be quite easy with SSH.NET if not Cisco for whatever reason decided to not allow non-interactive logon - meaning you can't pass on username and password but have to type it in at the console. Even worse: they put an additional (non-functional) user prompt in front of the actual user prompt. God...
Anyway I figured it out using plink.exe and it is working quite ok, however I want to inspect the terminal output so I can decide if some commands were executed correctly. I want to use the output for the login too as the prompt appears somewhat slow and I can't rely on constant timing.
I have found some articles about redirection of the output (eg Process.start: how to get the output?), but it's just not working. I was only able to collect the output when plink.exe has been closed, but I need to read the output live with plink still running.
Here's my code so far:
namespace WIFI
{
public class Program
{
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new myForm());
}
public static String ProcessInput(string user)
{
GlobalVar.hasError = false;
GlobalVar.status = "";
if (user.Length < 5 || user.Length > 10)
{
GlobalVar.status = "Username ungültig";
GlobalVar.hasError = true;
}
else
{
WLCconnection WLC = new WLCconnection();
WLC.ConnectWLC();
if (!GlobalVar.hasError) WLC.UserExists(user);
if (!GlobalVar.hasError) WLC.CreateUser(user);
WLC.CloseWLC();
}
return GlobalVar.status;
}
}
public static class GlobalVar
{
public static Boolean hasError;
public static String status;
}
public class WLCconnection
{
Process terminal = new Process();
StringBuilder terminalOutput = new StringBuilder();
Boolean telnet = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["telnet"]);
String WLChostname = System.Configuration.ConfigurationManager.AppSettings["WLChostname"];
String WLCusername = System.Configuration.ConfigurationManager.AppSettings["WLCusername"];
String WLCpassword = System.Configuration.ConfigurationManager.AppSettings["WLCpassword"];
public void ConnectWLC()
{
terminal.StartInfo.FileName = #System.Configuration.ConfigurationManager.AppSettings["plinkpath"];
terminal.StartInfo.UseShellExecute = false;
terminal.StartInfo.RedirectStandardInput = true;
terminal.StartInfo.RedirectStandardOutput = true;
terminal.StartInfo.RedirectStandardError = true;
terminal.StartInfo.CreateNoWindow = true;
if (telnet) terminal.StartInfo.Arguments = "-telnet " + WLChostname;
else terminal.StartInfo.Arguments = "-ssh " + WLChostname;
terminal.OutputDataReceived += (s, e) => terminalOutput.Append(e.Data);
//terminal.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
terminal.ErrorDataReceived += (s, e) => terminalOutput.Append(e.Data);
//terminal.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
terminal.Start();
terminal.BeginOutputReadLine();
terminal.BeginErrorReadLine();
int runs = 0;
if (!telnet)
{
while (!terminalOutput.ToString().Contains("login as:") && !GlobalVar.hasError)
{
Thread.Sleep(500);
if (runs < 20) runs++;
else GlobalVar.hasError = true;
}
terminal.StandardInput.Write("workaroundSSHproblem\n");
}
runs = 0;
while (!terminalOutput.ToString().Contains("User:") && !GlobalVar.hasError)
{
Thread.Sleep(500);
if (runs < 20) runs++;
else GlobalVar.hasError = true;
}
terminal.StandardInput.Write(WLCusername + "\n");
runs = 0;
while (!terminalOutput.ToString().Contains("Password:") && !GlobalVar.hasError)
{
Thread.Sleep(500);
if (runs < 20) runs++;
else GlobalVar.hasError = true;
}
terminal.StandardInput.Write(WLCpassword + "\n");
}
public void CloseWLC()
{
terminal.StandardInput.WriteLine("logout");
terminal.WaitForExit();
terminal.CancelOutputRead();
terminal.Close();
terminal.Dispose();
}
public Boolean UserExists(String user)
{
int runs = 0;
while (!terminalOutput.ToString().Contains("(Cisco Controller) >") && !GlobalVar.hasError)
{
Thread.Sleep(500);
if (runs < 20) runs++;
else GlobalVar.hasError = true;
}
terminal.StandardInput.Write("show netuser detail " + user);
if (!terminalOutput.ToString().Contains("blabla"))
{
GlobalVar.status = "User " + user + " bereits aktiviert";
GlobalVar.hasError = true;
}
return GlobalVar.hasError;
}
public void CreateUser(String user)
{
int runs = 0;
while (!terminalOutput.ToString().Contains("(Cisco Controller) >") && !GlobalVar.hasError)
{
Thread.Sleep(500);
if (runs < 20) runs++;
else GlobalVar.hasError = true;
}
terminal.StandardInput.Write("config netuser add " + user + " " + System.Configuration.ConfigurationManager.AppSettings["guestpassword"] + " wlan 3 userType guest lifetime 86400");
if (!GlobalVar.hasError)
{
if (UserExists(user))
{
GlobalVar.status = "";
GlobalVar.hasError = false;
}
else
{
GlobalVar.status = "User " + user + " konnte nicht aktiviert werden";
GlobalVar.hasError = true;
}
}
}
protected void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
terminalOutput.Append(outLine.Data);
}
}
}
I'd really appreciate your help!
For whom it may be of any help: I solved it using SSH.NET again, but this time not using the built in functions to login in but by using in combination with ShellStream to manually process in- and output. Working great so far.

Unable to cast object of type 'System.Threading.Timer' to type 'jabber.client.JabberClient' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am making a birthday notification in windows service that uses jabber-net library which is a XMPP and System.Threading that must send automatic messages to user every day, but i'm getting an error in logs which says
Unable to cast object of type 'System.Threading.Timer' to type 'jabber.client.JabberClient'. at SparkSalesCrdBirthdays.SparkBirthDayGreeting.j_OnAuthenticate(Object sender)
Here's my code
protected override void OnStart(string[] args)
{
this.WriteToFile("Simple Service started {0}");
JabberClient j = new JabberClient();
// what user/pass to log in as
j.User = "user";
j.Server = "server"; // use gmail.com for GoogleTalk
j.Password = "pass";
//j.Resource = "admin";
// don't do extra stuff, please.
j.AutoPresence = false;
j.AutoRoster = false;
j.AutoReconnect = -1;
j.KeepAlive = 10;
j.AutoLogin = true;
j.AutoStartTLS = false;
j.PlaintextAuth = true;
j.OnError += new bedrock.ExceptionHandler(j_OnError);
// what to do when login completes
j.OnAuthenticate += new bedrock.ObjectHandler(j_OnAuthenticate);
// listen for XMPP wire protocol
if (VERBOSE)
{
j.OnReadText += new bedrock.TextHandler(j_OnReadText);
j.OnWriteText += new bedrock.TextHandler(j_OnWriteText);
}
// Set everything in motion
j.Connect();
// wait until sending a message is complete
done.WaitOne();
// logout cleanly
j.Close();
this.ScheduleService();
}
protected override void OnStop()
{
this.WriteToFile("Simple Service stopped {0}");
this.Schedular.Dispose();
}
private Timer Schedular;
static void j_OnWriteText(object sender, string txt)
{
if (txt == " ") return; // ignore keep-alive spaces
Console.WriteLine("SEND: " + txt);
}
static void j_OnReadText(object sender, string txt)
{
if (txt == " ") return; // ignore keep-alive spaces
Console.WriteLine("RECV: " + txt);
}
private void j_OnAuthenticate(object sender)
{
try
{
JabberClient j = (JabberClient)sender;
DataTable dt = new DataTable();
string birthdaymsg = "";
string fullname;
string department;
string query = "SELECT CONCAT(FirstName, ' ', MiddleName, ' ', LastName) as Fullname, DepartmentDescription FROM vw_EmployeeOrganization WHERE DATEPART(d, BirthDate) = DATEPART(d,GETDATE()) AND DATEPART(m, BirthDate) = DATEPART(m, GETDATE()) AND DepartmentDescription IN('Client Relations--CDO', 'E-Learning', 'Sales ', 'Client Relations', 'Sales-Davao', 'Sales-CDO', 'Client Relations--Cebu', 'Sales-Cebu')";
string constr = ConfigurationManager.ConnectionStrings["HRIS"].ConnectionString;
lstUsers.Clear();
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
foreach (DataRow row in dt.Rows)
{
fullname = row["Fullname"].ToString();
department = row["DepartmentDescription"].ToString();
birthdaymsg = "Happy Birthday! " + fullname + " from " + department + "." +
System.Environment.NewLine + "May today be filled with sunshine and smile, laughter and love.";
string queryRecipient = "SELECT * FROM tbl_MPAlertUsers";
string constr2 = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection conn2 = new SqlConnection(constr2))
{
using (SqlCommand cmd2 = new SqlCommand(queryRecipient))
{
cmd2.Connection = conn2;
conn2.Open();
SqlDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
lstUsers.Add(reader["ADname"].ToString());
}
reader.Close();
conn2.Close();
}
}
//Send to Recipient
for (int i = 0; i <= lstUsers.Count - 1; i++)
{
if (lstUsers[i].ToString().Trim().Length > 1)
{
WriteToFile("Trying to send spark to: " + lstUsers[i].ToString());
j.Message(lstUsers[i], birthdaymsg);
}
}
done.Set();
}
this.ScheduleService();
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
}
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(j_OnAuthenticate));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
this.WriteToFile("Simple Service Mode: " + mode + " {0}");
//Set the Default Time.
DateTime scheduledTime = DateTime.MinValue;
if (mode == "DAILY")
{
//Get the Scheduled Time from AppSettings.
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next day.
scheduledTime = scheduledTime.AddDays(1);
}
}
if (mode.ToUpper() == "INTERVAL")
{
//Get the Interval in Minutes from AppSettings.
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
//Set the Scheduled Time by adding the Interval to Current Time.
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next Interval.
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");
//Get the difference in Minutes between the Scheduled and Current Time.
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
//Change the Timer's Due Time.
Schedular.Change(dueTime, Timeout.Infinite);
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
I hope someone can help me with this. I am stuck :(
Thank you.
The problem is that JabberClient's event is handled in j_OnAuthenticate and the timer's event is handled with it:
Schedular = new Timer(new TimerCallback(j_OnAuthenticate));
...
JabberClient j = new JabberClient();
j.OnAuthenticate += new bedrock.ObjectHandler(j_OnAuthenticate);
And in j_OnAuthenticate the first thing you do is cast the sender to JabberClient
private void j_OnAuthenticate(object sender)
{
try
{
JabberClient j = (JabberClient)sender;
...
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
The catch block handles and logs the exception.
You would have to change the code to do different things depending on the sender e.g.
if(sender is JabberClient)
{
//do something
}
else if(sender is Timer)
{
//do something else
}
Or give the timer a different callback function

Auto BrithdayMail send by using services

Hello I try to create auto emails send by service file but there is some problem.
this is BrithdayEmailService.cs file.
namespace BirthdayEmailSevice
{
partial class BirthdayEmailService : ServiceBase
{
private Timer scheduleTimer = null;
private DateTime lastRun;
private bool flag;
public BirthdayEmailService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailLog");
}
eventLogEmail.Source = "EmailSource";
eventLogEmail.Log = "EmailLog";
scheduleTimer = new Timer();
scheduleTimer.Interval = 1 * 5 * 60 * 1000;
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
flag = true;
lastRun = DateTime.Now;
scheduleTimer.Start();
eventLogEmail.WriteEntry("Started");
}
protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (flag == true)
{
ServiceEmailMethod();
lastRun = DateTime.Now;
flag = false;
}
else if (flag == false)
{
if (lastRun.Date < DateTime.Now.Date)
{
ServiceEmailMethod();
}
}
}
private void ServiceEmailMethod()
{
eventLogEmail.WriteEntry("In Sending Email Method");
EmailComponent.GetEmailIdsFromDB getEmails = new EmailComponent.GetEmailIdsFromDB();
getEmails.connectionString = ConfigurationManager.ConnectionStrings["CustomerDBConnectionString"].ConnectionString;
getEmails.storedProcName = "GetBirthdayBuddiesEmails";
System.Data.DataSet ds = getEmails.GetEmailIds();
EmailComponent.Email email = new EmailComponent.Email();
email.fromEmail = "example#gmail.com";
email.fromName = "example Name";
email.subject = "Birthday Wishes";
email.smtpServer = "smtp.gmail.com";
email.smtpCredentials = new System.Net.NetworkCredential("example1#gmail.com", "example1 password");
foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
{
email.messageBody = "<h4>Hello " + dr["CustomerName"].ToString() + "</h4><br/><h3>We Wish you a very Happy" +
"Birthday to You!!! Have a bash...</h3><br/><h4>Thank you.</h4>";
bool result = email.SendEmailAsync(dr["CustomerEmail"].ToString(), dr["CustomerName"].ToString());
if (result == true)
{
eventLogEmail.WriteEntry("Message Sent SUCCESS to - " + dr["CustomerEmail"].ToString() +
" - " + dr["CustomerName"].ToString());
}
else
{
eventLogEmail.WriteEntry("Message Sent FAILED to - " + dr["CustomerEmail"].ToString() +
" - " + dr["CustomerName"].ToString());
}
}
}
}
On scheduleTimer = new Timer(); got error
(This member is defined more than one)
Error:
Ambiguity between 'BirthdayEmailService.BirthdayEmailService.scheduleTimer' and 'BirthdayEmailService.BirthdayEmailService.scheduleTimer'
Also got error on BirthdayEmailService.Designer.cs this is file of design tool of service
error is :
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.eventLogEmail = new System.Diagnostics.EventLog();
**this.scheduleTimer = new System.Windows.Forms.Timer(this.components);**
((System.ComponentModel.ISupportInitialize)(this.eventLogEmail)).BeginInit();
//
// BirthdayEmailService
//
this.ServiceName = "BirthdayEmailService";
((System.ComponentModel.ISupportInitialize)(this.eventLogEmail)).EndInit();
}
those part is bold there is getting error as same as.
(This member is defined more than one)
Error:
Ambiguity between 'BirthdayEmailService.BirthdayEmailService.scheduleTimer' and 'BirthdayEmailService.BirthdayEmailService.scheduleTimer'
It could be because the name of the class and the namespace are the same one. See this post.

Categories