Showing posts with label Window Scheduled Task. Show all posts
Showing posts with label Window Scheduled Task. Show all posts

Wednesday, 12 October 2011

How to register Window Eventlog sources.

The issue:
I use the following code to register a windows eventlog source in code. It worked in the dev environment but not in UAT or PROD

// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created.  Exit the application to allow it to be registered.
return;
}

// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";

// Write an informational entry to the event log.    
myLog.WriteEntry("Writing to event log.");

The Cause:
Permission! The app is run as a scheduled task. It turns out the account the app is running under is no enough for creating a eventlog source. And windows keeps silent about it.

The Solution:
You can add a eventlog source directly into the registry. Best of all when you deploy, you can just export and import the registry.
HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Services
Eventlog

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363648(v=vs.85).aspx

Tuesday, 11 October 2011

windows service vs windows scheduled tasks

In general, I prefer windows scheduled tasks as long as the running frequency is less frequent than once every 30 seconds. I.e. more than 30 seconds between two consequent tasks.

windows scheduled tasks
* Easy to debug
* Easy to setup
* Can be run in silent mode, i.e. no console window flashes every time when the program is run.

windows service
* Run in background by default
* Can start and stop the service in the windows services.exe
* Can be run very frequently

Hide Console Window in C# Console Application; Run console application in a silent mode, KeepAlive Application or Service

The problem:
I created an window console application and run it as a windows scheduled task. But the console window flashes and goes back every time the app is run.

The solution
Option 1: (Best Option)
Change the output type from Console Application to Windows Application. This can be done under Project -> Properties -> Application in Visual Studio:

Option 2: Make a window service app using windows servicebase class