Error upon sending and executing multiple test files - c#

I am writing an application which launches a tester (.cmd), so I am passing in the tests that have been entered into a listbox. This method works perfectly fine if there is one test entered, but if there is 2 or more, it give me the error:
"An unhandled exception of type 'System.ComponentModel.Win32Exception'
occurred in System.dll
Additional information: The system cannot find the file specified"
The StartInfo.Filename and the currentTestFromListbox[i] both look correct in the debugger.
Anyone have any idea where I'm going wrong?
I apologize that my code is confusing--im just a beginner.
public void executeCommandFiles()
{
int i = 0;
int ii = 0;
int numberOfTests = listboxTestsToRun.Items.Count;
executeNextTest:
var CurrentTestFromListbox = listboxTestsToRun.Items.Cast<String>().ToArray();
string filenameMinusCMD = "error reassigning path value";
int fileExtPos = CurrentTestFromListbox[i].LastIndexOf(".");
if (fileExtPos >= 0)
{
filenameMinusCMD = CurrentTestFromListbox[i].Substring(0, fileExtPos);
}
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = #"pushd Y:\Tests\" + filenameMinusCMD + #"\" + CurrentTestFromListbox[i];
startInfo.WorkingDirectory = #"pushd Y:\Tests\" + filenameMinusCMD + #"\";
startInfo.FileName = CurrentTestFromListbox[i];
Process.Start(startInfo);
//Wait for program to load before selecting main tab
System.Threading.Thread.Sleep(10000);
//Select MainMenu tab by sending a left arrow keypress
SendKeys.Send("{LEFT}");
i++;
if (i < numberOfTests)
{
checkIfTestIsCurrentlyRunning:
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("nameOfProgramIAmTesting"))
{
System.Threading.Thread.Sleep(2000);
//if (ii > 150)
if (ii > 6) //test purposes only
{
MessageBox.Show("The current test (" + filenameMinusCMD + ") timed out at 5 minutes. The next test has been started.", "Test timed out",
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
ii++;
goto checkIfTestIsCurrentlyRunning;
}
goto executeNextTest;
}
}
}
}
Thanks!
-Joel

Here is your code re-factored. The sleeps/gotos were really bothering me. I couldn't really test it, but I think it should work the same. Let me know if it doesn't work or you have any questions.
This assumes your listbox has content like this in it:
testname.cmd
test2.cmd
test3.exe
lasttest.bat
Here is my attempt:
public void executeCommandFiles()
{
foreach (string test in listboxTestsToRun.Items)
{
//gets the directory name from given filename (filename without extension)
//assumes that only the last '.' is for the extension. test.1.cmd => test.1
string testName = test.Substring(0, test.LastIndexOf('.'));
//set up a FileInfo object so we can make sure the test exists gracefully.
FileInfo testFile = new FileInfo(#"Y:\Tests\" + testName + "\\" + test);
//check if it is a valid path
if (testFile.Exists)
{
ProcessStartInfo startInfo = new ProcessStartInfo(testFile.FullName);
//get the Process object so we can wait for it to finish.
Process currentTest = Process.Start(startInfo);
//wait 5 minutes then timeout (5m * 60s * 1000ms)
bool completed = currentTest.WaitForExit(300000);
if (!completed)
MessageBox.Show("test timed out");
//use this if you want to wait for the test to complete (indefinitely)
//currentTest.WaitForExit();
}
else
{
MessageBox.Show("Error: " + testFile.FullName + " was not found.");
}
}
}

Related

I am not able to insert more than 5120 records in Oracle table using .net application

I am using the below code to insert bulk over 100 000 records
C# function:
public void ExcelUpload(DataTable dt)
{
try
{
objBus.ClearMDPreprocessed();
lblError1.Visible = true;
lblError1.Text = "Preparing Sheet for Validations. Please Wait...";
using (StreamWriter wr = new StreamWriter(MapPath(ConfigurationManager.AppSettings["MASTER_DATA_FOLDER"].ToString()) + "\\RawMasterData_PREPROCESSED.txt"))//(#"e:\WorkingFolder\output.txt"))
{
foreach (DataRow row in dt.Rows)
{
wr.WriteLine(row["EMPNO"] + "," + row["MODEL"] + "," + row["PRIMARY_SUPERVISOR"] + "," + row["PROJECT_MANAGER"] + "," + row["ISBPS"] + "," + row["BU"]);
}
}
System.Diagnostics.Process sysprocess = new Process();
string myCommand = #"/c SQLLDR " + ConfigurationManager.AppSettings["ORA_CONN_MASTER_" + ConfigurationManager.AppSettings["CONN"].ToString().Trim()].ToString().Trim() + " LOG=" + MapPath(ConfigurationManager.AppSettings["MASTER_DATA_FOLDER"].ToString()) + "\\MasterDataUpd_PP.Log" + " CONTROL=" + MapPath(ConfigurationManager.AppSettings["MASTER_DATA_FOLDER"].ToString()) + "\\Ctrl_PreProcessed_Raw.txt";
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", myCommand);
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = MapPath(ConfigurationManager.AppSettings["MASTER_DATA_FOLDER"].ToString());
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
sysprocess = System.Diagnostics.Process.Start(startInfo);
sysprocess.WaitForExit();
if ((sysprocess.ExitCode == 4))
{
lblError1.Visible = true;
lblError1.Text = "Sheet ready for Validations.Click on Validate";
btnValidate.Visible = true;
btnDirectUpload.Visible = true;
}
else
HttpContext.Current.Response.Write("NOT DONE");
}
catch (Exception ex)
{
throw ex;
}
}
Ctrl_Preprocessed_Raw.txt content:
LOAD DATA
INFILE RawMasterData_PREPROCESSED.txt
BADFILE dataFile.bad
APPEND INTO TABLE MSI_MASTER_DATA_RAW
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(EMPNO,MODEL,PRIMARY_SUPERVISOR,PROJECT_MANAGER,ISBPS,BU)
I don't know C#, but LOAD DATA INFILE ... looks very much like SQL*Loader. It has a control file. In it, you can set error limit which terminates execution once that limit is reached. So, maybe it is set to 5120. Perhaps you could check that.
[EDIT]
Gosh, of course it is not set to 5120 ... you managed to load that much rows. Limit is, by default, set to 50. If you look at the SQL*Loader log file (as well as BAD file, if you set them to be used - and yes, you should have set it), you might find those information in there.
I have resolved it using the below steps:
1) startInfo.RedirectStandardOutput = false; //this I made to false
2) startInfo.RedirectStandardInput = true; //I have commented this line.
This resolved my issue, and I was able to insert bulk records in oracle through SQL loader without any issues with the above code. Thanks everyone for your inputs. :)

Parallel.ForEach(...) System Out of Memory exception

I've looked at Parallel.ForEach - System Out of Memory Exception regarding this issue but not much of a solution was given. I'm very new to using Parallel.ForEach, so I'm trying to figure out what's going on.
Diagnostic tools caps out at 1023 repeating (I understand this is an x86 to x64 arch restriction, but I wanted to offer the program in both formats.) I also don't feel like any program should ever meet that threshold. When I compile the program in x64, I sit around 1.1-1.4GB with MaxDegree . For sake of testing, I am running GC.Collection() at the end of each Parallel.ForEach iteration (I understand this isn't good practice, I'm just trying to troubleshoot at this point.)
Here's what I'm seeing:
Now if I try to use a Partitioner method, such as:
var checkforfinished = Parallel.ForEach<ListViewItem>(Partitioner.Create(0,lstBackupUsers.Items.Count), lstBackupUsers.Items.Cast<ListViewItem>(), opts, name =>
The I get an error of:
"No overload for method 'ForEach' takes 4 arguments"
That's fine, I modify my Parallel.ForEach statement so it looks like this:
var checkforfinished = Parallel.ForEach(Partitioner.Create(0,lstBackupUsers.Items.Count), lstBackupUsers.Items, opts, name => (I removed my casts)
and then my ForEach method won't accept the statement because it wants me to explicitly tell it that it's addressing a listviewbox.items method.
I am so confused on what to do.
Do I create a Partitioner, and if I do, how do I make my Parallel.ForEach method understand how to address a listviewbox?
update 1
I want to try to give as many details as possible because this is just rough. I'm sure it's easy, I'm just overcomplicationg it by an nth degree.
I have my Parallel.ForEach(//) running in a background worker function. My DoWork process is over 300 lines (I'm not an expert in C#, I'm just putting things together for a program at work.)
Here are bullet points of its basic structure
User clicks a "Start backup" button as seen in the screenshot
Button begins a separate function that checks to see which method the user selected to grab a list of usernames from (LDAP or flat text file)
That function then sends off a bgw_dowork() request
Inside the DoWork request, it looks like a summary of:
Check preliminary statements (bgw.cancellationpending for example)
Move on to grabbing some settings from the configurationmanager.appsettings
Begin the "complex" Parallel.ForEach command which Reads the listbox record rows and foreach row performs a very long list of commands to complete an operation for one user
The entire program, especially bgw_dowork heavily uses Google's v3 Drive API to login as a user, grab a file as recorded by other functions that prepare the user directory to be backed up (separate functions which login as a user, record their files (and fileIds) and their directories/subdirectories) and the bgw_dowork performs a chunk of the actual download functionality, which then calls off to the other functions to finish moving the files after they have been downloaded.
The actual "code" I use is (and I promise it's not pretty...)
private void bgW_DoWork(object sender, DoWorkEventArgs e)
{
{
try
{
txtFile.ReadOnly = true;
btnStart.Text = "Cancel Backup";
var appSettings = ConfigurationManager.AppSettings;
string checkreplace = ConfigurationManager.AppSettings["checkreplace"];
string userfile = txtFile.Text;
int counter = 0;
int arraycount = 0;
if (bgW.CancellationPending)
{
e.Cancel = true;
stripLabel.Text = "Operation was canceled!";
}
else
{
for (int z = 0; z >= counter; z++)
{
if (bgW.CancellationPending)
{
e.Cancel = true;
stripLabel.Text = "Operation was canceled!";
break;
}
else
{
double totalresource = int.Parse(ConfigurationManager.AppSettings["multithread"]);
totalresource = (totalresource / 100);
//var opts = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(Math.Ceiling((Environment.ProcessorCount * totalresource) * 1.0)) };
var opts = new ParallelOptions { MaxDegreeOfParallelism = 2 };
var part = Partitioner.Create(1, 100);
//foreach (ListViewItem name in lstBackupUsers.Items)
var checkforfinished = Parallel.ForEach(lstBackupUsers.Items.Cast<ListViewItem>(), name =>
{
try
{
string names = name.SubItems[0].Text;
lstBackupUsers.Items[arraycount].Selected = true;
lstBackupUsers.Items[arraycount].BackColor = Color.CornflowerBlue;
arraycount++;
stripLabel.Text = "";
Console.WriteLine("Selecting user: " + names.ToString());
txtLog.Text += "Selecting user: " + names.ToString() + Environment.NewLine;
txtCurrentUser.Text = names.ToString();
// Define parameters of request.
string user = names.ToString();
// Check if directory exists, create if not.
string savelocation = ConfigurationManager.AppSettings["savelocation"] + user + "\\";
if (File.Exists(savelocation + ".deltalog.tok"))
File.Delete(savelocation + ".deltalog.tok");
FileInfo testdir = new FileInfo(savelocation);
testdir.Directory.Create();
string savedStartPageToken = "";
var start = CreateService.BuildService(user).Changes.GetStartPageToken().Execute();
// This token is set by Google, it defines changes made and
// increments the token value automatically.
// The following reads the current token file (if it exists)
if (File.Exists(savelocation + ".currenttoken.tok"))
{
StreamReader curtokenfile = new StreamReader(savelocation + ".currenttoken.tok");
savedStartPageToken = curtokenfile.ReadLine().ToString();
curtokenfile.Dispose();
}
else
{
// Token record didn't exist. Create a generic file, start at "1st" token
// In reality, I have no idea what token to start at, but 1 seems to be safe.
Console.Write("Creating new token file.\n");
//txtLog.Text += ("Creating new token file.\n" + Environment.NewLine);
StreamWriter sw = new StreamWriter(savelocation + ".currenttoken.tok");
sw.Write(1);
sw.Dispose();
savedStartPageToken = "1";
}
string pageToken = savedStartPageToken;
int gtoken = int.Parse(start.StartPageTokenValue);
int mytoken = int.Parse(savedStartPageToken);
txtPrevToken.Text = pageToken.ToString();
txtCurrentToken.Text = gtoken.ToString();
if (gtoken <= 10)
{
Console.WriteLine("Nothing to save!\n");
//txtLog.Text += ("User has nothing to save!" + Environment.NewLine);
}
else
{
if (pageToken == start.StartPageTokenValue)
{
Console.WriteLine("No file changes found for " + user + "\n");
//txtLog.Text += ("No file changes found! Please wait while I tidy up." + Environment.NewLine);
}
else
{
// .deltalog.tok is where we will place our records for changed files
Console.WriteLine("Changes detected. Making notes while we go through these.");
lblProgresslbl.Text = "Scanning Drive directory.";
// Damnit Google, why did you change how the change fields work?
if (savedStartPageToken == "1")
{
statusStripLabel1.Text = "Recording folder list ...";
txtLog.Text = "Recording folder list ..." + Environment.NewLine;
exfunctions.RecordFolderList(savedStartPageToken, pageToken, user, savelocation);
statusStripLabel1.Text = "Recording new/changed files ... This may take a bit!";
txtLog.Text += Environment.NewLine + "Recording new/changed list for: " + user;
exfunctions.ChangesFileList(savedStartPageToken, pageToken, user, savelocation);
}
else
{
//proUserclass = proUser;
statusStripLabel1.Text = "Recording new/changed files ... This may take a bit!";
txtLog.Text += Environment.NewLine + "Recording new/changed list for: " + user + Environment.NewLine;
exfunctions.ChangesFileList(savedStartPageToken, pageToken, user, savelocation);
}
// Get all our files for the user. Max page size is 1k
// after that, we have to use Google's next page token
// to let us get more files.
StreamWriter logFile = new StreamWriter(savelocation + ".recent.log");
string[] deltafiles = File.ReadAllLines(savelocation + ".deltalog.tok");
int totalfiles = deltafiles.Count();
int cnttototal = 0;
Console.WriteLine("\nFiles to backup:\n");
if (deltafiles == null)
{
return;
}
else
{
double damn = ((gtoken - double.Parse(txtPrevToken.Text)));
damn = Math.Round((damn / totalfiles));
if (damn <= 0)
damn = 1;
foreach (var file in deltafiles)
{
try
{
if (bgW.CancellationPending)
{
stripLabel.Text = "Backup canceled!";
e.Cancel = true;
break;
}
DateTime dt = DateTime.Now;
string[] foldervalues = File.ReadAllLines(savelocation + "folderlog.txt");
cnttototal++;
bgW.ReportProgress(cnttototal);
proUser.Maximum = int.Parse(txtCurrentToken.Text);
stripLabel.Text = "File " + cnttototal + " of " + totalfiles;
double? mathisfun;
mathisfun = ((100 * cnttototal) / totalfiles);
if (mathisfun <= 0)
mathisfun = 1;
double mathToken = double.Parse(txtPrevToken.Text);
mathToken = Math.Round((damn + mathToken));
// Bring our token up to date for next run
txtPrevToken.Text = mathToken.ToString();
File.WriteAllText(savelocation + ".currenttoken.tok", mathToken.ToString());
int proval = int.Parse(txtPrevToken.Text);
int nowval = int.Parse(txtCurrentToken.Text);
if (proval >= nowval)
proval = nowval;
proUser.Value = (proval);
lblProgresslbl.Text = ("Current progress: " + mathisfun.ToString() + "% completed.");
// Our file is a CSV. Column 1 = file ID, Column 2 = File name
var values = file.Split(',');
string fileId = values[0];
string fileName = values[1];
string mimetype = values[2];
mimetype = mimetype.Replace(",", "_");
string folder = values[3];
string ext = null;
int folderfilelen = foldervalues.Count();
fileName = GetSafeFilename(fileName);
Console.WriteLine("Filename: " + values[1]);
logFile.WriteLine("ID: " + values[0] + " - Filename: " + values[1]);
logFile.Flush();
// Things get sloppy here. The reason we're checking MimeTypes
// is because we have to export the files from Google's format
// to a format that is readable by a desktop computer program
// So for example, the google-apps.spreadsheet will become an MS Excel file.
switch (mimetype)
{
(switch statement here removed due to body length issues for this post.)
}
if (ext.Contains(".doc") || ext.Contains(".xls"))
{
string whatami = null;
if (ext.Contains(".xls"))
{
whatami = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (ext.Contains(".doc"))
{
whatami = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
else if (ext.Contains(".ppt"))
{
whatami = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
}
if (fileName.Contains(".mov") || ext == ".ggl" || fileName.Contains(".mp4"))
{
txtLog.Text += Environment.NewLine + "Skipping file.";
return;
}
var requestfileid = CreateService.BuildService(user).Files.Export(fileId, whatami);
statusStripLabel1.Text = (savelocation + fileName + ext);
txtCurrentUser.Text = user;
string dest1 = Path.Combine(savelocation, fileName + ext);
var stream1 = new System.IO.FileStream(dest1, FileMode.OpenOrCreate, FileAccess.ReadWrite);
scrolltobtm();
requestfileid.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
logFile.WriteLine("Downloading: " + progress.BytesDownloaded);
txtLog.Text += ("Downloading ... " + progress.BytesDownloaded + Environment.NewLine);
scrolltobtm();
logFile.Flush();
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
logFile.WriteLine("[" + user + "] Download complete for: " + requestfileid.ToString());
txtLog.Text += ("[" + user + "] Download complete for: " + fileName + Environment.NewLine);
logFile.Flush();
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
logFile.WriteLine("Download failed.");
logFile.Flush();
break;
}
}
};
scrolltobtm();
GC.Collect();
GC.WaitForPendingFinalizers();
requestfileid.Download(stream1);
stream1.Close();
stream1.Dispose();
}
else
{
scrolltobtm();
var requestfileid = CreateService.BuildService(user).Files.Get(fileId);
//Generate the name of the file, and create it as such on the local filesystem.
statusStripLabel1.Text = (savelocation + fileName + ext);
string dest1 = Path.Combine(savelocation, fileName + ext);
var stream1 = new System.IO.FileStream(dest1, FileMode.OpenOrCreate, FileAccess.ReadWrite);
requestfileid.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
logFile.WriteLine("Downloading: " + progress.BytesDownloaded);
txtLog.Text += ("Downloading ... " + progress.BytesDownloaded + Environment.NewLine);
scrolltobtm();
logFile.Flush();
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
logFile.WriteLine("Download complete for: " + requestfileid.ToString());
txtLog.Text += (Environment.NewLine + "[" + user + "] Download complete for: " + fileName + Environment.NewLine);
logFile.Flush();
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
logFile.WriteLine("Download failed.");
logFile.Flush();
break;
}
}
};
scrolltobtm();
GC.Collect();
GC.WaitForPendingFinalizers();
requestfileid.Download(stream1);
stream1.Close();
stream1.Dispose();
}
}
catch (Google.GoogleApiException ex)
{
Console.Write("\nInfo: ---> " + ex.Message.ToString() + "\n");
}
}
}
exfunctions.MoveFiles(savelocation);
Console.WriteLine("\n\n\tBackup completed for selected user!");
txtLog.Text += ("\n\nBackup completed for selected user.\n\n");
statusStripLabel1.Text = "";
//logFile.Close();
//logFile.Dispose();
}
}
}
catch (Google.GoogleApiException ex)
{
Console.WriteLine("Info: " + ex.Message.ToString());
}
}
);
if (checkforfinished.IsCompleted == true)
{
MessageBox.Show("Parallel.ForEach() Finished!");
Console.WriteLine("Parallel.ForEach() Finished!");
}
else
{
MessageBox.Show("Parallel.ForEach() not completed!");
Console.WriteLine("Parallel.ForEach() not completed!");
}
}
}
}
}
catch (Google.GoogleApiException ex)
{
Console.WriteLine("Info: " + ex.Message.ToString());
}
}
}
You can see where I initiate the Parallel.ForEach(...) and then see what it is in charge of doing. It's a lot, and I understand it's not pretty, so I appreciate constructive criticism.

Copying a file that is a virus caused my program to terminate

I have made a tool that will copy files from a source to a destination. However during the copy, the software came across a virus that was flagged by the anti-virus software (Symantec).
The anti-virus then caused my software to close down, and quarantine the program as a "dropper".
Is there anyway I can gracefully handle this scenario, rather than shutting down my program completely?
I appreciate that the action was the result of the anti-virus, but is there anything I can do to help the situation? For example, Robocopy does not just terminate when it comes across a virus.
Here is my copy code;
void CopyFileExactly(CopyParameterBundle cpb, bool overwrite)
{
string CTP = "", CFP = "";
CFP = cpb.SourcePath;
if (cpb.RenameFile)
CTP = cpb.DestPath ;
else
CTP = cpb.DestPath;
//Check firstly if the file to copy exists
if (!File.Exists(CFP))
{
throw new FileNotFoundException();
}
//Check if destination file exists
//If it does, make it not read only so we can update MAC times
if (File.Exists(CTP))
{
var target = GetFile(CTP);//new FileInfo(CTP);
if (target.IsReadOnly)
target.IsReadOnly = false;
}
var origin = GetFile(CFP);//new FileInfo(CFP);
GetFile(CTP).Directory.Create();
//(new FileInfo(CTP)).Directory.Create();
origin.CopyTo(CTP, (overwrite ? true : false));
if (!File.Exists(CTP))
{
throw new FileNotFoundException("Destination file not found!");
}
var destination = GetFile(CTP);//new FileInfo(CTP);
if (destination.IsReadOnly)
{
destination.IsReadOnly = false;
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
destination.IsReadOnly = true;
}
else
{
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
}
if (performMD5Check)
{
var md5Check = compareFileMD5(CFP, CTP);
cpb.srcMD5Hash = md5Check.Item2;
cpb.dstMD5Hash = md5Check.Item3;
if (!md5Check.Item1)
throw new MD5MismatchException("MD5 Hashes do NOT match!");
}
}
The calling code;
void BeginCopy(int DegreeOfParallelism, int retryCount, int retryDelay)
{
object _lock;
//Setup cancellation token
po.CancellationToken = cts.Token;
//Set max number of threads
po.MaxDegreeOfParallelism = DegreeOfParallelism;
//Exceptio logging queue
var exceptions = new ConcurrentQueue<Exception>();
var completeItems = new ConcurrentQueue<CopyParameterBundle>();
var erroredItems = new ConcurrentQueue<CopyParameterBundle>();
//Logger logger = new Logger(sLogPath);
//logger.Write("Starting copy");
Task.Factory.StartNew(() =>
{
Parallel.ForEach(CopyParameters,
po,
(i, loopState, localSum) =>
{
localSum = retryCount;
do
{
try
{
//Go off and attempt to copy the file
DoWork(i);
//Incrememt total count by 1 if successfull
i.copyResults.TransferTime = DateTime.Now;
i.copyResults.TransferComplete = true;
completeItems.Enqueue(i);
//logger.Write("Copied file from: " + i.SourcePath + "\\" + i.SourceFile + " => " + i.DestPath + "\\" + i.SourceFile);
break;
}
catch (Exception ex)
{
//this.richTextBox1.AppendText("[-] Exception on: " + i.SourcePath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + System.Environment.NewLine);
//Exception was thrown when attempting to copy file
if (localSum == 0)
{
//Given up attempting to copy. Log exception in exception queue
exceptions.Enqueue(ex);
this.SetErrorText(exceptions.Count());
//Write the error to the screen
this.Invoke((MethodInvoker)delegate
{
this.richTextBox1.AppendText("[-] Exception on: " + i.SourcePath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + System.Environment.NewLine);
i.copyResults.TransferComplete = false;
i.copyResults.TransferTime = DateTime.Now;
i.copyResults.exceptionMsg = ex;
erroredItems.Enqueue(i);
//logger.Write("ERROR COPYING FILE FROM : " + i.SourcePath + "\\" + i.SourceFile + " => " + i.DestPath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + " => " + ex.Source);
});
}
//Sleep for specified time before trying again
Thread.Sleep(retryDelay);
localSum--;
}
//Attempt to Repeat X times
} while (localSum >= 0);
//Check cancellation token
po.CancellationToken.ThrowIfCancellationRequested();
Interlocked.Increment(ref TotalProcessed);
this.SetProcessedText(TotalProcessed);
//Update Progress Bar
this.Invoke((MethodInvoker)delegate
{
this.progressBar1.Value = (TotalProcessed);
});
});
//aTimer.Stop();
this.Invoke((MethodInvoker)delegate
{
this.label9.Text = "Process: Writing Log";
});
WriteLog(sLogPath, completeItems, erroredItems);
this.Invoke((MethodInvoker)delegate
{
this.label9.Text = "Process: Done!";
});
if (exceptions.Count == 0)
MessageBox.Show("Done!");
else
MessageBox.Show("Done with errors!");
EnableDisableButton(this.button2, true);
EnableDisableButton(this.button4, false);
});
}
What happened is most likely that the antivirus was aware of the virus file, so when it detected that a change in the file system (moving the file) occurred, it terminated the program because by moving the virus to a different location in your computer, it could cause problems (since it's a virus). It was flagged as dropper, basically a type of program that is designed to install the virus.
Edit: i forgot to mention that to solve the problem you will most likely need to license your program.

C# stop a process

I would to be able to stop a typeperf process i started in c# for remote machines.
What i got so far is:
ProcessStartInfo proc = new ProcessStartInfo();
public void startLogs()
{
for (int i = 0; i < remote_machines_num; i++)
{
string line = " -s " + machines[i]
+ " -si 5 \"\\Processor(_Total)\\% Processor Time\" -o C:\\logs\\"
+ machines[i] + ".csv";
proc.FileName = #"C:\WINDOWS\SYSTEM32\typeperf.exe";
proc.Arguments = line;
Process.Start(proc);
}
}
this really starts all monitors - but i would like to write a function that will stop monitoring and close all windows - how can i do that? thanks!
Get a reference to the started process and Kill() it.
var theRunningProc = Process.Start(proc);
theRunningProc.Kill();
Are you looking for this
http://alperguc.blogspot.com/2008/11/c-process-processgetprocessesbyname.html

How to display list process, when i run sql*loader in c#

How to display list process, when i run sql*loader in c#. I mean when i run sql*loader from cmd windows, i get list process how many row has been inserted. But when i run SQL*Loader from C#, i can't get process SQL*Loader.
This is my code:
string strCmd, strSQLLoader;
string strLoaderFile = "XLLOAD.CTL";
string strLogFile = "XLLOAD_LOG.LOG";
string strCSVPath = #"E:\APT\WorkingFolder\WorkingFolder\sqlloader\sqlloader\bin\Debug\8testskrip_HTTP.csv";
string options = "OPTIONS (SKIP=1, DIRECT=TRUE, ROWS=1000000,BINDSIZE=512000)";
string append = "APPEND INTO TABLE XL_XDR FIELDS TERMINATED BY ','";
string table = "OPTIONALLY ENCLOSED BY '\"' TRAILING NULLCOLS (xdr_id,xdr_type,session_start_time,session_end_time,session_last_update_time,session_flag,version,connection_row_count,error_code,method,host_len,host,url_len,url,connection_start_time,connection_last_update_time,connection_flag,connection_id,total_event_count,tunnel_pair_id,responsiveness_type,client_port,payload_type,virtual_type,vid_client,vid_server,client_addr,server_addr,client_tunnel_addr,server_tunnel_addr,error_code_2,ipid,c2s_pkts,c2s_octets,s2c_pkts,s2c_octets,num_succ_trans,connect_time,total_resp,timeouts,retries,rai,tcp_syns,tcp_syn_acks,tcp_syn_resets,tcp_syn_fins,event_type,flags,time_stamp,event_id,event_code)";
strCmd = "sqlldr xl/secreat#o11g control=" + strLoaderFile + " LOG=" + strLogFile;
System.IO.DirectoryInfo di;
try
{
System.Diagnostics.ProcessStartInfo cmdProcessInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
di = new DirectoryInfo(strCSVPath);
strSQLLoader = "";
strSQLLoader += "LOAD DATA INFILE '" + strCSVPath.ToString().Trim() + "' " + append + " " + table;
StreamWriter writer = new StreamWriter(strLoaderFile);
writer.WriteLine(strSQLLoader);
writer.Flush();
writer.Close();
// Redirect both streams so we can write/read them.
cmdProcessInfo.RedirectStandardInput = true;
cmdProcessInfo.RedirectStandardOutput = true;
cmdProcessInfo.UseShellExecute = false;
cmdProcessInfo.LoadUserProfile = true;
//System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
// Start the procses.
System.Diagnostics.Process pro = System.Diagnostics.Process.Start(cmdProcessInfo);
// Issue the dir command.
pro.StandardInput.WriteLine(strCmd);
// Exit the application.
pro.StandardInput.WriteLine("exit");
//Process[] processlist = Process.GetProcesses();
//foreach(Process pro in processlist){
Console.WriteLine("Process: {0} ID: {1}", pro.ProcessName, pro.Id);
Console.WriteLine(pro.StandardOutput.ReadLine());
//}
// Read all the output generated from it.
string strOutput;
strOutput = pro.StandardOutput.ReadToEnd();
pro.Dispose();
}
catch (Exception ex)
{
return;
}
finally
{
}
Thanks
When you send
pro.StandardInput.WriteLine("exit");
to the process, this will close the console and exit the process.
So when you call
Console.WriteLine("Process: {0} ID: {1}", pro.ProcessName, pro.Id);
it raises a
"Process has exited, so the requested
information is not available."
exception. To fix this, move your exit call to after this line.
Never ignore exceptions!!! They tell you useful things that help you to fix your problems!!

Categories