Code to check if an external program has loaded correctly before executing the next function

  • Thread starter Thread starter cally_kalpana
  • Start date Start date
C

cally_kalpana

Guest
Hi,

I have got a wpf program that executes 2 external program - DIGOUT.exe and LOGGER.exe. Now, this DIGOUT.exe loads another 2 program automatically - imsiggen.exe and imml75x.exe. The wpf program does not have to load the imsiggen and imml75x programs, it only needs to load the DIGOUT.exe and LOGGER.exe. But during start, it should check if all the exes exists, if it does, then terminate them and then subsequently start the 2 program.

However, for the LOGGER.exe to work properly, the DIGOUT.exe has to load the config file correctly. Only then, the LOGGER.exe would work as expected. So, I have got 2 functions that start the programs. However, the both the DIGOUT and LOGGER seems to start at the same time, I have tried including the delay and sleep thread, but it does not work properly.

This is my code, is there something wrong with my delay function, I don't think its right. I guess what I really want is to ensure that the code only executes the following method after the RUNDIGOUT() function finishes loading the exe. Please help.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using System.Threading;
using System.Threading.Tasks;



namespace HelloWorld
{
// /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
//public partial class MainWindow : Window
//{
// //constructor - when we create the object, it will be called immediately
// public MainWindow()
// {
// InitializeComponent();
// //this.Title = "Main Window in Code Only";
// //this.Width = 700;
// //this.Height = 300;

// }
//}

//because we are actually creating the blueprint
public partial class MainWindow : Window
{
string todays_machinedate = "";
string folders_name = "";
//string path = folders_name + "\\";

//setting timer variable of type Timer
private static System.Timers.Timer _delayTimer;

public MainWindow()
{
folders_name = CreateDirectory();
todays_machinedate = CreateFile();


try
{
Log("BPS Front End Started");

Process[] prs = Process.GetProcesses();

for (int i = 0; i < prs.Length; i++)
{
if (prs.ProcessName == "DIGOUT")
{
Trace.WriteLine(prs.ProcessName);
prs.Kill();
prs.WaitForExit();
Log(prs + " detected and got terminated ");
}
else if (prs.ProcessName == "imml75x")
{
Trace.WriteLine(prs.ProcessName);
prs.Kill();
prs.WaitForExit();
Log(prs + " detected and got terminated ");
}
else if (prs.ProcessName == "imsiggen")
{
prs.Kill();
prs.WaitForExit();
Log(prs + " detected and got terminated ");
}
else if (prs.ProcessName == "LOGGER")
{
prs.Kill();
prs.WaitForExit();
Log(prs + " detected and got terminated ");
}

}




RunDigOut();
Log("Start Digital Out and Pause for 1 minute");
delay(30000);
InitializeComponent();

Log("Time now");
delay(30000);
RunLogger();
Log("Start Logger");










}
catch (Exception ex)
{
Log(ex.Message);
}


//StartTimer();







List<TodoItem> items = new List<TodoItem>();
items.Add(new TodoItem() { Title = "Danny", Completion = 10 });
items.Add(new TodoItem() { Title = "Chong", Completion = 80 });
items.Add(new TodoItem() { Title = "Ning", Completion = 3 });

lbTodoList.ItemsSource = items;

}

private static string CreateDirectory()
{
string root = @"C:\Windmill\Log";

// If directory does not exist, create it.
try
{
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
}
catch (DirectoryNotFoundException ex)
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry(ex.ToString());
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
}

return root;
}

private static string CreateFile()
{
string todaysdate = DateTime.Now.ToString("dd-MM-yyyy");

Debug.WriteLine(todaysdate);
return todaysdate;
}

public void Log(string logMessage)
{
using (StreamWriter writetolog = File.AppendText(folders_name + "\\" + "Log-" + todays_machinedate + ".txt"))
{
//callingthe function with 2 parameters
writetolog.WriteLine($"{ DateTime.Now} - {logMessage} ");
}
}

private void RunDigOut()
{
Process digout = new Process();
digout.StartInfo.FileName = "C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Windmill 7.0/Digout.lnk";
digout.Start();
}

private void RunLogger()
{
Process newp = new Process();
newp.StartInfo.FileName = "C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Windmill 7.0/Logger.lnk";
newp.Start();
}

//private void StartTimer()
//{

// // Create a timer with a two second interval.
// aTimer = new System.Timers.Timer(5000);
// // Hook up the Elapsed event for the timer.
// //aTimer.Elapsed += OnTimedEvent;
// Log("The Elapsed event was raised at - " + DateTime.Now);
// //aTimer.AutoReset = true;
// aTimer.Start();
// Log("The Elapsed event was raised at - " + DateTime.Now);

//}


private static void delay(int Time_delay)
{
int i = 0;
// ameTir = new System.Timers.Timer();
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = Time_delay;
_delayTimer.AutoReset = false; //so that it only calls the method once
_delayTimer.Elapsed += (s, args) => i = 1;
_delayTimer.Start();
while (i == 0) { };
}









private void OnTimedEvent(Object source, ElapsedEventArgs e)
{


String last = File.ReadLines(@"C:/Windmill/Data/bps01.WLD").Last();


Log("Reading for Sensor's Logger, the time now is" + last);
if (last.Contains("ON"))
{

Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{

//MessageBox.Show("Sensor Contains" + last);
SolidColorBrush mySolidColorBrush = new SolidColorBrush();

////// Describes the brush's color using RGB values.
////// Each value has a range of 0-255.
mySolidColorBrush.Color = Color.FromRgb(0, 128, 0);
this.Stop_btn.Fill = mySolidColorBrush;
}));


}
//aTimer.Stop();
//aTimer.Dispose();
}




private void button_stopClick(object sender, RoutedEventArgs e)
{

Window1 secondWindow = new Window1();
secondWindow.Show();
//secondWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
}

private void LabelTest(object sender, EventArgs e)
{
//Userlogged.Content = lbTodoList.SelectedItem.ToString();

}

private void Test(object sender, SelectionChangedEventArgs e)
{
string storeindex;

storeindex = lbTodoList.SelectedIndex.ToString();


//type casting
TodoItem selItem = (TodoItem)lbTodoList.SelectedItem;
Userlogged.Content = selItem.Title;
}


}

public class TodoItem
{
public string Title { get; set; }
public int Completion { get; set; }
}



}

Continue reading...
 
Back
Top