windows service start and stop functions [Resolved]

Posted by Tobi under C# on 5/15/2013 | Points: 10 | Views : 4034 | Status : [Member] | Replies : 18
hi everybody

i want to know if the code in the start and stop functions of a windows service is executed only with the system's start and shutdown or everytime.
the service is running in localsystem session and i want to know if i stop the service and start it why my code in the functions in not executed
thanks




Responses

Posted by: Peermohamedmydeen on: 5/28/2013 [Member] Bronze | Points: 50

Up
0
Down

Resolved
Do something like this.

 public partial class YourService : ServiceBase

{

Timer mytimer;
private DateTime lastRun = DateTime.Now;

public YourService ()
{
InitializeComponent();

}

protected override void OnStart(string[] args)
{

//Log.Write(" Service Started."); //Custom logging to a log file.

if (mytimer == null)
mytimer = new Timer(5 * 1000.0); //Elapse every 5 seconds and make this configurable. while (1==1) is not the good approach.
mytimer.Elapsed += new ElapsedEventHandler(mytimer_Elapsed);
mytimer.Start();

}

protected override void OnStop()
{
if (mytimer != null)
{
mytimer.Stop();
mytimer.Dispose();
}

//Log.Write("Service Stopped.");
}


void mytimer_Elapsed(object sender, ElapsedEventArgs e)
{
//Disable timer when we are executing Any particular task. For instance when u write into the text file.
mytimer.Enabled = false;

Run();

//Enalbe timer after the test execution is done
mytimer.Enabled = true;
}


static void run()
{

if (Process.GetProcessesByName("notepad").Length == 0)
{
TextWriter file = new StreamWriter(@"C:\temp\journal.txt",true);
file.WriteLine("attention arret du processus anivirus effectué à:" + DateTime.Now.ToString() + "sur le pc:gerer le nom apres" + "\n");
file.Close();
}
}


}


If the Run method is a sole routine for this service you dont need to put a thread unless u do multi tasking.

Note : Please include the test file write logic in Onstrat() and OnStop() events from your code.


PMM


Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 5/30/2013 [Member] Bronze | Points: 50

Up
0
Down

Resolved
The method Run() is static and it is not accessible in non-static event. So mark the method as non-static and for the ambiguity try adding namespace system.Timers.Timer.

Both the errors should be resolved.


Thanks
PMM

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 5/30/2013 [Member] Bronze | Points: 50

Up
0
Down

Resolved
You welcome.

Sorry for the typo in my responses as I wrote the code in Notepad. :)

C# has great control over registries. Use Microsoft.Win32 namespace and use Registry.SetValue and Registry.GetValue methods to access the values.

If u have any specific issues on your code I am happy to help you.

Regards
Mydeen

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 6/4/2013 [Member] Bronze | Points: 50

Up
0
Down

Resolved
You can get the return value of Registry.GetValue as object and cast it to specifi type as needed.

If you want to have it as string then,

 string noSuch = (string) Registry.GetValue(keyName, 

"NoSuchName",
"Return this default if NoSuchName does not exist.");


If you want to have it as integer then,

 int tInteger = (int) Registry.GetValue(keyName, "", -1);

long tLong = (long) Registry.GetValue(keyName, "TestLong", long.MinValue);



or you can use int.parse() functions to handle null or empties.

Regards,
Mydeen

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 5/27/2013 [Member] Bronze | Points: 25

Up
0
Down
It should execute the OnStart() and OnStop() events while you start and stop the service respectively.

What I suspect is, the routine or piece of code you placed in the events may thrown exception and terminates without completing the full routine.

Can u please share the code to have better understanding.


Thanks
PMM

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 5/27/2013 [Member] Starter | Points: 25

Up
0
Down
thanks for your answear
i ll share the code but not for this problem because it was resolved!
now i have a bigger problem and i need some help please
i want my windows service to check if the antivirus is running and if not to write it in a file
the probleme is that there is not a function like onstart() and onstop() to loop while the service is running to check this(i m not sure)
my idea is to declar a thread to do this(is it the best way???)
here is the code but i cannot use the function threadstart() i dont know why

namespace test1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
if (File.Exists(@"C:\temp\journal.txt"))
{
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("attention demarrage2 effectué à:" + DateTime.Now.ToString() + "\n");
file.Close();
}
else
{
TextWriter file = File.CreateText(@"C:\temp\journal.txt");
file.WriteLine("attention premier demarrage du service apres deploiement effectué à:" + DateTime.Now.ToString() + "\n");
file.Close();
}
}

protected override void OnStop()
{
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("attention arretttttt effectué à:" + DateTime.Now.ToString() + "\n");
file.Close();
}

static void run()
{
while (1 == 1)
{
if (Process.GetProcessesByName("notepad").Length == 0)
{
TextWriter file = new StreamWriter(@"C:\temp\journal.txt",true);
file.WriteLine("attention arret du processus anivirus effectué à:" + DateTime.Now.ToString() + "sur le pc:gerer le nom apres" + "\n");
file.Close();
}
}
}
Thread thr = new Thread(new ThreadStart(run));


}
}
i really appreciate your help thanks

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 5/28/2013 [Member] Starter | Points: 25

Up
0
Down
thanks for your help
when i try this code
my first error is that the method run don't have an argument(when i search in th web i find that it should take a service as an argument and i dont understand this.
the second error is that there is ambiguity between system.threading and system.timer

the main function will not be used in this service??
thanks

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 5/30/2013 [Member] Starter | Points: 25

Up
0
Down
thank you very much PMM you saved my life by sharing whith me some code
my probleme is resolved and it works very well
thanks
thanks
thanks

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 5/30/2013 [Member] Starter | Points: 25

Up
0
Down
i had also to respect the cast(run not Run)

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 5/30/2013 [Member] Starter | Points: 25

Up
0
Down
now i would like to check some register keys values to know if my usb isn t activated
( value at 4 of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\USBSTORE) if not i want to write it in a log
if you have any advice or code can you share it
thanks

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 6/4/2013 [Member] Starter | Points: 25

Up
0
Down
thank you for your answear

i m trying to access to registry but don t know what is the return type of the method getvalue
should i use:
Object obj = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\USBSTORE","start",null);
or
something like this
localKey = localKey.OpenSubKey(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\USBSTORE");
registryValue = localKey.GetValue("start").ToString();
if i want to check a number value should i use string type or object type ?????
i really appreciate your help thanks


Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 6/4/2013 [Member] Starter | Points: 25

Up
0
Down
when i try to acces to register it doesn t work
this is my code:
static void run()
{

try
{

int cle = (int)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\USBSTORE", "start", -1);
// if (cle == 3)
// {
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("lavaleur du registre de la cle usb est: " + cle + "\n");
file.Close();
// }
}
catch {
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("acces impossible " + "\n");
file.Close();
}
here i want to check if the usb is activated but i have the catch message
Regards
tobi

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 6/4/2013 [Member] Bronze | Points: 25

Up
0
Down
What is the error message you get?



Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 6/4/2013 [Member] Starter | Points: 25

Up
0
Down
i dont have an error message but the writer write the catch message
file.WriteLine("acces impossible " + "\n");
then i conclude that the probleme is related to the getvalue instruction(i think that on of the parameter is wrong) because the writer works
it can also be the permissions??


Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 6/4/2013 [Member] Starter | Points: 25

Up
0
Down
here is my complet code if it can give you a better view of what i 've done:
namespace testregistre
{
public partial class Service1 : ServiceBase
{
Timer mytimer;
RegistryKey localKey;


public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
if (File.Exists(@"C:\temp\journal.txt"))
{
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("attention demarrage2 effectué à:" + DateTime.Now.ToString() + "\n");
file.Close();
}
else
{
TextWriter file = File.CreateText(@"C:\temp\journal.txt");
file.WriteLine("attention premier demarrage du service apres deploiement effectué à:" + DateTime.Now.ToString() + "\n");
file.Close();
}

if (mytimer == null)
mytimer = new Timer(15 * 1000.0); //Elapse every 5 seconds and make this configurable. while (1==1) is not the good approach.
mytimer.Elapsed += new ElapsedEventHandler(mytimer_Elapsed);
mytimer.Start();

if (Environment.Is64BitOperatingSystem)
{
localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
}
else
{
localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);
}


}

void mytimer_Elapsed(object sender, ElapsedEventArgs e)
{
//Disable timer when we are executing Any particular task. For instance when u write into the text file.
mytimer.Enabled = false;

run();

//Enalbe timer after the test execution is done
mytimer.Enabled = true;
}

static void run()
{

try
{

int cle = (int)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service\USBSTORE", "start", -1);
// if (cle == 3)
// {
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("lavaleur du registre de la cle usb est: " + cle + "\n");
file.Close();
// }
}
catch {
TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("acces impossible au registre " + "\n");
file.Close();
}
}

protected override void OnStop()
{
if (mytimer != null)
{
mytimer.Stop();
mytimer.Dispose();
}

TextWriter file = new StreamWriter(@"C:\temp\journal.txt", true);
file.WriteLine("attention arretttttt effectué à:" + DateTime.Now.ToString() + "\n");
file.Close();
}
}
}

i m really sorry to take some of your time
thank you for your help

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 6/5/2013 [Member] Starter | Points: 25

Up
0
Down
hi Mydeen
the first and second topic are resolved thats why i ve created a new topic for the access to registry
"the topic title is cannot access to registry using getvalue"

if you want to answear and help me you can also do it there

thanks

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Tobi on: 6/6/2013 [Member] Starter | Points: 25

Up
0
Down
the path was not correct
probleme resolved
thanks

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 6/6/2013 [Member] Bronze | Points: 25

Up
0
Down
Awesome. Thanks.

Mydeen

Tobi, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response