Program not exiting properly - c#

I am working on a program that is supposed to run for 3 days checking for pending messages and I want it to skip some of the processing that it does if there are pending messages in the database but I want it to continue to the next day and if there are pending messages on the last day I want the program to exit. The problem is that when I run it in debug mode in VS it starts over from the beginning including the Build process. This is the code that I am using to check for the last day of the run:
intDateCompare = DateTime.Compare(dtDate2, dtDate3);
if (intDateCompare == 0) {
Console.WriteLine("Finished, press <Enter> to quit");
strFinished = Console.ReadLine();
Environment.Exit(1);
}
It does the compare properly and runs the Exit command like expected when I put a breakpoint there but then it starts the Build process again. What am I doing wrong?
Thanks for any suggestions.

Related

continuing program after entering integer user input c#

when i run my code, my console suddenly shuts off after a number is entered into the console.
int age;
Console.WriteLine("How old are you?");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are {0} years old", age);
can someone help me with this problem? I never get to see the end result because it just shuts off. there are no errors that pop up but it is getting quite frustrating.
Add Console.ReadLine() or Console.ReadKey() as your last line.
When the execution of the program is done, the console windows closes. You have to make a way for a program to keep running so the console window stays open. Usually, this is achieved by adding
Console.ReadKey();
or
Console.ReadLine();
in the end of your code. This way the console is waiting for your input and it stays open. As soon as you hit any key in keyboard (in case of Console.ReadKey()) or Enter key (in case of Console.ReadLine()), execution is done and the console window exits.

execute query using time hour in console application c#

i want to truncate table using console application with parameter hour.
for example, i want to run query truncate at 12.00 AM using time in system.
this is my code in console application using c#.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string getHour = DateTime.Now.ToString("h:mm:ss tt");
if (getHour == "12:00:00 AM")
{
Console.WriteLine("Do action to run query truncate");
//in this line i will execute query truncate.
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
And this is not working. please give me solution or sample code to fix my problem.
thanks...
I would suggest few things on your code:
Don't use string comparison, but uses DateTime directly (take a look on TimeOfDay.TotalSeconds). This way, it makes the comparison a lot easier
Use repeated calls instead of just one call (unless you can really be sure that you run your program exactly at 12). This way you make your program work for you more.
To make it more robust, provide some ways to give tolerance to your system. This is how good automation should be.
Example:
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
while (true) { //read 2. assuming this is to be run forever in this example, but gives also some way to break the loop whenever necessary in your app
if (DateTime.Now.TimeOfDay.TotalSeconds <= 1) { //read 1. and 3. this way, you give tolerance of 1 second. Your action will be run on 12:00:00 - 12:00:01
Console.WriteLine("Do action to run query truncate");
// //in this line i will execute query truncate.
break; //break after saving once, for instance, and run again when the time close... This is to prevent possible multiple executions...
}
System.Threading.Thread.Sleep(500); //read 2. and 3. check every 500 millisecond, at least to give chance to check the time twice per second
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
When you run your program, it looks on the clock quickly, and if it is not exactly midnight immediately exits. (To be more precise it prints some message and waits until keypress). I believe you wish to wait until midnight. If the exact timing is not that important (I mean some seconds early or late is acceptable), the simplest solution is:
static void Main(string[] args)
{
Thread.Sleep(DateTime.Today.AddDays(1) - DateTime.Now);
Console.WriteLine("It's about midnight, I go to sleep");
}
I feel like the issue is with the flow of execution of your code.
You're calling the code once and then it stops. It checks once NOW and get the current time. If the time is 12:00:00 AM, you can pass into the if statement, but you'll need to literally run this at 12:00:00 System time on the dot, which is nearly impossible.
You should consider a Windows Service or using Windows Task Manager: C# Console Application - Keep it running.
As mentioned in the other answers you shouldn't be using your app to schedule the task. It looks like you are doing a database maintenance task so the first thing I would look at is...
1) See if your database can schedule tasks. SQL Server Agent for example can schedule stored procedures (or adhoc SQL) to be run at set times and would accomplish your task if you are using that for your database. More info here.
If your database can't do this or you want to do other things other than truncate the table then...
2) try using Windows Task Scheduler
This can launch an application at set times, is easy to setup and then your application can just do the job it's mean to do (e.g. truncate the table) and not worry about the scheduling.

Autosys Job Failing

I have a .net app that does a variety of file operations. It has been scheduled via task manager and runs without issue. We are moving the job to be controlled by autosys and have the job configured. When it kicks off I see all the files move as expected and I get a log file indicating that everything ran as expected. The app is working. Autosysy, however, reports that it failed.
Status/[Event] Time Ntry ES ProcessTime Machine
-------------- --------------------- -- -- --------------------- ----------------------------------------
RUNNING 09/26/2013 15:30:21 1 PD 09/26/2013 15:31:12
FAILURE 09/26/2013 15:31:59 1 PD 09/26/2013 15:32:17
[*** ALARM ***]
JOBFAILURE 09/26/2013 15:32:16 1 PD 09/26/2013 15:32:17
[STARTJOB] 09/26/2013 16:00:00 0 UP
The application is a winform app - here's the meat of the code:
static int Main(string[] args)
{
Console.WriteLine("Starting processing...");
Console.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture));
if (args.Length > 0) //if we call the app with args we do some stuff, otherwise we show the UI to let the user choose what to do
{
//stuff happens here that works, other method calls, etc.
Console.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture));
Console.WriteLine("Process complete.");
return 0;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FileLoader());
return 0;
}
The job IS working, it's doing everything that it is supposed to do without logging any exceptions BUT autosys still reports failure. What am I doing wrong?
Autosys will mark the job as successfully completed when the process ends. In your case you've told that it is an Win-Form application. So what may happen here is the autosys is starting the Application and also the application is working fine and it is doing what it suppose to do. But the process will not end unless untill someone manually close the window application or if you have some techinque to close itself. And so Autosys is assuming that the process not ended thus marking the job as failed.
The solution for this is make your application as console application or else I remember there is one property when setting up the Autosys job not to consider the Process ending so the job will just start the program and mark the job as completed.

Using timer to run application inside NUNIT

In Nunit as part of test I have to start an application let it run for i.e 1 min than stop it and next it reads results from file and asserts if values are correct. I can start and stop the application using Process.Start("app.exe"); however I am not sure how to keep it running for x seconds inside the [Test]. Any idea how to go about it? Thanks
[Test]
void TestFiles()
{
using(var process = Process.Start("app.exe"))
{
Thread.Sleep(1000);
process.Kill();
process.WaitForExit();
}
// Check your files now
}

Monitoring a remote process

I have a method that stops a service(s) but I also need to delete the logs. Usually this is not a problem but the process can take a little bit of time before closing. Again, although the service appears stopped, the process does take additional time to close properly. Since the process is still running, I cannot delete the logs so I need to find a way to monitor the .exe to know when its safe to delete the logs.
so far my best option is a do while loop, unfortunately the first iteration of the delete statement throws an exception and stops the program.
do
{
// delete logs
}
while (System.Diagnostics.Process.GetProcessesByName(processName, machineName).Length > 0);
Im sure there is a simple solution but my lack of experience is the real problem.
This is probably not the best answer either, but you could invert the loop to:
while (System.Diagnostics.Process.GetProcessesByName(processName, machineName).Length > 0)
{
// delete log files.
}
I would suppose this would evalutate the condition of the loop before executing the contents. But according to your statements, this will not execute the code until the process has exited.
A hackish way around this is to perform a loop, and break out manually once the conditions:
bool CloseProcessOperation = true; // Control variable incase you want to abort the loop
while (CloseProcessOperation)
{
if (System.Diagnostics.Process.GetProcessesByName(processName, machineName).Length > 0) { break; }
// break if no logs exist
// break for some other condition
// etc
// delete logs
}

Categories

Resources