I have a DotNetZip code for zipping the folder. It doesnt zip the file for the first time after cleaning the solution. After that it works fine. Can anybody know the issue why its happening??
Button Click Event Code
private void button3_Click(object sender, EventArgs e)
{
try
{
copy_stuff(textBox1.Text, textBox2.Text, textBox3.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Method that gets called from Button Click
private void copy_stuff(string srcFolder, string destFolder, string Backup)
{
using (ZipFile zip = new ZipFile())
{
zip.AddProgress += AddProgressHandler;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
zip.SaveProgress += SaveProgress;
zip.StatusMessageTextWriter = System.Console.Out;
zip.AddDirectory(destFolder);
zip.Save(Backup + "\\VibrantBackup" + DateTime.Now.ToString("yyyyMMdd hh.mm.ss") + ".zip");
label1.Text = "Compression completed.";
}
}
Add & Save Handlers for Progress
int _numEntriesToAdd = 0;
int _numEntriesAdded = 0;
void AddProgressHandler(object sender, AddProgressEventArgs e)
{
switch (e.EventType)
{
case ZipProgressEventType.Adding_Started:
_numEntriesToAdd = 0;
_numEntriesAdded = 0;
label1.Text = "Adding files to the zip...";
label1.Update();
Application.DoEvents();
break;
case ZipProgressEventType.Adding_AfterAddEntry:
_numEntriesAdded++;
label1.Text = String.Format("Adding file: {0} :: {2}",
_numEntriesAdded, _numEntriesToAdd, e.CurrentEntry.FileName);
label1.Update();
Application.DoEvents();
break;
case ZipProgressEventType.Adding_Completed:
label1.Text = "Added all files";
label1.Update();
Application.DoEvents();
break;
}
}
public void SaveProgress(object sender, SaveProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Saving_Started)
{
label1.Text = "Begin Saving: " + e.ArchiveName;
label1.Update();
Application.DoEvents();
}
else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
{
label1.Text = "Processing : " + e.CurrentEntry.FileName;
label1.Update();
label3.Text = "Files Processed: (" + (e.EntriesSaved + 1) + "/" + e.EntriesTotal + ")";
label3.Update();
Application.DoEvents();
progressBar3.Maximum = e.EntriesTotal;
progressBar3.Value = e.EntriesSaved + 1;
}
else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
{
//progressBar2.Value = (int)((e.BytesTransferred * 100) / e.TotalBytesToTransfer);
//label3.Text = "Writing: " + e.CurrentEntry.FileName + " (" + (e.EntriesSaved + 1) + "/" + e.EntriesTotal + ")";
label1.Update();
Application.DoEvents();
}
}
Related
I am trying to decompile over 30k vulkan shader files using shaderc from google.
All shaders are located in "C:\Users\Admin\Desktop\NMS MOD\SHADER MOD\v2.41\PC"
The tool used to decompile is spirv-cross.exe which I added to Windows Environment variables, which lets me run this simple bat file inside the shaders folder and works fine.
"spirv-cross --version 450 --vulkan-semantics --stage frag ATMOSPHERE_FRAG_CLOUD_769.SPV > ATMOSPHERE_FRAG_CLOUD_769.GLSL"
Since there is way too many to do this manually. I want to make a simple App to do this process and also get the stage type from file name (in this case "frag").
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Lazy_Me_3
{
public partial class Form1 : Form
{
public string PATH;
public string[] sFilesNames;
public int totalcount = 0;
public int currentcount = 0;
public Form1()
{
InitializeComponent();
}
private string GetStageType(string filename)
{
// Valid Stages = vertex, vert, fragment, frag, tesscontrol, tesc, tesseval, tese, geometry, geom, compute, comp
if (filename.Contains("_VERTEX_") || filename.Contains("_VERT_")) return "vert";
if (filename.Contains("_FRAGMENT_") || filename.Contains("_FRAG_")) return "frag";
if (filename.Contains("_TESSCONTROL_") || filename.Contains("_TESC_")) return "tesc";
if (filename.Contains("_TESSEVEL_") || filename.Contains("_TESE_")) return "tese";
if (filename.Contains("_GEOMETRY_") || filename.Contains("_GEOM_")) return "geom";
if (filename.Contains("_COMPUTE_") || filename.Contains("_COMP_")) return "comp";
else return "error";
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < sFilesNames.Count(); i++)
{
sFilesNames[i] = Path.GetFileName(sFilesNames[i]);
if (sFilesNames[i].Length > 1)
{
var newName = sFilesNames[i].Substring(0, sFilesNames[i].Length - 4);
sFilesNames[i] = newName;
}
}
foreach (var file in sFilesNames)
{
string stageType = GetStageType(file);
if (stageType != "error")
{
string args = "--version 450 --vulkan-semantics --stage " + stageType + " " + file + ".SPV" + " > " + file + ".GLSL";
Process process = new Process();
process.StartInfo.FileName = "spirv-cross";
process.StartInfo.Arguments = args;
process.StartInfo.WorkingDirectory = PATH;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit(5000);
currentcount += 1;
label1.Text = "Status : " + currentcount.ToString() + " / " + totalcount.ToString();
}
else MessageBox.Show("Error on finding stage type of file : " + file);
}
}
private void button2_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
sFilesNames = Directory.GetFiles(fbd.SelectedPath, "*.SPV");
totalcount = sFilesNames.Length;
PATH = fbd.SelectedPath;
label3.Text = "Directory : " + PATH;
label2.Text = "Total Count : " + totalcount.ToString();
label1.Text = "Status : 0 / " + totalcount.ToString();
button1.Enabled = true;
}
}
}
}
}
EDIT 1 : Bodge using cmd that works
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < sFilesNames.Count(); i++)
{
//sFilesNames[i] = Path.GetFileName(sFilesNames[i]);
if (sFilesNames[i].Length > 1)
{
var newName = sFilesNames[i].Substring(0, sFilesNames[i].Length - 4);
sFilesNames[i] = newName;
}
}
foreach (var file in sFilesNames)
{
string stageType = GetStageType(file);
if (stageType != "error")
{
var p = new ProcessStartInfo("cmd", #"/c spirv-cross --version 450 --vulkan-semantics --stage " + stageType + " " + file + ".SPV" + " > " + file + ".GLSL");
p.UseShellExecute = false;
p.CreateNoWindow = true;
var ps = Process.Start(p);
ps.WaitForExit();
currentcount += 1;
label1.Text = "Status : " + currentcount.ToString() + " / " + totalcount.ToString();
}
else
{
errorcount += 1;
label4.Text = "Errors : " + errorcount.ToString();
}
}
}
I am running multiple instances of an application that reads first line from a file, then it deletes the first line and saves the file under the same name. I found out that in some instances the applications will crash. I created a sample program just to better understand the issues I have.
If I run four instances of this program, sometimes multiple instances attempt to delete the same line. In the end the operation succeeds, but it is not efficient. How can I improve the code to avoid this? Perhaps each instance needs to lock the file while it uses it.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace ConcurrentFileAccess
{
public partial class MainForm : Form
{
bool gbAbort = false;
public MainForm()
{
InitializeComponent();
}
void BtnCreateFileClick(object sender, EventArgs e)
{
string sFile = #"S:\Temp\concurrentFileAccess.txt";
Stopwatch stopwatch = Stopwatch.StartNew();
if (File.Exists(sFile)) {
File.Delete(sFile);
}
if (!File.Exists(sFile)) {
List<string> list = new List<string>();
var fc = File.Create(sFile);
fc.Close();
for (int i = 1; i <= 200; i++) {
list.Add(i.ToString());
}
File.WriteAllLines(sFile, list);
listBox1.Items.Add("File " + sFile + " was created and it contains 200 lines");
} else {
string[] lines = File.ReadAllLines(sFile);
int nlines = lines.Length;
listBox1.Items.Add("File " + sFile + " already exists and it contains " + nlines + " lines");
}
stopwatch.Stop();
listBox1.Items.Add("File created in " + stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.fff"));
}
void BtnDeleteFromFileClick(object sender, EventArgs e)
{
gbAbort = false;
int nlines = 9999;
while (nlines > 0) {
nlines = DeleteOneLine();
Application.DoEvents();
if (gbAbort) {
return;
}
}
}
int DeleteOneLine()
{
string sFile = #"S:\Temp\concurrentFileAccess.txt";
listBox1.Items.Add("We are in DeleteLines()...");
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
int nLinesLeft = 9999;
string line0 = string.Empty;
Stopwatch stopwatch = Stopwatch.StartNew();
int ntry = 0;
while (ntry < 100) {
try {
string[] lines = File.ReadAllLines(sFile);
List<string> list = new List<string>(lines);
nLinesLeft = list.Count;
if (nLinesLeft > 0) {
line0 = list[0];
list.RemoveAt(0);
listBox1.Items.Add("Deleted line " + line0);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
listBox1.Items.Add("Writing to file after line " + line0 + " was deleted");
File.WriteAllLines(sFile, list);
nLinesLeft = list.Count;
Application.DoEvents();
} else {
nLinesLeft = 0;
break;
}
} catch (Exception) {
ntry++;
listBox1.Items.Add("ntry = " + ntry + ", could not delete line " + line0 + " from file. Attempting again...");
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
Application.DoEvents();
Thread.Sleep(50);
}
}
if(ntry >= 100) {
nLinesLeft = -1; // should never get here
}
stopwatch.Stop();
listBox1.Items.Add("ntry: " + ntry + ", lines Left: " + nLinesLeft + ", elapsed = " + stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.fff"));
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
return nLinesLeft;
}
void BtnAbortClick(object sender, EventArgs e)
{
gbAbort = true;
}
void BtnOpenAppFolderClick(object sender, EventArgs e)
{
string sFile = Application.ExecutablePath;
string sPath = Path.GetDirectoryName(sFile);
Process.Start(sPath);
}
void BtnOpenFileClick(object sender, EventArgs e)
{
string sFile = #"S:\Temp\concurrentFileAccess.txt";
if(File.Exists(sFile)) {
Process.Start(sFile);
}
else {
MessageBox.Show("File " + sFile + " not found");
}
}
}
}
I'm developing a sample program to connect multiple device using backgroundworker. Each device connected will be add to the list as new object. After finished connecting all the devices, i wanted to add an event handler for each connected devices. The problem that i'm facing now is the event handler doesn't firing at all. Below are the sample codes.
The Connect click button event :
private void btnConnect_Click(object sender, EventArgs e)
{
using (BackgroundWorker m_oWorker = new BackgroundWorker())
{
m_oWorker.DoWork += delegate (object s, DoWorkEventArgs args)
{
int iIpStart = 0;
int iIpEnd = 0;
string strIp1 = string.Empty;
string strIp2 = string.Empty;
list.Clear();
string[] sIP1 = txtIpStart.Text.Trim().ToString().Split('.');
string[] sIP2 = txtIpEnd.Text.Trim().ToString().Split('.');
iIpStart = Convert.ToInt32(sIP1[3]);
iIpEnd = Convert.ToInt32(sIP2[3]);
strIp1 = sIP1[0] + "." + sIP1[1] + "." + sIP1[2] + ".";
strIp2 = sIP2[0] + "." + sIP2[1] + "." + sIP2[2] + ".";
Ping ping = new Ping();
PingReply reply = null;
int iIncre = 0;
int iVal = (100 / (iIpEnd - iIpStart));
for (int i = iIpStart; i <= iIpEnd; i++)
{
Thread.Sleep(100);
string strIpconnect = strIp1 + i.ToString();
Console.Write("ip address : " + strIpconnect + ", status: ");
reply = ping.Send(strIpconnect);
if (reply.Status.ToString() == "Success")
{
if (ConnectDevice(strIpconnect))
{
strLastDevice = strIpconnect + " Connected";
isconnected = true;
}
else
{
isconnected = false;
}
}
else
{
isconnected = false;
}
m_oWorker.ReportProgress(iIncre);
iIncre = iIncre + iVal;
}
m_oWorker.ReportProgress(100);
};
m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
}
ConnectDevice function method. Connected device will be added to the list :
protected bool ConnectDevice(string sIP)
{
try
{
NewSDK sdk = new NewSDK();
if (sdk.Connect() == true)
{
list.Add(new objSDK { sdk = sdk, ipaddress = sIP });
return true;
}
else
{
}
}
catch() {}
return false;
}
the Backgroundworker :
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//If it was cancelled midway
if (e.Cancelled)
{
lblStatus.Text = "Task Cancelled.";
}
else if (e.Error != null)
{
lblStatus.Text = "Error while performing background operation.";
}
else
{
lblStatus.Text = "Task Completed...";
btnListen.Enabled = true;
}
}
void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Here you play with the main UI thread
progressBar1.Value = e.ProgressPercentage;
lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";
if (isconnected)
{
listBox2.Items.Add(strLastDevice);
string[] ssplit = sDeviceInfo.Split(';');
foreach (string sword in ssplit)
{
listBox1.Items.Add(sword);
}
}
}
The function to attached event :
private void RegisterEvent()
{
foreach (objSDK obj in list)
{
obj.sdk.OnTransaction += () =>
{
listBox1.Items.Add("ip : " + obj.IP + " transaction");
};
}
}
You have declared m_oWorker as a local variable. I'm guessing this was a mistake ( the m_ prefix should only be used for class member variables)?
Also, you declared it within a using statement, meaning that it that the framework will call Dispose() on it at the end of the using block. Even if you held on to a reference to it (and I don't think you do) it still means its resources will be deallocated, which is probably why it isn't handling any events.
I try another workaround by using thread and task and work perfectly. Thanks for all response
Halllo
I have made my first project and it works, well sort of, I can not get it to close serial port.
I am running 200hz in the Serialmonitor and the save funktion works perfect.
I suspect that it attempts to read data while I am trying to close the port.
It does not come up with an error but hanging in the debugger trying to close the port.
MY CODE IN VISUAL STUDIO 2015:
using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace Arduino_Serial
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data1;
private int runtime_sec = 0;
private float runtime_milis = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click_1(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = Port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += Myport_DataReceived;
try
{
myport.Open();
timer2.Enabled = true;
timer1.Enabled = true;
Data_tb.Text = "\"Arduino\"" + "\n";
Data_tb.AppendText("Time" + "\t" + "Raw_data" + "\t" + "MAP" + "\n");
Data_tb.AppendText("Sec " + "\t" + "Raw_data" + "\t" + "KPA" + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
void Myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data1 = myport.ReadLine();
Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
Data_tb.AppendText(("\n")+ (runtime_milis) + ("\t")+ in_data1 );
}
private void Stop_bt_Click(object sender, EventArgs e)
{
try
{
myport.ReadTimeout = 1000000000;
myport.Close();
timer2.Enabled = false;
timer1.Enabled = false;
runtime_milis = 0;
runtime_sec = 0;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void Save_bt_Click(object sender, EventArgs e)
{
try
{
datetime = DateTime.Now;
String time = datetime.Year + "-"+ datetime.Month + "-"+ datetime.Day + "_" + datetime.Hour + "." + datetime.Minute + "." + datetime.Second;
string pathfile = #"C:\DATA\";
string filename = "Arduino_" + time + ".msl";
System.IO.File.WriteAllText(pathfile + filename, Data_tb.Text);
MessageBox.Show("Data has been saved");
Close();
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
runtime_sec++;
}
private void timer2_Tick(object sender, EventArgs e)
{
runtime_milis++;
}
}
}
I have this code but it's not working...
The progressbar is not moving and the downloaded file size is 0kb.
I think I have some problem in my WHILE loop! How can I solve this problem? Please give me instructions!
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DirectoryInfo folder= new DirectoryInfo(#"C:\Cloud24");
try
{
{
long size= 0;
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(userid, userpass);
FileStream file = File.Create(folder+ "//" + downloadname);
byte[] filedata = request.DownloadData(ftpadress + "/" + downloadname);
while ((size= file.Read(filedata, 0, filedata.Length)) > 0)
{
file.Write(filedata, 0, filedata.Length);
size += (int)filedata.Length;
double dProgressPercentage = ((double)(size) / (double)filedata.Length);
backgroundWorker1.ReportProgress((int)(dProgressPercentage * 100));
}
file.Close();
MessageBox.Show(downloadname + " downloaded!" +
Environment.NewLine + "There: " + folder);
}
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
}
}
This should probably work, but I haven't actually tested it.
private async void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var folder = new DirectoryInfo(#"C:\Cloud24");
try
{
{
var manualResetEvent = new ManualResetEventSlim();
var client = new WebClient { Credentials = new NetworkCredential(userid, userpass) };
client.DownloadProgressChanged += (o, args) => backgroundWorker1.ReportProgress(args.ProgressPercentage);
client.DownloadDataCompleted += (o, args) => manualResetEvent.Set();
var filedata = client.DownloadDataAsync(ftpadress + "/" + downloadname);
manualResetEvent.Wait();
using (var stream = File.Create(folder + "//" + downloadname))
{
await stream.WriteAsync(filedata, 0, filedata.Length);
}
MessageBox.Show(downloadname + " downloaded!" + Environment.NewLine + "There: " + folder);
}
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
}
}