I wrote a program in C # that takes, from a WPF interface, a folder path, a prefix, and a prefix of substitution. The purpose of the program is to search in the folder all the files that start with the prefix and rename them with the new prefix. This program works without any problems.
Now I have to write a second program that must call the previous, passing the parameters using args []. I wrote this second program, it seems that all the parameters have passed correctly to the other (I checked it), but every time the replacement program runs out after a few seconds (while the normal run in my folder of Trial is almost instantly). I'm not able to have any message error or exception, I can only obtain the windows alert message that reports the crash.
Here is the significant part of the code of both programs ... Can anyone help me to find the problem? Is it a problem with settings passed from one program to another? Thanks a lot to everyone.
Can it maybe be a problem about the setting parameters of the calling?
Replace prefix program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace replace_prefix
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] args;
args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
((MainWindow)App.Current.MainWindow).Close();
sf_textBox.Text = args[1];
rp_textBox.Text = args[2];
np_textBox.Text = args[2];
replace();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void ok_button_Click(object sender, RoutedEventArgs e)
{
replace();
}
private void replace() {
if (sf_textBox.Text == "" || rp_textBox.Text == "" || np_textBox.Text == "")
MessageBox.Show(this, "Insert all required parameters", "Parameter missing", MessageBoxButton.OK, MessageBoxImage.Error);
else
{
using (StreamWriter w = File.CreateText("log.txt"))
{
DirectoryInfo d = new DirectoryInfo(sf_textBox.Text);
FileInfo[] Files = d.GetFiles("*.*");
string filename, log;
foreach (FileInfo file in Files)
{
filename = file.Name;
int Place = filename.IndexOf(rp_textBox.Text);
if (Place == 0)
{
log = "file " + filename + " renamed ";
filename = filename.Remove(Place, rp_textBox.Text.Length).Insert(Place, np_textBox.Text);
file.MoveTo(file.Directory.FullName + "\\" + filename);
Log(log + filename, w);
}
}
w.Close();
}
Environment.Exit(0);
}
}
public static void Log(string logMessage, TextWriter w)
{
w.Write(DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
w.Write(" --> ");
w.WriteLine(logMessage);
}
}
}
Calling method in the other program:
public void LaunchCommandLineApp()
{
using (StreamWriter wl = File.CreateText(job.name + "_log.txt"))
{
lock (wl) wl.WriteLine("\\n" + DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " launched");
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = job.process;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
var count = job.args.Count(c => c == ';');
startInfo.Arguments = "";// "-f ";
while (count > 1)
{
startInfo.Arguments += job.args.Substring(0, job.args.IndexOf(';', 0));
int i = job.args.IndexOf(';', 0) + 1, k = job.args.Length - 1;
job.args = job.args.Substring((job.args.IndexOf(';', 0) + 1), (job.args.Length - 1) - (job.args.IndexOf(';', 0)));
count--;
}
if (count == 1) {
int i = job.args.IndexOf(';', 0);
startInfo.Arguments += job.args.Substring(0, job.args.IndexOf(';', 0));
}
if (job.recurrency) job.updateRecurrency();
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
string tl;
try
{
tl = Path.GetDirectoryName(job.process);
}
catch (ArgumentException e) {
tl = null;
}
if (tl != null)
{
try
{
tl = tl + "\\log.txt";
StreamReader input = new StreamReader(tl);
tl = input.ReadLine();
while (tl != null)
{
wl.WriteLine(tl);
tl = input.ReadLine();
}
input.Close();
}
catch (Exception e) { }
}
lock (wl) wl.WriteLine(DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " successfully ended.");
}
}
catch (Exception e)
{
//add local process log
lock (wl) wl.WriteLine(DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " failed to ended. " + e.Message.ToString());
}
wl.Close();
InvokeExecutionFinished(new EventArgs());
}
//Send log via email
//sendNotification();
}
Crash report
Related
I am trying to capture the stdout of a process started in my code but still put the output to the console app that it is running.
My project is a .net core Windows application.
I attach a procedure thread to the process to get the stdout and in that thread I do a console write to also output it to the attached application. I suspect that it is trying to write it to my applications non existent console instead of the joined process. If so, is there a way to get the output and still have it written to the executed processes console?
Code -
private Process proc = null;
private void WriteStandardOutput()
{
using (StreamWriter writer = File.CreateText(exeOutputPath + "\\_out.txt"))
using (StreamReader reader = proc.StandardOutput)
{
writer.AutoFlush = true;
for (; ; )
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
Console.Out.WriteLine(textLine);
}
}
if (File.Exists(exeOutputPath + "\\_out.txt"))
{
FileInfo info = new FileInfo(exeOutputPath + "\\_out.txt");
// if the error info is empty or just contains eof etc.
if (info.Length < 4)
info.Delete();
}
}
///////////////function code
int exitCode;
if (!File.Exists(exePath) && !exePath.Contains("cmd.exe"))
throw new Exception("No executable specified for RunExtApp - " + this.name);
if (exePath.Contains("cmd.exe"))
runParams = "/K " + runParams;
//Start the executable
extApp = new ProcessStartInfo();
extApp.Arguments = runParams;
extApp.FileName = exePath; // Path.GetFileName(exePath);
extApp.WorkingDirectory = Path.GetDirectoryName(exePath);
extApp.UseShellExecute = false;
extApp.RedirectStandardOutput = true;
extApp.RedirectStandardError = true;
// Do you want to show a console window?
//extApp.WindowStyle = Hidden.ProcessWindowStyle;
//extApp.CreateNoWindow = true;
// Run the external process & wait for it to finish
using (proc = Process.Start(extApp))
{
Thread stdOutThread = new Thread(new ThreadStart(WriteStandardOutput));
stdOutThread.IsBackground = true;
stdOutThread.Name = "StandardOutput";
stdOutThread.Start();
proc.WaitForExit();
stdOutThread.Join();
// Retrieve the app's exit code
exitCode = proc.ExitCode;
proc.Close();
if (exitCode > 0)
throw new Exception("Failed to run external code - " + exePath + ". exit code - " + exitCode.ToString());
}
Test Exe - .net framework console application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleWriteTester
{
class Program
{
static void Main(string[] args)
{
for(int i = 0; i < 30; i ++)
{
Console.WriteLine("Line " + i.ToString());
System.Threading.Thread.Sleep(1000);
}
}
}
}
can some one take a look to my C# source that has a crash issue? The program is supposed to omit unwanted double clicks the mouse sometimes sends and it works but after a while using the program it crashes.
The line that crashes:
Application.Run(new TheContext());
This is the error code:
An unhandled exception of type 'System.NullReferenceException' occurred in Gma.System.MouseKeyHook.dll
I'm using Visual studio community 2017
Source:
program.cs:
https://pastebin.com/AX9VRi00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace MouseFixer
{
static class Program
{
static Mutex pmu;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Console.WriteLine("Hello");
try
{
Mutex.OpenExisting("MouseFixer");
MessageBox.Show("MouseFixer is already running", "", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
catch
{
pmu = new Mutex(true, "MouseFixer");
}
Application.Run(new TheContext());
}
}
}
thecontext.cs:
https://pastebin.com/G1cNzj4d
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Gma.System.MouseKeyHook;
using System.Diagnostics;
namespace MouseFixer
{
public class TheContext : ApplicationContext
{
// https://stackoverflow.com/questions/30061813/intercept-mouse-click
StringBuilder logText;
long lastClickTime;
long lastMouseUp;
bool ignoreClick = false;
void writeLog(string msg)
{
logText.Append(msg + Environment.NewLine);
File.AppendAllText("log.txt", logText.ToString());
logText.Clear();
}
bool errorShown = false;
void errorMsg(string str)
{
if(!errorShown)
MessageBox.Show(str);
errorShown = true;
}
long getTime()
{
return DateTimeOffset.Now.ToUnixTimeMilliseconds();
}
public TheContext()
{
Application.ApplicationExit += new EventHandler(this.OnExit);
logText = new StringBuilder();
lastClickTime = getTime();
lastMouseUp = getTime();
Hook.GlobalEvents().MouseDownExt += async (sender, e) =>
{
if (e.Button == MouseButtons.Left)
{
// e.Handled = true;
// writeLog("Handling click DOWN! " + e.Delta);
long lmu = (getTime() - lastMouseUp);
if (lmu < 10)
{
Debug.WriteLine("Too fast click - ignoring " + (getTime() - lastMouseUp) + Environment.NewLine);
e.Handled = true;
ignoreClick = true;
}
long lct = getTime() - lastClickTime;
lastClickTime = getTime();
Debug.WriteLine("MouseDOWN " + lct + " ( " + lmu + " ) " + Environment.NewLine);
}
};
Hook.GlobalEvents().MouseUpExt += async (sender, e) =>
{
if (e.Button == MouseButtons.Left)
{
if (!ignoreClick)
{
// e.Handled = true;
// writeLog("Handling click UP! " + e.Delta);
long lct = getTime() - lastClickTime;
lastClickTime = getTime();
Debug.WriteLine("MouseUP " + lct + Environment.NewLine);
lastMouseUp = getTime();
}
else
{
Debug.WriteLine("Ignoring click " + Environment.NewLine);
e.Handled = true;
ignoreClick = false;
}
}
};
}
private void OnExit(object sender, EventArgs e)
{
// File.AppendAllText("log.txt", logText.ToString());
}
}
}
I have created a Windows Service to fetch attendance by using real time event from a fingerprint device using Interop.zkemkeeper library. In service Machine is successfully connected but the service is not responding to the OnAttTransactionEx real time event means that after succesfull connection to machine attendance is not fetched using OnAttTransactionEx event. I don't know what is the problem.
Here's the code for Windows Service:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
using zkemkeeper;
using System.Threading;
using System.Windows.Forms;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
// private System.Timers.Timer timer1 = null;
string filePath = #"E:\file1.txt";
bool connSatus = false;
CZKEMClass axCZKEM1;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
/* timer1 = new Timer();
this.timer1.Interval = 10000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
*/
axCZKEM1 = new zkemkeeper.CZKEMClass();
Thread createComAndMessagePumpThread = new Thread(() =>
{
connSatus = axCZKEM1.Connect_Net("192.169.9.34", 4370);
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Machine is connected on" + "Date :" + DateTime.Now.ToString() + "status" + connSatus);
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
if (connSatus == true)
{
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("finger print Event is registered... ");
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
}
public void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
{
// if (OnAttTransactionEx != null) OnAttTransactionEx(sEnrollNumber, iIsInValid, iAttState, iVerifyMethod, iYear, iMonth, iDay, iHour, iMinute, iSecond, iWorkCode, axCZKEM1.MachineNumber, Tag);
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine(" OnAttTrasactionEx Has been Triggered,Verified OK on" + "Date :" + "Enrollnumber" + sEnrollNumber + DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
protected override void OnStop()
{
// timer1.Enabled = false;
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
axCZKEM1.Disconnect();
}
private void timer1_Tick(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Message is running on" + "Date :" + DateTime.Now.ToString());
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
}
}
corret version is that
protected override void OnStart(string[] args)
{
Thread createComAndMessagePumpThread = new Thread(() =>
{
axCZKEM1 = new zkemkeeper.CZKEMClass();
connSatus = axCZKEM1.Connect_Net("192.169.9.34", 4370);
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("Machine is connected on" + "Date :" + DateTime.Now.ToString() + "status" + connSatus);
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
if (connSatus == true)
{
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("finger print Event is registered... ");
writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
}
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
}
Here's my C# console program that uses Powerpoint to convert ppt files to folders of pngs. This is supposed to be an automated process that runs on its own server.
I expect that as soon as a thread creates an image from a file, it should immediately remove the images and the source file.
The actual behavior is that, if five threads are running, it'll wait for five folders of images to be created before any thread can move any files. I'm able to see the images being created, and compare that with the Console readout, so I can see that a thread isn't trying to move the file.
Only after all the other threads have made their images, will any thread try to move the files. I suspect this is wrong.
This is an Amazon EC2 Medium instance, and it appears to max out the CPU, so five threads might be too much for this.
I also find that I can hardly use Windows Explorer while this program is running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static int currThreads = 0;
static void Main(string[] args)
{
var inDir = args[0];
var outDir = args[1]+"\\";
var procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
Thread[] converterThreads = new Thread[threadLimit];
while (true)
{
System.Threading.Thread.Sleep(1000);
var filePaths = Directory.GetFiles(inDir, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".pptx") && !s.Contains("~$") || s.EndsWith(".ppt") && !s.Contains("~$"));
var arrPaths = filePaths.ToArray();
for(var i=0; i< arrPaths.Length; i++)
{
if (currThreads < threadLimit && currThreads < arrPaths.Length)
{
Console.WriteLine("currThreads= " + currThreads + " paths found= " + arrPaths.Length);
try
{
var fileNameWithoutExtension = arrPaths[currThreads].Replace(inDir, "").Replace(".pptx", "").Replace(".ppt", "").Replace("\\", "");
var filenameWithExtension = arrPaths[currThreads].Substring(arrPaths[currThreads].LastIndexOf("\\") + 1);
var dir = arrPaths[currThreads].Replace(".pptx", "").Replace(".ppt", "");
Conversion con = new Conversion(arrPaths[currThreads], dir, outDir, procDir, filenameWithExtension, fileNameWithoutExtension);
converterThreads[i] = new Thread(new ThreadStart(con.convertPpt));
converterThreads[i].Start();
Console.WriteLine(converterThreads[i].ManagedThreadId + " is converting " + fileNameWithoutExtension);
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to convert {0} ", arrPaths[i]) + e);
}
}
}
for (var i = 0; i < converterThreads.Length; i++)
{
if (converterThreads[i] != null)
{
if (!converterThreads[i].IsAlive)
{
converterThreads[i].Abort();
converterThreads[i].Join(1);
Console.WriteLine("thread " + converterThreads[i].ManagedThreadId + " finished, "+currThreads+" remaining");
converterThreads[i] = null;
}
}
}
if (currThreads == 0)
{
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
class Conversion{
static int numberOfThreads=0;
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
int elapsedTime;
System.Timers.Timer time;
public Conversion(String input, String output, String outDir, String processDir, String nameWith, String nameWithout)
{
this.input = input;
this.output = output;
this.outDir = outDir;
process = processDir;
this.nameWith = nameWith;
this.nameWithout = nameWithout;
numberOfThreads++;
Console.WriteLine("number of threads running: " + numberOfThreads);
Program.currThreads = numberOfThreads;
time = new System.Timers.Timer(1000);
time.Start();
time.Elapsed += new ElapsedEventHandler(OnTimedEvent);
elapsedTime = 0;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
elapsedTime++;
}
public void convertPpt()
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
try
{
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed");
}
moveFile();
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
Console.WriteLine("moving dir " + output);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
finally
{
numberOfThreads--;
Program.currThreads = numberOfThreads;
Console.WriteLine("took " + elapsedTime + "seconds");
}
}
}
}
Every 1000ms you get a list of files in inDir and potentially start a thread to process each file. You have very complex logic surrounding whether or not to start a new thread, and how to manage the lifetime of the thread.
The logic is too complex for me to spot the error without debugging the code. However, I would propose an alternative.
Have a single thread watch for new files and place the file path into a BlockingCollection of files for processing. That thread does nothing else.
Have N additional threads that retrieve file paths from the BlockingCollection and process them.
This is known as a Producer / Consumer pattern and is ideal for what you are doing.
The example code at the bottom of the linked MSDN page shows an implementation example.
On a side note, you are catching and swallowing Exception e3. Don't catch something you will not handle, it hides problems.
I have a code that is supposed to start a process in order to render animation. It works great and starts the process and all, but while the process is running, my program says not responding, and freezes refusing to update progress at all.
Here is the code that should be causing the issue:
void Render()
{
while (currentFrame <= lastFrame)
{
bool rendering = IsRendering("cmd");
if (rendering == false)
{
StreamWriter renderBatch = new StreamWriter(batchFile);
renderBatch.Write('"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"');
renderBatch.Close();
var renderProcess = new Process();
renderProcess.StartInfo = new ProcessStartInfo(batchFile);
//renderProcess.StartInfo.Arguments = '"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"';
renderProcess.StartInfo.UseShellExecute = false;
//renderProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
renderProcess.Start();
if (renderProcess.HasExited == true && currentFrame < lastFrame)
{
ProgressBar1.Value = (currentFrame - 1) / lastFrame;
currentFrame++; //goes onto the next frame once it is done rendering this frame
}
}
}
}
Here is the full code that it is in:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Net;
using System.Diagnostics;
using System.IO;
namespace Maya_Network_Render
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Globals ///////////////////////////////////////
string prefFile = "C:\\Program Files\\Maya Render Buddy Preferences\\options.txt";
string batchFile = "C:\\Program Files\\Maya Render Buddy Preferences\\render.bat";
int firstFrame;
int lastFrame;
int currentFrame;
// Globals //////////////////////////////////////
private void Form1_Load(object sender, EventArgs e)
{
if (Directory.Exists("C:\\Program Files\\Maya Render Buddy Preferences"))
{
if (File.Exists(prefFile))
{
StreamReader preferences = new StreamReader(prefFile);
string renderFilePath = preferences.ReadLine();
renderPathField.Text = renderFilePath;
preferences.Close();
}
else
{
File.Create(prefFile);
}
}
else
{
Directory.CreateDirectory("C:\\Program Files\\Maya Render Buddy Preferences");
File.Create(prefFile);
}
}
private void sceneBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog scenefinder = new OpenFileDialog();
scenefinder.Title = "Browse to your Maya scene file";
scenefinder.RestoreDirectory = true;
if (scenefinder.ShowDialog() == DialogResult.OK)
{
sceneFile.Text = scenefinder.FileName;
}
}
private void imageBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog imageFolderSelection = new FolderBrowserDialog();
imageFolderSelection.ShowDialog();
imagePath.Text = imageFolderSelection.SelectedPath;
}
private void renderButton_Click(object sender, EventArgs e)
{
string imageSavePath = imagePath.Text;
string scene = sceneFile.Text;
try
{
if (FirstFrameTextbox.Text != "" && LastFrameTextBox.Text != "") // if the textboxes are filled in then assign them to a variable
{
firstFrame = Convert.ToInt32(FirstFrameTextbox.Text);
lastFrame = Convert.ToInt32(LastFrameTextBox.Text);
if (File.Exists(scene))
{
if (File.Exists(batchFile))
{
currentFrame = firstFrame;
progressMessage.Text = " Rendering Frame " + currentFrame + " of " + lastFrame + " from " + scene;
Render();
}
else
{
File.Create(batchFile); // if there is no batch file then we make one!
currentFrame = firstFrame;
progressMessage.Text = " Rendering Frame " + currentFrame + " of " + lastFrame + " from " + scene;
Render();
}
}
else // if there is not a scene file we let the user know that
{
MessageBox.Show("Please fill in image path, project path and scene file", "Cannot find file");
progressMessage.Text = " ERROR! SCENE FILE OR IMAGE PATH IS MISSING";
}
}
else
{
MessageBox.Show("The numbers entered into the first or last frame fields are invalid", "invalid frame range");
}
}
catch (Exception f)
{
MessageBox.Show(f.ToString() + " Most commonly errors result non numerical input in the frame entry fields", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ChangeRenderPath_Click(object sender, EventArgs e)
{
OpenFileDialog renderfinder = new OpenFileDialog();
renderfinder.Title = "Browse to your Render.exe file";
renderfinder.RestoreDirectory = true;
if (renderfinder.ShowDialog() == DialogResult.OK)
{
StreamWriter preferences = new StreamWriter(prefFile);
renderPathField.Text = renderfinder.FileName;
preferences.Write(renderPathField.Text);
preferences.Close();
}
}
public bool IsRendering(string processName)
{
foreach (Process renderProcess in Process.GetProcesses())
{
if (renderProcess.ProcessName.Contains(processName))
{
return true;
}
}
return false;
}
void Render()
{
while (currentFrame <= lastFrame)
{
bool rendering = IsRendering("cmd");
if (rendering == false)
{
StreamWriter renderBatch = new StreamWriter(batchFile);
renderBatch.Write('"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"');
renderBatch.Close();
var renderProcess = new Process();
renderProcess.StartInfo = new ProcessStartInfo(batchFile);
//renderProcess.StartInfo.Arguments = '"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"';
renderProcess.StartInfo.UseShellExecute = false;
//renderProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
renderProcess.Start();
if (renderProcess.HasExited == true && currentFrame < lastFrame)
{
ProgressBar1.Value = (currentFrame - 1) / lastFrame;
currentFrame++; //goes onto the next frame once it is done rendering this frame
}
}
}
}
private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
{
if (DialogResult.No == MessageBox.Show("If this program is not open it will not assign renders. Would you still like to close?", "You are about to stop rendering!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
{
e.Cancel = true;
}
else
{
foreach (Process renderProcess in Process.GetProcesses())
{
if (renderProcess.ProcessName.Contains("cmd"))
{
renderProcess.Kill();
}
}
}
}
} // form closing brace
}
UI updates need to happen on a different thread than the main process, otherwise it will wait until the entire process is complete before showing you the updated UI.
Since you have a lot of "process" code inside your form there's not a simple fix - you will need to start the processing in another thread and set up events to pass updates back to the UI.