2

i've read about it and it looks pretty easy, but i don't know why it crashes everytime on the XmlSerializer Line, i'd like to know why since people answered questions for convertion of list into xml with something similar and it doesn't seem to work for me!

Here is the code :

Class :

[Serializable()]
    public class Pogos
    {
        public string Pogo { get; set; }
        public DateTime Date { get; set; }
    }

List for the daily pogos :

 public static List<Pogos> DailyPogos = null;

Setting the Daily Pogo list to what is in the .xml

 public static void SetDailyPogos()
    {
        string path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/DailyPogos.xml");

        if (File.Exists(path))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Pogos>));

            StreamReader reader = new StreamReader(path);
            DailyPogos = (List<Pogos>)serializer.Deserialize(reader);
            reader.Close();

            foreach (var pogo in DailyPogos)
            {
                if (pogo.Date.Date != DateTime.Now.Date)
                    DailyPogos.Remove(pogo);
            }
        }
        else
            DailyPogos = new List<Pogos>();
    }

Save the Daily Pogos (distinct) in the .xml

public static void SaveDailyPogos(List<string> pogos)
    {
        foreach (var pogo in pogos)
        {
            var matches = DailyPogos.Where(e => e.Pogo.Contains(pogo));
            foreach ( var match in matches)
            {
                DailyPogos.Remove(match);
            }
            var pog = new Pogos();
            pog.Pogo = pogo;
            pog.Date = DateTime.Now;
            DailyPogos.Add(pog);
        }

        string path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/DailyPogos.xml");

        //create the serialiser to create the xml
        XmlSerializer serialiser = new XmlSerializer(typeof(List<Pogos>));

        // Create the TextWriter for the serialiser to use
        TextWriter filestream = new StreamWriter(path);

        //write to the file
        serialiser.Serialize(filestream, DailyPogos);

        // Close the file
        filestream.Close();
    }

The line causing trouble ( no errors just crash ) :

XmlSerializer serializer = new XmlSerializer(typeof(List<Pogos>));

EDIT : I was pretty dumb in this situation, first, i could of watch the exception by adding a try catch which i don't know why i didn't.. Was probably tired. Exception was saying that it was failing because of the protection level of the application, which got fixed by adding "public" to the program class.

iamanoob
  • 208
  • 3
  • 13
  • 1
    What does "no errors just crash" mean? Are you running this under the debugger? Turn on "break on all exceptions" and edit the post to show what managed exception you get. – Patrick Apr 23 '16 at 07:20
  • 1
    Need sample of xml – jdweng Apr 23 '16 at 08:12
  • Can you share the full `ToString()` output of the exception including the exception type, traceback and message? – dbc Apr 23 '16 at 17:57

2 Answers2

1

I cannot reproduce the exception you claim to see -- given that the Pogo class is as you say, then new XmlSerializer(typeof(List<Pogos>)) will not throw an exception.

You should doublecheck that this class is public and has a public parameterless constructor in your actual application. If not, then new XmlSerializer(typeof(List<Pogos>)) will indeed throw an exception.

That being said, you have two coding errors near the calls to create an XmlSerializer, namely that you are modifying the DailyPogos collection while enumerating through it with a foreach statement. This will throw an exception as explained in the documentation:

IEnumerator.MoveNext Method ()

Exceptions: InvalidOperationException: The collection was modified after the enumerator was created.

To avoid these exceptions use you can use List.RemoveAll(). Modify SetDailyPogos() as follows:

XmlSerializer serializer = new XmlSerializer(typeof(List<Pogos>));
using (var reader = new StreamReader(path))
{
    DailyPogos = (List<Pogos>)serializer.Deserialize(reader);
}
var now = DateTime.Now;
DailyPogos.RemoveAll(p => p.Date.Date != now.Date);

And SaveDailyPogos():

foreach (var pogo in pogos)
{
    DailyPogos.RemoveAll(p => p.Pogo.Contains(pogo));
    var pog = new Pogos();
    pog.Pogo = pogo;
    pog.Date = DateTime.Now;
    DailyPogos.Add(pog);
}

Since the exception thrown from these foreach statements happens near to the call to construct an XmlSerializer, perhaps you are mistaking the source of the exception?

dbc
  • 104,963
  • 20
  • 228
  • 340
  • i get this exception : Program is inaccessible due to its protection level. Only public types can be processed. Also thanks for the errors correction! – iamanoob Apr 25 '16 at 17:28
  • Anyway, fixed it thanks a lot! It was indeed the protection level, my Program class wasn't public... – iamanoob Apr 25 '16 at 17:33
0

If I understand you correctly, you have a List of objects that you want to Serialize then deSerialize to\from XML.....

Try this....

Classes.....

[Serializable()]
public class Pogos
{
    public string Pogo { get; set; }
    public DateTime Date { get; set; }
}

Usings.....

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

Code.....

    static void Main(string[] args)
    {
        List<Pogos> dObjToSerialize = new List<Pogos>();

        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 1" });
        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 2" });
        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 3" });
        dObjToSerialize.Add(new Pogos() { Date = DateTime.Now, Pogo = "Pogo 4" });

        Serialize(dObjToSerialize); // find you XML in a file called "xml.xml" in the build folder

        List<Pogos> dObjToDeserialize = Deserialize<List<Pogos>>();

    } // Put a break-point here and dObjToDeserialize will contain your objects from the "xml.xml"

    private static void Serialize<T>(T data)
    {

        // Use a file stream here.
        using (TextWriter WriteFileStream = new StreamWriter("xml.xml"))
        {
            // Construct a SoapFormatter and use it  
            // to serialize the data to the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));

            try
            {
                // Serialize EmployeeList to the file stream
                SerializerObj.Serialize(WriteFileStream, data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }
        }
    }

    private static T Deserialize<T>() where T : new()
    {
        //List<Employee> EmployeeList2 = new List<Employee>();
        // Create an instance of T
        T ReturnListOfT = CreateInstance<T>();


        // Create a new file stream for reading the XML file
        using (FileStream ReadFileStream = new FileStream("xml.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Construct a XmlSerializer and use it  
            // to serialize the data from the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
            try
            {
                // Deserialize the hashtable from the file
                ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }

        }
        // return the Deserialized data.
        return ReturnListOfT;
    }

    // function to create instance of T
    public static T CreateInstance<T>() where T : new()
    {
        return (T)Activator.CreateInstance(typeof(T));
    }
}
Monty
  • 1,534
  • 2
  • 10
  • 12