Issues handling multiple calls at the same time - c#

private void Recorder_ExecuteCode(object sender, EventArgs e)
{
fileName = "";
SendMail = false;
CallIsAlive = true;
Recorder recorder = new Recorder();
// Use the call ID as the filename and create a media sink.
Random rnd = new Random();
fileName = string.Format("C:\\recordings\\Inbound Call\\EmergencyCall {0}.wma", DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year.ToString() + " - " + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + rnd.Next().ToString());
WmaFileSink fileSink = new WmaFileSink(fileName);
Console.WriteLine("Recording for 10 seconds.");
// Set the recorder to use the media sink and attach
// it to the flow.
recorder.SetSink(fileSink);
recorder.AttachFlow(Program.MyCall.Flow);
// Start recording.
recorder.Start();
SendMail = true;
}
The above piece of code sets up a recorder that attaches to the audiovideoflow of the inbound call.
The issue im having is that if 2 calls come in at the same time and try and call the Recorder_executeCode function, the program crashes here:
recorder.AttachFlow(Program.MyCall.Flow);
Visual Studio reports the following error:
InvalidOperationException was unhandled by user code.
AudioVideoFlow is already bound to a Recorder.
How would I go about changing the code to allow more than one copy of the function to run at the same time if two or more callers call in at the same time.
Edit
The issue was being caused by using the global variable: MyCall
I fixed the issue by setting the filename string using the Call.CallId
private void Recorder_ExecuteCode(object sender, EventArgs e)
{
string fileName;
SendMail = false;
Recorder recorder = new Recorder();
// Use the call ID as the filename and create a media sink.
//Random rnd = new Random();
fileName = string.Format("C:\\recordings\\Inbound Call\\EmergencyCall {0}.wma", acceptCallActivityInboundCall1.CallProvider.ToneController.AudioVideoFlow.Call.CallId.ToString());
WmaFileSink fileSink = new WmaFileSink(fileName);
Console.WriteLine("Recording for 10 seconds.");
// Set the recorder to use the media sink and attach
// it to the flow.
recorder.SetSink(fileSink);
recorder.AttachFlow(acceptCallActivityInboundCall1.CallProvider.ToneController.AudioVideoFlow);
// Start recording.
recorder.Start();
SendMail = true;
}

Related

C# Update Table Button Not Working Automatically

I have some c# code and recently I added a button to the form designer which runs a simple update table query (update a SQL table). The table is updated as I would expect when I manually click the button in Debug mode, however when I run the entire program, it appears the method/button to update the SQL table is either ignored or simply not being picked up. As I mentioned, this works fine when I go into Debug and click on the button manually, however what I need it to do is run the method and click the button automatically as it is doing for the other methods. I have gone through this hundreds of times and am at the end of the road. Below is my code;
private void updateClosedModuleState()
{
System.Data.SqlClient.SqlConnection saConn = new System.Data.SqlClient.SqlConnection();
saConn.ConnectionString = GlobalDef.strSQLConnection;
//MessageBox.Show(saConn.ConnectionString);
try
{
saConn.Open();
SqlCommand command = saConn.CreateCommand();
command.CommandTimeout = saConn.ConnectionTimeout;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = " UPDATE SATA_AllocationObject "
+ " SET State = REPLACE(State, 'A', 'I') "
+ " where AllocationObjectType = 4 "
+ " and Hostkey in (select hostkey from TRAN_UnitEClosedModules)";
command.ExecuteNonQuery();
}
catch (Exception act)
{
MessageBox.Show("Ooops! Error " + act.Message.ToString() + " when updating Module State");
}
finally
{
saConn.Close();
}
pictureBox19.Visible = true;
}
This is the code for the button click;
private void cmdUpdateClosedModuleState_Click(object sender, EventArgs e)
{
updateClosedModuleState();
}
Lastly, these are the method details in the form designer;
this.cmdUpdateClosedModuleState.Location = new System.Drawing.Point(517, 114);
this.cmdUpdateClosedModuleState.Name = "cmdUpdateClosedModuleState";
this.cmdUpdateClosedModuleState.Size = new System.Drawing.Size(107, 23);
this.cmdUpdateClosedModuleState.TabIndex = 41;
this.cmdUpdateClosedModuleState.Text = "UpdateModState";
this.cmdUpdateClosedModuleState.UseVisualStyleBackColor = true;
this.cmdUpdateClosedModuleState.Click += new System.EventHandler(this.cmdUpdateClosedModuleState_Click);
I have also tried to use a TableAdapter and use a Fill to update the SQL Table via the button, and that works...only when I click the button in Debug mode;
private void newupdate()
{
//throw new NotImplementedException();
this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
}
I assigned a buttton to run the Fill on the TableAdapter;
private void newupdate_Click(object sender, EventArgs e)
{
//this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
newupdate();
}
So in a nutshell, I need the program to run this method like it does with all the other ones without my intervention.
I have attached a photo of the form - when I click 'Run All' everything runs except for the UpdateClosedModState; [1]: https://i.stack.imgur.com/dJryA.png
The code behind the Run All command is;
private void cmdRunAll_Click(object sender, EventArgs e)
{
begin();
}
In the form designer we have;
this.cmdRunAll.Location = new System.Drawing.Point(381, 375);
this.cmdRunAll.Name = "cmdRunAll";
this.cmdRunAll.Size = new System.Drawing.Size(107, 21);
this.cmdRunAll.TabIndex = 10;
this.cmdRunAll.Text = "Run All";
this.cmdRunAll.UseVisualStyleBackColor = true;
this.cmdRunAll.Click += new System.EventHandler(this.cmdRunAll_Click);
And at the start of the form, we have this to begin running the app;
if (args.Length > 0)
{
lArgsExists = true;
// strDetails = strDetails + ": About to run app.";
// runApp(args[0], lArgsExists);
begin();
}
}
public void runApp(string cnfgPath, bool gui)
{
if (gui == true)
{
strDetails = strDetails + " Running app.";
begin();
}
else
{
textBox2.Text = GlobalDef.appStatus.ToString();
begin();
//MessageBox.Show("Opening form!");
}
}
public void begin()
{
String sqlServerLogin = GlobalDef.sqlServerlogin;
String password = GlobalDef.password;
String instanceName = GlobalDef.instanceName;
String remoteSvrName = GlobalDef.remoteSvrName;
string strNow = DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year;
string strSQLConnection = GlobalDef.strSQLConnection;
textBox2.Text = GlobalDef.appStatus.ToString();
//string path = #"E:\Allocator\StudentAllocatorTest\logs\Error.log";
string path = GlobalDef.path;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error details");
}
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine();
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(strDetails.ToString());
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(DateTime.Now.ToString() + ": Starting load for " + GlobalDef.instanceName);
}
try
{
string connString = GlobalDef.connString;
OracleConnection oraCon = new OracleConnection(connString);
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"data source=" + remoteSvrName + ";" +
"persist security info=true;initial catalog=" + instanceName + ";User Id=" + sqlServerLogin + "; Password=" + password + ";";
// Clear transfer tables before running any subroutine
clearTransTables();
// Loads Department details into SA TransTables
updateDepartment(oraCon, strSQLConnection);
// Loads new POSA modules into SA TransTables
updatePOSA(oraCon, strSQLConnection, path);
// Loads new POSY modules into SA TransTables
updatePOSY(oraCon, strSQLConnection, path);
// Remove open option links for modules which do not have the timetable flag checked
RemoveUnneededOOCourses(oraCon, strSQLConnection, path);
// Loads top-level OO structure into SA TransTables
OpenOption(oraCon, strSQLConnection, path);
// Loads Dept level OO structure into SA TransTables
OptionByDept(oraCon, strSQLConnection, path);
// Links OOByDept Allocation Objects to OO Objects via TransTables
linkOOAndOOByDept(path);
// Loads new Course modules into SA TransTables
updateCourse(oraCon, strSQLConnection, path);
// Links OO courses to OOByDept AllocationObjects via TransTables
OpenOptionCourses(oraCon, strSQLConnection, path);
//Adds All Courses to various hidden groups via TransTables
updateAllHidden(oraCon, strSQLConnection, path);
// Loads new students into SA TransTables
//TransferStudent(oraCon, strSQLConnection);
// Loads prerequisite allocations into SA TransTables
UploadPrerequisites(oraCon, strSQLConnection);
//button1_Click();
// Loads Closed Modules from UnitE to TRAN_UnitEClosedModules
uploadUnitEClosedModules(oraCon, strSQLConnection);
//Runs the transfer service which loads the data in the TransTables into the database
runTransferservice(path);
///
newupdate();
// update Closed Modules to 'I' State
updateClosedModuleState();
// Used to create a structure for programmes which had yet to be set up by faculties
// DefaultCourseStructure(oraCon, strSQLConnection);
// Creates UNITe course enrolments and cancels changed course selections
uploadAllocationsToUNITe(oraCon, strSQLConnection, path);
// pictureBox11.Visible = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString() + ": Completed load for " + GlobalDef.instanceName);
}
Application.Exit();
}
}
private void updateDepartment(OracleConnection oraCon, string strSQLConnection)
{
try
{
....and it goes on with the subroutines listed above.
Any help would be greatly appreciated.
Thank you in advance.

Calling Python script from Winform C# Application

I want to call a Python script from my winform C# application. I checked for some solutions and followed following approaches. One using Inter-Process communication and one using IronPython
Approach 1 : Using Inter-Process Communication
private void BtnSumPy_Click(object sender, EventArgs e)
{
string python = #"C:\Programs\Python\Python37-32\python.exe";
// python app to call
string myPythonApp = #"C:\mypath\\SamplePy\SamplePy2\SamplePy2.py";
// dummy parameters to send Python script
int x = 3;
int y = 4;
// Create new process start info
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
// make sure we can read the output from stdout
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
// start python app with 3 arguments
// 1st arguments is pointer to itself,
// 2nd and 3rd are actual arguments we want to send
myProcessStartInfo.Arguments = myPythonApp + " " + x + " " + y;
Process myProcess = new Process();
// assign start information to the process
myProcess.StartInfo = myProcessStartInfo;
// start the process
myProcess.Start();
// Read the standard output of the app we called.
// in order to avoid deadlock we will read output first
// and then wait for process terminate:
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
/*if you need to read multiple lines, you might use:
string myString = myStreamReader.ReadToEnd() */
// wait exit signal from the app we called and then close it.
myProcess.WaitForExit();
myProcess.Close();
lblAns.Text = myString;
}
The issue with above approach is that Python.exe will have to installed on the local machines as well, as winform app is going to run locally on the system.
Approach 2: Using IronPython
private void BtnJsonPy_Click(object sender, EventArgs e)
{
// 1. Create Engine
var engine = Python.CreateEngine();
//2. Provide script and arguments
var script = #"C:\Users\simeh\source\HDFC\repos\SamplePy\SamplePy2\SamplePy2.py"; // provide full path
var source = engine.CreateScriptSourceFromFile(script);
// dummy parameters to send Python script
int x = 3;
int y = 4;
var argv = new List<string>();
argv.Add("");
argv.Add(x.ToString());
argv.Add(y.ToString());
engine.GetSysModule().SetVariable("argv", argv);
//3. redirect output
var eIO = engine.Runtime.IO;
var errors = new MemoryStream();
eIO.SetErrorOutput(errors, Encoding.Default);
var results = new MemoryStream();
eIO.SetOutput(results, Encoding.Default);
//4. Execute script
var scope = engine.CreateScope();
var lib = new[]
{
"C:\\path\\SamplePy\\packages\\IronPython.2.7.9\\lib",
"C:\\path\\SamplePy\\packages\\IronPython.2.7.9",
};
engine.SetSearchPaths(lib);
engine.ExecuteFile(script, scope);
//source.Execute(scope);
//5. Display output
string str(byte[] x1) => Encoding.Default.GetString(x1);
Console.WriteLine("Errrors");
Console.WriteLine(str(errors.ToArray()));
Console.WriteLine();
Console.WriteLine("Results");
Console.WriteLine(str(results.ToArray()));
}
The issue I get here is that I keep getting errors like 'Json module error' or 'PIL module error'
I read somewhere that PIL won't currently work with IronPython because it uses a native C library.
The python script has ML logic and uses OCR etc., for image processing and hence requires PIL, which cannot be done in IronPython.
So any better approach or ways or suggestions on how to call Python script from Winform C# application.
Thanks In Advance!!!..
The solution is here for 'import error' open the cmd and go to the AppData>Local>Programs>Python>Python37-32 then write this
pip3 install json
if u wanna run .py file from c# the import modules must be in the directory of python.exe
for example ı imported the cv2 and the others libs to Python37-32 dir. After this my program worked fine.
This is my code:
timer1.Enabled = true;
progressBar1.Value += 10;
string myPythonApp = "C://Users//giris//Desktop//staj_proje_son//main.py";
string cmdArguments = "/c \"python " + myPythonApp + " " + "--ogrencioptik " + textBox2.Text + " " + "--cevapkagidi " + textBox1.Text + " " + "--sonuckayit " + textBox3.Text + "\"";
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.UseShellExecute = false;
start.WorkingDirectory = "C://Users//giris//Desktop//staj_proje_son//";
start.Arguments = cmdArguments;
start.RedirectStandardOutput = false;
start.RedirectStandardError = true;
start.CreateNoWindow = true;
Process process = Process.Start(start);
timer1.Start();
process.WaitForExit();
timer1.Stop();
timer1.Enabled = false;
progressBar1.Value = 100;
MessageBox.Show("İşlem Bitti");
button3.Enabled = true;
Note:
All the textbox.text is the path for a folder.

C# Error 1053 the service did not respond to the start or control request in a timely fashion

I realize there are a ton of these posts, but none them, believe it or not, resolve my problem.
I have the following code here that uses the ManagementEventWatcher class to kill a process from another in house app if it runs too long, which it occasionally does and kills the cpu.
Anyway, it gets this error instantaneously when starting the service. Nothing in the event log. Currently I have it testing with notepad.exe.
public AppXKiller()
{
InitializeComponent();
this.ServiceName = "AppXKiller";
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
static void Main()
{
ServiceBase.Run(new AppXKiller());
}
protected override void OnStart(string[] args)
{
registerWatcher();
}
protected override void OnContinue()
{
base.OnContinue();
}
public void registerWatcher()
{
string pol = "2";
string appName = "notepad.exe";
string queryString =
"SELECT *" +
" FROM __InstanceOperationEvent " +
"WITHIN " + pol +
" WHERE TargetInstance ISA 'Win32_Process' " +
" AND TargetInstance.Name = '" + appName + "'";
// You could replace the dot by a machine name to watch to that machine
string scope = #"\\.\root\CIMV2";
// create the watcher and start to listen
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
watcher.EventArrived += new EventArrivedEventHandler(this.OnEventArrived);
watcher.Start();
}
private void OnEventArrived(object sender, EventArrivedEventArgs e)
{
Thread.Sleep(20000);
Process[] localByName = Process.GetProcessesByName("notepad");
if (localByName.Length > 0)
{
localByName[0].Kill();
}
}
protected override void OnStop()
{
}
}
Turns out that the application has to be the release version of the build, not the debug version. This makes no sense but oh well. I guess if I want to test and debug the app I have to do it in release mode.
Choose Release from the drop down menu up top (somewhere under tools depending on the size of your screen). It probably says debug.
Build the app.
Install the service from the release folder.

How do I save continuous console output to a text file in c#?

I'm quite a noob at programming and I've been stuck at this for a while now. I'm using the following code to get continuous data output streamed to a command prompt. How can I ensure that the output gets copied to a text file after closing the prompt manually?
public static void Main(string[] args)
{
Connector connector;
Console.WriteLine("HelloEEG!");
// Initialize a new Connector and add event handlers
connector = new Connector();
connector.DeviceConnected += new EventHandler(OnDeviceConnected);
connector.DeviceConnectFail += new EventHandler(OnDeviceFail);
connector.DeviceValidating += new EventHandler(OnDeviceValidating);
// Scan for devices across COM ports
// The COM port named will be the first COM port that is checked.
connector.ConnectScan("COM40");
// Blink detection needs to be manually turned on
connector.setBlinkDetectionEnabled(true);
Thread.Sleep(400000);
System.Console.WriteLine("Goodbye.");
connector.Close();
Environment.Exit(0);
}
// Called when a device is connected
static void OnDeviceConnected(object sender, EventArgs e)
{
Connector.DeviceEventArgs de = (Connector.DeviceEventArgs)e;
Console.WriteLine("Device found on: " + de.Device.PortName);
de.Device.DataReceived += new EventHandler(OnDataReceived);
}
// Called when scanning fails
static void OnDeviceFail(object sender, EventArgs e)
{
Console.WriteLine("No devices found! :(");
}
// Called when each port is being validated
static void OnDeviceValidating(object sender, EventArgs e)
{
Console.WriteLine("Validating: ");
}
// Called when data is received from a device
static void OnDataReceived(object sender, EventArgs e)
{
Device.DataEventArgs de = (Device.DataEventArgs)e;
DataRow[] tempDataRowArray = de.DataRowArray;
TGParser tgParser = new TGParser();
tgParser.Read(de.DataRowArray);
/* Loops through the newly parsed data of the connected headset*/
// The comments below indicate and can be used to print out the different data outputs.
for (int i = 0; i < tgParser.ParsedData.Length; i++)
{
//string temp = tgParser.ParsedData[1].ToString;
//Console.WriteLine(tgParser.ParsedData.Length + " + " + temp);
if (tgParser.ParsedData[i].ContainsKey("Raw"))
{
//Console.WriteLine("Raw Value:" + tgParser.ParsedData[i]["Raw"]);
//Console.WriteLine("Raw Value:" + tgParser.ParsedData[i]["Raw"]);
}
if (tgParser.ParsedData[i].ContainsKey("PoorSignal"))
{
//The following line prints the Time associated with the parsed data
//Console.WriteLine("Time:" + tgParser.ParsedData[i]["Time"]);
Console.WriteLine("Time:" + tgParser.ParsedData[i]["Time"]);
//A Poor Signal value of 0 indicates that your headset is fitting properly
Console.WriteLine("Poor Signal:" + tgParser.ParsedData[i]["PoorSignal"]);
poorSig = (byte)tgParser.ParsedData[i]["PoorSignal"];
}
if (tgParser.ParsedData[i].ContainsKey("Attention"))
{
//Console.WriteLine("Att Value:" + tgParser.ParsedData[i]["Attention"]);
Console.WriteLine("Att Value:" + tgParser.ParsedData[i]["Attention"]);
}
if (tgParser.ParsedData[i].ContainsKey("Meditation"))
{
//Console.WriteLine("Med Value:" + tgParser.ParsedData[i]["Meditation"]);
Console.WriteLine("Med Value:" + tgParser.ParsedData[i]["Meditation"]);
}
if (tgParser.ParsedData[i].ContainsKey("EegPowerDelta"))
{
//Console.WriteLine("Delta: " + tgParser.ParsedData[i]["EegPowerDelta"]);
Console.WriteLine("Delta: " + tgParser.ParsedData[i]["EegPowerDelta"]);
}
if (tgParser.ParsedData[i].ContainsKey("BlinkStrength"))
{
//Console.WriteLine("Eyeblink " + tgParser.ParsedData[i]["BlinkStrength"]);
Console.WriteLine("Eyeblink " + tgParser.ParsedData[i]["BlinkStrength"]);
}
}
}
It will be much better to log every console output to a file as it happens. Instead of waiting to write to file when the app is closed manually. To save yourself a lot of coding, you can use log4net to handle the logging.
There's several different ways of approaching this, and with a bit of research I'm sure you could find a few, however this is the solution I would use for this particular action :
As Jonesy mentioned in the comments, I would firstly tidy up your Main. Create a separate class to perform the console writeline and the text output at the same time.
In this class perhaps use a loop to output the data to a file as and when it happens, therefore you wouldn't have to code in the logic when the console is closed manually, which in turn would cover unexpected errors and loss of logs.
This might work.
public static void WriteToFileAndConsole()
{
string outFile = "ConsoleOut.txt";
using (FileStream fileStream = new FileStream(outFile, FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
using (TextWriter originalConsoleOut = Console.Out)
{
Console.SetOut(writer);
Console.WriteLine("Hello To File");
Console.SetOut(originalConsoleOut);
}
}
}
Console.WriteLine("Hello to console only");
}

FileSystemWatcher Access to a FileShare: Possible permission iusse?

I'm written a basic application that watches one network File Share directory and when a new file is created in that directory it then fires an external application that parses that file. I've also tested with a local directory and everything worked. I've tested it with debug code like so and the application will work:
#if DEBUG
Service1 mysService1 = new Service1();
mysService1.OnDebug(); //calls onStart(Null);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
Then when I switch to release, build and install the service nothing will happen. So since the path worked i figured this was down to permissions?
I went to Task Manager>Services>Services..> right clicked on my service>Properties>Log On> and have given it my credentials.
I've also gone to the root folder of where my application is on the network Right click>Security>Edit. Then I gave my account Modify, Read & Execute, Listing folder contents, and Read permissions and of course those permissions propagated to all of the folders under its hierarchy.
I even tried mapping it to the network drive Z and trying to access it that one.
With everything I tried the service still refuses to do anything. I've added more debugging code where I would check if the file was changed or deleted and write it down in text files. Once again it would work and detect those changes in debug but upon install nothing would happen.
I'm pretty sure this is probably still some kind of permission issue can anyone tell me what else I could do to remedy this issue?
EDIT:
There was a request for more code. Also note that my Utility class was able to produce a stack trace. It lead to an issue with System.IO.FileStream error started from this line of code in the FileWatcher.cs System.IO.File.AppendAllText(PathLocation() + "\logFile.txt", Environment.NewLine + " Started! " + DateTime.Now.ToString());
Service1.cs:
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
try
{
FileWatcher f = new FileWatcher();
}
catch (Exception e)
{
new ErrorMailer(e, DateTime.Now.ToString());
}
}
FileWatcher.cs:
private FileSystemWatcher _fileWatcher;
static ProcessStartInfo start;
public FileWatcher()
{
System.IO.File.AppendAllText(PathLocation() + "\\logFile.txt", Environment.NewLine + " Started! " + DateTime.Now.ToString());
_fileWatcher = new FileSystemWatcher(PathLocation());
HasMailClerkBeenRun = false;
start = new ProcessStartInfo();
_fileWatcher.Created += new FileSystemEventHandler(_fileWatcher_Created);
_fileWatcher.Deleted += new FileSystemEventHandler(_fileWatcher_Deleted);
_fileWatcher.Changed += new FileSystemEventHandler(_fileWatcher_Changed);
_fileWatcher.EnableRaisingEvents = true;
}
{
string value = String.Empty;
value = #"Z:\MyAppDirectory\DirectoryFileWatcherIsWatching"; //#"\\FileShareName\RootDirectory\MyAppDirectory\DirectoryFileWatcherIsWatching";
return value;
}
void _fileWatcher_Changed(object sender, FileSystemEventArgs e)
{
System.IO.File.AppendAllText(PathLocation() + "\\logFile.txt", Environment.NewLine + "Started from the bottom now we changed! " + DateTime.Now.ToString());
}
void _fileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
System.IO.File.AppendAllText(PathLocation() + "\\logFile.txt", Environment.NewLine + "Started from the bottom now we deleted! " + DateTime.Now.ToString());
}
void _fileWatcher_Created(object sender, FileSystemEventArgs e)
{
System.IO.File.AppendAllText(PathLocation() + "\\logFile.txt", Environment.NewLine + "Started from the bottom now we here! " + DateTime.Now.ToString());
LaunchExternalApp();
}
private void LaunchExternalApp()
{
start.UseShellExecute = false;
start.RedirectStandardError = true;
start.RedirectStandardInput = true;
start.RedirectStandardOutput = true;
start.CreateNoWindow = true;
start.ErrorDialog = false;
start.WindowStyle = ProcessWindowStyle.Hidden;
start.FileName =#"Z:\MyAppDirectory\AppExcutionLocation\MyApp.exe"
Thread thread1 = new Thread(new ThreadStart(A));
thread1.Start();
thread1.Join();
}
static void A()
{
using (Process proc = Process.Start(start))
{
proc.WaitForExit();
//HasMailClerkBeenRun = true;
// Retrieve the app's exit code
/// int exitCode = proc.ExitCode;
}
Thread.Sleep(100);
Console.WriteLine('A');
}
Check that the service is running under the same account as the interactive user account that you are using when checking the share or mapping the drive. If not, try switching it to use this account.
I have no idea why you are calling System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite), but I suspect that removing that line will solve your problem. If it doesn't, please post more code.

Categories