Looking for Cleaner Code structure, and little xml help.

I'm pretty new to C# and need advise on how to Structure up code in a good way, making classes and methods.

Here is a small example code I wrote that I would like to structure better.
For example the xml node fetching is declared 2 times, when thay load on a button and when they are saved by another button.

How could I for example write a class or method that is located in a different .cs file and just call the method or class instead of writing the code several times ?

I also wonder how I can create the LocalTitle node directly under Root as the first child ?
As it is now I create LocalTitle node by saying that it should be added before OriginalTitle which is the firstchild, but if the OriginalTitle is missing then this wont work I guess.

Any examples ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
 
 
namespace XML_Update_sample
{
    public partial class Form1 : Form
    {
        XmlDocument xmlDoc = new XmlDocument();
        public String Xml_File;
 
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Load_xml_button_Click(object sender, EventArgs e)
        {
            if (open_xml_dialog.ShowDialog() == DialogResult.OK)
            {
                
                Xml_File = open_xml_dialog.FileName;
                xmlDoc.Load(Xml_File);
 
                XmlNode root = xmlDoc.DocumentElement;
                XmlNode LocalTitle = xmlDoc.SelectSingleNode("/Title/LocalTitle");
                XmlNode OriginalTitle = xmlDoc.SelectSingleNode("/Title/OriginalTitle");
                XmlNode SortTitle = xmlDoc.SelectSingleNode("/Title/SortTitle");
 
                
                if (LocalTitle == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_LocalTitle = xmlDoc.CreateElement("LocalTitle");
                    root.AppendChild(New_LocalTitle);
                    root.InsertBefore(New_LocalTitle, xmlDoc.SelectSingleNode("/Title/OriginalTitle"));
                }
                if (LocalTitle != null)
                {
                    LocalTitle_textbox.Text = LocalTitle.InnerText;
                }
 
                
                if (OriginalTitle == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_OriginalTitle = xmlDoc.CreateElement("OriginalTitle");
                    root.AppendChild(New_OriginalTitle);
                    root.InsertAfter(New_OriginalTitle, xmlDoc.SelectSingleNode("/Title/LocalTitle"));
                }
                if (OriginalTitle != null)
                {
                    OriginalTitle_textbox.Text = OriginalTitle.InnerText;
                }
 
 
 
                if (SortTitle == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_SortTitle = xmlDoc.CreateElement("SortTitle");
                    root.AppendChild(New_SortTitle);
                    root.InsertAfter(New_SortTitle, xmlDoc.SelectSingleNode("/Title/OriginalTitle"));
                }
                if (SortTitle != null)
                {
                    SortTitle_textbox.Text = SortTitle.InnerText;
                }
 
 
            }
 
        
        }
 
        private void Load_trailer_button_Click(object sender, EventArgs e)
        {
            if (open_trailer_dialog.ShowDialog() == DialogResult.OK)
            {
                string Trailer_File = open_trailer_dialog.FileName;
                Trailer_textbox.Text = Trailer_File;
                MessageBox.Show(Trailer_File);
            }  
        }
 
 
 
 
        private void Save_xml_button_Click(object sender, EventArgs e)
        {
            XmlNode LocalTitle = xmlDoc.SelectSingleNode("/Title/LocalTitle");
            XmlNode OriginalTitle = xmlDoc.SelectSingleNode("/Title/OriginalTitle");
            XmlNode SortTitle = xmlDoc.SelectSingleNode("/Title/SortTitle");
 
            LocalTitle.InnerText = LocalTitle_textbox.Text;
            OriginalTitle.InnerText = OriginalTitle_textbox.Text;
            SortTitle.InnerText = SortTitle_textbox.Text;
 
            xmlDoc.Save(Xml_File);
        }
 
    }
}

Open in new window

LVL 1
SmykenAsked:
Who is Participating?
 
anyoneisSoftware DeveloperCommented:
I can't think of anything more valuable to a beginning C# programmer than the this book:

Design Patterns Explained: A New Perspective on Object-Oriented Design (Second Edition) by Alan Shalloway and James R. Trott

The web site for the book is here:

http://www.netobjectives.com/resources/books/design-patterns-explained

I would advise buying it and making the commitment to working through it.

David
0
 
anyoneisSoftware DeveloperCommented:
Well, the first thing that comes to mind is to create a specialized version of XmlDocument by deriving your own MediaDocument from it. That said, you should "prefer containment to inheritance."

This latter path would have you create a similar MediaDocument with similar methods and properties, but rather than inherit from XmlDocument, it would contain an XmlDocument field, and its methods and properties would forward calls to the contained XmlDocument as needed.

David
0
 
SmykenAuthor Commented:
Ouch I don't understand a bit of what you wrote, as I said I'm totally new to C#.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Tony McCreathTechnical SEO ConsultantCommented:
Heres the basis of a class you could use to manage this XML better. Typical use would be:

// loading
Title title = new Title();
title.Load(Xml_File);
string localTitle = title.LocalTitle;

// saving
title.LocalTitle = LocalTitle_textbox.Text;
title.Save(Xml_File);
namespace PlayRoom
{
	/// <summary>
	/// Contains info about a Title
	/// Can read/write to/from an XML file
	/// </summary>
	public class Title
	{
		#region Constructors
		/// <summary>
		/// Default constructor
		/// </summary>
		public void Title() {}
 
		/// <summary>
		/// set all the porperties
		/// </summary>
		public void Title(string localTitle, string originalTitle, string sortTitle) 
		{ 
			// TODO: set the properties
		}
		#endregion
 
		#region Properties
		public string LocalTitle { get; set;}
		public string OriginalTitle { get; set;}
		public string SortTitle { get; set;}
		#endregion
 
		#region XML Serialisation
		/// <summary>
		/// Sets properties based on data from an XML file
		/// </summary>
		/// <param name="xmlFile"></param>
		public void Load(string xmlFile) 
		{
			// TODO: load into an XML document and set properties based on its content
		}
 
		/// <summary>
		/// Write properties to a file in XML format
		/// </summary>
		/// <param name="xmlFile"></param>
		public void Save(string xmlFile) 
		{
			// TODO: create an XmlDocument that contains our properties then save it
		}
		#endregion
 
 
	}
}

Open in new window

0
 
SmykenAuthor Commented:
Thanks Tiggerito

This seems to be the right way, I have looked at some opensource application and they are written in this way.
Is there any chance that you could explain a bit more ?
Also I will be using a treeview that when selectedindex changes the path will be picked from the selected node to set the path to the xml file, how would I pull that to the save void ?
I'm not sure how I would go about using the get/set values.
Also could you tell me why you write this:  public void Title() {}

Thanks !
0
 
Tony McCreathTechnical SEO ConsultantCommented:
Your indicating that the XML contains more than one instance of your Title item. i.e. there will be mutliple Title elements in the XML.

Could you comfirm this and provide a complete example of the XML that you will be working with.

The get; set; is automaitic in .Net 3.5 and is just a way to say a property that has a private field.

I stated the default constructor i.e. Title() as you heave to implicetly specify it if other constructors are specified.
0
 
SmykenAuthor Commented:
Here is a copy/paste of a mymovies.xml example file:

Below the Xml is my current source code for reading the xml file that is picked when a node in treeview is selected.

My problem is that I somehow have hard time to make a code simple or to put it in some classes, methods or/and into different .cs files, all my code is sadly in my form.cs file.
This looks awful and is not so good even if Im a total newbie to programming.
Any code example and explanation would be greatly appriciated !


 
<Title>
  <LocalTitle>American Psycho</LocalTitle>
  <OriginalTitle>American Psycho</OriginalTitle>
  <SortTitle>American Psycho</SortTitle>
  <LocalTrailer>
    <URL>\\HOMESERVER\Trailers\American Psycho\american psycho trailer.flv</URL>
  </LocalTrailer>
  <Added>2009-03-19 01:57:52</Added>
  <ProductionYear>2000</ProductionYear>
  <RunningTime>101</RunningTime>
  <IMDBrating>7.7</IMDBrating>
  <MPAARating />
  <Description>American Psycho is about the life of an upper class Wall Street business man in the 1980s whos psychotic behavior is increased more and more as his business life goes on. Based on the Bret Easton novel of the same name, this dark comical look into the lives of yuppies is violent yet beautifully done by the flawless Christian Bale as the serial killer/investment banker who just wants to fit in.</Description>
  <Type />
  <AspectRatio />
  <TMDbId>1359</TMDbId>
  <Genres>
    <Genre>Thriller</Genre>
    <Genre>Psychological Thriller</Genre>
    <Genre>Mature</Genre>
    <Genre>Violence</Genre>
  </Genres>
  <Persons>
    <Person>
      <Name>Mary Harron</Name>
      <Type>Director</Type>
      <Role />
    </Person>
    <Person>
      <Name>Christian Bale</Name>
      <Type>Actor</Type>
      <Role>Patrick Bateman</Role>
    </Person>
    <Person>
      <Name>Reese Witherspoon</Name>
      <Type>Actor</Type>
      <Role>Evelyn Williams</Role>
    </Person>
    <Person>
      <Name>Justin Theroux</Name>
      <Type>Actor</Type>
      <Role>Timothy Bryce</Role>
    </Person>
    <Person>
      <Name>Josh Lucas</Name>
      <Type>Actor</Type>
      <Role>Craig McDermott</Role>
    </Person>
    <Person>
      <Name>Bill Sage</Name>
      <Type>Actor</Type>
      <Role>David Van Patten</Role>
    </Person>
    <Person>
      <Name>Chloë Sevigny</Name>
      <Type>Actor</Type>
      <Role>Jean</Role>
    </Person>
    <Person>
      <Name>Samantha Mathis</Name>
      <Type>Actor</Type>
      <Role>Courtney Rawlinson</Role>
    </Person>
    <Person>
      <Name>Matt Ross</Name>
      <Type>Actor</Type>
      <Role>Luis Carruthers</Role>
    </Person>
    <Person>
      <Name>Jared Leto</Name>
      <Type>Actor</Type>
      <Role>Paul Allen</Role>
    </Person>
    <Person>
      <Name>Willem Dafoe</Name>
      <Type>Actor</Type>
      <Role>Det. Donald Kimball</Role>
    </Person>
    <Person>
      <Name>Cara Seymour</Name>
      <Type>Actor</Type>
      <Role>Christie</Role>
    </Person>
    <Person>
      <Name>Guinevere Turner</Name>
      <Type>Actor</Type>
      <Role>Elizabeth</Role>
    </Person>
    <Person>
      <Name>Stephen Bogaert</Name>
      <Type>Actor</Type>
      <Role>Harold Carnes</Role>
    </Person>
    <Person>
      <Name>Monika Meier</Name>
      <Type>Actor</Type>
      <Role>Daisy</Role>
    </Person>
    <Person>
      <Name>Krista Sutton</Name>
      <Type>Actor</Type>
      <Role>Sabrina</Role>
    </Person>
  </Persons>
  <Studios />
</Title>
 
 
 
 
 
 
 
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
 
 
namespace XML_Update_sample
{
    public partial class Form1 : Form
    {
        public XmlDocument xmlDoc = new XmlDocument();
 
        public Form1()
        {
            InitializeComponent();
 
            TreeNode booktitles = treeView1.Nodes.Add("Movies");
            treeView1.Sort();
            treeView1.ExpandAll();
            treeView1.FullRowSelect = true;
            treeView1.ShowLines = false;
            treeView1.ShowNodeToolTips = true;
 
 
            XmlDocument doc = new XmlDocument();
            doc.Load("AMFOPTIONS.xml");
 
            XmlNodeList LocationList = doc.GetElementsByTagName("Location");
 
            foreach (XmlNode node in LocationList)
            {
                XmlElement LocationElement = (XmlElement)node;
 
                string Location = LocationElement.InnerText;
 
                DirectoryInfo dir = new DirectoryInfo(Location);
                AddNode(dir, booktitles);
            }
 
        }
 
        public void AddNode(DirectoryInfo dir, TreeNode node)
        {
            try
            {
                foreach (DirectoryInfo dInfo in dir.GetDirectories())
                {
                    TreeNode mainNext = node.Nodes.Add(dInfo.Name);
                    AddNode(dInfo, mainNext);
                    mainNext.ToolTipText = dInfo.FullName;
                    mainNext.Name = dInfo.FullName;
                }
            }
            catch (UnauthorizedAccessException)
            {
                node.Nodes.Add("Access denied");
            }
 
            // Catch other exceptions
            catch (Exception)
            {
                node.Nodes.Add("Error accessing directory!");
            }
 
 
        }
 
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            xmlDoc = new XmlDocument();
            Front_picbox.Invalidate();
            Front_picbox.Image = null;
            Back_picbox.Invalidate();
            Back_picbox.Image = null;
            Drop_picbox.Invalidate();
            Drop_picbox.Image = null;
            LocalTitle_textbox.Invalidate();
            LocalTitle_textbox.Clear();
            OriginalTitle_textbox.Invalidate();
            OriginalTitle_textbox.Clear();
            SortTitle_textbox.Invalidate();
            SortTitle_textbox.Clear();
            Year_textbox.Invalidate();
            Year_textbox.Clear();
            Time_textbox.Invalidate();
            Time_textbox.Clear();
            Imdb_textbox.Invalidate();
            Imdb_textbox.Clear();
            Mpaa_combobox.Invalidate();
            Mpaa_combobox.Text = "";
            Description_textbox.Invalidate();
            Description_textbox.Clear();
            Type_combobox.Invalidate();
            Type_combobox.Text ="";
            Trailer_textbox.Invalidate();
            Trailer_textbox.Clear();
            Aratio_combobox.Invalidate();
            Aratio_combobox.Text = "";
 
 
            string path_xml = (treeView1.SelectedNode.Name.ToString() + @"\mymovies.xml");
            string path_front = (treeView1.SelectedNode.Name.ToString() + @"\Folder.jpg");
            string path_back = (treeView1.SelectedNode.Name.ToString() + @"\Back.jpg");
            string path_backdrop = (treeView1.SelectedNode.Name.ToString() + @"\backdrop.jpg");
 
            if (File.Exists(path_front))
            {
 
                Image bild = Image.FromFile(path_front);
                Front_picbox.Image = bild;
            }
            if (File.Exists(path_back))
            {
 
                Image bild = Image.FromFile(path_back);
                Back_picbox.Image = bild;
            }
            if (File.Exists(path_backdrop))
            {
 
                Image bild = Image.FromFile(path_backdrop);
                Drop_picbox.Image = bild;
            }
 
            if (File.Exists(path_xml))
            {
 
 
 
                xmlDoc.Load(path_xml);
 
                XmlNode root = xmlDoc.DocumentElement;
                XmlNode LocalTitle = xmlDoc.SelectSingleNode("/Title/LocalTitle");
                XmlNode OriginalTitle = xmlDoc.SelectSingleNode("/Title/OriginalTitle");
                XmlNode SortTitle = xmlDoc.SelectSingleNode("/Title/SortTitle");
                XmlNode Year = xmlDoc.SelectSingleNode("/Title/ProductionYear");
                XmlNode Time = xmlDoc.SelectSingleNode("/Title/RunningTime");
                XmlNode Trailer = xmlDoc.SelectSingleNode("/Title/LocalTrailer/URL");
                XmlNode Imdb = xmlDoc.SelectSingleNode("/Title/IMDBrating");
                XmlNode Mpaa = xmlDoc.SelectSingleNode("/Title/MPAARating");
                XmlNode Description = xmlDoc.SelectSingleNode("/Title/Description");
                XmlNode MType = xmlDoc.SelectSingleNode("/Title/Type");
                XmlNode Aratio = xmlDoc.SelectSingleNode("/Title/AspectRatio");
 
                if (LocalTitle == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_LocalTitle = xmlDoc.CreateElement("LocalTitle");
                    root.AppendChild(New_LocalTitle);
                    root.InsertBefore(New_LocalTitle, xmlDoc.SelectSingleNode("/Title/OriginalTitle"));
                }
                if (LocalTitle != null)
                {
                    LocalTitle_textbox.Text = LocalTitle.InnerText;
                }
 
 
                if (OriginalTitle == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_OriginalTitle = xmlDoc.CreateElement("OriginalTitle");
                    root.AppendChild(New_OriginalTitle);
                    root.InsertAfter(New_OriginalTitle, xmlDoc.SelectSingleNode("/Title/LocalTitle"));
                }
                if (OriginalTitle != null)
                {
                    OriginalTitle_textbox.Text = OriginalTitle.InnerText;
                }
 
 
 
                if (SortTitle == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_SortTitle = xmlDoc.CreateElement("SortTitle");
                    root.AppendChild(New_SortTitle);
                    root.InsertAfter(New_SortTitle, xmlDoc.SelectSingleNode("/Title/OriginalTitle"));
                }
                if (SortTitle != null)
                {
                    SortTitle_textbox.Text = SortTitle.InnerText;
                }
 
 
                if (Year == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_Year = xmlDoc.CreateElement("ProductionYear");
                    root.AppendChild(New_Year);
                    root.InsertAfter(New_Year, xmlDoc.SelectSingleNode("/Title/SortTitle"));
                }
                if (Year != null)
                {
                    Year_textbox.Text = Year.InnerText;
                }
 
 
                if (Time == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_Time = xmlDoc.CreateElement("RunningTime");
                    root.AppendChild(New_Time);
                    root.InsertAfter(New_Time, xmlDoc.SelectSingleNode("/Title/ProductionYear"));
                }
                if (Time != null)
                {
                    Time_textbox.Text = Time.InnerText;
                }
 
 
                if (Trailer == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_LocalTrailer = xmlDoc.CreateElement("LocalTrailer");
                    root.AppendChild(New_LocalTrailer);
                    root.InsertAfter(New_LocalTrailer, xmlDoc.SelectSingleNode("/Title/RunningTime"));
                    XmlElement New_Trailer = xmlDoc.CreateElement("URL");
                    New_LocalTrailer.AppendChild(New_Trailer);
 
                }
                if (Trailer != null)
                {
                    Trailer_textbox.Text = Trailer.InnerText;
                }
 
 
 
                if (Imdb == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_Imdb = xmlDoc.CreateElement("IMDBrating");
                    root.AppendChild(New_Imdb);
                    root.InsertAfter(New_Imdb, xmlDoc.SelectSingleNode("/Title/LocalTrailer"));
                }
                if (Imdb != null)
                {
                    Imdb_textbox.Text = Imdb.InnerText;
                }
 
 
                if (Mpaa == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_Mpaa = xmlDoc.CreateElement("MPAARating");
                    root.AppendChild(New_Mpaa);
                    root.InsertAfter(New_Mpaa, xmlDoc.SelectSingleNode("/Title/IMDBrating"));
                }
                if (Mpaa != null)
                {
                    Mpaa_combobox.SelectedText = Mpaa.InnerText;
                }
 
 
                if (Description == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_Description = xmlDoc.CreateElement("Description");
                    root.AppendChild(New_Description);
                    root.InsertAfter(New_Description, xmlDoc.SelectSingleNode("/Title/MPAARating"));
                }
                if (Description != null)
                {
                    Description_textbox.Text = Description.InnerText;
                }
 
 
                if (MType == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_MType = xmlDoc.CreateElement("Type");
                    root.AppendChild(New_MType);
                    root.InsertAfter(New_MType, xmlDoc.SelectSingleNode("/Title/Description"));
                }
                if (MType != null)
                {
                    Type_combobox.SelectedText = MType.InnerText;
                }
 
 
                if (Aratio == null)
                {
                    //MessageBox.Show("Node Missing Creating New Element");
                    XmlElement New_Aratio = xmlDoc.CreateElement("AspectRatio");
                    root.AppendChild(New_Aratio);
                    root.InsertAfter(New_Aratio, xmlDoc.SelectSingleNode("/Title/Type"));
                }
                if (Aratio != null)
                {
                    Aratio_combobox.SelectedText = Aratio.InnerText;
                }
 
            }
        }
 
        private void Load_trailer_button_Click(object sender, EventArgs e)
        {
            if (open_trailer_dialog.ShowDialog() == DialogResult.OK)
            {
                string Trailer_File = open_trailer_dialog.FileName;
                Trailer_textbox.Text = Trailer_File;
            }  
        }
 
 
 
 
        private void Save_xml_button_Click(object sender, EventArgs e)
        {
            XmlNode LocalTitle = xmlDoc.SelectSingleNode("/Title/LocalTitle");
            XmlNode OriginalTitle = xmlDoc.SelectSingleNode("/Title/OriginalTitle");
            XmlNode SortTitle = xmlDoc.SelectSingleNode("/Title/SortTitle");
            XmlNode Year = xmlDoc.SelectSingleNode("/Title/ProductionYear");
            XmlNode Time = xmlDoc.SelectSingleNode("/Title/RunningTime");
            XmlNode Trailer = xmlDoc.SelectSingleNode("/Title/LocalTrailer/URL");
            XmlNode Imdb = xmlDoc.SelectSingleNode("/Title/IMDBrating");
            XmlNode Mpaa = xmlDoc.SelectSingleNode("/Title/MPAARating");
            XmlNode Description = xmlDoc.SelectSingleNode("/Title/Description");
            XmlNode MType = xmlDoc.SelectSingleNode("/Title/Type");
            XmlNode Aratio = xmlDoc.SelectSingleNode("/Title/AspectRatio");
 
            LocalTitle.InnerText = LocalTitle_textbox.Text;
            OriginalTitle.InnerText = OriginalTitle_textbox.Text;
            SortTitle.InnerText = SortTitle_textbox.Text;
            Year.InnerText = Year_textbox.Text;
            Time.InnerText = Time_textbox.Text;
            Trailer.InnerText = Trailer_textbox.Text;
            Imdb.InnerText = Imdb_textbox.Text;
            Mpaa.InnerText = Mpaa_combobox.Text;
            Description.InnerText = Description_textbox.Text;
            MType.InnerText = Type_combobox.Text;
            Aratio.InnerText = Aratio_combobox.Text;
 
            xmlDoc.Save(treeView1.SelectedNode.Name.ToString() + @"\mymovies.xml");
        }
 
    }
}

Open in new window

0
 
Tony McCreathTechnical SEO ConsultantCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.