System.ArgumentException: "Invalid parameter" - c#

When I use my compiled C# code from Microsoft Visual Studio 2022, I get this error:
System.ArgumentException: "Invalid parameter."
I tried to restart Visual Studio, but it didn't helped, so I am trying to get help from here. Google doesn't provide any information about this.
This is a part of my code:
private void saveButton_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
string path = #"E:\DarkHorse\Projects\Data\Data\Data\";
File.Create(path + text + ".txt").Close();
string text2 = $"**Never mind**"
File.WriteAllText(path + text + ".txt", text2);
button2.Visible=false;
button2.Enabled=false;
KrButton.Enabled = false;
KrButton.Visible = false;
SettingsButton.Location = new Point(647, 278);
pictureBox1.Enabled=false;
pictureBox1.Visible=false;
pictureBox1.Image.Dispose();
secrettext.Visible = true;
secrettext.Enabled = true;
closeButton2.Visible = false;
button1.Visible = true;
textBox1.Visible = true;
addButton.Enabled = true;
addButton.Visible = true;
saveButton.Visible = false;
saveButton.Enabled = false;
closeButton2.Enabled = false;
button1.Enabled = true;
textBox1.Enabled = true;
this.Size = new Size(900, 450);
infoLabel.Size = new Size(407, 199);
infoLabel.Enabled = false;
infoLabel.Visible = false;
Names.Text = "People Finder";
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
textBox10.Clear();
textBox11.Clear();
textBox12.Clear();
textBox13.Clear();
textBox14.Clear();
textBox2.Visible = false;
textBox2.Enabled = false;
textBox3.Visible = false;
textBox3.Enabled = false;
if (pictureBox1.Image == null)
{
File.Copy(path + "null.jpg", path + text +".jpg");
}
else
{
pictureBox1.Image.Save(path + text + ".png");
}
}

Have you tried to use Uri.IsWellFormedOriginalString to check your paths? Or just try another drive path. Like instead of C:\ use D:\ etc.
Maybe you don't have rights to read/copy the source file or write the target file.
And the last thing, please use try-catch. Maybe it can give more information about this problem.

Related

Open for the second time a file give errors

I have a program that start work. I can open and store files. But when I open a file (e.g. File 1) the program reads it and than when I want to open a second file (e.g. File 2) I get errors.
Opening files goes with bindingSource.DataSource I assume the issue is there but I have tried to set it to Null but that give other errors.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
string CheckConnection;
_bindingSource.DataSource = null;
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "XML File (*.xml)|*.xml";
ofd.Title = "Open Client Profile File";
if (ofd.ShowDialog() == DialogResult.OK)
{
lblCompanyName.Enabled = true;
lblClientNumber.Enabled = true;
lblSiteName.Enabled = true;
lblMachineTotal.Enabled = true;
lblImo.Enabled = true;
cmbMachineName.Enabled = true;
lblPower.Enabled = true;
lblMachineType.Enabled = true;
lblFrequency.Enabled = true;
lblSpeed.Enabled = true;
//Deserialize
_root = HelperXml.DeserializeXMLFileToObject<XmlRoot>(ofd.FileName);
ClientFileName = ofd.FileName; //Store current filename
lblCompanyName.ForeColor = Color.Black;
lblCompanyName.Text = "Company Name: " + _root.CompanyProfile.CompanyName;
lblSiteName.Text ="Sitename: " + _root.CompanyProfile.SiteName;
lblImo.Text = "IMO: " + _root.CompanyProfile.Imo.ToString();
lblMachineTotal.Text = "Machine Total: " + _root.CompanyProfile.MachineTotal.ToString();
lblClientNumber.Text = "Clientnumber: " + _root.CompanyProfile.ClientNumber.ToString();
_bindingSource.DataSource = _root.MachineProfiles.ToList();
cmbMachineName.DataSource = _bindingSource;
lblPower.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.NominalPower));
lblFrequency.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.Frequency));
lblMachineType.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.TypeDescription));
lblSpeed.DataBindings.Add("Text", _bindingSource, nameof(MachineProfile.NominalSpeed));
_bindingSource2.DataSource = _root.MachineMeasurements.ToList();
dataGridView1.DataSource = _bindingSource2;
dataGridView1.DataBindings.Add("Text", _bindingSource2, nameof(MachineMeasurement.MeasurementDate));
}
}
CheckConnection = statusLblDevice.Text.ToString();
//Enable "ImportData" button function only when a clientfile has been loaded and a device has been detected.
if (CheckConnection.Contains("VM25")== true && lblSiteName.Text != null)
{
importDataToolStripMenuItem.Enabled = true;
}
}
Above is the code that opens a file this is connected to other classes but I think there is not the issue. I think prior to run this code all should be empty or so.
Does anybody know how I could do this?
Without adding any code I get this error:
System.ArgumentException: 'This causes two bindings in the collection to bind to the same property.
This is the error message I get when I added the code for making the bindingSource null
System.ArgumentException: 'Cannot bind to the property or column NominalPower on the DataSource.
Parameter name: dataMember'

c# ignoring else if statement

I am trying to make a winforms application so when something is clicked it checks a webpage for it's response.
I have tested the web page to see if it is a PHP error but it works fine from that side.
It is completely ignoring the else if statement and skips to the else statement below it even though the response is "Unassigned".
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://fms.psrpc.co.uk/apiconfirmD.php?" + ApiKey);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (response)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
if (reader.ReadToEnd() == "Changed")
{
label2.Visible = false;
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
timer1.Enabled = true;
}
else if (reader.ReadToEnd() == "Unassigned")
{
string message = "Error Code: B66794O37945O46791K##Error booking on.#Please make sure you have been assigned to a vehicle.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
string message = "Error Code: B002875O46883O84655K##Error booking on.#Please make sure you have booked a shift and have been assigned.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
}
}
No, it is not being ignored. You are reading all the data in your first if block by calling reader.ReadToEnd(). This way, there is no further data available to read in your else if statement; it returns empty string. Thus condition does not match and final else block gets executed.
Modify the code something like below. Notice the temporary data variable in below code.
StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();//Read the data in temp variable.
//Use this variable to check the conditions further.
if (data == "Changed")
{
//Your code here
}
else if (data == "Unassigned")
{
//Your code here
}
else
{
//Your code here
}
You have an error in your general logic. When you enter the first if statement, you're reading to the end of the stream with the code reader.ReadToEnd(). In the next statement (the else), you're reading the stream again, but it has already been read, so it will return an empty string, thus the last else statement will effectively be hit.
You can also read about this on MSDN: StreamReader.ReadToEnd() Method.
Definition of the return value:
The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string ("").
Your code should look like this:
StreamReader reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
if(result == "Changed")
{
label2.Visible = false;
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
timer1.Enabled = true;
}
else if(result == "Unassigned")
{
string message = "Error Code: B66794O37945O46791K##Error booking on.#Please make sure you have been assigned to a vehicle.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
string message = "Error Code: B002875O46883O84655K##Error booking on.#Please make sure you have booked a shift and have been assigned.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}

command prompt commands executing in windows application

i am trying in windows application i need to run another one application that's tetpdflib. that tetpdflib runs in command prompt only. when i drag and drop exe to the command prompt it will execute. for that i followed some coding
Process tetmlProcess = new Process();
tetmlProcess.StartInfo.CreateNoWindow = true;
tetmlProcess.StartInfo.RedirectStandardOutput = true;
tetmlProcess.StartInfo.UseShellExecute = false;
tetmlProcess.StartInfo.FileName = #"cmd.exe";
tetmlProcess.StartInfo.Arguments = "cd C:\\Users\\sw_chn\\Documents\\PDFlib\\TET 5.0 32-bit\\bin\\tet.exe";
tetmlProcess.Start();
but i cant get output.. and also i need to run following command prompt lines also
cd tet.exe
and tet -m filename
how to execute those commands in that process.
thats the full coding
public static string inputfile = string.Empty;
public static string outputfolder = string.Empty;
private void btninputbrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog inputFileBrowser = new OpenFileDialog();
DialogResult result = inputFileBrowser.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
inputfile = inputFileBrowser.FileName;
txtinput.Text = inputFileBrowser.FileName;
}
}
private void btnoutputbrowse_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog folderbrowsing = new FolderBrowserDialog();
DialogResult result = folderbrowsing.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
outputfolder = folderbrowsing.SelectedPath;
txtoutput.Text = folderbrowsing.SelectedPath;
}
}
private void btnok_Click(object sender, RoutedEventArgs e)
{
MoveInputFileToOutPutFolder();
}
private void MoveInputFileToOutPutFolder()
{
try
{
string[] splitinput = inputfile.Split('\\');
outputfolder = System.IO.Path.Combine(outputfolder,splitinput.LastOrDefault());
if (File.Exists(outputfolder))
{
File.Delete(outputfolder);
}
File.Copy(inputfile,outputfolder);
TetmlApplicationRunning();
}
catch (Exception)
{
throw;
}
}
private void TetmlApplicationRunning()
{
try
{
Process tetmlProcess = new Process();
//tetmlProcess.StartInfo.CreateNoWindow = true;
//tetmlProcess.StartInfo.RedirectStandardOutput = true;
//tetmlProcess.StartInfo.UseShellExecute = false;
tetmlProcess.StartInfo.FileName = #"C:\\Users\\sw_chn\\Documents\\PDFlib\\TET 5.0 32-bit\\bin\\tet.exe";
tetmlProcess.StartInfo.WorkingDirectory = #"C:\\Users\\sw_chn\\Documents\\PDFlib\\TET 5.0 32-bit\\bin";
tetmlProcess.StartInfo.Arguments = "tetml -m wordplus" + inputfile;
tetmlProcess.Start();
}
catch (Exception)
{
throw;
}
}
}
}
You can do it like below. you won't need to run cmd.exe you can directly run tet.ext. Added comments in code.
Process tetmlProcess = new Process();
tetmlProcess.StartInfo.CreateNoWindow = true;
tetmlProcess.StartInfo.RedirectStandardOutput = true;
tetmlProcess.StartInfo.UseShellExecute = false;
// Instead of cmd.exe you run the tet.exe
tetmlProcess.StartInfo.FileName = #"C:\\Users\\sw_chn\\Documents\\PDFlib\\TET 5.0 32-bit\\bin\\tet.exe";
//Set The working directory to C:\Users\sw_chn\Documents\PDFlib\TET 5.0 32-bit\bin\ if needed
tetmlProcess.StartInfo.WorkingDirectory = #"C:\\Users\\sw_chn\\Documents\\PDFlib\\TET 5.0 32-bit\\bin";
//Use the arguments required for tet.exe
tetmlProcess.StartInfo.Arguments = "-m filename";
tetmlProcess.Start();
Note: This code is directly typed in here (have no access to visual studio now) so may contain syntax errors. Treat this only as guideline.
try the following snippet:
var proc = new ProcessStartInfo();
string yourCommand;
yourCommand = "calc.exe";
proc.UseShellExecute = true;
proc.WorkingDirectory = #"C:\Windows\System32";
proc.FileName = #"C:\Windows\System32\cmd.exe";
proc.Arguments = "/c " + yourCommand;
proc.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(proc);
I run calculator; you can run your program as tet.exe and you must set the other parameters such as WorkingDirectory and FileName based on your .exe file.
This line of code
proc.WindowStyle = ProcessWindowStyle.Normal;
displays the cmd.exe window. If you are gonna not to display that, change the mentioned line of code to proc.WindowStyle = ProcessWindowStyle.Hidden;
I hope that work out!
I owuld not try to simulate the command prompt, but execute the application directly. I assume that for this application output is sent to the console. You can redirect this output, but it is not possible to combine this with shell execute. I use the full path name to the application, which I set in the "Options" class and is stored in the registry. An example:
static public String CompileScript(String InputFile, String OutputFile)
{
Process Compiler = new Process();
String Result = String.Empty;
try
{
Compiler.StartInfo.FileName = CLuaCreatorOptions.TrainSimulatorDirectory + "\\luac.exe";
Compiler.StartInfo.Arguments = "-v -o " + OutputFile + " " + InputFile;
Compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Compiler.StartInfo.CreateNoWindow = true;
Compiler.StartInfo.UseShellExecute = false;
Compiler.StartInfo.RedirectStandardOutput = true;
Compiler.StartInfo.RedirectStandardError = true;
Compiler.Start();
Result = Compiler.StandardOutput.ReadToEnd() + "\n" + Compiler.StandardError.ReadToEnd();
Compiler.WaitForExit();
}
catch (Exception e)
{
return "Error compiling script " + e.Message + "\r\n" + Result;
}
return Result;
}
This example runs the LUA compiler and returns all error messages (async) to a string "Result". I show this sting in a multiline textbox in the forms application tha calls this compiler.
These three lines do the trick for you to redirect the output.
Compiler.StartInfo.UseShellExecute = false;
Compiler.StartInfo.RedirectStandardOutput = true;
Compiler.StartInfo.RedirectStandardError = true;
To actually obtain the information, you need to run the application and pick up the output. You need to wait till the application exits to get complete results, the last three lines do that for you:
Compiler.Start();
Result = Compiler.StandardOutput.ReadToEnd() + "\n" + Compiler.StandardError.ReadToEnd();
Compiler.WaitForExit();
Finally, you probably want to suppress the command window to be visible. This code will do that for you:
Compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Compiler.StartInfo.CreateNoWindow = true;

Handling errors while inside a button

I have a windows form that involes filling out textboxes with information and then clicking connect. I have error messages that pops up if any of the textboxes are empty but when I hit OK the program just continues and I end up getting run-time errors because there's insufficient information, and the program crashes. What I want is for the program to go back to the point before I hit "Connect" whenever any textbox is not filled out correctly.
This is the code:
private void cmdConnect_Click(object sender, EventArgs e)
{
if (cmdConnect.Text == "Connect")
{
if (txtGroup.Text == "")
{
txtGroup.Text = "_Group01";
}
if (txtItemID.Text == "")
{
MessageBox.Show("Please enter ItemID.", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
switch (cboServer.Text)
{
case "":
MessageBox.Show("Please select and OPC server", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case "RSLinx Remote OPC Server":
if (txtMachine.Text == "")
{
MessageBox.Show("Please enter a machine name for remote connection", "Connect Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
else
{
oOpcServer.Connect(cboServer.Text, txtMachine.Text);
}
break;
case "RSLinx OPC Server":
oOpcServer.Connect(cboServer.Text);
break;
default:
if (txtMachine.Text == "")
{
oOpcServer.Connect(cboServer.Text);
}
else
{
oOpcServer.Connect(cboServer.Text, txtMachine.Text);
}
break;
}
oOpcGroup = oOpcServer.OPCGroups.Add(txtGroup.Text);
oOpcGroup.IsSubscribed = true;
oOpcGroup.IsActive = false;
oOpcGroup.UpdateRate = 1000;
ClHandle = 1;
oOpcGroup.OPCItems.DefaultAccessPath = txtAccessPath.Text;
oOpcGroup.OPCItems.AddItem(txtItemID.Text, ClHandle);
cmdItemWrite.Enabled = true;
cmdItemRead.Enabled = true;
cmdSyncWrite.Enabled = true;
cmdSyncRead.Enabled = true;
cmdAsyncWrite.Enabled = true;
cmdAsyncRead.Enabled = true;
cmdAdvise.Enabled = true;
txtSubValue.Enabled = true;
cboServer.Enabled = false;
txtMachine.Enabled = false;
txtGroup.Enabled = false;
txtAccessPath.Enabled = false;
txtItemID.Enabled = false;
cmdConnect.Text = "Disconnect";
}
else
{
oOpcServer.OPCGroups.RemoveAll();
oOpcGroup = null;
oOpcServer.Disconnect();
cmdConnect.Text = "Connect";
cmdItemWrite.Enabled = false;
cmdItemRead.Enabled = false;
cmdSyncWrite.Enabled = false;
cmdSyncRead.Enabled = false;
cmdAsyncWrite.Enabled = false;
cmdAsyncRead.Enabled = false;
cmdAdvise.Enabled = false;
txtSubValue.Enabled = false;
cboServer.Enabled = true;
txtMachine.Enabled = true;
txtGroup.Enabled = true;
txtAccessPath.Enabled = true;
txtItemID.Enabled = true;
}
oOpcGroup.DataChange += new RsiOPCAuto.DIOPCGroupEvent_DataChangeEventHandler(oOpcGroup_DataChange);
}
Adding a return statment after each message box would do the trick and cause the method to exit without doing the work at end.
Simplest solution, as Dervall mentioned is adding return statements after each MessageBox.Show call. But more elegant solution is using validation and error provider to highlight incorrect input data prior to executing connect logic.
Anyway, here is some thoughts on refactoring your code.
private void cmdConnect_Click(object sender, EventArgs e)
{
if (cmdConnect.Text == "Disconnect")
{
Disconnect();
SetControlsToDisconnectedState();
return;
}
if (String.IsNullOrWhiteSpace(txtGroup.Text))
txtGroup.Text = "_Group01";
if (String.IsNullOrWhiteSpace(txtItemID.Text))
{
ShowErrorMessage("Connect Error", "Please enter ItemID.");
return;
}
if (String.IsNullOrWhiteSpace(cboServer.Text))
{
ShowErrorMessage("Connect Error", "Please select and OPC server");
return;
}
Connect(cboServer.Text, txtMachine.Text);
DoSomethingWithGroup(txtGroup.Text, txtAccessPath.Text, txtItemID.Text);
SetControlsToConnectedState();
}
What changed:
It's more readable, when you verify which text on button, then which it don't have
Method ShowErrorMessage does exactly what it says
Verify text with IsNullOrWhiteSpace because it could be full of white spaces
Control state changing moved to separate code
Connecting/Disconnecting now separated from UI
Here other methods:
private void ShowErrorMessage(string title, string message)
{
MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void SetControlsToConnectedState()
{
UpdateControls(true);
}
private void SetControlsToDisconnectedState()
{
UpdateControls(false);
}
private void UpdateControls(bool isConnected)
{
cmdConnect.Text = isConnected ? "Disconnect" : "Connect";
cmdItemWrite.Enabled = isConnected;
cmdItemRead.Enabled = isConnected;
cmdSyncWrite.Enabled = isConnected;
cmdSyncRead.Enabled = isConnected;
cmdAsyncWrite.Enabled = isConnected;
cmdAsyncRead.Enabled = isConnected;
cmdAdvise.Enabled = isConnected;
txtSubValue.Enabled = isConnected;
cboServer.Enabled = !isConnected;
txtMachine.Enabled = !isConnected;
txtGroup.Enabled = !isConnected;
txtAccessPath.Enabled = !isConnected;
txtItemID.Enabled = !isConnected;
}
private void Disconnect()
{
oOpcServer.OPCGroups.RemoveAll();
oOpcGroup = null;
oOpcServer.Disconnect();
}
private void Connect(string serverName, string machineName)
{
switch (serverName)
{
case "RSLinx Remote OPC Server":
if (String.IsNullOrWhiteSpace(machineName))
{
ShowErrorMessage("Connect Error", "Please enter a machine name for remote connection");
return;
}
oOpcServer.Connect(serverName, machineName);
break;
case "RSLinx OPC Server":
oOpcServer.Connect(serverName);
break;
default:
if (String.IsNullOrWhiteSpace(machineName))
oOpcServer.Connect(serverName);
else
oOpcServer.Connect(serverName, machineName);
break;
}
}
private void DoSomethingWithGroup(string groupName, string accessPath, string itemID)
{
oOpcGroup = oOpcServer.OPCGroups.Add(groupName);
oOpcGroup.IsSubscribed = true;
oOpcGroup.IsActive = false;
oOpcGroup.UpdateRate = 1000;
ClHandle = 1;
oOpcGroup.OPCItems.DefaultAccessPath = accessPath;
oOpcGroup.OPCItems.AddItem(itemID, ClHandle);
oOpcGroup.DataChange += new RsiOPCAuto.DIOPCGroupEvent_DataChangeEventHandler(oOpcGroup_DataChange);
}

Sending Email with Attachment that accepts particular file type in ASP.NET C#

Now i fixed the filtering of file extension but i have a problem on "catch" it doesn't display any error message but good, it is not sending the email with wrong file type.
but my problem is here:
catch(Exception err)
{
Console.WriteLine(err.Message);
lblStatus.ForeColor = Color.Red;
lblFile.ForeColor = Color.Red;
lblStatus.Text = "There was an error occured while submitting your application";
lblFile.Text = " Accepts .doc, .docx and .pdf files only!";
return ;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileUpload1.HasFile)
{
var fileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
try
{
string strExtension = Path.GetExtension(fileName);
if (strExtension == ".docx" || strExtension == ".doc" || strExtension == ".pdf")
{
MailMessage myMessage = new MailMessage();
myMessage.To.Add(new MailAddress("someone#yahoo.com"));
myMessage.From = new MailAddress("me#gmail.com");
myMessage.Subject = txtSubject.Text;
myMessage.Body = "<html><body><br/><b>Sender Name:</b> " + txtName.Text.ToString() + "<br/><br/><b>Email:</b> " + txtEmail.Text.ToString() +
"<br/><br/><b>Contact Number:</b> " + txtContact.Text.ToString() + "<br/><br/><b>Subject</b> " + txtSubject.Text.ToString() +
"<br/><br/><b>CV Summary:</b><br/><br/>" + txtSummary.Text.ToString() + "</body></html>";
myMessage.IsBodyHtml = true;
myMessage.Attachments.Add(new Attachment(fileUpload1.PostedFile.InputStream, fileName));
SmtpClient mySmtp = new SmtpClient();
mySmtp.Host = "smtp.gmail.com";
mySmtp.Credentials = new System.Net.NetworkCredential("me#gmail.com", "mypassword");
mySmtp.EnableSsl = true;
mySmtp.Send(myMessage);
lblStatus.ForeColor = Color.Green;
lblStatus.Text = "We will contact you once you have been shortlisted to the position you are applying for. <br/> You may now close this window.";
txtName.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
txtSummary.Text = "";
txtContact.Text = "";
}
}
catch(Exception err)
{
Console.WriteLine(err.Message);
lblStatus.ForeColor = Color.Red;
lblFile.ForeColor = Color.Red;
lblStatus.Text = "There was an error occured while submitting your application";
lblFile.Text = " Accepts .doc, .docx and .pdf files only!";
return ;
}
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
txtSummary.Text = "";
txtContact.Text = "";
}
Here is a nicer way to do it:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileUpload1.HasFile) ;
{
var fileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
try
{
string strExtension = Path.GetExtension(fileName);
if (strExtension != ".docx" || strExtension != ".doc" || strExtension != ".pdf")
{
lblFile.ForeColor = Color.Red;
lblFile.Text = "You can attach .doc,.docx and pdf files only";
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "There was an error occured while sending your email. Please try again later.";
return;
}
MailMessage myMessage = new MailMessage();
myMessage.From = new MailAddress(txtEmail.Text);
myMessage.To.Add(new MailAddress("EMAIL#yahoo.com"));
myMessage.Subject = txtSubject.Text;
myMessage.Body = "<html><body><br/><b>Sender Name:</b> " + txtName.Text.ToString() + "<br/><br/><b>Email:</b> " + txtEmail.Text.ToString() +
"<br/><br/><b>Contact Number:</b> " + txtContact.Text.ToString() + "<br/><br/><b>Subject</b> " + txtSubject.Text.ToString() +
"<br/><br/><b>CV Summary:</b><br/><br/>" + txtSummary.Text.ToString() + "</body></html>";
myMessage.IsBodyHtml = true;
myMessage.Attachments.Add(new Attachment(fileUpload1.PostedFile.InputStream, fileName));
SmtpClient mySmtp = new SmtpClient();
mySmtp.Host = "smtp.gmail.com";
mySmtp.Credentials = new System.Net.NetworkCredential("EMAIL#gmail.com", "PASSWORD");
mySmtp.EnableSsl = true;
mySmtp.Send(myMessage);
lblStatus.ForeColor = Color.Green;
lblStatus.Text = "Email successfully sent! We will contact you as soon as you have been shortlisted for the position you are applying for.<br/> Thank You. You can close this window now. ";
txtName.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
txtSummary.Text = "";
txtContact.Text = "";
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Basically, you only want to catch exceptions i.e. IO or mail sending failures.
This code will return if the extension is not a doc, docx or pdf and not call the send mail code.
Also, the myMessage.From() address must be a valid email address and the one that you supplied via your NetworkCredentials()
Here is a cut down version of the code that I have tested and verified that it is working:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile) ;
{
var fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
try
{
string strExtension = Path.GetExtension(fileName);
if (strExtension != ".docx" || strExtension != ".doc" || strExtension != ".pdf")
{
lblFile.ForeColor = Color.Red;
lblFile.Text = "You can attach .doc,.docx and pdf files only";
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "There was an error occured while sending your email. Please try again later.";
return;
}
MailMessage myMessage = new MailMessage();
myMessage.To.Add(new MailAddress("OtherPersonsEmail#email.xyz"));
myMessage.From = new MailAddress("YourEmailAddress#gmail.com");
myMessage.Subject = "Test";
myMessage.Body = "asd asd as d";
myMessage.IsBodyHtml = true;
myMessage.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, fileName));
SmtpClient mySmtp = new SmtpClient();
mySmtp.Host = "smtp.gmail.com";
mySmtp.Credentials = new System.Net.NetworkCredential("YourEmailAddress#gmail.com", "YourPassword");
mySmtp.EnableSsl = true;
mySmtp.Send(myMessage);
}
catch(Exception ex)
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = ex.Message;
Console.WriteLine(ex.Message);
}
}
}

Categories

Resources