No overload for 'button1_Click' matches delegate - c#

I don't understand why I get this error... Can anyone help me?
private void button1_Click(object sender, EventArgs e, string filePath)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
Filenametext.Text = of.FileName;
//Create an instance for the openbox dialog
//And opens the explorer to select the wanted file.
{
DataRow row;
DataService m_WsData = new DataService();
string XMLFileName = ConfigurationSettings.AppSettings["XMLPath"].ToString() + DateTime.Now.Ticks.ToString() + ".xml";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("ISO-8859-1"));
{
DataSet ds = m_WsData.GEDS();
string line = "";
int lineNo = 0;
string lineStart = "";
string lineEnd = "";
string[] fileRow;
{
line = sr.ReadLine();
if (line != null)
{
fileRow = line.Split(new Char[] { ';' });
if (lineNo == 0)
{
lineStart = fileRow[0];
}
if (fileRow[0] != "00" && fileRow[0] != "99")
{
row = ds.Tables["FuelFileData"].NewRow();
row["TransNo"] = fileRow[0];
row["CustomerNo"] = fileRow[1];
row["TruckNo"] = fileRow[2];
row["FuelDate"] = fileRow[3];
row["FuelTime"] = fileRow[4];
row["Place"] = fileRow[5];
row["FuelTypeNo"] = fileRow[6];
row["FuelDescription"] = fileRow[7];
row["DriverNo"] = fileRow[8];
row["Blank"] = fileRow[9];
row["TransType"] = fileRow[10];
row["Fuel"] = fileRow[11];
row["FuelCost"] = fileRow[12];
row["MileageFile"] = fileRow[13];
row["DrivenKm"] = fileRow[14];
row["AverageConsFile"] = fileRow[15];
//row["ImportedGuid"]=fileRow[16];
}
lineEnd = fileRow[0];
lineNo++;
}
} while (line != null);
lineStart = lineStart.Trim() + lineEnd.Trim();
fs.Close();
if (lineStart == "0099")
{
ds.WriteXml(XMLFileName);
System.IO.File.Delete(XMLFileName);
}
}
}
}

Cause
You cannot add parameters on event handler methods.
The Click event is defined as
public event RoutedEventHandler Click;
which means that the handler must match the delegate RoutedEventHandler which is
public delegate void RoutedEventHandler(Object sender, RoutedEventArgs e);
Solution
Remove the string filePath parameter and pass the path via a public property.

Related

File upload saving the folder instead of the file

I'm performing upload of files into DB with Telerik's ASP.NET RadAsyncpload, which is very similar to the normal fileUpload.
My problem is that, when using the variable to store the Data, it saves as "null". in alternative i tried to use Server.MapPath, which is for is turn saving the folder localtion instead of the File.
What am i doing wrong?
//partial class declarations
(...)
string Ficheiro = string.Empty;
string FileTipo = string.Empty;
byte[] fileBytes = null;
//Save method, triggered by save button after upload
public void SaveFile(object sender, EventArgs e)
{
ListagemTimesheet model = new ListagemTimesheet();
model.IDRecursoHumano = Convert.ToInt32(rdpInvestigadorE.Text);
model.IDEstadoTimesheet = Convert.ToInt32(rcbEstado.SelectedValue);
model.Observações = Obervaçoestxt.Text;
model.AssinaturaTimesheet = txtAssinaturaTimesheet.Text;
model.DataEnvio = DataEnvio.SelectedDate.Value;
if (Objecto.ID > 0)
{
model.ID = Convert.ToInt32(FileID.Text);
if (!string.IsNullOrEmpty(Ficheiro) && FileTipo != null)
{
model.FileName = Path.GetFileNameWithoutExtension(Ficheiro); //FileName
model.FileTipo = Path.GetExtension(FileTipo); //FileExtension
model.FileContent = fileBytes; //Content null
model.FileContent = Encoding.ASCII.GetBytes(HttpContext.Current.Server.MapPath("~/TargetFiles/ + model.FileName")); //Content saved is location of the folder
//Upload method
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
RadAsyncUpload1.Visible = false;
Stream fileStream = e.File.InputStream;
Ficheiro = e.File.FileName; // sintaxe metodo
FileTipo = e.File.ContentType;
e.IsValid = true;
byte[] fileBytes = new byte[fileStream.Length - 1 + 1];
fileStream.Read(dados, 0, System.Convert.ToInt32(fileStream.Length));
fileStream.Close();
}
You appear to be reading your file data into a local variable called dados, but is never assigned to the global variable.
Your file data should most likely go into the fileBytes variable, to enable your SaveFile function to read the value.
So you should read the fileStream directly into your fileBytes variable.
...
byte[] fileBytes = new byte[fileStream.Length - 1 + 1];
...
Full code
//Save method, triggered by save button after upload
public void SaveFile(object sender, EventArgs e)
{
ListagemTimesheet model = new ListagemTimesheet();
model.IDRecursoHumano = Convert.ToInt32(rdpInvestigadorE.Text);
model.IDEstadoTimesheet = Convert.ToInt32(rcbEstado.SelectedValue);
model.Observações = Obervaçoestxt.Text;
model.AssinaturaTimesheet = txtAssinaturaTimesheet.Text;
model.DataEnvio = DataEnvio.SelectedDate.Value;
if (Objecto.ID > 0)
{
model.ID = Convert.ToInt32(FileID.Text);
if (!string.IsNullOrEmpty(Ficheiro) && FileTipo != null)
{
model.FileName = Path.GetFileNameWithoutExtension(Ficheiro); //FileName
model.FileTipo = Path.GetExtension(FileTipo); //FileExtension
model.FileContent = fileBytes; // This will now be the data loaded from the filestream in your RadAsyncUpload1_FileUploaded function
// This returns the path in the content because Encoding.ASCII.GetBytes simply changes the string path to a byte array
//model.FileContent = Encoding.ASCII.GetBytes(HttpContext.Current.Server.MapPath("~/TargetFiles/ + model.FileName")); //Content saved is location of the folder
//Upload method
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
RadAsyncUpload1.Visible = false;
Stream fileStream = e.File.InputStream;
Ficheiro = e.File.FileName; // sintaxe metodo
FileTipo = e.File.ContentType;
e.IsValid = true;
// Read the file stream into your fileBytes variable
byte[] fileBytes = new byte[fileStream.Length - 1 + 1];
fileStream.Read(fileBytes, 0, System.Convert.ToInt32(fileStream.Length));
fileStream.Close();
}
RESOLVED!
I was missing copy the stream to the variable fileBytes.
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
RadAsyncUpload1.Visible = false; //false
var liItem = new HtmlGenericControl("li");
Ficheiro = e.File.FileName; // sintaxe metodo
FileTipo = e.File.ContentType;
e.IsValid = true;
e.File.InputStream.Position = 0;
fileBytes = new byte[e.File.InputStream.Length];
for (int totalBytesCopied = 0; totalBytesCopied < e.File.InputStream.Length; )
totalBytesCopied += e.File.InputStream.Read(fileBytes, totalBytesCopied, Convert.ToInt32(e.File.InputStream.Length) - totalBytesCopied); //conversao para bytes
e.File.InputStream.Close();
if (File.Exists("~/App_Data/RadUploadTemp"))
{
e.IsValid = false;
e.File.SaveAs(Server.MapPath(
Path.Combine(RadAsyncUpload1.TargetFolder, e.File.GetNameWithoutExtension() + "1" + e.File.GetExtension())));
}
}

How to do unit test on a method that has StreamReader and Database access

I have never done unit tests before. I'd like to learn how to do it. I'd like to use Visual Studio unit test and moq.
My project is transferring data from interbase to SQL Server. Firstly, I extract data from interbase into a plain text file. The layout is FieldName + some spaces up to 32 char length + field value. Then, I write a method that reads the text file line by line; once it reaches the next record, it inserts the current record into SQL Server.
So it involves in stream reader and SQL database insertion. For the stream reader, I read some post on the Internet and I pass the Stream reader as the method's parameter; but the SQL Server part, I have no idea how to simplify my method so that it can be tested.
I really need your help.
public partial class TableTransfer
{
#region declare vars
public string FirstFldName = "";
public string ErrorMsg = "";
public List<MemoBlobTrio> MemoBlobs = null;
public string SqlServerTableName = "";
#endregion
public bool DoTransfer(System.IO.StreamReader sr, Func<TransferShare, string, string, bool> TransferTable)
{
#region declare var
bool DoInsert = true;
TransferShare transferShare = null;
string line = string.Empty;
string blobLines = string.Empty;
string fldName = string.Empty;
string value = string.Empty;
bool Is1stLine = true;
bool isMemoFld = false;
MemoBlobTrio memoBlobTrio = null;
int idx = 0;
#endregion
try
{
using(sr)
{
transferShare = new TransferShare();
ConnectSQLServer(transferShare);
transferShare.StartInsert(SqlServerTableName);
bool readNext = true;
do
{
try
{
if (readNext)
line = sr.ReadLine();
if ((line != null) && (line.Trim() != ""))
{
fldName = line.Length > 30 ? line.Substring(0, 31).TrimEnd() : "";
Is1stLine = fldName == FirstFldName;
if (Is1stLine)
{
if (DoInsert)
EndInsert(transferShare, line);
else
transferShare.ClearSQL();
DoInsert = true;
}
idx = 0;
isMemoFld = false;
while (idx < MemoBlobs.Count)
{
if (fldName == (MemoBlobs[idx] as MemoBlobTrio).fbFldName)
{
memoBlobTrio = MemoBlobs[idx] as MemoBlobTrio;
line = InsertMemoBlob(transferShare, sr, memoBlobTrio.ssFldName, fldName, memoBlobTrio.fbNextFldName);
readNext = false;
isMemoFld = true;
}
idx++;
}
if (!isMemoFld)
{
if (line.Length > 31)
value = line.Remove(0, 31);
else
value = "";
if (!TransferTable(transferShare, fldName, value))
DoInsert = false;
readNext = true;
}
}
}
catch (Exception err)
{
HandleError(err, line);
}
} while (line != null);
if (DoInsert)
EndInsert(transferShare, line);
}
}
finally
{
transferShare.SQLConn.Dispose();
}
return true;
}
private static void ConnectSQLServer(TransferShare transferShare)
{
TransferShare.SQLServerConnStr = "Data Source=" + Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True";
transferShare.SQLConn.ConnectionString = TransferShare.SQLServerConnStr;
transferShare.SQLConn.Open();
}
}
public class TransferShare
{
public void StartInsert(string TableName)
{
tableName = TableName;
}
public void EndInsert(TransferShare transferShare, string line)
{
SqlCommand Cmd = null;
try
{
sqlInsFld = sqlInsFld.Remove(sqlInsFld.Length - 1);
sqlInsValue = sqlInsValue.Remove(sqlInsValue.Length - 1);
sqlInsFld = "Insert into " + tableName + " (" + sqlInsFld + ")";
sqlInsValue = " Values (" + sqlInsValue + ")";
Cmd = new SqlCommand(sqlInsFld + sqlInsValue, SQLConn);
Cmd.ExecuteNonQuery();
}
catch (Exception err)
{
throw (new Exception(err.Message));
}
finally
{
sqlInsFld = "";
sqlInsValue = "";
}
}
}

How I can close a text file after I edited?

I have a text file installer_input.txt and a checkedListBox2 in a form application. I want to edit the text file if I have some changes in checkesListBox2. I have two parts of code, I know that are so long, but I need some help :
private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory.ToString();
var lin = (path + "config.ini").ToString();
var lines = File.ReadAllLines(lin);
string InstallerFile = lines.Where(txt => txt.Contains("IstallerFile="))
.Select(txt => txt.Split('=')[1].Replace("\"", "")).FirstOrDefault();
string pathTemp = #"C:\temp\";
string[] pathArr = InstallerFile.Split('\\');
string[] fileArr = pathArr.Last().Split('\\');
string fileArr1 = String.Join(" ", fileArr);
string installerfilename = string.Format("{0}{1}", pathTemp, fileArr1);
IEnumerable<string> inilines = File.ReadAllLines(installerfilename).AsEnumerable();
bool IsChecked = checkedListBox2.CheckedItems.Contains(checkedListBox2.SelectedItem);
else if (fileArr1.Equals("installer_input.txt"))
{
if (IsChecked && checkedListBox2.CheckedItems.Count != checkedListBox2.Items.Count)
inilines = inilines.Select(line => line == string.Format("#product.{0}", checkedListBox2.SelectedItem)
? Regex.Replace(line, string.Format("#product.{0}", checkedListBox2.SelectedItem), string.Format(#"product.{0}", checkedListBox2.SelectedItem))
: line);
else if (!IsChecked || checkedListBox2.CheckedItems.Count == checkedListBox2.Items.Count)
inilines = inilines.Select(line => (line == string.Format("product.{0}", checkedListBox2.SelectedItem))
? Regex.Replace(line, string.Format(#".*product.{0}", checkedListBox2.SelectedItem), string.Format(#"#product.{0}", checkedListBox2.SelectedItem))
: line);
if (checkedListBox2.CheckedItems.Count == checkedListBox2.Items.Count)
checkBox1.Checked = true;
else
checkBox1.Checked = false;
string strWrite = string.Join(Environment.NewLine, inilines.ToArray());
File.WriteAllText(installerfilename, strWrite);
}
}
And the second code is :
private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
{
CheckBox cb = sender as CheckBox;
SetAllItemsChecked(cb.Checked);
var installerLines = ReadInstallerLines();
SetAllProductsChecked(installerLines.ToList(), cb.Checked);
SaveInstaller(installerLines);
}
private void SetAllItemsChecked(bool check)
{
for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
{
this.checkedListBox2.SetItemChecked(i, check);
}
}
private IEnumerable<string> ReadInstallerLines()
{
var lin = (path + "config.ini").ToString();
var lines = File.ReadAllLines(lin);
string InstallerFile = lines.Where(txt => txt.Contains("IstallerFile="))
.Select(txt => txt.Split('=')[1].Replace("\"", "")).FirstOrDefault();
string pathTemp = #"C:\temp\";
string[] pathArr = InstallerFile.Split('\\');
string[] fileArr = pathArr.Last().Split('\\');
string fileArr1 = String.Join(" ", fileArr);
string installerfilename = pathTemp + fileArr1;
string installertext = File.ReadAllText(installerfilename);
return File.ReadLines(pathTemp + fileArr1);
}
private void SetAllProductsChecked(IList<string> installerLines, bool check)
{
for (var i = 0; i < installerLines.Count; i++)
{
if (installerLines[i].Contains("product="))
{
installerLines[i] = check
? installerLines[i].Replace("#product", "product")
: installerLines[i].Replace("product", "#product");
}
if (installerLines[i].Contains("product."))
{
installerLines[i] = check
?installerLines[i].Replace("#product.", "product.")
: installerLines[i].Replace("product.", "#product.");
}
}
}
private void SaveInstaller(IEnumerable<string> installerLines)
{
var lin = (path + "config.ini").ToString();
var lines = File.ReadAllLines(lin);
string InstallerFile = lines.Where(txt => txt.Contains("IstallerFile="))
.Select(txt => txt.Split('=')[1].Replace("\"", "")).FirstOrDefault();
string pathTemp = #"C:\temp\";
string[] pathArr = InstallerFile.Split('\\');
string[] fileArr = pathArr.Last().Split('\\');
string fileArr1 = String.Join(" ", fileArr);
string installerfilename = pathTemp + fileArr1;
File.WriteAllLines(installerfilename, installerLines);
}
}
First works, I can check the boxes from the list, but when I try to make click on checkBox1 I have the next error: The process cannot access the file 'C:\temp\installer_input.txt' because it is used by another process.
How I can make program to works? And how I can optimize my code ?
Basically a single thread/process can access a resource which is the file in this case at one instance what you can do is use EventWaitHandle to wait untill some other process or thread has occupied the file like this:
EventWaitHandle waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, "SHARED_BY_ALL_PROCESSES");
waitHandle.WaitOne();
/* process file*/
waitHandle.Set();

Showing the values when form loaded

Hi all i have main form with a treeview control with a set of files displayed under each node. If i had my mouse over that node i will read the values that are present in the text file by using the following code
private void treeViewACH_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
{
string strFile = string.Empty;
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat(" {0}", e.Node);
strFile = messageBoxCS.ToString().Substring(11);
strFilePath = Directory.GetCurrentDirectory();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = strFilePath + "\\ACH" + "\\" + strFile;
if ((File.Exists(strFilePath)))
{
StreamReader sr = new StreamReader(strFilePath);
StringComparison compareType = StringComparison.InvariantCultureIgnoreCase;
string fileName = Path.GetFileNameWithoutExtension(strFilePath);
string extension = Path.GetExtension(strFilePath);
if (fileName.StartsWith("FileHeader", compareType)
&& extension.Equals(".txt", compareType))
{
string s = sr.ReadToEnd();
StringBuilder sb = new StringBuilder();
//sb.Append("RecordTypeCode\tPriorityCode");
//sb.Append("\n");
//sb.Append("--------------------------------------------------");
//sb.Append("\n");
objFile.ReferenceTypeCode = s.Substring(0, 1);
sb.Append(objFile.ReferenceTypeCode);
string PriorCode = s.Substring(1, 2);
sb.Append(PriorCode);
objFile.getValues(sb.ToString());
frmTemp frmtemp = new frmTemp();
frmtemp.Show();
}
}
Now i would like to place the values in each textboxes on the form load. But as it is a different form i can not access the values from the business layer
I have coded like this on form load
BL.FileHeader objFile = new FileHeader();
private void frmTemp_Load(object sender, EventArgs e)
{
textBox1.Text = objFile.ReferenceTypeCode;
}
But i am unable to display the values any help please..
Add a property to your frmTemp class for each value that you want to display. In your NodeMouseHover handler, assign values to those properties right after you create the instance of the form. Then, in the frmTemp_Load handler, assign the values of those properties to the TextBox controls.
Got the answer by the following
frmTemp frmtmp = new frmTemp(strFileHeader);
frmtmp.Show();
public frmTemp(string str)
{
InitializeComponent();
if (str.StartsWith("1"))
{
this.textBox1.Text = str.Substring(0, 1);
}
else if (str.StartsWith("5"))
{
this.textBox1.Text = str.Substring(0, 1);
this.textBox2.Text = str.Substring(4, 16);
}
}

Need to parse a string till the end of the file

i have the following code ..i need to loop through end of the file as per the commented code shown below how i can do it ?
namespace BVParser
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\SourceAscii.msg", Encoding.Unicode);
string message = sr.ReadToEnd();
StreamWriter sw = new StreamWriter(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\DestAsciiOutNewWOEncodingUnicode.txt");
sw.Write(message);
sw.Close();
sr.Close();
// StreamReader srseek = new StreamReader(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\DestAsciiOutNewWOEncodingUnicode6.txt");
FileStream fs = new FileStream(#"D:\Jaison\JaisonWorking\EmailParse\Sample.BV.application.Mails\Sample.BV.application.Mails\ToTest\Test\DestAsciiOutNewWOEncodingUnicode6.txt", FileMode.Open, FileAccess.Read);
StreamReader r = new StreamReader(fs);
int index = message.IndexOf("prod-");
//Label2.Text = index.ToString();
Cluster.Text = message.Substring(index + 5, 2);
int indexend = message.IndexOf(" ", index);
int indexdiff = indexend - index;
Servers.Text = message.Substring(index, indexdiff);
// Loops should start here.. checking indexat("EOF")
While ()
{
int exindex = message.IndexOf("Exception:");
int checkspace = exindex;
checkspace--;
if (checkspace == ' ')
{
exindex = message.IndexOf("Exception:", exindex);
}
int trav = exindex;
while (message[trav] != '.') // || message[trav] != ' '
{
trav--;
}
int expdiff = exindex - trav + 9;
Exceptions.Text = message.Substring(trav, expdiff);
int lastdescindex = message.IndexOf('\n', exindex);
int firstdescindex = exindex + 10;
int diffdesc = lastdescindex - firstdescindex;
Desc.Text = message.Substring(firstdescindex, diffdesc);
// } Loop should end here.
fs.Close();
}
}
}
This is an example of something I've done...
StreamReader reader = File.OpenText(filename);
string line = null
while ((line = reader.ReadLine()) != null)
{
// ... your stuff here
}
reader.Close();
reader.Dispose();
I also suggest using a StreamReader.
Since it's IDisposable, You can also construct it with the 'using' statement:
using (var reader = new StreamReader(path))
{
string line = null
while ((line = reader.ReadLine()) != null)
{
// do something
}
}

Categories