I need my caml query to return only text, e.g. now it's returning me this
<div class=ExternalClass104BBsdfEEDCEdddsf48C68C18AsdfB056FBsdfAB805>Real Content.....</div>
When I want Real Content..... only. Code I am using is,
using System;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
namespace SPSandeep.ConsoleApplication
{
class Program
{
public static DataTable dt = null;
static void Main (string[] args)
{
using (SPSite site = new SPSite("http://ws2003/credit"))
{
using (SPWeb web = site.OpenWeb())
{
SPList mainList = web.Lists["Team Discussion"];
foreach (SPListItem folder in mainList.Folders)
{
Console.WriteLine("Folder Name: " + folder.Name);
Console.WriteLine("Folder ID: " + folder.ID);
// Read body of attachment
Console.WriteLine("Body: " + folder.Fields["Body"].GetFieldValueAsText(folder["Body"]));
Console.WriteLine("Threading: " + folder.Fields["Threading"].GetFieldValueAsText(folder["Threading"]).Length);
Console.WriteLine("=============================");
RenderAllReponses(mainList, folder.ID);
Console.WriteLine("=============================");
}
}
}
Console.ReadKey();
}
public static void RenderAllReponses (SPList mainList, int parentID)
{
SPQuery query = new SPQuery();
query.Query = string.Format("<Where><Eq><FieldRef Name='ParentFolderId' /><Value Type='Number'>{0}</Value></Eq></Where>", parentID.ToString());
query.ViewFields = #"<FieldRef Name='ows_ParentFolderId' /><FieldRef Name='Threading' /><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='Body' />";
query.ViewAttributes = "Scope='RecursiveAll'";
dt = mainList.GetItems(query).GetDataTable();
if (null != dt)
{
foreach (DataRow listItem in dt.Rows)
{
if (listItem["Threading"].ToString().Length == 56)
{
RenderResponse(listItem, 56);
}
}
}
}
public static void RenderResponse (DataRow listItem1, int length)
{
DataRow[] listItems = dt.Select(string.Format("Threading Like '{0}*' AND LEN(Threading)={1}", listItem1["Threading"], length));
foreach (DataRow item in listItems)
{
Console.WriteLine("Item DisplayName: " + item["Title"]); // Returns Title of Discussion
Console.WriteLine("List ID: " + item["ID"] );
//Console.WriteLine("List Folder ID: " + listItem["ParentFolderId"] + "<BR>"); // Returns ID of Parent Discussion
Console.WriteLine("Body: " + item["Body"]);
Console.WriteLine("Threading: " + item["Threading"].ToString().Length );
int newLength = length + 10;
RenderResponse(item, newLength);
}
}
}
}
Related
I am trying to read the list of test in particular folder in ALM. It gets the subfolders but not able to read the test cases. No failure is coming, it is just not entering the second foreach loop
static void Main(string[] args)
{
TDConnection con = createConnection("", "", "", "");
TreeManager TreeMgr = con.TreeManager;
var SubjRoot = TreeMgr.get_NodeByPath(#"Subject\Regression");
TestFactory TestFact = SubjRoot.TestFactory;
var SubjectNodeList = SubjRoot.FindChildren("", false, "");
foreach (var node in SubjectNodeList)
{
System.Console.WriteLine(node.path);
var TestFilter = TestFact.Filter;
TestFilter.Filter["TS_SUBJECT"] = #"""" + node.path + #"""";
var TestList = TestFact.NewList(TestFilter.Text);
foreach (var oTest in TestList)
{
Console.WriteLine("Test Name=" + oTest.Name + "' Test Type=" + oTest.Type);
}
}
Console.ReadKey();
}
This is my table:
ItemsTable
Id, Codes, Price, Weight
I want to produce one or many xml files based on these rules using C#.
Within the xml there can not be more than 99 items, if it is more it should start a new xml file. There can not be more than 99 items in MyItems, if there are more it should start a new MyCollection.
<xml>
<MyCollections>
<!--- 0 to 99 MyCollection items allowed-->
<MyCollection>
<Code>6201110000</Code>
<MyItems>
<!--- 0 to 99 MyItems allowed -->
<MyItem>
<Sequence>1</Price>
<Price>10</Price>
<Weight>20</Weight>
</MyItem>
....
<MyItem>
<Sequence>99</Price>
<Price>300</Price>
<Weight>2</Weight>
</MyItem>
</Item>
</MyCollection>
<MyCollection>
<Code>6201110000</Code>
<MyItems>
<MyItem>
<Sequence>100</Price>
<Price>10</Price>
<Weight>20</Weight>
</MyItem>
.....
</MyCollection>
The loops is complicated. I think I got it right. I used Xml Linq.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string PATH = #"c:\temp\";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("Codes", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Columns.Add("Weight", typeof(int));
dt.Rows.Add(new object[] { "1", "620111000", 1.00, 20 });
dt.Rows.Add(new object[] { "2", "610433000", 4.00, 30 });
dt.Rows.Add(new object[] { "3", "620111005", 7.00, 50 });
dt.Rows.Add(new object[] { "4", "620111006", 6.00, 60 });
dt.Rows.Add(new object[] { "5", "620111006", 5.00, 70 });
string xml = "<xml><MyCollections></MyCollections></xml>";
var groups = dt.AsEnumerable().OrderBy(x => x.Field<string>("Codes")).GroupBy(x => x.Field<string>("Codes")).ToList();
XDocument doc = XDocument.Parse(xml);
XElement myCollections = doc.Descendants("MyCollections").FirstOrDefault();
int sequence = 0;
int file_count = 1;
XElement myCollection = null;
XElement myItems = null;
string firstGroupName = "";
string code = "";
foreach (var group in groups)
{
code = group.Key;
//only add here if there is not 99 items in file
//other wise it will be added later
if (sequence < 99)
{
myCollection = new XElement("MyCollection", new XElement("Code", code));
myCollections.Add(myCollection);
myItems = new XElement("MyItems");
myCollection.Add(myItems);
firstGroupName = group.Key;
}
foreach (DataRow row in group)
{
sequence++;
if (sequence > 99)
{
if (firstGroupName == code)
{
doc.Save(PATH + code + "_" + file_count.ToString() + ".xml");
}
else
{
doc.Save(PATH + firstGroupName + "_" + code + "_" + file_count.ToString() + ".xml");
}
file_count++;
sequence = 1;
doc = XDocument.Parse(xml);
myCollections = doc.Descendants("MyCollections").FirstOrDefault();
myCollection = new XElement("MyCollection", new XElement("Code", code));
myCollections.Add(myCollection);
myItems = new XElement("MyItems");
myCollection.Add(myItems);
}
XElement myItem = new XElement("MyItem", new object[] {
new XElement("Sequence", sequence),
new XElement("Price", row.Field<decimal>("Price")),
new XElement("Weight", row.Field<int>("Weight"))
});
myItems.Add(myItem);
}
}
if (myItems.Elements("MyItem") != null)
{
if (firstGroupName == code)
{
doc.Save(PATH + code + "_" + file_count.ToString() + ".xml");
}
else
{
doc.Save(PATH + firstGroupName + "_" + code + "_" + file_count.ToString() + ".xml");
}
}
}
}
}
You can query your table with take ans skip.
Let's say you have two methods:
private IList<string> Query(string s)
{
// Execute your SQL query
}
private void SerializeItems(IList<object> itemsList)
{
//Serialize your itemslist to an xml file
}
You can read 99 item and serialize them:
var offset = 99;
var readMore = true;
while (readMore)
{
var itemsList = Query(
$#"SELECT ... FROM ... OFFSET {offset} ROWS FETCH NEXT 99 ROWS ONLY;");
SerializeItems(itemsList);
offset += 99;
readMore = itemsList.Count == 99;
}
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.
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.
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();