Why does program lag and freeze while starting process? - c#

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.

Related

C# WUApiLib: Failing to Install Updates with 0x80240024 Even Though Updates are Found

I have followed instructions found on this site, which was found when I researched Stack Overflow and found this question. However, I can't seem to figure out why my code is hitting the catch block. I have a break at the IInstallationResult line, which the code hits but then goes to the catch, stating 0x80240024 (There are no updates), even though there are certainly updates available and I list them in the text box.
What am I missing here?
using System;
using System.Windows.Forms;
using WUApiLib;
namespace TEST.DetectWindowsUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetUpdates(bool downloadUpdates, bool installUpdates)
{
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
UpdateCollection updatesToInstall = new UpdateCollection();
UpdateDownloader downloader = uSession.CreateUpdateDownloader();
IUpdateInstaller installer = uSession.CreateUpdateInstaller();
uSearcher.Online = true;
try
{
ISearchResult sResult = uSearcher.Search("IsInstalled=0 And Type='Software'");
lblUpdateCount.Text = sResult.Updates.Count.ToString();
foreach (IUpdate update in sResult.Updates)
{
txtUpdatesList.AppendText("Title: " + update.Title + Environment.NewLine);
txtUpdatesList.AppendText("IsInstalled: " + update.IsInstalled.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("Downloaded: " + update.IsDownloaded.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("IsMandatory: " + update.IsMandatory.ToString() + Environment.NewLine);
txtUpdatesList.AppendText(Environment.NewLine);
if (downloadUpdates)
{
if (update.IsDownloaded == false)
{
do
{
downloader.Updates.Add(update);
downloader.Download();
}
while (update.IsDownloaded == false);
if (update.IsDownloaded == true)
{
updatesToInstall.Add(update);
}
}
else
{
updatesToInstall.Add(update);
}
}
if (installUpdates)
{
installer.Updates = updatesToInstall;
IInstallationResult installationRes = installer.Install();
for (int i = 0; i < updatesToInstall.Count; i++)
{
txtUpdatesList.AppendText("Installing " + updatesToInstall[i].Title + "...");
if (installationRes.GetUpdateResult(i).HResult == 0)
{
txtUpdatesList.AppendText("INSTALL SUCCESS FOR " + updatesToInstall[i].Title);
}
else
{
txtUpdatesList.AppendText("INSTALL FAIL FOR " + updatesToInstall[i].Title);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message + ": " + ex.HelpLink);
}
}
private void btnGetUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(false, false);
}
private void btnInstallUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(true, true );
}
}
}
Turns out it was an issue with privileges. I ran as administrator and it functioned appropriately.

Cannot Convert From Double To String c# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have tried this, but it is giving me an error of "cannot convert from double to string", I wanted to change a variable ProgressBarMegabyte to the equation below.
ProgressBarMegabyte = (Int32.Parse(ProgressBarMegabyte) + Double.Parse(Convert.ToString(ProgressedMegabytes)));
My Whole Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace SoftwareStoreClientDownloader
{
public partial class OfflineInstaller : Form
{
public OfflineInstaller()
{
InitializeComponent();
FormClosing += OfflineInstaller_FormClosing;
}
private void OfflineInstaller_FormClosing(object sender, FormClosingEventArgs e)
{
File.WriteAllText("C:\\Closed.txt", "true");
}
private void OfflineInstaller_Load(object sender, EventArgs e)
{
if (!Directory.Exists("C:\\Program Files\\SoftwareStoreOffline"))
{
Directory.CreateDirectory("C:\\Program Files\\SoftwareStoreOffline");
}
}
private void BrowseButton_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.DefaultExt = "iso";
s.AddExtension = false;
s.CheckPathExists = true;
s.ShowDialog();
try
{
BrowseFileTextBox.Text = s.FileName;
}
catch (Exception dew)
{
}
}
private async void button1_Click(object sender, EventArgs e)
{
var i = 2;
button1.Enabled = false;
button1.Text = "Initializing";
await Initialize();
button1.Text = "Downloading";
TotalProgressBar.Maximum = Int32.Parse(Parts);
if (Int32.Parse(Parts) > 99)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part001.exe",
MainDirectory + "\\" + "Setup-Files.part001.exe");
}
else
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part01.exe",
MainDirectory + "\\" + "Setup-Files.part01.exe");
}
var TotalProgressBytes = ((Int32.Parse(TotalBytes) / 1024d / 1024d) * Int32.Parse(Parts));
var TotalMegabytes = TotalProgressBytes;
var ProgressedMegabytes = (Int32.Parse(TotalBytes) / 1024d / 1024d);
var ProgressBarMegabyte = string.Empty;
ProgressBarMegabyte = ProgressedMegabytes.ToString();
while (i < Int32.Parse(Parts) + 1)
{
if (Int32.Parse(Parts) < 100)
{
if (i < 10)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part0" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part0" + i + ".rar");
}
else
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
}
else if (Int32.Parse(Parts) > 99)
{
if (i < 10 && i < 100)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part00" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part00" + i + ".rar");
}
else if(i > 10 && i < 100)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part0" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part0" + i + ".rar");
}
else if (i > 99)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
}
else if (Int32.Parse(Parts) < 10)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
DownloadProgressLabel.Text = "Status: (" + i + "/" + Parts + ")";
if (i < TotalProgressBar.Maximum)
{
TotalProgressBar.Value = i;
}
if (first == false)
{
TotalProgressLabel.Text = "(" + ProgressBarMegabyte + " MB / " + TotalMegabytes + " MB)";
first = true;
}
else
{
TotalProgressLabel.Text = "(" + ProgressBarMegabyte + " MB / " + TotalMegabytes + " MB)";
}
int Equation = Convert.ToInt32(Int32.Parse(ProgressBarMegabyte) +
Double.Parse(Convert.ToString(ProgressedMegabytes)));
ProgressBarMegabyte = Equation.ToString();
i++;
}
if (Int32.Parse(Parts) > 99)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part001.exe").WaitForExit();
});
}
else if (Int32.Parse(Parts) < 100)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part01.exe");
});
}
else if(Int32.Parse(Parts) < 10)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part1.exe");
});
}
}
private bool first = false;
private string MainDirectory = "C:\\Program Files\\SoftwareStoreOffline";
private string TotalBytes = string.Empty;
private async Task Download(string link, string Filename)
{
using (var client = new WebClient())
{
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadFileAsync(new Uri(link), Filename);
while (client.IsBusy)
{
await Task.Delay(10);
}
}
}
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
}
else if (e.Error != null)
{
}
else
{
}
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
TotalBytes = e.TotalBytesToReceive.ToString();
DownloadProgressBar.Value = e.ProgressPercentage;
}
private string Parts = string.Empty;
private string Database = string.Empty;
private string Version = string.Empty;
private async Task Initialize()
{
try
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineDatabaseNumber.txt",
MainDirectory + "\\OfflineDatabaseNumber.txt");
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineParts.txt",
MainDirectory + "\\OfflineParts.txt");
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineVersion.txt",
MainDirectory + "\\OfflineVersion.txt");
Parts = File.ReadLines(MainDirectory + "\\OfflineParts.txt").First();
Database = File.ReadLines(MainDirectory + "\\OfflineDatabaseNumber.txt").First();
Version = File.ReadLines(MainDirectory + "\\OfflineVersion.txt").First();
}
catch (Exception dew)
{
Console.WriteLine(dew);
throw;
}
}
}
}
I'm trying to use that equation, because I wanted to solve the progress bar, which I eventually figured out. I used the int
Instead of using the Convert.ToString()
you can simply do: ProgressedMegabytes.ToString()
You problem is with different types:
ProgressBarMegabyte is a string
ProgressedMegabytes is double as you said.
Then your assignent is:
sting = int + double
Hence you error. To fix it - simply convert the result to string:
double ProgressedMegabytes = 1.5;
string ProgressBarMegabyte = "83345603 .....................";
ProgressBarMegabyte = (Int32.Parse(ProgressBarMegabyte.TrimEnd('.')) + ProgressedMegabytes).ToString();
Console.WriteLine(ProgressBarMegabyte); // 83345604.5
And be careful with the value of ProgressBarMegabyte - you are working with an assumption that it is a number!
This is not an answer to your question - I just wanted to post a refactored version of your code that might help you to move forward.
private async void button1_Click(object sender, EventArgs e)
{
var i = 2;
await Initialize();
var name = Parts > 99 ? "part001" : "part01";
await Download($"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline{Database}/master/SoftwareStore{Version}Setup-Files.{name}.exe", $"{MainDirectory}\\Setup-Files.{name}.exe");
var format = new string('0', Parts.ToString().Length)
while (i < Parts + 1)
{
await Download($"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline{Database}/master/SoftwareStore{Version}Setup-Files.part{i.ToString(format)}.rar", $"{MainDirectory}\\Setup-Files.{i.ToString(format)}.rar");
i++;
}
await Task.Factory.StartNew(() =>
{
Process.Start($#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part{1.ToString(format)}.exe").WaitForExit();
});
}
private string MainDirectory = "C:\\Program Files\\SoftwareStoreOffline";
private async Task Download(string link, string Filename)
{
using (var client = new WebClient())
{
await client.DownloadFileTaskAsync(link, Filename);
}
}
private int Parts;
private string Database = string.Empty;
private string Version = string.Empty;
private async Task Initialize()
{
try
{
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineDatabaseNumber.txt", MainDirectory + "\\OfflineDatabaseNumber.txt");
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineParts.txt", MainDirectory + "\\OfflineParts.txt");
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineVersion.txt", MainDirectory + "\\OfflineVersion.txt");
Parts = int.Parse(File.ReadLines(MainDirectory + "\\OfflineParts.txt").First());
Database = File.ReadLines(MainDirectory + "\\OfflineDatabaseNumber.txt").First();
Version = File.ReadLines(MainDirectory + "\\OfflineVersion.txt").First();
}
catch (Exception dew)
{
Console.WriteLine(dew);
throw;
}
}
I solved the problem myself using cheap methods:
int Equation = Convert.ToInt32(Int32.Parse(ProgressBarMegabyte)
+ Double.Parse(Convert.ToString(ProgressedMegabytes)));
ProgressBarMegabyte = Equation.ToString();

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";
}

Try to launch an application from another application continue to crash

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

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);
}

Categories