Getting all the items from the listbox winform - c#

Good day!
I am having troubles on getting all the items, selected or not, from the listbox. Whenever I click the send button, the only items that I could get is the ones I selected (This is the current results of my code below: http://imgur.com/jA94Bjm). What I want is to get all the items from the textbox not just from the selected ones and which is not repeating.
private void cmd_send_Click_1(object sender, EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
try
{
String pno = textBox4.Text.ToString();
String path = textBox5.Text.ToString();
String name = textBox6.Text.ToString();
String user = textBox7.Text.ToString();
output.Text += "\n Sent data : " + pno + " " + user + " " + name + " " + path;
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + " " + textBox4.Text + " " + textBox5.Text + " " + textBox6.Text + " " + textBox7.Text;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}

If you want to access all your items from your listbox, you have to iterate all of the items and access the value of that item. Here's a sample how you can achieve this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
class Process
{
public int ProcessId { get; set; }
public string FilePath { get; set; }
public string FileName { get; set; }
public string User { get; set; }
}
static void Main(string[] args)
{
Process p1 = new Process();
p1.ProcessId = 1;
p1.FileName = "Tool.exe";
p1.FilePath = #"C:\Tool.exe";
p1.User = "User1";
Process p2 = new Process();
p2.ProcessId = 2;
p2.FileName = "Tool2.exe";
p2.FilePath = #"C:\Tool2.exe";
p2.User = "User2";
Process p3 = new Process();
p3.ProcessId = 3;
p3.FileName = "Tool3.exe";
p3.FilePath = #"C:\Tool3.exe";
p3.User = "User3";
ListBox listBox = new ListBox();
listBox.Items.Add(p1);
listBox.Items.Add(p2);
listBox.Items.Add(p3);
for (int i = 0; i < listBox.Items.Count; i++)
{
Process p = (Process)listBox.Items[i]; //Access the value of the item
Console.WriteLine("Process id: {0}", p.ProcessId);
Console.WriteLine("Process filename: {0}", p.FileName);
Console.WriteLine("Process file path: {0}", p.FilePath);
Console.WriteLine("Process user: {0}", p.User);
}
Console.ReadLine();
}
}
}
We have a sample class Process with different properties. Each Process is added on ListBox which is later accessed inside the loop.

Related

Accessing Variables by multiple threads in web application [duplicate]

This question already has an answer here:
Asp.net losing values of variables
(1 answer)
Closed 4 years ago.
I am running a web Form where I call a new thread on a button press to execute an Rdotnet snippet of code ( I needed the thread because the current thread kept sending stack overload errors ).
In the Rdotnet function , I have it access a global class variable and put data into it. Once the function completes and the button submit function is over I try to access that global class on another button click ( separate button ), however it is empty. I assume that the thread ends so all data in it ends to, so I tried returning the class and putting it into the global variable in the buttonclick function itself,same result.
I need help.
public partial class BTForm : Page
{
List<DirectorDetail> Details = new List<DirectorDetail>();
BindingList<string> Test = new BindingList<string>();
List<string> Line = new List<string>();
List<string> output = new List<string>();
WebDetails BTlibrary;
OpenFileDialog ofd = new OpenFileDialog();
List<string> Months = new List<string>();
List<string> Year = new List<string>();
BTBill Billfile = new BTBill();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
addMonth();
addyear();
foreach (var x in Months)
{
DropDownList1.Items.Add(x);
}
foreach (var y in Year)
{
DropDownList2.Items.Add(y);
}
}
try
{
ListBox4.DataSource = Test;
ListBox4.DataBind();
}
catch(Exception x)
{
Console.Write(x);
}
}
protected void Submit_Click(object sender, EventArgs e)
{
Thread current = Thread.CurrentThread;
WebDetails BTlibrary2 =BTlibrary;
Thread t = new Thread(() => { BTlibrary2 = processes(BTlibrary2); }, 2500000);
t.Start();
t.Join();
BTlibrary = BTlibrary2;
// Thread.Sleep(10000);
}
public WebDetails processes(WebDetails library)
{
if (FileUpLoad1.HasFile)
{
string location = #"C:/BTBill/" + FileUpLoad1.FileName;
Billfile.Tablename = FileUpLoad1.FileName;
try
{
Billfile.Month = DropDownList1.SelectedItem.ToString();
Billfile.Year = DropDownList2.SelectedItem.ToString();
Billfile.Filename = Cleaning.PathCleaning(location);
Billfile.Limit = TextBox3.Text.ToString();
string fpath = Billfile.Month + " " + Billfile.Year + " Query " + "Limit -£ " + Billfile.Limit + "\\";
string filename = Billfile.Month + " " + Billfile.Year + " Query " + "Limit -£ " + Billfile.Limit;
Billfile.Savelocation = "//lonvmfs01/commonwealth_Data/BT BILL Alert/" + filename;
Billfile.Sfilename = "//lonvmfs01/commonwealth_Data/BT BILL Alert/" + filename;
}
catch (Exception x)
{
Error1.Text = "Please Select Month and year\nERROR : " + x;
}
FileUpLoad1.SaveAs(#"C:\BTBill\" + FileUpLoad1.FileName);
library = Executable.executable(Billfile);
// FileUpLoad1.
// = "File Uploaded: " + FileUpLoad1.FileName;
}
else
{
Label1.Text = "No File Uploaded.";
}
DataFrame Director = library.Director;
DataFrame bill = library.Query;
DataFrame limit = library.Btlim;
int colcount = Director.RowCount;
for (int x = 0; x < colcount; x++)
{
string cost_centre = Director[x, 0].ToString();
string director = Director[x, 1].ToString();
string email_address = Director[x, 2].ToString();
double total = SendMail.calculatetotal(bill, limit, cost_centre);
if (total > 0)
{
Line.Add(x + " )\t" + cost_centre + "\t" + director + "\t\t" + email_address + "\t" + total);
Test.Add(x + " )\t" + cost_centre + "\t" + director + "\t\t" + email_address + "\t" + total);
}
}
ListBox4.DataSource = Test;
ListBox4.DataBind();
//foreach (var x in getline().ToArray())
// {
// ListBox4.Items.Add(x);
// }
// ListBox4.DataBind();
return library;
}
protected void Sendmail(object sender, EventArgs e)
{
DataFrame Director = BTlibrary.Director;
DataFrame bill = BTlibrary.Query;
DataFrame limit = BTlibrary.Btlim;
string test;
foreach (Object selecteditem in ListBox4.GetSelectedIndices() )
{
test = ListBox4.Items[(int)selecteditem].Text;
System.Diagnostics.Debug.WriteLine(test);
test = test.Substring(0, 1);
output.Add(test);
}
List<int> index = new List<int>();
for (int y = 0; y < output.Count; y++)
{
index.Add(Convert.ToInt32(output[y]));
}
for (int y = 0; y < index.Count; y++)
{
DirectorDetail temp = new DirectorDetail();
temp.cost_centre = Director[index[y], 0].ToString();
temp.director = Director[index[y], 1].ToString();
temp.email_address = Director[index[y], 2].ToString();
for (int count = 0; count < limit.RowCount; count++)
{
if (limit[count, 0].ToString() == temp.cost_centre)
{
temp.limit = limit[count, 1].ToString();
}
}
Details.Add(temp);
}
SendMail.Mailing(BTlibrary.Query, BTlibrary.Deplist, BTlibrary.Btlim, BTlibrary.Bill, Details);
//Session["Details"] = Details;
// this.Close();
}
private void addyear()
{
DateTime time = System.DateTime.UtcNow;
int baseyear = time.Year - 3;
for (int x = baseyear; x < (baseyear + 10); x++)
{
Year.Add(x.ToString());
}
}
// returns the list of years
public List<string> getYear()
{
return Year;
}
// returns the list of months
public List<String> getMonth()
{
return Months;
}
//adds months to a list
private void addMonth()
{
Months.Add("January");
Months.Add("February");
Months.Add("March");
Months.Add("April");
Months.Add("May");
Months.Add("June");
Months.Add("July");
Months.Add("August");
Months.Add("September");
Months.Add("October");
Months.Add("November");
Months.Add("December");
}
public List<string> getline()
{
return Line;
}
}
public static WebDetails executable(BTBill bill)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null,true,rinit);
// engine.Initialize();
//install and make connection to Postgres
// engine.Evaluate("install.packages('RPostgreSQL') \n install.packages('gridExtra')");
engine.Evaluate("require('RPostgreSQL')" + "\n" +
"pw <- {'admin'}" + "\n" +
"drv <- RPostgreSQL::PostgreSQL()" + "\n" +
"drv <- dbDriver('PostgreSQL')" +"\n"+
"con <- dbConnect(drv, dbname = 'postgres'," +"\n"+
"host = 'localhost', port = 5432," +"\n"+
"user = 'postgres', password = pw)");
engine.Evaluate("postgresmfile<- dbGetQuery(con,'select * from masterfile')" + "\n" +
"Contact <- dbGetQuery(con, 'select * from contact')"+"\n"+
"btlim<- dbGetQuery(con, ' select * from bt_departmentlimit')"+"\n"+
"dbDisconnect(con)");
engine.Evaluate("BTBill = read.csv(file<-'"+bill.Filename+"', header=TRUE, sep=',',skip=1)");
// building dataframes and queries
DataFrame BTBill = engine.Evaluate("BTBill").AsDataFrame();
DataFrame MasterFile = engine.Evaluate("postgresmfile").AsDataFrame();
DataFrame BTLim = engine.Evaluate("btlim").AsDataFrame();
DataFrame Contact= engine.Evaluate("Contact ").AsDataFrame();
DataFrame Query = engine.Evaluate("Merged <- merge(BTBill,postgresmfile,by.x='SERVICE.NO',by.y = 'service_number')" + "\n"+ "Merged_2 <- merge(Merged,Contact,by.x='cost_centre',by.y='cost_centre') " + "\n"+
"query <- Merged_2[c('SERVICE.NO','username','cost_centre','job_post','USAGE.CHARGES','TOTAL.COST','USAGE.START.DATE','USAGE.END.DATE','director','email_address')]").AsDataFrame();
DataFrame Merge2 = engine.Evaluate("Merged_2").AsDataFrame();
DataFrame maillist = engine.Evaluate("data.frame(query)" +"\n"+
"test <-subset(query, TOTAL.COST >= "+bill.Limit+ ", select = c(SERVICE.NO,username,cost_centre,job_post, TOTAL.COST, USAGE.START.DATE, USAGE.END.DATE,director,email_address,USAGE.CHARGES))").AsDataFrame();
DataFrame DepList = engine.Evaluate("x<-test[c('cost_centre','director','email_address')]" + "\n" +
"ux<-unique(x) ").AsDataFrame();
DataFrame DepList2=engine.Evaluate("y <-query[c('cost_centre', 'director', 'email_address')]" + "\n" +
"uy<-unique(y) ").AsDataFrame();
engine.Evaluate("dir.create(file.path('" + bill.Savelocation + "'))");
//creating pdf files for each department head
engine.Evaluate("write.csv(Merged_2, file = '" + bill.Savelocation + "/MasterFile.csv');");
for (int count = 0; count < DepList.RowCount; count++)
{
DataFrame temp = engine.Evaluate("data.frame(query);" +
"test2 <-subset(query, USAGE.CHARGES >= " + bill.Limit + " & cost_centre=='"+DepList[count,0]+"', select = c(SERVICE.NO,username,cost_centre,job_post, USAGE.CHARGES, USAGE.START.DATE, USAGE.END.DATE,director,email_address))").AsDataFrame();
engine.Evaluate("library(gridExtra);");
engine.Evaluate("pdf('" + bill.Sfilename +"/"+ DepList[count, 0] + ".pdf', height=20, width=20);" );
try
{
engine.Evaluate("grid.table(test2); dev.off() ;");
}
catch (Exception e)
{
}
}
SendMailForm form = new SendMailForm();
WebDetails web = new WebDetails(DepList2, Query, BTLim);
web.Deplist = DepList;
web.Bill = bill;
engine.Evaluate("write.csv(test, file = '" + bill.Savelocation + "/Users over threshold.csv')");
engine.Dispose();
return web;
// form.Director=DepList2;
//form.bill = Query;
//form.limit = BTLim;
List<DirectorDetail> output = form.Details;
SendMail.Mailing(Query, DepList,BTLim, bill,output);
// to filter by department
// DataFrame maillist = engine.Evaluate("data.frame(query)" + "\n" +
// "test <-subset(query, TOTAL.COST >= " + bill.Limit + "& Cost.Centre=='"+bill.Dep+"', select = c(SERVICE.NO, User.Name, Cost.Centre, ROLE.JOB.POST, TOTAL.COST, USAGE.START.DATE, USAGE.END.DATE,DIRECTOR,EMAIL.ADDRESS))").AsDataFrame();
//engine.Evaluate("install.package('dplyr')");
}
}
}
It seems my problem turned out to be unrelated to variable sharing through threads, but instead to deal with the way button click instances worked.
long story short, in order to share a variable between two event instances, the easiest way to do it is through Sessions.
I needed to put the BTlibrary in a session and access it in the second button click event for it to get the value saved from the previous.
protected void Submit_Click(object sender, EventArgs e)
{
Thread current = Thread.CurrentThread;
WebDetails BTlibrary2 =BTlibrary;
Thread t = new Thread(() => { BTlibrary2 = processes(BTlibrary2); }, 2500000);
t.Start();
t.Join();
Session["BTLib"] = BTlibrary2;
// Thread.Sleep(10000);
}
protected void Sendmail(object sender, EventArgs e)
{
List<DirectorDetail> Details = new List<DirectorDetail>();
BTlibrary = (WebDetails) Session["BTLib"];
this worked

Memory usage is growing while processing files

I'm developing an application that reads a xml file folder , and each file it to do some checks and copied to a new folder based on some criteria.
But memory usage continues to grow when it arrives in the foreach loop , and I believe that should not happen , because the variables do not increase at each iteration , are only overwritten.
Here is my code:
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
namespace XMLOrganizer
{
public partial class Form1 : Form
{
string selectedFolder;
public Form1()
{
InitializeComponent();
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
selectedFolder = folderBrowserDialog1.SelectedPath;
organizeBtn.Enabled = true;
}
private void organizeBtn_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Selecione o tipo de nota", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
return;
}
if (comboBox1.SelectedIndex != 2)
{
OrganizeXml(label2, selectedFolder, comboBox1);
}
//ORGANIZAR LOTES
else
{
string folder = selectedFolder;
label2.Text = "Arquivos sendo processados, aguarde...";
label2.Refresh();
string[] files = Directory.GetFiles(folder, "*.xml", SearchOption.AllDirectories);
int atualFile = 1, totalXML = files.Length;
foreach (string file in files)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(file);
XmlNodeList enviNFe = xmlDocument.GetElementsByTagName("enviNFe");
string versao = ((XmlElement)enviNFe[0]).Attributes["versao"].Value;
XmlNodeList NFe = ((XmlElement)enviNFe[0]).GetElementsByTagName("NFe");
Directory.CreateDirectory(selectedFolder + #"\NOTAS");
label2.Text = "Processando arquivo " + atualFile + " de " + totalXML;
string notaXML;
foreach (XmlElement nota in NFe)
{
notaXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"" + versao + "\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + nota.OuterXml + "</nfeProc>";
XmlNodeList infNFe = nota.GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
File.WriteAllText(selectedFolder + "\\NOTAS\\" + chave + ".xml", notaXML);
}
}
OrganizeXml(label2, selectedFolder + "\\NOTAS", comboBox1);
}
}
private static void OrganizeXml(Label label2, string selectedFolder, ComboBox comboBox1)
{
string folderMove = String.Empty;
string folder = selectedFolder;
label2.Text = "Arquivos sendo processados, aguarde...";
label2.Refresh();
string[] files = Directory.GetFiles(folder, "*.xml", SearchOption.AllDirectories);
int i = 1, arquivos = files.Length;
Directory.CreateDirectory(folder + #"\ORGANIZADO");
if (comboBox1.SelectedIndex != 2)
{
Directory.CreateDirectory(folder + #"\ORGANIZADO\OUTROS");
Directory.CreateDirectory(folder + #"\ORGANIZADO\LOTES");
}
foreach (string file in files)
{
XmlDocument xmlDocument = new XmlDocument();
try
{
xmlDocument.Load(file);
if (xmlDocument.DocumentElement.Name != "nfeProc")
{
XmlNodeList NFe = xmlDocument.GetElementsByTagName("NFe");
var nota = ((XmlElement) NFe[0]);
if (nota != null)
{
XmlNodeList infNFe = ((XmlElement) NFe[0]).GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
string versao = infNFe[0].Attributes["versao"].Value;
string notaXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"" + versao +
"\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + nota.OuterXml +
"</nfeProc>";
string dirNote = Path.GetDirectoryName(file);
File.WriteAllText(dirNote + "\\fix_" + chave + ".xml", notaXML);
}
}
//
//
//
}
catch (XmlException)
{
XmlDocument doc = new XmlDocument();
string arquivo = ReadFileToString(file);
arquivo = RemoveSpecialCharacters(arquivo);
if (arquivo == "")
{
File.Move(file, folder + #"\ORGANIZADO\OUTROS\corrupt_" + Path.GetFileName(file));
continue;
}
try
{
doc.LoadXml(arquivo);
doc.PreserveWhitespace = true;
doc.Save(file);
}
catch (XmlException)
{
File.Move(file, folder + #"\ORGANIZADO\OUTROS\corrupt_" + Path.GetFileName(file));
files = files.Where(f => f != file).ToArray();
}
}
}
foreach (string file in files)
{
string arquivoLoad = file;
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(arquivoLoad);
XmlNodeList NFe = xmlDocument.GetElementsByTagName("NFe");
XmlNodeList enviNFe = xmlDocument.GetElementsByTagName("enviNFe");
if (NFe.Count == 0)
{
if (File.Exists(folder + #"\ORGANIZADO\OUTROS\no_NFe_" + Path.GetFileName(arquivoLoad)))
{
Random rnd = new Random();
File.Copy(arquivoLoad,
folder + #"\ORGANIZADO\OUTROS\no_NFe_" + rnd.Next(1, 5000) + Path.GetFileName(arquivoLoad));
}
else
{
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\OUTROS\no_NFe_" + Path.GetFileName(arquivoLoad));
}
continue;
}
XmlNodeList infNFe = ((XmlElement)NFe[0]).GetElementsByTagName("infNFe");
string chave = infNFe[0].Attributes["Id"].Value.Replace("NFe", "");
if (xmlDocument.DocumentElement.Name != "nfeProc")
{
File.Move(arquivoLoad, folder + #"\ORGANIZADO\OUTROS\no_nfeProc_" + Path.GetFileName(arquivoLoad));
arquivoLoad = Path.GetDirectoryName(file) + "\\fix_" + chave + ".xml";
}
if (enviNFe.Count > 0)
{
if (File.Exists(folder + #"\ORGANIZADO\LOTES\" + Path.GetFileName(arquivoLoad)))
{
Random rnd = new Random();
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\LOTES\" + rnd.Next(1, 5000) + Path.GetFileName(arquivoLoad));
}
else
{
File.Copy(arquivoLoad, folder + #"\ORGANIZADO\LOTES\" + Path.GetFileName(arquivoLoad));
}
continue;
}
//XmlNodeList infNFe = ((XmlElement)NFe[0]).GetElementsByTagName("infNFe");
XmlNodeList ide = ((XmlElement)infNFe[0]).GetElementsByTagName("ide");
string tpNF = ((XmlElement)ide[0]).GetElementsByTagName("tpNF")[0].InnerText;
//if (tpNF == "0") continue;
XmlNodeList emit = ((XmlElement)infNFe[0]).GetElementsByTagName("emit");
string emitInfoCod;
if (((XmlElement)emit[0]).GetElementsByTagName("CNPJ").Count > 0)
{
emitInfoCod = ((XmlElement)emit[0]).GetElementsByTagName("CNPJ")[0].InnerText;
}
else if (((XmlElement)emit[0]).GetElementsByTagName("CPF").Count > 0)
{
emitInfoCod = ((XmlElement)emit[0]).GetElementsByTagName("CPF")[0].InnerText;
}
else
{
emitInfoCod = "0";
}
string ide_dEmi = (((XmlElement)ide[0]).GetElementsByTagName("dEmi").Count > 0)
? ((XmlElement)ide[0]).GetElementsByTagName("dEmi")[0].InnerText
: ((XmlElement)ide[0]).GetElementsByTagName("dhEmi")[0].InnerText;
string[] data = ide_dEmi.Split('-');
string folderName = data[0] + "\\" + data[1];
string organizeStyle = String.Empty;
if (comboBox1.SelectedIndex == 0 || comboBox1.SelectedIndex == 2)
{
organizeStyle = folder + #"\ORGANIZADO\" + emitInfoCod + #"\" + folderName;
}
else
{
organizeStyle = folder + #"\ORGANIZADO\" + folderName + #"\" + emitInfoCod;
}
if (!Directory.Exists(organizeStyle))
{
Directory.CreateDirectory(organizeStyle);
}
folderMove = organizeStyle + "\\";
if (!File.Exists(folderMove + chave + ".xml"))
{
File.Copy(arquivoLoad, folderMove + chave + ".xml");
}
label2.Text = "Arquivos sendo processados, aguarde... (" + i + " / " + arquivos + ")";
label2.Refresh();
i++;
}
label2.Text = "Notas organizadas com sucesso!";
label2.Refresh();
}
public static string ReadFileToString(string filePath)
{
using (StreamReader streamReader = new StreamReader(filePath))
{
string text = streamReader.ReadToEnd();
streamReader.Close();
return text;
}
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, #"[^\u0000-\u007F]", string.Empty);
}
private void exitBtn_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
How can I determine what 's going on?
The value of a variable pointing to a reference type is not the object at all, its just the memory address where the object lives.
So when you do the following:
while (true)
{
var myVariable = new MyReferenceType();
}
The only memory you are really reusing is the variable itself (think of a 32 or 64 bit pointer). But on every iteration your are allocating somewhere in memory space enough to fit the new object you've just created and that memory is most definitely not the memory reserved to the previous object.
This is essentially why your memory usage is growing. The "old" objects of previous iterations with no live reference will eventually get collected by the GC, but that could be never if the GC decides that it has enough memory available to avoid it.

How to Serialize a list of objects

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace AppPrueba
{
public partial class Form1 : Form
{
ArrayList listaFilas = new ArrayList();
public Form1()
{
InitializeComponent();
}
List<Empleados> emp = new List<Empleados>();
List<Agenda> agen = new List<Agenda>();
static public void SerializeToXML(List<Agenda> agen)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Agenda>));
TextWriter textWriter = new StreamWriter(#"C:\agenda.xml");
serializer.Serialize(textWriter, agen);
textWriter.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog(this);
string strfilename = openFileDialog1.FileName;
txtPath.Text = strfilename;
if ((strfilename.Trim().Length > 0) && (File.Exists(strfilename)))
{
string[] readText = File.ReadAllLines(strfilename);
if (strfilename.EndsWith("Agenda.txt"))
{
lstLinesBeforeChange.Items.Clear();
foreach (string s in readText)
{
lstLinesBeforeChange.Items.Add(s);
}
}
else
{
lstLinesBeforeChange.Items.Clear();
foreach (string s in readText)
{
lstLinesBeforeChange.Items.Add(s);
}
}
}
}
private void btnModify_Click(object sender, EventArgs e)
{
string strfilename = txtPath.Text;
string[] readText = File.ReadAllLines(strfilename);
if (strfilename.EndsWith("Agenda.txt"))
{
lstLinesAfterChange.Items.Clear();
foreach (string s in readText)
{
int nroEmp = Convert.ToInt32(s.Substring(0, 4));
string nombre = s.Substring(4, 15);
string telef = s.Substring(19, 10);
string ciudad = s.Substring(29);
Agenda unAgenda = new Agenda();
unAgenda.NroEmp = nroEmp;
unAgenda.Nombre = nombre.TrimStart().TrimEnd();
unAgenda.Telefono = telef;
unAgenda.Localidad = ciudad;
agen.Add(unAgenda);
agen.Sort(delegate(Agenda a1, Agenda a2)
{
return a1.NroEmp.CompareTo(a2.NroEmp);
});
}
foreach (Agenda a in agen)
{
string agenOrd = a.NroEmp.ToString() + "\t" + a.Nombre + "\t" + a.Telefono + "\t" + a.Localidad;
lstLinesAfterChange.Items.Add(agenOrd);
}
}
else
{
lstLinesAfterChange.Items.Clear();
foreach (string s in readText)
{
string[] sSinBarra = s.Split('|');
int nroEmp = Convert.ToInt32(sSinBarra[0]);
string nombre = sSinBarra[1];
string posicion = sSinBarra[2];
int nroOficina = Convert.ToInt32(sSinBarra[3]);
int piso = Convert.ToInt32(sSinBarra[4]);
string fechaIng = sSinBarra[5];
int dia = Convert.ToInt32(fechaIng.Substring(0, 2));
int mes = Convert.ToInt32(fechaIng.Substring(2, 2));
int año = Convert.ToInt32(fechaIng.Substring(4, 4));
string fechaIngreso = dia + "/" + mes + "/" + año;
fechaIng = fechaIngreso;
Empleados unEmpleado = new Empleados();
unEmpleado.NroEmpleado1 = nroEmp;
unEmpleado.Nombre1 = nombre.TrimEnd().TrimStart();
unEmpleado.Posicion = posicion.TrimEnd().TrimStart();
unEmpleado.NroOficina = nroOficina;
unEmpleado.Piso = piso;
unEmpleado.FechaIngreso = fechaIngreso;
emp.Add(unEmpleado);
emp.Sort(delegate(Empleados e1, Empleados e2)
{
return e1.NroEmpleado1.CompareTo(e2.NroEmpleado1);
});
}
foreach (Empleados em in emp)
{
string empOrd = em.NroEmpleado1.ToString() + "\t" + em.Nombre1 + "\t" + em.Posicion + "\t" + em.NroOficina.ToString()
+ "\t" + em.Piso.ToString() + "\t" + em.FechaIngreso;
lstLinesAfterChange.Items.Add(empOrd);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//saveFileDialog1.ShowDialog();
//if (saveFileDialog1.FileName != "")
//{
// FileStream fs = (FileStream)saveFileDialog1.OpenFile();
// fs.Close();
//}
SerializeToXML(agen);
}
}
}
I have this, and i want to serialize to xml both lists :
List<Empleados> emp = new List<Empleados>();
List<Agenda> agen = new List<Agenda>();
I used SerializeToXML method that i found in other tutorial but when i run it an error shows up
"Error 1 Inconsistent accessibility: parameter type
'System.Collections.Generic.List' is less accessible
than method
'AppPrueba.Form1.SerializeToXML(System.Collections.Generic.List)' C:\Users\722825\Desktop\Santi
Cosas\AppPrueba\AppPrueba\Form1.cs 27 28 AppPrueba"
Thanks in advance if you can help me!
All the classes that you are trying to serialize to xml should be public. And for collection serialization you cannot use generics - either use untyped collections, like, ArrayList , or create a non-generic descendant class form List .
agen is private and SerializeToXML is public static. You need agen public
Your error says that the variabel List agen = new List(); needs to be public like this: public List agen = new List();

How can I write a console application which can search Users Directory?

I asked guru but I still couldn't solve the problem that I have.
I want to write a console program searching certain files, like xls, doc or *pdf.
I wrote a code like this but when it comes to the say, Users Directory, it cates UnauthorizedAccessException.
How can I write a console application which can search Users Directory?
I set clickonce off and build it with manifest which requireAdministrator.
So, on Vista or 7, it runs as an administrator, with the elevation dialogue.
Here's the full code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
//
private const string FILE_NAME = "search.txt";
private const string SEARCH_WORDS1 = "*.doc";
private const string SEARCH_WORDS2 = "*.ppt";
private const string SEARCH_WORDS3 = "*.jtd";
private const string SEARCH_WORDS4 = "*.pdf";
private const string END_WORDS = "\r\nSearch is finished.\r\n";
//This funcion echoes the messages.
void FileCheck()
{
string echo_words = "\r\nNow starts searching these files!" + SEARCH_WORDS1 + " "
+ SEARCH_WORDS2 + " " + SEARCH_WORDS3 + " " + SEARCH_WORDS4 + " "
+ "!\r\n";
if (File.Exists(FILE_NAME))
{
Console.WriteLine("{0} is already exists. Replace it to the new one.", FILE_NAME);
Console.WriteLine(echo_words);
File.Delete(FILE_NAME);
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
sw.WriteLine(FILE_NAME + " is already exists. Replace it to the new one.\r\n");
sw.WriteLine(echo_words);
sw.Close();
}
}
else
{
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
Console.WriteLine(echo_words);
sw.WriteLine(echo_words);
sw.Close();
}
}
}
//This function write to a file that search is finished.
void EndMessage()
{
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
Console.WriteLine(END_WORDS);
sw.WriteLine(END_WORDS);
sw.Close();
}
}
//This function searches files given and write to a file.
void DirSearch(string sDir, string SEARCH_WORDS, int row)
{
int i;
i = 0;
string DeviceError = "off";
try
{
foreach (var d in Directory.GetDirectories(sDir))
{
DirectoryInfo di = new DirectoryInfo(d);
if ((di.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
//ReparsePoint could not be serached
continue;
}
try
{
foreach (string file in Directory.GetFiles(d, SEARCH_WORDS, SearchOption.AllDirectories))
{
Console.WriteLine(file);
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(file);
sw.Close();
i++;
}
}
}
catch (UnauthorizedAccessException)
{
//Unauthorized
Console.WriteLine(d + " is not allowd to be read !!");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(d + " is not allowd to be read");
sw.Close();
}
}
}
}
catch (IOException)
{
//Device is not ready
DeviceError = "on";
}
if (DeviceError == "off")
{
if (i > 0)
{
Console.WriteLine(i + "numbers " + SEARCH_WORDS + " Files were found!\r\n");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(i + "numbers " + SEARCH_WORDS + " Files were found!\r\n");
sw.Close();
}
}
else
{
Console.WriteLine(SEARCH_WORDS + " Files were not found !\r\n");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(SEARCH_WORDS + " Files were not found !\r\n");
sw.Close();
}
}
}
}
//Main
static void Main(string[] args)
{
Program x = new Program();
string[] drives = Environment.GetLogicalDrives();
int row = drives.GetLength(0);
string my_documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Console.WriteLine("Logical Drives are " + row + ".");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine("Logical Drives are " + row + ".");
sw.Close();
}
int i = 0;
x.FileCheck();
while (row > 0)
{
x.DirSearch(drives[i], SEARCH_WORDS1, row);
x.DirSearch(drives[i], SEARCH_WORDS2, row);
x.DirSearch(drives[i], SEARCH_WORDS3, row);
x.DirSearch(drives[i], SEARCH_WORDS4, row);
row--;
i++;
}
x.EndMessage();
}
}
}
The error you're getting is caused by the file system permissions. The only way around would be to grant the credentials you're using access to the specified folders, run the application as 'Administrator' or run the application as the specific user for each User's folder.

How to keep logs in C#?

This is a WinForm written in C#.
Lets say I'm generating a random named text file in my selected directory. When the button is clicked teh first time, i write the data contained in the textboxes into that text file. If the user wants to do the same thing with different data in the textboxes then the click on the button should write the new data into the text file without losing the old data. It's like keeping logs, is this possible?
My code is like:
private readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt");
wFile.WriteLine("Name Surname:" + text1.Text + text2.Text);
wFile.WriteLine("Other:" + text3.Text + text4.Text);
wFile.WriteLine("Money:" + textBox1.Text + " TL.");
wFile.WriteLine("*************************************");
wFile.Close();
}
else
{
return;
}
}
You can append to the text in the file.
See
File.AppendText
using (StreamWriter sw = File.AppendText(pathofFile))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
where pathofFile is the path to the file to append to.
Have a look at using something like this:
StreamWriter fw = new StreamWriter(#"C:\Logs\MyFile.txt",true);
fw.WriteLine("Some Message" + Environment.Newline);
fw.Flush();
fw.Close();
Hope that helps. See MSDN StreamWriter for more information
Updated: Removed old example
Also if you are trying to create a unique file you can use Path.GetRandomFileName()
Again from the MSDN Books:
The GetRandomFileName method returns a
cryptographically strong, random
string that can be used as either a
folder name or a file name.
UPDATED: Added a Logger class example below
Add a new class to your project and add the following lines (this is 3.0 type syntax so you may have to adjust if creating a 2.0 version)
using System;
using System.IO;
namespace LogProvider
{
//
// Example Logger Class
//
public class Logging
{
public static string LogDir { get; set; }
public static string LogFile { get; set; }
private static readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Logging() {
LogDir = null;
LogFile = null;
}
public static string RandomFileName()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
public static void AddLog(String msg)
{
String tstamp = Convert.ToString(DateTime.Now.Day) + "/" +
Convert.ToString(DateTime.Now.Month) + "/" +
Convert.ToString(DateTime.Now.Year) + " " +
Convert.ToString(DateTime.Now.Hour) + ":" +
Convert.ToString(DateTime.Now.Minute) + ":" +
Convert.ToString(DateTime.Now.Second);
if(LogDir == null || LogFile == null)
{
throw new ArgumentException("Null arguments supplied");
}
String logFile = LogDir + "\\" + LogFile;
String rmsg = tstamp + "," + msg;
StreamWriter sw = new StreamWriter(logFile, true);
sw.WriteLine(rmsg);
sw.Flush();
sw.Close();
}
}
}
Add this to your forms onload event
LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings";
LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();
Now adjust your button click event to be like the following:
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StringBuilder logMsg = new StringBuilder();
logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine);
logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine);
logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine);
logMsg.Append("*************************************" + Environment.NewLine);
LogProvider.Logging.AddLog(logMsg.ToString());
} else
{
return;
}
Now you should only create one file for the entire time that application is running and will log to that one file every time you click your button.
You might want to take a look at log4net and the RollingFileAppender
Sure. Just open the file for appending with something like System.IO.File.AppendText

Categories