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();
Related
I want to retrieve the data from a .vcf file. It is in vcf format.
I need the regular expression formula for each item of data mentioned below. I tried but could not make it work.
BEGIN:VCARD
VERSION:2.1
FN;CHARSET=utf-8:s James F ' Ernande.
ADR;WORK;X-EDIT=0;X-POS=280,43,54,269,0,0,0,0;CHARSET=utf-8:;;P.O. Box No: 570, P. C-112, Ruwi Muscat, Sultanate Ofoman;;;;
X-IS-TAKE-ADR;CHARSET=utf-8:23.62866567746918;58.26649072858852;
N;X-EDIT=0;X-POS=33,89,29,178;CHARSET=utf-8:s;James F ' Ernande. ;;;
EMAIL;WORK;X-EDIT=0;X-POS=116,59,26,237;CHARSET=utf-8:james#om.bluerhine.com
EMAIL;WORK;X-EDIT=0;X-POS=142,61,26,234;CHARSET=utf-8:oman#onn.bluerhine.com
EXCHANGEDATE:2019-06-16
EXCHANGEDATE:2019-06-16
AUTHOR:IntSig-iOS-iPhone
ORG;WORK;X-EDIT=0;X-POS=0,0,0,0,59,29,33,295,0,0,0,0;CHARSET=utf-8:;Business Development Manaus)r;
TEL;WORK;X-EDIT=0;X-POS=88,107,23,142;CHARSET=utf-8:+96897641700
TEL;WORK;X-EDIT=0;X-POS=332,133,28,182;CHARSET=utf-8:+96822022247
TEL;WORK;X-EDIT=0;X-POS=328,36,27,92;CHARSET=utf-8:24796647
END:VCARD
Code:
Regex regex = new Regex(#"(?<strElement>(FN)) (:(?<strFN>[^\r\n]*))", options);// For retrieving the First Name
Regex regex = new Regex(#"((?<strElement>(EMAIL)) (;*(?<strAttr>(HOME|WORK)))* (;(?<strPref>(PREF)))* (;[^:]*)* (:(?<strValue>[^\n\r]*)))");//for retrieving Email
I am not getting the exact regular expression formula required.
Here is a simple parser :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication124
{
class Program
{
static void Main(string[] args)
{
string input =
"BEGIN:VCARD\n" +
"VERSION:2.1\n" +
"FN;CHARSET=utf-8:s James F ' Ernande.\n" +
"ADR;WORK;X-EDIT=0;X-POS=280,43,54,269,0,0,0,0;CHARSET=utf-8:;;P.O. Box No: 570, P. C-112, Ruwi Muscat, Sultanate Ofoman;;;;\n" +
"X-IS-TAKE-ADR;CHARSET=utf-8:23.62866567746918;58.26649072858852;\n" +
"N;X-EDIT=0;X-POS=33,89,29,178;CHARSET=utf-8:s;James F ' Ernande. ;;;\n" +
"EMAIL;WORK;X-EDIT=0;X-POS=116,59,26,237;CHARSET=utf-8:james#om.bluerhine.com\n" +
"EMAIL;WORK;X-EDIT=0;X-POS=142,61,26,234;CHARSET=utf-8:oman#onn.bluerhine.com\n" +
"EXCHANGEDATE:2019-06-16\n" +
"EXCHANGEDATE:2019-06-16\n" +
"AUTHOR:IntSig-iOS-iPhone\n" +
"ORG;WORK;X-EDIT=0;X-POS=0,0,0,0,59,29,33,295,0,0,0,0;CHARSET=utf-8:;Business Development Manaus)r;\n" +
"TEL;WORK;X-EDIT=0;X-POS=88,107,23,142;CHARSET=utf-8:+96897641700\n" +
"TEL;WORK;X-EDIT=0;X-POS=332,133,28,182;CHARSET=utf-8:+96822022247\n" +
"TEL;WORK;X-EDIT=0;X-POS=328,36,27,92;CHARSET=utf-8:24796647\n" +
"END:VCARD";
ParseVCF parseVCF = new ParseVCF(input);
}
}
public class ParseVCF
{
public string version { get; set; }
public List<string> data = new List<string>();
enum State
{
FIND_BEGIN,
GET_VERSION,
PROCESS_DATA,
FOUND_END
}
public ParseVCF(string input)
{
StringReader reader = new StringReader(input);
string line = "";
State state = State.FIND_BEGIN;
while(((line = reader.ReadLine()) != null) && (state != State.FOUND_END))
{
line = line.Trim();
if (line.Length > 0)
{
switch (state)
{
case State.FIND_BEGIN :
if (line.StartsWith("BEGIN:"))
{
state = State.GET_VERSION;
}
break;
case State.GET_VERSION :
string[] split = line.Split(new char[] { ':' });
version = split[1];
state = State.PROCESS_DATA;
break;
case State.PROCESS_DATA :
if(line.StartsWith("END"))
{
state = State.FOUND_END;
}
else
{
data.Add(line);
}
break;
}
}
}
}
}
}
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.
I am trying to backup my database objects' scripts to disk. I have been able to put together the below code that does this, but I have to specify each object type (eg Tables, Functions, Stored Procedures).
Is there a way to loop through all these objects without specifying each collection?
using System;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Text;
public static void BackupDB(Server srv, Database db, string savePath)
{
string objPath;
string objFile;
string objTxt;
foreach (StoredProcedure obj in db.StoredProcedures)
{
if (obj.IsSystemObject == false)
{
objPath = savePath + "Stored Procedures\\";
Directory.CreateDirectory(objPath);
objFile = objPath + obj.Schema + "." + obj.Name + ".sql";
objTxt = GetScriptString(srv, obj);
File.WriteAllText(objFile, objTxt);
}
}
foreach (Table obj in db.Tables)
{
if (obj.IsSystemObject == false)
{
objPath = savePath + "Tables\\";
Directory.CreateDirectory(objPath);
objFile = objPath + obj.Schema + "." + obj.Name + ".txt";
objTxt = GetScriptString(srv, obj);
File.WriteAllText(objFile, objTxt);
}
}
static private string GetScriptString(Server server, SqlSmoObject obj)
{
StringBuilder output = new StringBuilder();
Scripter scr = new Scripter(server);
var script = scr.EnumScript(new SqlSmoObject[] { obj });
foreach (var line in script)
{
output.AppendLine(line);
}
return output.ToString();
}
EDIT:
Using Grant Winney's answer, I was able to put together the below method to get iterate through all the objects without repeating lines:
public static void BackupDB(Server srv, Database db, string savePath)
{
string objPath;
string objFile;
string objTxt;
Dictionary<string, IEnumerable<ScriptSchemaObjectBase>> dboDict =
new Dictionary<string, IEnumerable<ScriptSchemaObjectBase>>();
dboDict.Add("Stored Procedures", db.StoredProcedures.Cast<StoredProcedure>().Where(x => !x.IsSystemObject));
dboDict.Add("Functions", db.UserDefinedFunctions.Cast<UserDefinedFunction>().Where(x => !x.IsSystemObject));
dboDict.Add("Tables", db.Tables.Cast<Table>().Where(x => !x.IsSystemObject));
dboDict.Add("Views", db.Views.Cast<View>().Where(x => !x.IsSystemObject));
foreach (KeyValuePair<string, IEnumerable<ScriptSchemaObjectBase>> dict in dboDict)
{
IEnumerable<ScriptSchemaObjectBase> dboObjects = dict.Value;
objPath = savePath + dict.Key + "\\";
Directory.CreateDirectory(objPath);
foreach (ScriptSchemaObjectBase obj in dboObjects)
{
objFile = objPath + obj.Schema + "." + obj.Name + ".sql";
objTxt = GetScriptString(srv, obj);
File.WriteAllText(objFile, objTxt);
}
}
}
Move the similar code into a separate method, and take advantage of the fact that each of those classes implements the same base class, which is where Schema and Name are located.
You can use LINQ to filter the items first, then pass the filtered list to the other method.
public static void BackupDB(Server srv, Database db, string savePath)
{
string objPath;
string objFile;
string objTxt;
BackupObjects(db.StoredProcedures.Cast<StoredProcedure>().Where(x => !x.IsSystemObject));
BackupObjects(db.Tables.Cast<Table>().Where(x => !x.IsSystemObject));
}
private static void BackupObjects(IEnumerable<ScriptSchemaObjectBase> objects)
{
foreach (ScriptSchemaObjectBase obj in objects)
{
objPath = savePath + "Stored Procedures\\";
Directory.CreateDirectory(objPath);
objFile = objPath + obj.Schema + "." + obj.Name + ".sql";
objTxt = GetScriptString(srv, obj);
File.WriteAllText(objFile, objTxt);
}
}
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.
i am created one xml file name is data.xml in this xml file i am storing this information
like bellow
<products>
<cloths Id="1">
<ClothName>Sharts</ClothName>
<Size>40</Size>
<Price>1050</Price>
<Amount>1000000</Amount>
<images>c:\users\venkateshg\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\ImgUpload\Tulips.jpg</images>
</cloths>
</products>
This is a C# Code i devloped
XmlDocument XDoc = new XmlDocument(); // root
XmlElement XElemRoot = XDoc.CreateElement("products");
XDoc.AppendChild(XElemRoot);
XmlElement XCloths = XDoc.CreateElement("cloths");
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("data.xml"));
int idval ;
if (ds.Tables[0].Rows.Count > 1)
{
idval = ds.Tables[0].Columns[5][0];
if (idval == 0)
{
idval = 1;
}
else
{
idval += 1;
}
}
else
{
idval = 1;
}
XCloths.SetAttribute("Id",idval.ToString());
XElemRoot.AppendChild(XCloths);
XmlElement XClothName = XDoc.CreateElement("ClothName");
XClothName.InnerText = TextBox1.Text;
XCloths.AppendChild(XClothName);
XmlElement XSize = XDoc.CreateElement("Size");
XSize.InnerText = TextBox2.Text; ;
XCloths.AppendChild(XSize);
XmlElement XPrice = XDoc.CreateElement("Price");
XPrice.InnerText = TextBox3.Text;
XCloths.AppendChild(XPrice);
XmlElement XAmount = XDoc.CreateElement("Amount");
XAmount.InnerText = "1000000";
XCloths.AppendChild(XAmount);
FileUpload1.ToolTip = "Select Image For Upload...";
string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
if (FileUpload1.HasFile)
{
//Check File is available in Fileupload control and then upload to server path
string fname = FileUpload1.FileName;
//spath = #"~\ImgUpload\" + FileUpload.FileName;
string fpath = Server.MapPath("ImgUpload");
fpath = fpath + #"\" + FileUpload1.FileName;
string getext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
string filename = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
string strFilePath = filename + DateTime.Now.ToString("yyyyMMdd") + getext;
if (getext != ".JPEG" && getext != ".jpeg" && getext != ".JPG" && getext != ".jpg" && getext != ".png" && getext != ".tif" && getext != ".tiff")
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "successfull", "alert('Please upload only jpeg, jpg,png,tif,tiff'); window.location = 'Default.aspx';", true);
}
else
{
FileUpload1.SaveAs(Server.MapPath(#"~\ImgUpload\" + strFilePath));
Image1.ImageUrl = #"~\ImgUpload\" + strFilePath;
ViewState["fname"] = fname;
ViewState["fPath"] = #"~\ImgUpload\" + strFilePath;
XmlElement Ximages = XDoc.CreateElement("images");
Ximages.InnerText = fpath;
XCloths.AppendChild(Ximages);
}
}
else
{
}**
The problem is if i submitting each time the date is going to Reload the same id "1"
i want to continue to id 1,2,3,4,5................in one xml file
Unless you have some intricate purpose for your dataset, I believe you can drop it entirely.
Then you'd have something as follows:
XDocument xDoc;
int lastId = 0;
var path = Server.MapPath("data.xml");
if (File.Exists(path))
{
xDoc = XDocument.Load(path);
var existingCloths = xDoc.Root.Elements("cloths");
if (existingCloths.Any())
{
lastId = existingCloths.Max(c => Int32.Parse(c.Attribute("Id").Value));
}
}
else
{
xDoc = new XDocument(new XElement("products"));
}
var xCloths = XDoc.CreateElement("cloths");
xDoc.Add(new XAttribute("Id",
(lastId + 1).ToString(CultureInfo.InvariantCulture));
xDoc.Root.Add(xCloths);
//[...]
I personally find it significantly easier to just create a Class and serialize and deserialize to xml.
If you want to customize the Class you will need to add in the appropriate [XMLRoot] [XMLElement] and [XMLAttribute] tags to the Products class
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace UShort
{
class Program
{
static void Main(string[] args)
{
Products prod = new Products();
prod.Cloths = new List<Products.cloths>();
Products.cloths jacket = new Products.cloths();
jacket.ClothName = "MyJacket";
jacket.amount = 12345;
jacket.price = (float)123.45;
jacket.size = 12;
jacket.images = "c:\\asdasd.jpg";
prod.Cloths.Add(jacket);
// String contining XML. Do what you want with it.
string ProductXML = XMLTools.convertObjToXMLString(prod);
// Create an object from an XML string of the same format.
Products NewProduct = (Products)XMLTools.convertXMLStringToObject(ProductXML, typeof(Products));
}
public class Products
{
public List<cloths> Cloths = new List<cloths>();
public class cloths
{
public string ClothName = string.Empty;
public int size = 0;
public float price = 0;
public long amount = 0;
public string images = string.Empty;
}
}
public static class XMLTools
{
/// <summary>
/// Overwrites the encoding to use UTF-8
/// </summary>
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
public static string convertObjToXMLString(object obj)
{
try
{
XmlSerializer serObj = new XmlSerializer(obj.GetType());
Utf8StringWriter sw = new Utf8StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
serObj.Serialize(xtw, obj);
return sw.ToString();
}
catch (Exception)
{
throw;
}
}
public static object convertXMLStringToObject(string xmlString, Type objectType)
{
try
{
TextReader txr = new StringReader(xmlString);
XmlSerializer serObj = new XmlSerializer(objectType);
return serObj.Deserialize(txr);
}
catch (Exception)
{
throw;
}
}
}
}
}