C# App Installer - installed App not opening - c#

I have created Setup.exe of my Application in Visual Studio 2019, using C#, in my computer. I installed the app in another laptop, by copying the debug folder with setup files, to that laptop. But, after installation, when I clicked the App, it is not opening. I have also tried changing the target dotnet frame work of application in Visual Studio, to match with the laptop. But same effect. This App have references to some external dll files such as a spectrometer related dlls and the tool mathematica's dll. If everything works fine, this App is supposed to collect data from spectrometer and do signal processing and display results at dotnet GUI.
References and dlls used
Ocean Optics Spectrometer related - common64.dll, NETOmniDriver-NET40.dll
Wolfram Mathemtica tool related - ml32i4.dll, Wolfram.NETLink.dll
Please help me in opening my App.
Please find code below.
namespace JointApp1
{
public partial class Form1 : Form
{
int numberOfSpectrometersFound;
int spectrometerIndex; // indicates which spectrometer we are using
OmniDriver.CCoWrapper wrapper;
private Wolfram.NETLink.MathKernel mathKernel;
public Form1(string[] args)
{
InitializeComponent(args);
wrapper = new OmniDriver.CCoWrapper();
spectrometerIndex = -1;
}
private void button5_Click(object sender, EventArgs e)
{
numberOfSpectrometersFound = wrapper.openAllSpectrometers();
if (numberOfSpectrometersFound < 1)
{
listBox1.Items.Add("No spectrometers found");
spectrometerIndex = -1; // set it to an invalid value
return;
}
spectrometerIndex = 0; // arbitrarily choose the first
// spectrometer for this demo
listBox1.Items.Add("Selecting spectrometer: " +
wrapper.getName(spectrometerIndex));
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Program Files\Wolfram Research\Mathematicanew\12.0\SystemFiles\Links\NETLink\Examples\Part1\MathKernelApp\JointApps\rd.csv");
string line;
if (sr != null) sr.Close();
//end of graph
int numberOfPixels; // number of CCD elements/pixels provided by the spectrometer
double[] spectrum;
if (spectrometerIndex == -1)
return; // no available spectrometer
numberOfPixels = wrapper.getNumberOfPixels(spectrometerIndex);
// Set some acquisition parameters and then acquire a spectrum
spectrum = (double[])wrapper.getSpectrum(spectrometerIndex);
// Display the raw pixel values of this spectrum
var csv = new StringBuilder();
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Imprint KGT\Documents\Visual Studio 2012\editingg for lamda\WindowsFormsApplication1\wn.txt");
for (int i = 0; i < numberOfPixels; ++i)
{
double[] array = new double[1044];
var first = spectrum[i].ToString();
var newLine = string.Format("{0},{1}",lines[i], first);
csv.AppendLine(newLine);
}
File.WriteAllText((#"C:\Program Files\Wolfram Research\Mathematicanew\12.0\SystemFiles\qwer.csv"), csv.ToString());
for (int index = 0; index < numberOfPixels; ++index)
{
listBox2.Items.Add("Raman Shift[" + lines[index] + "] = " +
spectrum[index]);
double qw = spectrum[1];
}
}
private async void Button4_Click(object sender, System.EventArgs e)
{
statusStrip1.Text = "calling mathematica.......detecting pesticide presence.....";
if (mathKernel.IsComputing) { mathKernel.Abort(); }
else
{
try
{
mathKernel.Compute("linkName = \"Bob\"");
mathKernel.Compute("remoteLinkObj = LinkOpen[linkName, LinkMode -> Listen]");
mathKernel.Compute("Needs[\"JLink`\"]");
mathKernel.Compute("$FrontEndLaunchCommand = \"C:\\Program Files\\Wolfram Research\\Mathematicanew\\12.0\\Mathematica.exe\"");
mathKernel.Compute("UseFrontEnd[nb = CreateDocument[Null, Visible -> False]; NotebookWrite[nb, Cell[BoxData[{RowBox[{RowBox[{\"linkName\", \"=\", \"\\\"Bob\\\"\"}], \";\"}], \" \", RowBox[{RowBox[{\"feLinkObject\", \"=\", RowBox[{\"LinkOpen\", \"[\", RowBox[{\"linkName\", \",\", RowBox[{\"LinkMode\", \"\\[Rule]\", \"Connect\"}]}], \"]\"}]}], \";\"}], \" \", RowBox[{RowBox[{\"SetAttributes\", \"[\", RowBox[{\"remoteEval\", \",\", \"HoldRest\"}], \"]\"}], \";\"}], \" \", RowBox[{RowBox[{RowBox[{\"remoteEval\", \"[\", RowBox[{\"link_LinkObject\", \",\", \"expr_\"}], \"]\"}], \":=\", RowBox[{\"(\", RowBox[{RowBox[{\"LinkWrite\", \"[\", RowBox[{\"link\", \",\", RowBox[{\"Unevaluated\", \"[\", \"expr\", \"]\"}]}], \"]\"}], \";\", RowBox[{\"LinkRead\", \"[\", \"link\", \"]\"}]}], \")\"}]}], \";\"}]}], \"Input\"]]; SelectionMove[nb, Previous, Cell]; SelectionEvaluate[nb]; NotebookClose[nb]]");
mathKernel.Compute("NotebookEvaluate[\"greenchillicode.nb\"]");
string a = mathKernel.Result.ToString();
//la
textBox1.Text = a;
mathKernel.Compute("evalLoop[link_LinkObject] := Module[{resultOfEval, exprIn, exprOut, evalMessages}, evalMessages = {}; collectMessages[m_] := AppendTo[evalMessages, m]; Internal`AddHandler[\"Message\", collectMessages]; While[True, evalMessages = {}; exprIn = LinkRead[link, Hold]; resultOfEval = Check[exprOut = ReleaseHold[exprIn], $Failed]; Which[resultOfEval === $Failed, LinkWrite[link, EvalError[\"In\" -> exprIn, \"Out\" -> exprOut, \"Messages\" -> evalMessages]], True, LinkWrite[link, exprOut]]]; Internal`RemoveHandler[\"Message\", collectMessages]; LinkWrite[link, \"Evaluation loop is off\"]]");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
private void Show(System.Drawing.Image image)
{
throw new System.NotImplementedException();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.SuspendLayout();
//
// Form1
//
this.ClientSize = new System.Drawing.Size(1378, 744);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "23april";
this.ResumeLayout(false);
}
}
}

Related

Project cannot run anymore [Visual Studio]

I have a project that is not running anymore. I keep getting an error dialog that says "This application cannot be started. Do you want to view more information about this issue?". Also in the console, it says "The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." Someone told me to uncheck the "Prefer 32-bit" option. When I do that, although the error dialog box is gone, the console still displays The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." I cannot open the wpf app.
EDIT: By the way, the release folder is empty. When the app was working, my release folder had some things in it.
public MainWindow()
{
InitializeComponent();
}
public void readstuff (){
}
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
private void BrowseButton2(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath2.Text = fd.FileName;
}
private void SavingPathButton2(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\Nx3200\\supplier\\FONEX\\LambdaGain";
fs.ShowDialog();
savingPath2.Text = fs.FileName;
}
private void StartConversion2(object sender, RoutedEventArgs e)
{
try
{
Byte [] a1 = File.ReadAllBytes(filePath2.Text);
Byte[] a2 = new Byte[2 * (a1.Length)];
int i = 0;
while(i < a1.Length) {
a2[2*i] = a1[i];
a2[(2 * i) + 1] = 0;
i++;
}
try
{
string fullPath = Path.Combine(savingPath2.Text, "new");
File.WriteAllBytes(savingPath2.Text, a2);
MessageBox.Show("Conversion Complete");
} catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "X-Formatter";
frm3.ShowDialog();
}
}
catch (FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "X-Formatter";
frm1.ShowDialog();
}
}
private void BrowseButton1(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath1.Text = fd.FileName;
}
private void SavingPathButton1(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\folder1\\savelocation";
fs.ShowDialog();
savingPath1.Text = fs.FileName;
}
private void StartConversion1(object sender, RoutedEventArgs e)
{
try
{
Byte[] a1 = File.ReadAllBytes(filePath1.Text);
Byte[] a2 = new Byte[(a1.Length) / 2];
a2[0] = a1[0];
int i = 2;
int j = 1;
while (i < a1.Length)
{
a2[j] = a1[i];
i = i + 2;
j += 1;
}
try
{
File.WriteAllBytes(savingPath1.Text, a2);
MessageBox.Show("Conversion Complete");
}
catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "XGIGA formatter";
frm3.ShowDialog();
}
} catch(FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "XGIGA Formatter";
frm1.ShowDialog();
}
}
private void FilePath1_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AboutBox1 ab = new AboutBox1();
ab.Text = "XGIGA Formatter";
ab.ShowDialog();
}
}

Listbox Item holds data

Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}

C# Launcher based on WebClient

I'm creating simple launcher for my other application and I need advise on logical part of the program. Launcher needs to check for connection, then check for file versions (from site), compare it with currently downloaded versions (if any) and if everything is alright, start the program, if not, update (download) files that differs from newest version. The files are:
program.exe, config.cfg and mapFolder. The program.exe and mapFolder must be updated, and config.cfg is only downloaded when there is no such file. Additionaly mapFolder is an folder which contains lots of random files (every new version can have totally different files in mapFolder).
For the file version I thought I would use simple DownloadString from my main site, which may contain something like program:6.0,map:2.3, so newest program ver is 6.0 and mapFolder is 2.3. Then I can use FileVersionInfo.GetVersionInfo to get the version of current program (if any) and include a file "version" into mapFolder to read current version.
The problem is I dont know how to download whole folder using WebClient and what's the best way to do what I want to do. I've tried to download the mapFolder as zip and then automatically unpack it, but the launcher need to be coded in .net 3.0.
Here is my current code, that's just a prototype to get familiar with whole situation, dont base on it.
`
WebClient wc = new WebClient();
string verifySite = "google.com/downloads/version";
string downloadSite = "google.com/downloads/program.exe";
Uri verifyUri, downloadUri = null;
string userVer, currVer = "";
string downloadPath = Directory.GetCurrentDirectory();
string clientName = "program.exe";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(FileDownloaded);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FileDownloadProgress);
chckAutorun.Checked = Properties.Settings.Default.autorun;
checkConnection();
if(!checkVersion())
downloadClient();
else
{
pbDownload.Value = 100;
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
}
private bool checkConnection()
{
verifyUri = new Uri("http://" + verifySite);
downloadUri = new Uri("http://" + downloadSite);
WebRequest req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
verifyUri = new Uri("https://" + verifySite);
downloadUri = new Uri("https://" + downloadUri);
req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
return false;
}
private void downloadClient()
{
try
{
wc.DownloadFileAsync(downloadUri, Path.Combine(downloadPath, clientName));
}
catch { }
}
private bool checkVersion()
{
lblProgress.Text = "checking for updates";
try
{
currVer = FileVersionInfo.GetVersionInfo(Path.Combine(downloadPath, clientName)).FileVersion;
}
catch {
currVer = "";
}
try
{
userVer = wc.DownloadString(verifyUri);
}
catch {
userVer = "";
}
return currVer == userVer && currVer != "";
}
private void FileDownloaded(object sender, AsyncCompletedEventArgs e)
{
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
private void FileDownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
long received = e.BytesReceived / 1000;
long toReceive = e.TotalBytesToReceive / 1000;
lblProgress.Text = string.Format("{0}KB {1}/ {2}KB", received, Repeat(" ", Math.Abs(-5 + Math.Min(5, received.ToString().Length))*2), toReceive);
pbDownload.Value = e.ProgressPercentage;
}
private void btnPlay_Click(object sender, EventArgs e)
{
btnPlay.Enabled = false;
if(checkVersion())
{
lblProgress.Text = "Starting...";
Process.Start(Path.Combine(downloadPath, clientName));
this.Close();
}
else
{
downloadClient();
}
}
public static string Repeat(string instr, int n)
{
if (string.IsNullOrEmpty(instr))
return instr;
var result = new StringBuilder(instr.Length * n);
return result.Insert(0, instr, n).ToString();
}
private void chckAutorun_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.autorun = chckAutorun.Checked;
Properties.Settings.Default.Save();
}`
I've managed to achieve what I need by enabling autoindex on web server and download string of files in folder ending with .map .
string mapSite = wc.DownloadString(new Uri("http://" + mapsSite));
maps = Regex.Matches(mapSite, "<a href=\"(.*).map\">");
foreach (Match m in maps)
{
string mapName = m.Value.Remove(0, 9).Remove(m.Length - 11);
downloaded = false;
wc.DownloadFileAsync(new Uri("http://" + mapsSite + mapName), Path.Combine(downloadPath, #"mapFolder/" + mapName));
while (!downloaded) { }
}

C# Backgroundworker download progress in label, get bytes in label

I've created an application that patches my game servers files.
However, I've got 3 problems which I can't solve:
When downloading a new patch, it doesn't update the progressbar instantly, but refreshes it after around 30-40 seconds
I want a label to show how much mega bytes they are downloading, and how much they have so far (for example: 122Mb/750Mb
When downloading, I want a label to show ~% of how much it has downloaded so far
I am not sure how to add number 2 and 3, and the number 1 problem just seems ridiculous, because there's nothing that indicates it should refresh after 30-40 seconds in my coding (at least as far as I know)
My backgroundWorker1_DoWork:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Defines the server's update directory
string Server = "http://localhost/dl/game-updates/";
//Defines application root
string Root = AppDomain.CurrentDomain.BaseDirectory;
//Make sure version file exists
FileStream fs = null;
if (!File.Exists("version"))
{
using (fs = File.Create("version"))
{
}
using (StreamWriter sw = new StreamWriter("version"))
{
sw.Write("1.0");
}
}
//checks client version
string lclVersion;
using (StreamReader reader = new StreamReader("version"))
{
lclVersion = reader.ReadLine();
}
decimal localVersion = decimal.Parse(lclVersion);
//server's list of updates
XDocument serverXml = XDocument.Load(#Server + "Updates.xml");
//The Update Process
foreach (XElement update in serverXml.Descendants("update"))
{
string version = update.Element("version").Value;
string file = update.Element("file").Value;
decimal serverVersion = decimal.Parse(version);
string sUrlToReadFileFrom = Server + file;
string sFilePathToWriteFileTo = Root + file;
if (serverVersion > localVersion)
{
Uri url = new Uri(sUrlToReadFileFrom);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
Int64 iSize = response.ContentLength;
Int64 iRunningByteTotal = 0;
using (System.Net.WebClient client = new System.Net.WebClient())
{
using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
{
using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[iSize];
while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
streamLocal.Write(byteBuffer, 0, iByteSize);
iRunningByteTotal += iByteSize;
double dIndex = (double)(iRunningByteTotal);
double dTotal = (double)byteBuffer.Length;
double dProgressPercentage = (dIndex / dTotal);
int iProgressPercentage = (int)(dProgressPercentage * 100);
backgroundWorker1.ReportProgress(iProgressPercentage);
}
streamLocal.Close();
}
streamRemote.Close();
}
}
//unzip
using (ZipFile zip = ZipFile.Read(file))
{
foreach (ZipEntry zipFiles in zip)
{
zipFiles.Extract(Root + "\\", true);
}
}
//download new version file
WebClient webClient = new WebClient();
webClient.DownloadFile(Server + "version.txt", #Root + "version");
//Delete Zip File
deleteFile(file);
}
}
}
My backgroundWorker1_ProgressChanged:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = "Downloading updates...";
}
And my backgroundWorker1_RunWorkerCompleted:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
settings_btn.Enabled = true;
start_btn_disabled.Enabled = false;
start_btn_disabled.Visible = false;
start_btn.Visible = true;
start_btn.Enabled = true;
progressBar1.Value = 100;
label1.Text = "Client is up to date!";
}
Also, a side note: I'm also having a bit problems of updating labels in backgroundWorker2_DoWork?
Any ideas?
Here's some working code which updates a label on Form1 using the BackgroundWorker.
Create a new Windows Form project and drop it in your code and it'll work.
It's super ugly, but it works.
After that, just plug your code into the DoWork method and calculate your value and send to ReportProgress.
Keep in mind that the work done in DoWork method is the actual Background Thread.
That means that in that method (DoWork) you cannot access UI (form) elements because they are on the UI thread.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FakeCountingWork();
}
private void FakeCountingWork()
{
int totalNumber = 100;
int progressCounter = 0;
while (progressCounter < totalNumber)
{
int fakecounter = 0;
for (int x = 0; x < 100000000; x++)
{
fakecounter++;
}
progressCounter++;
backgroundWorker1.ReportProgress(progressCounter);
}
}
}
################################## EDITED TO ADD OTHER FUNCTIONALITY
Okay, here's how you can implement a label which displays the number of bytes downloaded so far.
Add a second label named label2 to your form.
Next alter the following methods from my previous example.
Here we are going to use the UserState to pass an extra value to the ProgressChanged Event. It's very simple. You can see that I'm generating a random number and it will now appear in Label2. This is where you could show your number of bytes.
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
label2.Text = e.UserState.ToString();
}
private void FakeCountingWork()
{
int totalNumber = 100;
int progressCounter = 0;
Random rnd = new Random();
while (progressCounter < totalNumber)
{
int fakecounter = 0;
for (int x = 0; x < 100000000; x++)
{
fakecounter++;
}
progressCounter++;
updateValue = rnd.Next();
backgroundWorker1.ReportProgress(progressCounter,updateValue);
}
}
I would imagine this is because you are trying to update UI objects on a different thread. HAve you tried using the Dispatcher if using wpf? https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke(v=vs.110).aspx
or Invoke if using Winforms? https://msdn.microsoft.com/fr-ca/library/zyzhdc6b(v=vs.85).aspx
Edit:
As #daylight pointed out to be, the UI was being updated in the progresschanged event, which executes on the thread which created the background worker, therefore there shouldn't be an issue regarding threading. See https://msdn.microsoft.com/en-us/library/ka89zff4(v=vs.110).aspx for more info

Capture Sound from microphone using Directx DirectSound

I am creating a simple application that records input from the microphone and store it into array of bytes. So I have searched a lot about this and eventually ended up using Directx DirectSound. Here is the code I am using:
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
private Thread CaptureSoundThread = null;
public CaptureBuffer applicationBuffer = null;
private SecondaryBuffer soundBuffer = null;
private Device soundDevice = null;
private void Form1_Load(object sender, EventArgs e)
{
soundDevice = new Device();
soundDevice.SetCooperativeLevel(this, CooperativeLevel.Normal);
// Set up our wave format to 44,100Hz, with 16 bit resolution
WaveFormat wf = new WaveFormat();
wf.FormatTag = WaveFormatTag.Pcm;
wf.SamplesPerSecond = 44100;
wf.BitsPerSample = 16;
wf.Channels = 1;
wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8);
wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign;
int samplesPerUpdate = 512;
// Create a buffer with 2 seconds of sample data
BufferDescription bufferDesc = new BufferDescription(wf);
bufferDesc.BufferBytes = samplesPerUpdate * wf.BlockAlign * 2;
bufferDesc.ControlPositionNotify = true;
bufferDesc.GlobalFocus = true;
soundBuffer = new SecondaryBuffer(bufferDesc, soundDevice);
}
private void button1_Click(object sender, EventArgs e)
{
CaptureSoundThread = new Thread(new ThreadStart(WaitThread));
CaptureSoundThread.Start();
}
private void WaitThread()
{
while (true)
{
byte[] CaptureData = null;
CaptureData = (byte[])applicationBuffer.Read(0,
typeof(byte), LockFlag.None);
soundBuffer.Write(0, CaptureData, LockFlag.None);
// Start it playing
soundBuffer.Play(0, BufferPlayFlags.Looping);
}
}
But when I try to run the application, I get this annoying error:
BadImageFormatException
Could not load file or assembly 'Microsoft.DirectX.DirectSound.dll' or one
of its dependencies. is not a valid Win32 application. (Exception from
HRESULT: 0x800700C1)
I actually had to download the Microsoft.DirectX.DirectSound.dll from the internet because I couldn't find them in the Visual Studio assemblies.
EDIT : I JUST SOLVED THAT by reading this article : http://www.codeproject.com/Articles/383138/BadImageFormatException-x86-i-x64
EDIT : I JUST SOLVED THAT by reading this article : http://www.codeproject.com/Articles/383138/BadImageFormatException-x86-i-x64

Categories