I'm writing a Chat Program in C# (Windows Forms Application), the solution contains to projects which both consist of one form ( see picture ). While sending messages to each other works, I'm trying to record the conversation session in a .txt file named dateTime.txt using StreamWriter. Creating the file if it does not exist yet works, but whenever I open the text file, it only contains the last string that was written to it instead of containing the whole "conversation".
Does anybody know how to fix this?
This is the code of one of the forms, but since the forms do exactly the same, the code is the same too so i'm only posting the code of one Form. Would be great if somebody knows what I have to change so the whole conversation is recorded in the text file.
namespace Assignment3Client
{
public partial class Chat : Form
{
NamedPipeClientStream clientPipe = new NamedPipeClientStream("pipe2");
NamedPipeServerStream serverPipe = new NamedPipeServerStream("pipe1");
string msg = String.Empty;
string msgStr;
string name;
byte[] ClientByte;
public Chat()
{
InitializeComponent();
}
private void btnStartChat_Click(object sender, EventArgs e)
{
this.Text = "Waiting for a connection....";
if (txtBoxName.Text.Length == 0)
{
MessageBox.Show("please enter a name first.");
}
else
{
name = txtBoxName.Text;
clientPipe.Connect();
serverPipe.WaitForConnection();
if (serverPipe.IsConnected)
{
this.Text = "You are connected, " + name + "!";
btnStartChat.Enabled = false;
btnSend.Enabled = true;
txtBoxMsg.Enabled = true;
txtBoxMsg.Focus();
receiveWorker.RunWorkerAsync();
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
msg = "[" + name + ": " + DateTime.Now + "] " + txtBoxMsg.Text;
txtBoxChat.AppendText(msg + "\n");
FileWriter(msg);
sendWorker.RunWorkerAsync(msg); //start backgroundworker and parse msg string to the dowork method
txtBoxMsg.Clear();
txtBoxMsg.Focus();
}
private void sendWorker_DoWork(object sender, DoWorkEventArgs e)
{
Byte[] msgByte = System.Text.Encoding.GetEncoding("windows-1256").GetBytes(msg);
serverPipe.Write(msgByte, 0, msg.Length);
}
private void receiveWorker_DoWork(object sender, DoWorkEventArgs e)
{
ClientByte = new Byte[1000];
int i;
for (i = 0; i < ClientByte.Length; i++)
{
ClientByte[i] = 0x20;
}
clientPipe.Read(ClientByte, 0, ClientByte.Length);
msgStr = System.Text.Encoding.GetEncoding("windows-1256").GetString(ClientByte);
receiveWorker.ReportProgress(i, msgStr);
}
private void receiveWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if ((string)e.UserState == String.Empty)
{ MessageBox.Show("no message"); }
else
{
string message = (string)e.UserState;
txtBoxChat.AppendText(message);
FileWriter(message);
txtBoxChat.BackColor = System.Drawing.Color.DarkBlue;
txtBoxChat.ForeColor = System.Drawing.Color.White;
}
}
private void receiveWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (clientPipe.IsConnected)
{
receiveWorker.RunWorkerAsync();
}
else
{
txtBoxMsg.Enabled = false;
btnSend.Enabled = false;
MessageBox.Show("Connection lost");
}
}
private void Chat_Activated(object sender, EventArgs e)
{
txtBoxChat.BackColor = new System.Drawing.Color();
txtBoxChat.ForeColor = new System.Drawing.Color();
}
private void exitMenuStrip_Click(object sender, EventArgs e)
{
this.Close();
}
private void conMenuSrip_Click(object sender, EventArgs e)
{
}
private void errMenuStrip_Click(object sender, EventArgs e)
{
}
public void FileWriter(string message)
{
string path = #"C:\Users\selin\Documents\TAFE\Term 3\dateTime.txt";
FileStream conLog;
if (!File.Exists(path))
{
conLog = new FileStream(path, FileMode.Create);
}
else
{
conLog = new FileStream(path, FileMode.Open);
}
StreamWriter writer = new StreamWriter(conLog);
writer.WriteLine(message);
writer.AutoFlush = true;
writer.Close();
MessageBox.Show("written to file" + message);
}
}
}
in FileWriter(string message) change
conLog = new FileStream(path, FileMode.Open);
to
conLog = new FileStream(path, FileMode.Append);
Related
I am currently working on a file copying facility that allows me to select a source and a destination for the folders to be copied from and to. A progress bar is displayed after the user clicks on Copy.
The only issue is that All of my functions reside in one file which is form1.cs (as follows)
namespace CopyFacility
{
public partial class Form1 : Form
{
BackgroundWorker background = new BackgroundWorker();
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
OpenFileDialog openFile = new OpenFileDialog();
public Form1()
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
string inputFile = null;
string outputFile = null;
private void CopyFile(string source, string destination, DoWorkEventArgs e)
{
FileStream fsOut = new FileStream(destination, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756];
int readBytes;
while((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
if(background.CancellationPending)
{
e.Cancel = true;
background.ReportProgress(0);
fsIn.Close();
fsOut.Close();
return;
}
else
{
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int) (fsIn.Position * 100 / fsIn.Length));
}
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Background_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
fileProgressBar.Value = e.ProgressPercentage;
}
private void Background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been cancelled";
}
else
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been completed";
}
}
private void Background_DoWork(object sender, DoWorkEventArgs e)
{
CopyFile(inputFile, outputFile + #"\" + Path.GetFileName(inputFile),e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
background.CancelAsync();
}
private void btnCopy_Click(object sender, EventArgs e)
{
if(background.IsBusy)
{
lblProgress.Visible = true;
}
else
{
fileProgressBar.Visible = true;
background.RunWorkerAsync();
}
}
private void btnSource_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK )
{
inputFile = openFile.FileName;
btnSource.Text = inputFile;
}
}
private void btnDestination_Click(object sender, EventArgs e)
{
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
outputFile = folderBrowser.SelectedPath;
btnDestination.Text = outputFile + #"\" + Path.GetFileName(inputFile);
}
}
}
}
I was wondering how I could go about putting the function "CopyFile" into it's own class that can be called whenever the button is clicked?
When I try creating a new class method and inserting the functions related to the copying function into a new class "CopyFunction.cs" , I get a following error from the code "InitializingComponent();" as follows
public CopyPresenter(BackgroundWorker background, FolderBrowserDialog folderBrwoser, OpenFileDialog openFile)
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
The error says that the "InitializeComponent" doesn't exist in the current context.
I created an app for my dad. It's just a simple dictation program. The thing is when he installed it on his computer it stalled and said the general access denied error.
The first time it gave the error I used SaveFileDialog sfd = new SaveFileDialog() then added the usually 'if statement" to make sure the dialog was ok. However the app had an access file denied.
I did the same thing with Environment.GetFolder and it installed on his computer to the location and ran fine. However, when I use the saveFileDialog1 and openFileDialog1 out of the tool box it does not save or open a txt document.
It works on my laptop and not his. Could this be due to an error in the code vs his computer. Also what is the correct way to use the Environement.GetFolder with the SaveFileDialog.
I can also post the full code to the program if needed.
private void lblOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Title = "Open File";
open.Filter = "Text Files (*txt) | *.txt";
if (open.ShowDialog() == DialogResult.OK)
{
StreamReader read = new StreamReader(File.OpenRead(open.FileName));
txtTextBox.Text = read.ReadToEnd();
read.Dispose();
}
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
This is the Enviroment i used on my screen recorder. i when i click save it brings up a dialog box i put in the file name press save and it does nothing. It saves the file but not as i specified. So i am trying to merge the above and below codes. The above code does not grant access however the below does
string OutputPath;
OutputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + #"\\IvanSoft Desktop Recorder" + saveFileDialog1;
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string fileName = saveFileDialog1.FileName;
fileName = "Tutorial";
}
the whole code to the program
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading;
namespace AGM_Speech
{
public partial class Form1 : Form
{
public SpeechRecognitionEngine recognizer;
public Grammar grammar;
public Thread RecThread;
public Boolean RecognizerState = true;
public Form1()
{
InitializeComponent();
}
private void lblAbout_Click(object sender, EventArgs e)
{
this.Hide();
About about = new About();
about.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
GrammarBuilder builder = new GrammarBuilder();
builder.AppendDictation();
grammar = new Grammar(builder);
recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammarAsync(grammar);
recognizer.SetInputToDefaultAudioDevice();
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
RecognizerState = true;
RecThread = new Thread(new ThreadStart(RecThreadFunction));
RecThread.Start();
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
txtTextBox.Text += (e.Result.Text.ToLower() + " ");
txtTextBox.SelectionStart = txtTextBox.Text.Length - 0;
txtTextBox.SelectionLength = 0;
});
}
public void RecThreadFunction()
{
while (true)
{
try
{
recognizer.RecognizeAsync();
}
catch
{
}
}
}
private void lblStartSpeech_Click(object sender, EventArgs e)
{
RecognizerState = true;
}
private void lblStopSpeech_Click(object sender, EventArgs e)
{
RecognizerState = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RecThread.Abort();
RecThread = null;
grammar = null;
recognizer.UnloadAllGrammars();
recognizer.Dispose();
}
private void lblOpenFile_Click(object sender, EventArgs e)
{
string open = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamReader reader = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
private void txtSearch_Click(object sender, EventArgs e)
{
txtSearch.Clear();
lblGo_Click(null, null);
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)ConsoleKey.Enter)
{
lblGo_Click(null, null);
}
}
private void lblGo_Click(object sender, EventArgs e)
{
int index = 0;
String temp = txtTextBox.Text;
txtTextBox.Text = "";
txtTextBox.Text = temp;
while (index <= txtTextBox.Text.LastIndexOf(txtSearch.Text))
{
txtTextBox.Find(txtSearch.Text, index, txtTextBox.TextLength, RichTextBoxFinds.None);
txtTextBox.SelectionColor = Color.YellowGreen;
index = txtTextBox.Text.IndexOf(txtSearch.Text, index) + 1;
}
}
}
}
It's hard to say where you're failing, because there isn't much in the way of try/catch or logging.
Can you use this instead, and paste the stack trace that shows in the Message Box?
private string fileOutputLocation { get; set; }
private void lblSaveFile_Click(object sender, EventArgs e)
{
bool fileSelected = false;
Try(() =>
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
save.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "IvanSoft Desktop Recorder");
if (save.ShowDialog() == DialogResult.OK)
{
fileOutputLocation = save.FileName;
fileSelected = true;
}
});
if (fileSelected)
{
bool fileSaved = SaveFile();
MessageBox.Show("File saved successfully: " + fileSaved.ToString());
}
}
private bool SaveFile()
{
TryDeleteFile();
bool fileSaved = false;
Try(()=>
{
File.WriteAllText(fileOutputLocation, txtTextBox.Text);
fileSaved = true;
});
return fileSaved;
}
private void TryDeleteFile()
{
Try(()=>
{
if (File.Exists(fileOutputLocation))
{
File.Delete(fileOutputLocation);
}
});
}
private void Try(Action action)
{
try
{
action();
}
catch (Exception e)
{
MessageBox.Show(string.Format("The following exception was thrown:\r\n{0}\r\n\r\nFile path: {1}", e.ToString(), fileOutputLocation));
}
}
With this, plus the events logged to the Windows Event Viewer (Start>Run>Eventvwr>Security), we should be able to tell you what the problem is.
Lastly, if you're just providing an executable to run, you should check the properties of the file to ensure it's not blocked in Windows.
I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
using System;
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.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}
There is a server and multiple clients. The server accepts the connection requests from multiple clients. The sockets created are stored in an array. There is a list box in my application. On selecting a particular item it refers to the corresponding socket in the array of sockets (eg if I select first item, it will consider first socket in the array). But the problem is - as the clients can connect to the server in random fashion how the server keep tracks of the clients if it has to send data to a particular client.
Here is my code:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
int i=0;
TcpListener listener = new TcpListener(8888);
listener.Start();
while(true)
{
Socket soc = listener.AcceptSocket();
socarray[i] = soc;
i++;
if (i == NUMBEROFCLIENTS)
break;
}
// Thread writetodatabase = new Thread(datawrite);
// writetodatabase.Start();
Application.Run(new Form1());
}
private void button5_Click(object sender, EventArgs e)
{
if (listBox1.Text == "Reader1")
{
reader_flag = 1;
toolStripStatusLabel1.Text = "reader1 selected";
a = toolStripStatusLabel1.Text;
}
if (listBox1.Text == "Reader2")
{
reader_flag = 2;
toolStripStatusLabel1.Text = "reader2 selected";
a = toolStripStatusLabel1.Text;
}
}
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string a;
public static int reader_flag = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Form3 formmm = new Form3();
formmm.Show();
}
private void button4_Click(object sender, EventArgs e)
{
Form2 formm = new Form2();
formm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
byte[] bytesFrom = new Byte[1000];
Program.socarray[0].Receive(bytesFrom);
char[] stuffed = System.Text.Encoding.UTF8.GetString(bytesFrom).ToCharArray();
int i;
char escape='#';
List<char> unstuffed = new List<char>();
for(i=0;i<stuffed.Length;i++)
{
if(stuffed[i]==escape)
{
i++;
unstuffed.Add(stuffed[i]);
}
else
{
unstuffed.Add(stuffed[i]);
}
}
unstuffed.RemoveAt(0);
unstuffed.RemoveAt(unstuffed.Count-1);
char[] final;
final = unstuffed.ToArray();
string foo = new string(final);
textBox1.Text = foo;
System.IO.File.WriteAllText(#"C:\Users\cdac\Desktop\server\server\TextFile2.txt", foo);
}
finally { }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Form4 mm = new Form4();
mm.Show();
}
private void toolStripStatusLabel1_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = a;
}
private void button5_Click(object sender, EventArgs e)
{
if (listBox1.Text == "Reader1")
{
reader_flag = 1;
toolStripStatusLabel1.Text = "reader1 selected";
a = toolStripStatusLabel1.Text;
}
if (listBox1.Text == "Reader2")
{
reader_flag = 2;
toolStripStatusLabel1.Text = "reader2 selected";
a = toolStripStatusLabel1.Text;
}
}
private void button6_Click(object sender, EventArgs e)
{
string MyConString = "server=localhost;" +
"database=cdac;"+
"User Id=root;"
+"password=cdac56;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
connection.Open();
//StreamReader reader = new StreamReader("C:\\tag_log_030610.txt");
StreamReader reader = new StreamReader("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(';');
//command.CommandText = "insert into st_attn(rollno,Th_attn,Name) values('" + parts[0] + "','" + parts[1] + "','" + parts[2] + "')";
command.CommandText = "insert into st_attn(rollno) values('" + parts[0] + "')";
Reader = command.ExecuteReader();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Client-Server apps ALWAYS start with a request from the client to the server. No matter if it's a business app, a game, a website, a webservice or even something to tell the time, the client will always first ask the server.
This means that if you're using sockets, you will always have to let the request come from the client. He will send a request to the server. The server will then keep a record internally of where they can find the client. This is kept in the Endpoint property of the Socket. But normally, you will not have to worry about this unless you're working with push apps.
I have been working on a manager application for a Minecraft server, when I run my program, the console shows and disappears, if I run it manually, it runs without and problems.
Batch file code:
java -Xmx1024M -jar craftbukkit-1.7.2-R0.3.jar -o false
My full code (MessageBoxes are in Polish, becouse im from Poland, but later i will add support for other languages):
using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Process server;
private Boolean runServer()
{
if (!File.Exists(textBox2.Text))
{
MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Process process = new Process
{
StartInfo =
{
FileName = textBox2.Text,
//Arguments = textBox3.Text,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
}
};
process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
server = process;
if (process.Start())
return true;
else
{
MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private String ReadFile(String filename, int line)
{
StreamReader reader = new StreamReader(filename);
for (int i = 0; i < line; i++)
{
reader.ReadLine();
}
return reader.ReadLine();
}
private void ReloadOPs()
{
if (!File.Exists(textBox1.Text))
{
MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
tabControl1.SelectedTab = tabPageOptions;
textBox1.SelectAll();
return;
}
String line = ReadFile(textBox1.Text, 0);
comboBox1.Items.Clear();
for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
{
if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
{
comboBox1.Items.Add(line);
line = ReadFile(textBox1.Text, i);
}
}
MessageBox.Show("Lista graczy z OP, została odświeżona.");
}
// OPs combobox (OPs)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
groupBox1.Text = comboBox1.SelectedItem.ToString();
groupBox1.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = Application.StartupPath.ToString() + #"\ops.txt";
ReloadOPs();
}
// Reload OPs button (OPs)
private void button1_Click(object sender, EventArgs e)
{
ReloadOPs();
}
// Save button (Options)
private void button4_Click(object sender, EventArgs e)
{
}
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
addConsoleMessage(e.Data.ToString(), true);
}
// Run server button (Menu)
private void button5_Click(object sender, EventArgs e)
{
if (!runServer())
return;
server.BeginOutputReadLine();
button6.Enabled = true;
}
// Stop server button (Menu)
private void button6_Click(object sender, EventArgs e)
{
if(!server.HasExited)
server.Kill();
button6.Enabled = false;
}
private void addConsoleMessage(String message, Boolean refresh)
{
listBox1.Items.Add(message);
if (refresh)
listBox1.Refresh();
}
}
}
My problem is that program crashes becouse InvaildOperationException was unhandled (listBox1.Items.Add(message) in addConsoleMessage).
External error information: Invalid operation between threads: the control 'listBox1' is accessed from a thread other than the thread it was created.
You cannot update UI form background thread. Try this
WPF
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
{
addConsoleMessage(e.Data.ToString(), true);
});
}
Update
In WinForms the Invoke/BeginInvoke methods are directly on the control objects as you can see from the docs of System.Windows.Forms.Control. So you'd have listBox1.BeginInvoke(...) for example.