?
Solved

Simple problem tahts driving me mad, loading XML

Posted on 2011-03-14
7
Medium Priority
?
263 Views
Last Modified: 2013-12-17
Hi all,

I know this is a very basic problem but I seem to have tried so many ideas im obviously doing something very simple wrong and as I am new to programming (about 5 weeks) I just can't get my head round how to do it.

I have made an app im using as an address book to store contacts, when the program is closed it saves (or generates) an XML file. like the following.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfContactDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ContactDetails>
    <Name>John Hedges</Name>
    <Mobile>87686767868767</Mobile>
    <Secphone>06785 567787</Secphone>
    <Email>Hedgeart@googlemail.com</Email>
    <Website>http://</Website>
    <Address>64 Flint Hollow Road, Oxford, Ox39 4JT</Address>
    <Notes>Plumber</Notes>
  </ContactDetails>
  <ContactDetails>
    <Name>Dave Parry</Name>
    <Mobile>67877896786867869</Mobile>
    <Secphone />
    <Email>D_Paz@someemail.com</Email>
    <Website>http://</Website>
    <Address />
    <Notes>Drinking Buddy</Notes>
  </ContactDetails>
  <ContactDetails>
    <Name>Shelly</Name>
    <Mobile>07460903356</Mobile>
    <Secphone />
    <Email>Shellby@someemail.com</Email>
    <Website>http://</Website>
    <Address />
    <Notes>G/F</Notes>
  </ContactDetails>
</ArrayOfContactDetails>

Open in new window


ContactDetails is a class and the information is put together as  a List<ContactDetails> contactlist.

All I want to do is when the user reopens the program it loads the XML data and  a Listbox(containing the 'Name' data) is populated, so its exacly how the user leaved it when they exited.

Many Thanks

John


0
Comment
Question by:Bronco78th
  • 4
  • 3
7 Comments
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35129699
Looks like you used XML serialization, so to read the file you created:

using System.Text.Xml;
using System.IO;

// Create the XML serializer/de-serializer to read the XML file
// You need to tell the XML serializer what kind of object it's
// going to de-serialize, in this case a List<ContactDetails>
XmlSerializer serializer = new XmlSerializer(typeof(List<ContactDetails>));

// Open the XML file
Stream xmlStream = File.OpenRead("C:\\your.file.xml");
// De-serialize the XML file
List<ContactDetails> contacts = (List<ContactDetails>)serializer.Deserialize(xmlStream);
// Close the XML file
xmlStream.Dispose();

Open in new window

0
 

Author Comment

by:Bronco78th
ID: 35130589
Hi tgerbert

Many thanks for the quick reply, however it seems that hasn't solved the issue, my app is still not picking up that data. Can I just clarify where should I put that deserilisation code?

Heres both the Serilization and Deserlization code that I currently have

Serilization/Writer - - - -

 XmlSerializer writer = new XmlSerializer(typeof(List<ContactDetails>));
                StreamWriter file = new StreamWriter("contactdata.xml");
                writer.Serialize(file, contactlist);
                file.Close(); 

Open in new window


Deserialization (as your code above):-----

     public MainWindow()
        {
            InitializeComponent();

            XmlSerializer serializer = new XmlSerializer(typeof(List<ContactDetails>));
            Stream xmlStream = File.OpenRead("contactdata.xml");
            List<ContactDetails> contacts = (List<ContactDetails>)serializer.Deserialize(xmlStream);
            xmlStream.Dispose();

            UpdatelistNames();

        }

Open in new window


I should have also mentioned in my first post im using WPF and Net 4.0.

Many Thanks

John
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35132688
You should put it where you want to read the XML file.  I would probably put it in it's own method (or even in it's own class).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			List<ContactDetails> contacts = ReadContactDetails("C:\\test.xml");

			UpdateListBox(contacts);
		}

		private void UpdateListBox(List<ContactDetails> contacts)
		{
			NamesListBox.Items.Clear();

			foreach (ContactDetails contact in contacts)
				NamesListBox.Items.Add(contact.Name);
		}

		public List<ContactDetails> ReadContactDetails(string PathToXMLFile)
		{
			XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
			using (Stream xmlStream = File.OpenRead(PathToXMLFile))
				return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
		}
	}

}

Open in new window


Your code above looks basically correct, though if that's your complete code then it doesn't look like you're doing anything with the List<ContactDetails> that serializer.Deserialize() is giving you - the list is just assigned to the "contacts" variable, and then the method ends.

Since the contacts variable was defined in the MainWindow() method, it's only accessible from within that method and only exists as long as that method is running.  If you want to set a variable in that method, and then be able to use it even after that method has ended, you can declare a class-level variable and use that instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;

namespace WpfApplication1
{
	public partial class MainWindow : Window
	{
		// Class-level variable to hold contacts list
		private List<ContactDetails> contactsList = new List<ContactDetails>();

		public MainWindow()
		{
			InitializeComponent();

			// Fill the contactsList
			contactsList = ReadContactDetails("C:\\test.xml");

			UpdateListBox();
		}

		private void UpdateListBox()
		{
			NamesListBox.Items.Clear();

			// Read contacts from the class-level variable
			foreach (ContactDetails contact in contactsList)
				NamesListBox.Items.Add(contact.Name);
		}

		public List<ContactDetails> ReadContactDetails(string PathToXMLFile)
		{
			XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
			using (Stream xmlStream = File.OpenRead(PathToXMLFile))
				return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
		}
	}

}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:Bronco78th
ID: 35133282
rightio ive upped the points value just becuase this is doing my nut as much im sure my incompetance is doing yours...will be well worth the money spent registering here if I can get this sorted.

Anyway its still not showing up. so back to basics....as oviously something is wrong elsewhere. ive stripped out all the code ive got for everything else and stuck in all the releveant bits.

namespace ContactBook
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        [Serializable]
        public class ContactDetails
        {

            public string Name;
            public string Mobile;
            public string Secphone;
            public string Email;
            public string Website;
            public string Address;
            public string Notes;

        }

        List<ContactDetails> contactlist = new List<ContactDetails>();
        private List<ContactDetails> contactsList = new List<ContactDetails>();


        public MainWindow()
        {
            InitializeComponent();

            // Fill the contactsList
            contactsList = ReadContactDetails("C:\\data.xml");

            UpdatelistNames();
        }


        //DESERIALIZER

        public List<ContactDetails> ReadContactDetails(string contactlist)
        {
            XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
            using (Stream xmlStream = File.OpenRead("data.xml"))
                return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
        }


        //SAVE CHANGES MESSAGE ON PROGRAM CLOSE + SERILIZATION AND WRITE DATA FILE
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult key = MessageBox.Show(
                "Do you want to Save Changes?",
                "Confirm",
                MessageBoxButton.YesNoCancel,
                MessageBoxImage.Warning,
                MessageBoxResult.No);
            e.Cancel = (key == MessageBoxResult.Cancel);
            if (key == MessageBoxResult.Yes)
            {
                //IM AWARE I HAVE NO ACTURAL CHECKS FOR CHANGES,LOW PRIORITY RIGHT NOW :)

                XmlSerializer writer = new XmlSerializer(contactlist.GetType());
                StreamWriter file = new StreamWriter("data.xml");
                writer.Serialize(file, contactlist);
                file.Close();


            }
        }


        // UPDATES LISTBOX

        private void UpdatelistNames()
        {
            listNames.Items.Clear();

            //Enables/Disables buttons if no items are in the List.
            if (contactlist.Count == 0)
            {
                btnDelete.IsEnabled = false;
                btnCopyfromclipboard.IsEnabled = false;
                btnGentext.IsEnabled = false;
                btnEditcontact.IsEnabled = false;

                menuDeletecontact.IsEnabled = false;
                menuCopycontactclipboard.IsEnabled = false;
                menuEditcontact.IsEnabled = false;
                menuGenTextfile.IsEnabled = false;

            }
            else
            {
                foreach (ContactDetails c in contactlist)
                {
                    listNames.Items.Add(c.Name);
                }

                btnDelete.IsEnabled = true;
                btnCopyfromclipboard.IsEnabled = true;
                btnGentext.IsEnabled = true;
                btnEditcontact.IsEnabled = true;

                menuDeletecontact.IsEnabled = true;
                menuCopycontactclipboard.IsEnabled = true;
                menuEditcontact.IsEnabled = true;
                menuGenTextfile.IsEnabled = true;
            }
        }


        //Compares in the selctions in the listbox
        private void listNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listNames.SelectedIndex != -1)
            {
                String CompareName = listNames.Items[listNames.SelectedIndex].ToString();
                foreach (ContactDetails c in contactlist)
                {
                    if (c.Name == CompareName)
                    {
                        tbName.Text = c.Name;
                        tbMobile.Text = c.Mobile;
                        tbSecphone.Text = c.Secphone;
                        tbEmail.Text = c.Email;
                        tbWebsite.Text = c.Website;
                        tbAddress.Text = c.Address;
                        tbNotes.Text = c.Notes;
                    }
                }
            }
        }

        //BUTTON THAT ADDS NEW CONTACT TO 'contactlist' and listbox
        private void btnCreatecontact_Click(object sender, RoutedEventArgs e)
        {
            String thisName = tbNamefield.Text;
            String thisMobile = tbMobilefield.Text;
            String thisSecphone = tbSecphonefield.Text;
            String thisEmail = tbEmailfield.Text;
            String thisWebsite = tbWebsitefield.Text;
            String thisAddress = tbAddressfield.Text;
            String thisNotes = tbNotesfield.Text;

            if (thisName != "")
            {
                ContactDetails c = new ContactDetails();
                c.Name = thisName;
                c.Mobile = thisMobile;
                c.Secphone = thisSecphone;
                c.Email = thisEmail;
                c.Website = thisWebsite;
                c.Address = thisAddress;
                c.Notes = thisNotes;
                contactlist.Add(c);
                UpdatelistNames();

            }
            else
            {
                MessageBox.Show("You must fill in the Name field");
            }

            tbNamefield.Text = "";
            tbMobilefield.Text = "";
            tbSecphonefield.Text = "";
            tbEmailfield.Text = "";
            tbWebsitefield.Text = "http://";
            tbAddressfield.Text = "";
            tbNotesfield.Text = "";
        }
    }
}
      

Open in new window


Presumably by clicking 'debug' in VS isn't making a difference?...it should still read and ultimatily load the datafile regardless of how I acturally run the program right?

Anyway, sorry to be the thron in your side today.

John
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 800 total points
ID: 35139873
I think you just had some confusion between variables.  See comments in the code snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{

		[Serializable]
		public class ContactDetails
		{
			// For sake of testing, I'm just using one property in this object (this is unrelated to your question)
			public string Name;
		}

		//List<ContactDetails> contactlist = new List<ContactDetails>(); <-- seems like a duplicate
		private List<ContactDetails> contactsList = new List<ContactDetails>();
		
		public MainWindow()
		{
			InitializeComponent();

			// Added check for existence of data file
			if (!File.Exists("data.xml"))
				MessageBox.Show("Cannot find data.xml file."); // Really, should just start with blank contacts list/new file in this case

			// Fill the contactsList
			contactsList = ReadContactDetails("data.xml"); // <-- Changed to use same path in Window_Closing

			UpdatelistNames();
		}

		//DESERIALIZER
		public List<ContactDetails> ReadContactDetails(string dataFilePath) // <-- Changed parameter name to dataFilePath
		{
			XmlSerializer deSerializer = new XmlSerializer(typeof(List<ContactDetails>));
			using (Stream xmlStream = File.OpenRead(dataFilePath)) // <-- Changed to use the path passed into this method by contactlist parameter
				return (List<ContactDetails>)deSerializer.Deserialize(xmlStream);
		}

		public void WriteContactDetails(List<ContactDetails> contacts, string dataFilePath) // <-- Added separate method for saving
		{
			XmlSerializer serializer = new XmlSerializer(typeof(List<ContactDetails>));
			Stream dataFileStream = File.Create(dataFilePath);
			serializer.Serialize(dataFileStream, contacts);
			dataFileStream.Dispose();
		}

		//SAVE CHANGES MESSAGE ON PROGRAM CLOSE + SERILIZATION AND WRITE DATA FILE
		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			MessageBoxResult key = MessageBox.Show(
				"Do you want to Save Changes?",
				"Confirm",
				MessageBoxButton.YesNoCancel,
				MessageBoxImage.Warning,
				MessageBoxResult.No);
			e.Cancel = (key == MessageBoxResult.Cancel);
			if (key == MessageBoxResult.Yes)
			{
				//IM AWARE I HAVE NO ACTURAL CHECKS FOR CHANGES,LOW PRIORITY RIGHT NOW :)
				WriteContactDetails(contactsList, "data.xml");
			}
		}

		// UPDATES LISTBOX
		private void UpdatelistNames()
		{
			listNames.Items.Clear();

			foreach (ContactDetails contact in contactsList)
				listNames.Items.Add(contact.Name);

			//Enables/Disables buttons if no items are in the List.
			/* Just for the sake of testing, I've commented out this block
			 * of code so I can run/test the rest of your code without
			 * having to create all these buttons and other controls
			if (contactlist.Count == 0)
			{
				btnDelete.IsEnabled = false;
				btnCopyfromclipboard.IsEnabled = false;
				btnGentext.IsEnabled = false;
				btnEditcontact.IsEnabled = false;

				menuDeletecontact.IsEnabled = false;
				menuCopycontactclipboard.IsEnabled = false;
				menuEditcontact.IsEnabled = false;
				menuGenTextfile.IsEnabled = false;

			}
			else
			{
				foreach (ContactDetails c in contactlist)
				{
					listNames.Items.Add(c.Name);
				}

				btnDelete.IsEnabled = true;
				btnCopyfromclipboard.IsEnabled = true;
				btnGentext.IsEnabled = true;
				btnEditcontact.IsEnabled = true;

				menuDeletecontact.IsEnabled = true;
				menuCopycontactclipboard.IsEnabled = true;
				menuEditcontact.IsEnabled = true;
				menuGenTextfile.IsEnabled = true;
			}*/
		}


		//Compares in the selctions in the listbox
		/* Not related, commented out for testing
		private void listNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (listNames.SelectedIndex != -1)
			{
				String CompareName = listNames.Items[listNames.SelectedIndex].ToString();
				foreach (ContactDetails c in contactlist)
				{
					if (c.Name == CompareName)
					{
						tbName.Text = c.Name;
						tbMobile.Text = c.Mobile;
						tbSecphone.Text = c.Secphone;
						tbEmail.Text = c.Email;
						tbWebsite.Text = c.Website;
						tbAddress.Text = c.Address;
						tbNotes.Text = c.Notes;
					}
				}
			}
		}*/

		//BUTTON THAT ADDS NEW CONTACT TO 'contactlist' and listbox
		/*private void btnCreatecontact_Click(object sender, RoutedEventArgs e)
		{
			String thisName = tbNamefield.Text;
			String thisMobile = tbMobilefield.Text;
			String thisSecphone = tbSecphonefield.Text;
			String thisEmail = tbEmailfield.Text;
			String thisWebsite = tbWebsitefield.Text;
			String thisAddress = tbAddressfield.Text;
			String thisNotes = tbNotesfield.Text;

			if (thisName != "")
			{
				ContactDetails c = new ContactDetails();
				c.Name = thisName;
				c.Mobile = thisMobile;
				c.Secphone = thisSecphone;
				c.Email = thisEmail;
				c.Website = thisWebsite;
				c.Address = thisAddress;
				c.Notes = thisNotes;
				contactlist.Add(c);
				UpdatelistNames();

			}
			else
			{
				MessageBox.Show("You must fill in the Name field");
			}

			tbNamefield.Text = "";
			tbMobilefield.Text = "";
			tbSecphonefield.Text = "";
			tbEmailfield.Text = "";
			tbWebsitefield.Text = "http://";
			tbAddressfield.Text = "";
			tbNotesfield.Text = "";
		}*/
	}

}

Open in new window

0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35139908
>> Presumably by clicking 'debug' in VS isn't making a difference?

Biggest issue there is that VS will compile your .exe, and put it in the "SolutionName\ProjectName\bin\debug" folder and run it from there.  The significance of that is that if you put a data.xml file in "C:\Users\Bronco\Documents\Visual Studio\Projects\SolutionName\" and then click Debug, and your application just specifies "data.xml" without the entire fully qualified path, it's going to look in the current directory for that file, which will be "C:\Users\Bronco\Documents\Visual Studio\Projects\SolutionName\ProjectName\bin\debug\"
0
 

Author Comment

by:Bronco78th
ID: 35140825
Holy moly we got there!!!....that worked!!

Now to apply this new found knowledge to the rest of the program.

Many Thanks sir!

John
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question