How to get the newly opened apps WPF - c#

Is there any way to get the newly open apps? I have a function that gets the running apps every 10 seconds, place them on a listbox and sends them to the other window if you click the send button.
What I wanted to happen is to get the newly opened app and send it to the other window. For example:
for the first 10 secs, I have opened notepad and chrome, after clicking send, those two will be sent to the other window. For the next 10 secs, I opened another app which is firefox. So my opened apps are now notepad, chrome and firefox so when I click send, I only want firefox to be sent to the other window so it wouldn't be redundant. Is this even possible?
There's the codes, in case if it brings of any help.
private void SendData()
{
String processID = "";
String processName = "";
String processFileName = "";
String processPath = "";
string hostName = System.Net.Dns.GetHostName();
listBox1.BeginUpdate();
try
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
try
{
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + " " + processID + " " + processPath + " " + processFileName + " " + hostName;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}

Store the Id of previously sent processes in a list and only send the process info of a process if it's id is not in the list.
private List<int> listedProcesses = new List<int>();
//...
try
{
if(!listedProcesses.Contains(piis[i].Id)
{
listedProcesses.Add(piis[i].Id);
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
}
//...
Also: when you close processes these two lines will no longer be valid:
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
Because the number of processes can now be lower than the number of items in the listbox.
To keep them in sync you will also have to remove items from the listbox when processes are closed.
To fix it even more efficient (and easier) you could simply clear the listbox and add a new item for each process returned by GetAllProcessInfos();

Have a hook as described here: How to hook into application and process startup in windows?
using System.Management;
// Run this in another thread and make sure you dispose the event watcher before exit
var start = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
start.EventArrived += new EventArrivedEventHandler(delegate (object sender, EventArrivedEventArgs e) {
console.WriteLine("Name: {0}, Command Line: {1}", e.NewEvent.Properties["ProcessName"].Value, e.NewEvent.Properties["Commandline"].Value);
});
start.Start()

Related

How to fix issue of zkemkeeper.dll realtime events inside windows service?

i'm setting up windows service and want it to sync the device attendance to SQL Server database using zkemkeeper real time event. i have successfully created service as well as tested the service on my local system which run windows 10 and another one window 8 service work fine and sync the attendance record to DB server at real time. Now after successful testing on local system i deployed service over production server where service successfully established the connection with device but it didn't respond to Real time event for testing purpose i have created winform app and run it over the server and find out it is working and listening to real time event but i need service to work properly not win form application any help will be appreciated thanks below is my code !
public partial class AttendanceSyncService_405 : ServiceBase
{
public AttendanceSyncService_405()
{
InitializeComponent();
}
System.Timers.Timer timer = new System.Timers.Timer();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
protected override void OnStart(string[] args)
{
//var thread = new Thread();
//thread.SetApartmentState(ApartmentState.STA);
//thread.Start();
WriteToFile("Service is started at " + DateTime.Now);
Connect();
// LoadCurrentMonthAtt();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 900000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
if (bIsConnected == true)
{
WriteToFile("Service recall at " + DateTime.Now);
WriteToFile("Device Status Connected at " + DateTime.Now);
}
else
{
WriteToFile("Device Status DisConnected at " + DateTime.Now);
WriteToFile("Service recall at " + DateTime.Now);
Connect();
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
private void Connect()
{
try
{
int idwErrorCode = 0;
bIsConnected = axCZKEM1.Connect_Net("192.168.0.177", 4370);
if (bIsConnected == true)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
iMachineNumber = 1;
if (axCZKEM1.RegEvent(iMachineNumber, 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);
}
else
{
WriteToFile("RT Events didn't registered at " + DateTime.Now);
}
axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
WriteToFile("Device Connection Established Successfully at " + DateTime.Now);
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
WriteToFile("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString() + " at " + DateTime.Now);
}
}
catch(Exception ex)
{
WriteToFile("Exception :" + ex.Message + " at " + DateTime.Now);
}
}
private 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)
{
DateTime Attendancedate = new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond);
string row = sEnrollNumber + "," + Attendancedate.ToString();
WriteToFile("Attendane :" + row + " Marked At: " + DateTime.Now);
if (bIsConnected == false)
{
Connect();
return;
}
decimal empserial = decimal.Parse(sEnrollNumber);
attInsert(empserial, Attendancedate);
}
private void attInsert(decimal empserial, DateTime Attendancedate)
{
try
{
WriteToFile("Attendance Entry Arrived for EMP-Serial :" + empserial + " At: " + DateTime.Now + " for Insertion");
DBAccess db = new DBAccess();
DataSet attCount = db.GetDataSetFromQuery("select Count(att.[todayCount]) as attCount from tblAttendance att where (att.attDate = Convert(date,GETDATE()) AND att.fkSerial ='" + empserial.ToString() + "')");
int count = int.Parse(attCount.Tables[0].Rows[0]["attCount"].ToString());
Boolean INOUT = (count % 2 == 0) ? true : false;
WriteToFile("Attendane Count :" + count + " & In/Out : " + INOUT + " Marked At: " + DateTime.Now);
db.Parameters.AddWithValue("fkSerial", empserial);
db.Parameters.AddWithValue("attTerminalId", "Time1");
db.Parameters.AddWithValue("attDateTime", Attendancedate);
db.Parameters.AddWithValue("attTgId", 3);
db.Parameters.AddWithValue("attINOUT", INOUT);
db.Parameters.AddWithValue("attEmpCode", "no need");
db.ExecuteNonQuery("spInsertAttendance");
WriteToFile("Attendance Inserted of EMP-Serial :" + empserial + " At: " + DateTime.Now);
}
catch (Exception ex)
{
WriteToFile("Exception in insert method :" + ex.Message + " At: " + DateTime.Now);
}
}
}
Type This Code in Your IntializeComponent and it will respond to realtime events
private void InitializeComponent()
{
Thread createComAndMessagePumpThread = new Thread(() =>
{
axCZKEM1 = new zkemkeeper.CZKEMClass();
bool connSatus = axCZKEM1.Connect_Net(192.168.0.177, 4370);
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);
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}

C# Multiple Ping start and overlap their Results

I have created a code that will continously test the if the connection is available and is supposed to be able to change the IP and always needs to run so it can show in a notificion if the connection is available or not. I can execute it with no errors but when I click the send button again it starts another ping that will also put the results in the label box overlapping each other. I am open to all sugestions to fixing this.
private async void Button1_Click(object sender, EventArgs e) //send button
{
int unterbrechung = 0;
await Task.Delay(12);
//Erstellen Variablen
string value = (comboBox1.SelectedItem as dynamic).Value;
double laufzeit = 0;
double delayins = 0;
int delay = 1000;
int onetimebubble = 1; //Zum verhindern von wieder erscheinen der Warnmeldung
//Zum verhindern das MiniIcon ein weiterers mal zu ändern.
int onetimeminired = 0;
int onetimeminigreen = 0;
//Ping Variablen deklarieren und setzen
Ping pingSender = new Ping();
PingOptions options = new PingOptions
{
DontFragment = true
};
pingSender.SendAsyncCancel();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
unterbrechung = 1;
//Ping senden und bei fehler entsprechende meldung anzeigen
while (unterbrechung == 1)
{
try
{
//Ping ausführen und Ausgabe meldung
PingReply reply = pingSender.Send(value, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
labelOutput.Text = "Address :" + reply.Address.ToString() + " " + Environment.NewLine +
"Status :" + reply.Status + " " + Environment.NewLine +
"Laufzeit in s :" + laufzeit;
labelOutput.BackColor = System.Drawing.Color.Green;
//Reset der Variable
if (onetimeminigreen == 0)
{
//ändern Symbol + vorheriger test
minIcon.Icon = Properties.Resources.Symbol2;
onetimeminigreen = 1;
onetimeminired = 0;
}
if (onetimebubble == 0)
{
onetimebubble = 1;
}
}
}
catch(PingException)
{
//Reset Laufzeit
laufzeit = 0;
//ausgabe fehlermeldung
labelOutput.Text = "Address :" + value + " " + Environment.NewLine +
"Status :Failed" + Environment.NewLine +
"Laufzeit in s :" + laufzeit;
labelOutput.BackColor = System.Drawing.Color.Red;
await Task.Delay(10);
if (onetimeminired == 0)
{
//ändern Symbol + vorheriger test
minIcon.Icon = Properties.Resources.Symbol1;
onetimeminigreen = 0;
onetimeminired = 1;
}
if (onetimebubble == 1)
{
//ausgabe Warnmeldung + vorheriger test
minIcon.BalloonTipIcon = ToolTipIcon.Error;
minIcon.BalloonTipTitle = "Ping Failed!";
minIcon.BalloonTipText = "Sie haben keine verbindung zu ihrem Host";
minIcon.ShowBalloonTip(1000);
onetimebubble = 0;
}
}
//Ausführen delay
await Task.Delay(delay);
//erechnen des Delay in sekunden und laufzeit berechnung
delayins = delay / 1000;
laufzeit = laufzeit + delayins;
}
}
EDIT Forgot the Question. How do I change my programm in the way that if I click the button again it cancels all other pings I started before. that "unterbrechung" was something I tried to achieve that but failed.
Encapsulate pinging
As Fildor suggested I added a new class for the Ping that simply returns the result
public bool Ping(string ipaddress)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions
{
DontFragment = true
};
int timeout = 120;
pingSender.SendAsyncCancel();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
try
{
PingReply reply = pingSender.Send(ipaddress, timeout, buffer, options);
if(reply.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}
}
catch (PingException)
{
return false;
}
}
METHOD PING AND UI CHANGES As Fildor also suggested I now added a method that will execute the ping and also the change the UI according to the Pings Result
private void ExecPingAndChangeUI()
{
runtime = 0; //reset runtime
delayins = interval / 1000; // umwandeln in Sekunden
if (comboBox1.SelectedItem != null) //Überprüfen ob ein Element in der Combobox ausgewählt wurde
{
value = (comboBox1.SelectedItem as dynamic).Value; //Auslesen der Combobox
status = Ping(value); //Auslesen des Ping ergebnisses
if (status == true)
{
//Ausgabe an OutputLabel
labelOutput.Text = "Address : " + Environment.NewLine + value + Environment.NewLine + Environment.NewLine +
"Status : " + Environment.NewLine + "Success" + Environment.NewLine + Environment.NewLine +
"Laufzeit in s: " + Environment.NewLine + runtime + "s";
labelOutput.BackColor = System.Drawing.Color.Green;
if (minIcon.Icon != Properties.Resources.Symbol2) //ändern Symbol + Test ob symbol schon das ausgewählte ist
{
minIcon.Icon = Properties.Resources.Symbol2;
}
if (onetimebubble == false)
{
onetimebubble = true;
}
runtime = runtime + delayins; //laufzeit berechnung
}
else if (status == false)
{
runtime = 0; //Reset Laufzeit
//Ausgabe an OutputLabel
labelOutput.Text = "Address : " + Environment.NewLine + value + Environment.NewLine + Environment.NewLine +
"Status : " + Environment.NewLine + "Failed" + Environment.NewLine + Environment.NewLine +
"Laufzeit in s: " + Environment.NewLine + runtime + "s";
labelOutput.BackColor = System.Drawing.Color.Red;
if (minIcon.Icon != Properties.Resources.Symbol1) //ändern Symbol + vorheriger test
{
minIcon.Icon = Properties.Resources.Symbol1;
}
if (onetimebubble == true) //ausgabe Warnmeldung + vorheriger test
{
minIcon.ShowBalloonTip(1000);
onetimebubble = false;
}
runtime = runtime + delayins; //laufzeit berechnung
}
}
else
{
labelOutput.Text = "Bitte ein Element auswählen!"; //falls nichts in der Combobox ausgewählt wurde
}
}
I would like to recommend a "little" refactoring of that code:
Encapsulate pinging
Write a class that has only one purpose: Send a ping and return the result.
If the Ping class is a high enough abstraction for you, I would make an instance a private class property, that will be configured by the method of point 1 in next paragraph.
Introduce a Timer
Since you want to do recurring ping, it seems reasonable to use a Timer for that. This implies following steps:
Have a method that uses above mentioned ping class to execute the ping and updates the UI according to the delivered result. It should gather all needed information to execute the ping ( target, data ... ) so you can change ping target on the fly and it will be reflected accordingly when the next tick fires.
Change the contents of the button_click handler and the containing class as such:
2.1. have a property of type Timer. (default = null)
2.2. on button click:
2.2.1. check if timer property is not null:
True - stop timer and null property ( = stop pinging ),
False - go on
2.2.2. Create a Timer , set timer property to reference that and start it. The timer's tick shall execute the method of point 1.
Remarks
You may want to have a second button to explicitly stop pinging without starting a new ping. Hint: You could use a ToggleButton and use its state information to decide whether to start or stop pinging.
Note: The timer may execute it's tick handler (method from point 1.) on a separate thread depending on what timer implementation you use. So you may need to marshal UI-Updates to the UI thread. There are several possible methods to do that. I advise you to do the research yourself, as you stated you are a novice coder. You will learn a lot in the course.
Also, you may want to make sure that when the timer fires a tick, the last ping has returned (so they won't overlap).
Note: In order to improve this answer, I will add some references for you to start with later, when I'm at home.
Timer: see https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx (Code example inside)
You can add a line of code at the beginning and at the end of your method to enable/disable
private async void Button1_Click(object sender, EventArgs e)
{
Button1.Enabled = false;
....
....
....
Button1.Enabled = true;
}
This should work fine with async/await.

start and stop data saving on .txt file using button on c#

I have a sensor that connected to pc and data comes continuously like this picture:
I want to add two start and stop button and save data from start button pressed time and stop saving data when pressed stop button.
I write this code:
richTextBox1.AppendText(textBox1.Text + "\n");
System.IO.File.WriteAllLines(#"C:\Users\Mohammad_Taghi\Desktop\a.txt",richTextBox1.Lines);
but this code save whole of data in .txt file and is not controllable.
this is that part of code on richtextbox2:
public void detectFingers(Leap.Frame frame)
{
foreach(Finger finger in frame.Fingers)
{
richTextBox2.AppendText("Finger ID: " + finger.Id + Environment.NewLine +
"Finger Type: " + finger.Type + Environment.NewLine +
"Finger Length:" + finger.Length + Environment.NewLine +
"Finger width:" + finger.Width + Environment.NewLine);
foreach (Bone.BoneType boneType in (Bone.BoneType[])Enum.GetValues(typeof(Bone.BoneType)))
{
Bone bone = finger.Bone(boneType);
richTextBox3.AppendText("Bone Type: " + bone.Type +Environment.NewLine +
"Bone Length: " +bone.Length +Environment.NewLine+
"Bone Width : " + bone.Width +Environment.NewLine +
"Previous Joint : "+bone.PrevJoint + Environment.NewLine+
"Next Joint :" + bone.NextJoint + Environment.NewLine+
"Direction : " + bone.Direction + Environment.NewLine+;
}
}
}
As data comes in continuously you need to save from when the data should be stored uptil when. Printing the textBox1.Text will, of course, print everything.
You need to set a variable to store the information after the "Start" button is pressed until the "Stop" button is pressed. Here is some code:
private bool isLogging = false;
private string myLog = "";
//This is where the input from the sensor arrives
private void myInput(string s)
{
textBox1.Text += s + "\n";
if (isLogging)
myLog += s + "\n";
}
private void buttonOnStart_Click(object sender, EventArgs e)
{
//Clear log string
myLog = "";
//Start logging
isLogging = true;
}
private void buttonOnStop_Click(object sender, EventArgs e)
{
//Stop logging
isLogging = false;
//Pring only the logged messages
System.IO.File.WriteAllLines(#"C:\Users\Mohammad_Taghi\Desktop\a.txt", myLog);
}

Why does program lag and freeze while starting process?

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.

Does anyone have an idea why this could happen??The same code not working in different PC'S?? Could this be a PostgreSQL issue?

Hi I've used the below code in C# to take the backup of a database in PostgreSQL.This code runs when the backup button is clicked
private void lnkSCBackup_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Postgre backups (*.backup)|*.backup";
save.ShowDialog();
if (save.FileName != "")
{
string saveFileName = "\"" + save.FileName + "\"";
string host = S ystem.Configuration.ConfigurationSettings.AppSettings["HOST"].ToString().Trim();
string port = System.Configuration.ConfigurationSettings.AppSettings["PORT"].ToString().Trim();
string userName = System.Configuration.ConfigurationSettings.AppSettings["USERNAME"].ToString().Trim();
string password = System.Configuration.ConfigurationSettings.AppSettings["PASSWORD"].ToString().Trim();
string dataBase = System.Configuration.ConfigurationSettings.AppSettings["DATABASE"].ToString().Trim();
try
{
string Creten = "pg_dump -h " + host + " -U " + userName + " -p " + port + " -F c -b -v " + dataBase + " > " + saveFileName;
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + Creten);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
//Gets the total processing time for this particular process
string totalProcessingTime = proc.TotalProcessorTime.Ticks.ToString();
//progress bar working
progressBar1.Visible = true;
progressBar1.BringToFront();
progressBar1.Minimum = 0;
progressBar1.Maximum = int.Parse(totalProcessingTime);
progressBar1.Step = 500;
progressBar1.Value = 0;
this.lblBackup.Visible = true;
this.lblBackup.Text = "Backing Up Database";//To show the user it is backing up
this.lblBackup.Font = new Font("Microsoft Sans Serif", 9, System.Drawing.FontStyle.Regular);
this.Refresh();
while (progressBar1.Value < progressBar1.Maximum)
{
progressBar1.Value += 10;//= 10000;
}
progressBar1.Visible = false;
this.lblBackup.Visible = false;
int exitCode = proc.ExitCode;
if (exitCode.Equals(0))
{
MessageBox.Show(" Backup Success ");
}
else
{
MessageBox.Show(" Backup not Success ");
}
}
catch (Exception objException)
{
// Log the exception
}
}
Now my problem is this part of code works fine in my system and the backup is taken properly.
But does not work in another system it finally comes and gets stuck in statement
string result = proc.StandardOutput.ReadToEnd();
Does anyone have an idea why this could happen??The same code not working in different PC'S??? Could this be a PostgreSQL issue
Thanks in advance!!!!
It's not all strange that "The same code not working in different PC'S", as different machines can have different environments. For one thing, your are invoking the system command
pg_dump -h " + host + " -U " + userName + " -p " + port + " -F c -b -v " + dataBase
Have you checked that it works in the second machine? (i.e. pg_dump is in your path AND you can connect to your pg DB with those parameters)?

Categories