Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to create a windows C# service which runs on server connected with 10 to 15 target devices via LAN. So here is the what I am doing in service i am reading the data from csv file which is in following format:

TargetComputername1,Date1,Time1,Password1
TargetComputername2,Date2,Time2,Password2
TargetComputername3,Date3,Time3,Password3
.
.
TargetComputernameN,DateN,TimeN,PasswordN



I have to run a vbs inside service but on the specified date & time in csv with Targetname and password as parameter.

So for N device i think i have to create N different instance of timer and pass the parameters how should i do that?

Pleas help thanks in advance...

What I have tried:

C#
using (var parser = new TextFieldParser(AppPath + "\\iPXEScheduler.csv"))
{
	parser.TextFieldType = FieldType.Delimited;
	parser.SetDelimiters(",");

	string[] line;
	int count = 1;
	while (!parser.EndOfData)
	{
		count++;
		line = parser.ReadFields();
		if (bStringContains(line[0], sDeviceNameGet("StoreID"), StringComparison.OrdinalIgnoreCase))
		{
			if (validate(line, count))
			{
				SetupTimer();
			}
		}
	}
}

//validate function
private bool validate(string[] line, int count)
{
	/*for reference
	line[0]=device name
	line[1]=Date
	line[2]=time
	line[3]=countdown
	line[4]=Password
	*/

	//Local variables
	bool bISValidate = true;
	Double dLOCCountDown = 1.0;
	string sLOCTime;
	DateTime dtScheduledDateTime = DateTime.Now.AddYears(1000); //Any imaginary date just to sufice try catch;
	string[] DateTimeformat = { "MM/dd/yyyy HH:mm", "M/d/yyyy H:mm", "MM/d/yyyy H:mm", "M/dd/yyyy H:mm", "M/d/yyyy HH:mm", "MM/d/yyyy HH:mm", "M/dd/yyyy HH:mm" };

	if (line.Length != 5)
	{
		WriteLog("There are more or less then 5 parameter specified in csv at line : " + count);
		bISValidate = false;
		goto Error;
	}
	if (line[0]=="" && line[1]=="" && line[2]=="" && line[3]==""&&line[4]=="")
	{
		WriteLog("One of the parameter found blank at : " + count);
		bISValidate = false;
		goto Error;
	}
	if (line[0].Length != 12)
	{
		WriteLog("Please check the device name at line : " + count);
		bISValidate = false;
		goto Error;
	}

	//In case POS close is specified instead of Time.
	if (bStringContains(line[2], "CLOSE", StringComparison.OrdinalIgnoreCase))
	{
		sLOCTime = "00:00";
	}
	else
	{
		sLOCTime = line[2];
	}

	//Validating date and time
	try
	{
		dtScheduledDateTime = DateTime.ParseExact(line[1] + " " + line[2], DateTimeformat, null, System.Globalization.DateTimeStyles.None);
	}
	catch(Exception ex)
	{
		WriteLog("Error parsing date and time : " + ex.Message);
		WriteLog("Correct date format is : MM/dd/yyyy and time is : HH:mm (24 hours)");
		bISValidate = false;
		goto Error;
	}

	//Parse the count down value
	try
	{
		dLOCCountDown = Double.Parse(line[3]);
		if (dLOCCountDown < 1.0 && dLOCCountDown > 99.0)
		{
			WriteLog("Countdown can not be less then 1 and greater then 99 " + dLOCCountDown);
			bISValidate = false;
			goto Error;
		}

	}
	catch(Exception ex)
	{
		WriteLog("Error parsing CoutDown : " + ex.Message);
	}

	//Validate password only for digits
	if (!IsDigitsOnly(line[4]))
	{
		WriteLog("Password seems to contain character other then digit which is not allowed at line : " + count);
		bISValidate = false;
		goto Error;
	}

	Error:
	if (bISValidate == false)
	{
		return false;
	}
	else
	{
		DateTime dtGLOScheduleDateTime = dtScheduledDateTime;
		Double dGLOCountDown = dLOCCountDown;
		string sGLOPassword = DecryptPassword(line[4]); //line[4] contains password;
		string sGLODevice = line[0]; //contains Device name;
		return true;
	}
}


//timer function:

private void SetupTimer()
{
	Timer Countdown = new Timer();
	Countdown.AutoReset = false;
	WriteLog(dtGLOScheduleDateTime.ToString());
	Countdown.Interval = (dtGLOScheduleDateTime.Subtract(DateTime.Now).TotalSeconds * 1000) - (dGLOCountDown * 24 * 60 * 60 * 1000);
	Countdown.Elapsed += (sender, e) => Countdown_Elapsed(sender, e, sGLOPassword);
	Countdown.Start();

}

private void Countdown_Elapsed(object sender, ElapsedEventArgs e, string sGLOPassword)
{
	WriteLog(DateTime.Now.ToString() + " : " + sGLOPassword);

}


But how do i pass the parameter as well
Posted
Updated 20-Apr-16 5:12am
v3
Comments
Sergey Alexandrovich Kryukov 18-Apr-16 17:10pm    
And? What's the problem? Pass parameter where, and why it's the problem?
Your sample is full of irrelevant code, different parsing, etc. Pretty dirty.
But why do you have to develop a service? Why not using existing Windows scheduler service?
—SA
Rahulronny 18-Apr-16 17:52pm    
Problem is how to setup multiple timer for each target computer to schedule and pass parameter in that....inbuilt scheduler not because want process the output of execution...
Sergey Alexandrovich Kryukov 18-Apr-16 19:09pm    
You don't need multiple timers; you also don't need a timer with periodic ticks; one timer will be enough.
But you did not answer why don't you use available Windows scheduler...
—SA
Rahulronny 19-Apr-16 5:41am    
Thanks, how can i use single timer to schedule all devices..I don't use windows scheduler because what ever i want to execut i want its output in eventlog and also some time it not only based on Date & time it can be date and Event based also..thats why i am not using the windows scheduler...if you know the solution can you give some kind of pseudo code...thanks very much for the response..

Advice: Change your code in order to use only 1 timer.
 
Share this answer
 
You're not going to use a timer for each item in the text file. You use a single timer, that "ticks" once a minute. You then check the current time against the time listed for each item. If the current hour and minute is the same, kick off whatever code is doing the work for a single machine and pass the parameters for that machine to it.
 
Share this answer
 
Comments
Rahulronny 19-Apr-16 5:43am    
Yeah i thought this one but is there not a probablity that date and time never becomes equal..due to even slight difference..
Dave Kreskowiak 19-Apr-16 8:26am    
True if you do the naive comparison of two DateTime objects which will compare right down to the millisecond. You don't do that. You compare the Date, Hour and Minute properties separately.
I'm not sure you need such service at all, but we'll discuss it later.

First of all, let me explain why don't need multiple timers. Moreover, you also don't a need periodically firing timer. First of all, let's assume your schedules are not too tight, so you have enough time to reset a timer on each event.

Here is what you do. Let's say, you have 10-15 devices with different intercepting schedules, each schedule can be complicated. You have to create a queue of all united schedules of all devices. It should be ordered by time of required event. The queue element should reference appropriate time and device. No wonder, all the devices will appear in this united schedule, mixed in some, possibly irregular order. Not to worry.

You event handler should be the handler of one single event. At initialization, you initialize your timer and setup its tick time, taking current real time and first entry of the queue. The handler takes the top queue entry, performs its work according the the information in the queue element, and then reset timer to a next element. Already used element is removed from the queue.

Now, the second part of the answer, another alternative… Why creating this service at all? Why not using already available service? You can use the Windows service called Windows Task Scheduler, please see:
http://en.wikipedia.org/wiki/Task_Scheduler[^],
http://msdn.microsoft.com/en-us/library/aa383614.aspx[^],
http://msdn.microsoft.com/en-us/library/aa384006%28v=VS.85%29.aspx[^].

See the last link above for use of the Windows Task Scheduler. You can use its API in your program using Task Scheduler Managed Wrapper, see http://taskscheduler.codeplex.com/[^].

But if can be even simpler.
You can use Windows Task Scheduler using Windows utilities AT.EXE or SchTasks.EXE, see:
http://en.wikipedia.org/wiki/At_(Windows)[^],
http://technet.microsoft.com/en-us/library/bb490866.aspx[^],
http://en.wikipedia.org/wiki/Schtasks[^],
http://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx[^].

—SA
 
Share this answer
 
Comments
Rahulronny 20-Apr-16 16:39pm    
Thanks very much appreciate your suggestion...i have 10-15 device and all can be scheduled at single time also so queue is not a solution i guess...i am able o do it via single and multiple timer both but i am prefering the single timer which fires every 60 seconds and compare time just hours and minutes and go ahead...this is working nicely untill i got the situation where all 15 device have same time...so i am trying to be cunning here i'll add some extra minutes then the actaul time to make it different if all the time are same and will go ahead that will work...thanks..anyway if you have any idea about adding extra time if i found same time in a collection of list then pls let me know..
Sergey Alexandrovich Kryukov 20-Apr-16 17:58pm    
Again, you don't need to fire every minute; this would be wasteful. You need fired-once timer, reset on each schedule item. Extra time? The point is: you know each schedule in advance, so you can modify it to your criteria, and, in the handler, you only need to determine next invocation time using the read time read from System.DateTime.Now.

Is it clear? Will you accept the solution formally?

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900