Click here to Skip to main content
15,896,606 members
Articles / Web Development / HTML

XML Data Files, XML Serialization, and .NET

Rate me:
Please Sign up or sign in to vote.
4.82/5 (28 votes)
27 Aug 200317 min read 340.5K   6.4K   130  
Describes a means to build XML data files using XML Schema and xsd.exe to facilitate easy XML Serialization
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Reflection;
using System.Threading;

namespace CardfileSerializationDemo
{
	/// <summary>
	/// Summary description for frmMain.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{
		// Instance data
		private Cards _cards = null;
		private string _fileName = "";
		private CardType _cardCache = null;
		private XmlSchemaCollection _xschemaCache = null;

		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem mnuFileNew;
		private System.Windows.Forms.MenuItem mnuFileOpen;
		private System.Windows.Forms.MenuItem mnuFileSave;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem mnuFileSaveAs;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem mnuFileExit;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem menuItem5;
		private System.Windows.Forms.MenuItem mnuInsertNote;
		private System.Windows.Forms.MenuItem mnuInsertImage;
		private System.Windows.Forms.MenuItem mnuInsertContact;
		private System.Windows.Forms.MenuItem menuItem6;
		private System.Windows.Forms.MenuItem mnuHelpAbout;
		private System.Windows.Forms.MenuItem menuItem7;
		private System.Windows.Forms.MenuItem mnuEditCut;
		private System.Windows.Forms.MenuItem mnuEditCopy;
		private System.Windows.Forms.MenuItem mnuEditPaste;
		private System.Windows.Forms.MenuItem mnuEditDel;
		private System.Windows.Forms.MenuItem mnuFileProps;
		private System.Windows.Forms.MenuItem menuItem8;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox tbDeckName;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.ListView lvCards;
		private System.Windows.Forms.ImageList ilCardTypes;
		private System.Windows.Forms.ColumnHeader hdrType;
		private System.Windows.Forms.ColumnHeader hdrName;
		private System.ComponentModel.IContainer components;

		public frmMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// Hook up a global exception handler...*not*
			// that we'll ever use it, but this *is* a demo
			// app after all...
			Application.ThreadException += new ThreadExceptionEventHandler(this.threadException);

			// Start with a "new" deck
			mnuFileNew_Click(null, null);
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMain));
			this.mainMenu1 = new System.Windows.Forms.MainMenu();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.mnuFileNew = new System.Windows.Forms.MenuItem();
			this.mnuFileOpen = new System.Windows.Forms.MenuItem();
			this.mnuFileSave = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.mnuFileSaveAs = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.mnuFileProps = new System.Windows.Forms.MenuItem();
			this.menuItem8 = new System.Windows.Forms.MenuItem();
			this.mnuFileExit = new System.Windows.Forms.MenuItem();
			this.menuItem7 = new System.Windows.Forms.MenuItem();
			this.mnuEditCut = new System.Windows.Forms.MenuItem();
			this.mnuEditCopy = new System.Windows.Forms.MenuItem();
			this.mnuEditPaste = new System.Windows.Forms.MenuItem();
			this.mnuEditDel = new System.Windows.Forms.MenuItem();
			this.menuItem4 = new System.Windows.Forms.MenuItem();
			this.menuItem5 = new System.Windows.Forms.MenuItem();
			this.mnuInsertNote = new System.Windows.Forms.MenuItem();
			this.mnuInsertImage = new System.Windows.Forms.MenuItem();
			this.mnuInsertContact = new System.Windows.Forms.MenuItem();
			this.menuItem6 = new System.Windows.Forms.MenuItem();
			this.mnuHelpAbout = new System.Windows.Forms.MenuItem();
			this.label1 = new System.Windows.Forms.Label();
			this.tbDeckName = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.lvCards = new System.Windows.Forms.ListView();
			this.hdrType = new System.Windows.Forms.ColumnHeader();
			this.hdrName = new System.Windows.Forms.ColumnHeader();
			this.ilCardTypes = new System.Windows.Forms.ImageList(this.components);
			this.SuspendLayout();
			// 
			// mainMenu1
			// 
			this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItem1,
																					  this.menuItem7,
																					  this.menuItem4,
																					  this.menuItem6});
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 0;
			this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.mnuFileNew,
																					  this.mnuFileOpen,
																					  this.mnuFileSave,
																					  this.menuItem2,
																					  this.mnuFileSaveAs,
																					  this.menuItem3,
																					  this.mnuFileProps,
																					  this.menuItem8,
																					  this.mnuFileExit});
			this.menuItem1.Text = "&File";
			// 
			// mnuFileNew
			// 
			this.mnuFileNew.Index = 0;
			this.mnuFileNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
			this.mnuFileNew.Text = "&New";
			this.mnuFileNew.Click += new System.EventHandler(this.mnuFileNew_Click);
			// 
			// mnuFileOpen
			// 
			this.mnuFileOpen.Index = 1;
			this.mnuFileOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
			this.mnuFileOpen.Text = "&Open...";
			this.mnuFileOpen.Click += new System.EventHandler(this.mnuFileOpen_Click);
			// 
			// mnuFileSave
			// 
			this.mnuFileSave.Enabled = false;
			this.mnuFileSave.Index = 2;
			this.mnuFileSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
			this.mnuFileSave.Text = "&Save";
			this.mnuFileSave.Click += new System.EventHandler(this.mnuFileSave_Click);
			// 
			// menuItem2
			// 
			this.menuItem2.Index = 3;
			this.menuItem2.Text = "-";
			// 
			// mnuFileSaveAs
			// 
			this.mnuFileSaveAs.Enabled = false;
			this.mnuFileSaveAs.Index = 4;
			this.mnuFileSaveAs.Text = "Save As...";
			this.mnuFileSaveAs.Click += new System.EventHandler(this.mnuFileSaveAs_Click);
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 5;
			this.menuItem3.Text = "-";
			// 
			// mnuFileProps
			// 
			this.mnuFileProps.Enabled = false;
			this.mnuFileProps.Index = 6;
			this.mnuFileProps.Text = "P&roperties...";
			this.mnuFileProps.Click += new System.EventHandler(this.mnuFileProps_Click);
			// 
			// menuItem8
			// 
			this.menuItem8.Index = 7;
			this.menuItem8.Text = "-";
			// 
			// mnuFileExit
			// 
			this.mnuFileExit.Index = 8;
			this.mnuFileExit.Shortcut = System.Windows.Forms.Shortcut.CtrlQ;
			this.mnuFileExit.Text = "E&xit";
			this.mnuFileExit.Click += new System.EventHandler(this.mnuFileExit_Click);
			// 
			// menuItem7
			// 
			this.menuItem7.Index = 1;
			this.menuItem7.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.mnuEditCut,
																					  this.mnuEditCopy,
																					  this.mnuEditPaste,
																					  this.mnuEditDel});
			this.menuItem7.Text = "&Edit";
			// 
			// mnuEditCut
			// 
			this.mnuEditCut.Enabled = false;
			this.mnuEditCut.Index = 0;
			this.mnuEditCut.Shortcut = System.Windows.Forms.Shortcut.CtrlX;
			this.mnuEditCut.Text = "Cu&t";
			this.mnuEditCut.Click += new System.EventHandler(this.mnuEditCut_Click);
			// 
			// mnuEditCopy
			// 
			this.mnuEditCopy.Enabled = false;
			this.mnuEditCopy.Index = 1;
			this.mnuEditCopy.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
			this.mnuEditCopy.Text = "&Copy";
			this.mnuEditCopy.Click += new System.EventHandler(this.mnuEditCopy_Click);
			// 
			// mnuEditPaste
			// 
			this.mnuEditPaste.Enabled = false;
			this.mnuEditPaste.Index = 2;
			this.mnuEditPaste.Shortcut = System.Windows.Forms.Shortcut.CtrlV;
			this.mnuEditPaste.Text = "&Paste";
			this.mnuEditPaste.Click += new System.EventHandler(this.mnuEditPaste_Click);
			// 
			// mnuEditDel
			// 
			this.mnuEditDel.Enabled = false;
			this.mnuEditDel.Index = 3;
			this.mnuEditDel.Shortcut = System.Windows.Forms.Shortcut.Del;
			this.mnuEditDel.Text = "&Delete";
			this.mnuEditDel.Click += new System.EventHandler(this.mnuEditDel_Click);
			// 
			// menuItem4
			// 
			this.menuItem4.Index = 2;
			this.menuItem4.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItem5});
			this.menuItem4.Text = "&Insert";
			// 
			// menuItem5
			// 
			this.menuItem5.Index = 0;
			this.menuItem5.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.mnuInsertNote,
																					  this.mnuInsertImage,
																					  this.mnuInsertContact});
			this.menuItem5.Text = "New card";
			// 
			// mnuInsertNote
			// 
			this.mnuInsertNote.Index = 0;
			this.mnuInsertNote.Text = "Note";
			this.mnuInsertNote.Click += new System.EventHandler(this.mnuInsertNote_Click);
			// 
			// mnuInsertImage
			// 
			this.mnuInsertImage.Index = 1;
			this.mnuInsertImage.Text = "Image";
			this.mnuInsertImage.Click += new System.EventHandler(this.mnuInsertImage_Click);
			// 
			// mnuInsertContact
			// 
			this.mnuInsertContact.Index = 2;
			this.mnuInsertContact.Text = "Contact";
			this.mnuInsertContact.Click += new System.EventHandler(this.mnuInsertContact_Click);
			// 
			// menuItem6
			// 
			this.menuItem6.Index = 3;
			this.menuItem6.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.mnuHelpAbout});
			this.menuItem6.Text = "&Help";
			// 
			// mnuHelpAbout
			// 
			this.mnuHelpAbout.Index = 0;
			this.mnuHelpAbout.Text = "About...";
			this.mnuHelpAbout.Click += new System.EventHandler(this.mnuHelpAbout_Click);
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(9, 9);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(84, 27);
			this.label1.TabIndex = 0;
			this.label1.Text = "Deck name:";
			// 
			// tbDeckName
			// 
			this.tbDeckName.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right);
			this.tbDeckName.Location = new System.Drawing.Point(93, 9);
			this.tbDeckName.Name = "tbDeckName";
			this.tbDeckName.Size = new System.Drawing.Size(618, 20);
			this.tbDeckName.TabIndex = 1;
			this.tbDeckName.Text = "";
			this.tbDeckName.TextChanged += new System.EventHandler(this.tbDeckName_TextChanged);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(9, 37);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(117, 27);
			this.label2.TabIndex = 2;
			this.label2.Text = "Cards:";
			// 
			// lvCards
			// 
			this.lvCards.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right);
			this.lvCards.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																					  this.hdrType,
																					  this.hdrName});
			this.lvCards.FullRowSelect = true;
			this.lvCards.GridLines = true;
			this.lvCards.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
			this.lvCards.HideSelection = false;
			this.lvCards.Location = new System.Drawing.Point(9, 65);
			this.lvCards.MultiSelect = false;
			this.lvCards.Name = "lvCards";
			this.lvCards.Size = new System.Drawing.Size(702, 279);
			this.lvCards.SmallImageList = this.ilCardTypes;
			this.lvCards.TabIndex = 3;
			this.lvCards.View = System.Windows.Forms.View.Details;
			this.lvCards.Resize += new System.EventHandler(this.lvCards_Resize);
			this.lvCards.DoubleClick += new System.EventHandler(this.lvCards_DoubleClick);
			this.lvCards.SelectedIndexChanged += new System.EventHandler(this.lvCards_SelectedIndexChanged);
			// 
			// hdrType
			// 
			this.hdrType.Text = "";
			this.hdrType.Width = 18;
			// 
			// hdrName
			// 
			this.hdrName.Text = "Card name";
			this.hdrName.Width = 300;
			// 
			// ilCardTypes
			// 
			this.ilCardTypes.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
			this.ilCardTypes.ImageSize = new System.Drawing.Size(16, 16);
			this.ilCardTypes.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilCardTypes.ImageStream")));
			this.ilCardTypes.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// frmMain
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(719, 353);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.lvCards,
																		  this.label2,
																		  this.tbDeckName,
																		  this.label1});
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Menu = this.mainMenu1;
			this.Name = "frmMain";
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
			this.Text = "Cardfile Serialization Demo Application";
			this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new frmMain());
		}

		public void threadException(object sender, ThreadExceptionEventArgs e)
		{
			DialogResult result = DialogResult.Cancel;
			try 
			{
				string strErr = String.Format("Application error, {0}",e.Exception.Message);
				result = MessageBox.Show(strErr, "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
			} // try
			catch (Exception)
			{
				try 
				{
					MessageBox.Show("Fatal application error...quitting now.", "Fatal Error", 
						MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
				} // try
				finally 
				{
					Application.Exit();
				} // finally
			} // catch
 
			// Exits on abort
			if (result == DialogResult.Abort) 
				Application.Exit();
		}

		private bool PromptSave()
		{
			bool bCancel = false;
			DialogResult result = MessageBox.Show("You have unsaved cards...save now?","Save?",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question);
			if ( result == DialogResult.Yes ) 
			{
				// Save the cards...
				mnuFileSave_Click(null, null);
			} // if
			else if ( result == DialogResult.Cancel )
			{
				// They aborted, so cancel...
				bCancel = true;
			} // else if

			return bCancel;
		}

		private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			// If we have cards that have been edited, we'll ask to
			// save them...
			e.Cancel = false;
			if ( this._cards != null )
			{
				if ( this._cards.Dirty )
				{
					if ( PromptSave() )
					{
						// User canceled...
						e.Cancel = true;
					} // if
				} // if
			} // if
		}

		private void mnuFileExit_Click(object sender, System.EventArgs e)
		{
			// Just quit...
			Application.Exit();
		}

		private void mnuFileNew_Click(object sender, System.EventArgs e)
		{
			// Check for the existence of cards
			if ( this._cards != null )
			{
				if ( this._cards.Dirty )
				{
					// Prompt to save the cards
					if ( !PromptSave() )
					{
						// They saved their cards, or at least didn't
						// cancel, so blow the existing cards away
						// and create new...
						this._cards = new Cards();

						// New file...
						this._fileName = "";
					} // if
				} // if
			} // if
			else
			{
				// We have none, so create some...
				this._cards = new Cards();

				// New file...
				this._fileName = "";
			} // else

			// Enable deck handling UI menu items, like "Save". When we
			// actually have a card we'll enable the editing menu items.
			EnableHandlerMenuItems(true);
		}

		private void mnuFileOpen_Click(object sender, System.EventArgs e)
		{
			// Load a card deck
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.AddExtension = true;
			dlg.CheckFileExists = true;
			dlg.CheckPathExists = true;
			dlg.DefaultExt = ".crd";
			dlg.Filter = "CardFile File (*.crd)|*.crd|All Files (*.*)|*.*";
			dlg.Multiselect = false;
			dlg.Title = "Open card file...";
			if ( dlg.ShowDialog() == DialogResult.OK )
			{
				// Set cursor
				this.Cursor = Cursors.WaitCursor;

				// Load the card file
				this._fileName = dlg.FileName;
				LoadCards(this._fileName);

				// Load the listview
				ResetCardList();

				// Load the deck name edit control...this will set the dirty
				// bit, so we'll reset it afterwards
				tbDeckName.Text = this._cards.Props.Name;
				this._cards.Dirty = false;

				// Enable deck handling UI menu items, like "Save". When we
				// actually have a card we'll enable the editing menu items.
				EnableHandlerMenuItems(true);

				// Reset cursor
				this.Cursor = Cursors.Arrow;
			} // if
		}

		private void mnuFileSave_Click(object sender, System.EventArgs e)
		{
			// Check to see if we have a filename
			if ( this._fileName.Length > 0 )
			{
				// Set cursor
				this.Cursor = Cursors.WaitCursor;

				// Save the card deck
				SaveCards(this._fileName);

				// Reset cursor
				this.Cursor = Cursors.Arrow;
			} // if
			else
			{
				// No filename, so default to a SaveAs()
				mnuFileSaveAs_Click(null, null);
			} // else
		}

		private void mnuFileSaveAs_Click(object sender, System.EventArgs e)
		{
			// We have a new deck that hasn't been assigned
			// a filename, so get a filename and then save.
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.AddExtension = true;
			dlg.CheckPathExists = true;
			dlg.OverwritePrompt = true;
			dlg.DefaultExt = ".crd";
			dlg.FileName = "CardFile";
			dlg.Filter = "CardFile File (*.crd)|*.crd|All Files (*.*)|*.*";
			dlg.FilterIndex = 0;
			dlg.Title = "Save cards as...";
			if ( dlg.ShowDialog() == DialogResult.OK )
			{
				// Set cursor
				this.Cursor = Cursors.WaitCursor;

				// Pull the filename
				this._fileName = dlg.FileName;

				// Set the default author name
				this._cards.Props.Author = SystemInformation.UserName;

				// Give opportunity to adjust properties
				mnuFileProps_Click(null, null);

				// Save...
				SaveCards(this._fileName);

				// Reset cursor
				this.Cursor = Cursors.Arrow;
			} // if
		}

		private void mnuFileProps_Click(object sender, System.EventArgs e)
		{
			// Bring up the properties dialog
			if ( this._cards != null )
			{
				frmProps dlg = new frmProps();
				dlg.Props = this._cards.Props;
				if ( dlg.ShowDialog() == DialogResult.OK )
				{
					// New properties given...
					this._cards.Props = dlg.Props;

					// We're dirty
					this._cards.Dirty = true;
				} // if
			} // if
		}

		private void mnuEditCut_Click(object sender, System.EventArgs e)
		{
			// Cut the selected card...
			ListViewItem item = lvCards.SelectedItems[0];
			if ( item != null )
			{
				CardType card = this._cards.Items.FindByID((Int32)item.Tag);
				if ( card != null )
				{
					// Remove the card from the collection
					this._cards.Items.Remove(card);

					// Remove the card from the listview
					lvCards.Items.Remove(item);

					// Copy to the card cache
					_cardCache = card;

					// We're dirty
					this._cards.Dirty = true;
				} // if
			} // if
		}

		private void mnuEditCopy_Click(object sender, System.EventArgs e)
		{
			// Cut the selected card...
			ListViewItem item = lvCards.SelectedItems[0];
			if ( item != null )
			{
				CardType card = this._cards.Items.FindByID((Int32)item.Tag);
				if ( card != null )
				{
					// Copy to the card cache
					_cardCache = new CardType(card);
				} // if
			} // if
		}

		private void mnuEditPaste_Click(object sender, System.EventArgs e)
		{
			// Add the card in the card cache to the collection and
			// display in the listview.
			if ( _cardCache.Header.ID == -1 ) _cardCache.Header.ID = this._cards.NextID++; // was a copy
			this._cards.Items.Add(_cardCache);

			string[] texts = new string[2];
			texts[0] = " "; // will not be displayed
			texts[1] = _cardCache.Header.Name;
			ListViewItem item = new ListViewItem(texts,Convert.ToInt32(_cardCache.Header.Type));
			item.Tag = _cardCache.Header.ID;
			lvCards.Items.Add(item);

			// We're dirty
			this._cards.Dirty = true;
		}

		private void mnuEditDel_Click(object sender, System.EventArgs e)
		{
			// Just do a cut, in case they want it back...
			mnuEditCut_Click(null, null);
		}

		private void mnuInsertNote_Click(object sender, System.EventArgs e)
		{
			// Create the new card
			CreateCard(CardTypeHeaderType.Note);
		}

		private void mnuInsertImage_Click(object sender, System.EventArgs e)
		{
			// Create the new card
			CreateCard(CardTypeHeaderType.Image);
		}

		private void mnuInsertContact_Click(object sender, System.EventArgs e)
		{
			// Create the new card
			CreateCard(CardTypeHeaderType.Contact);
		}

		private void mnuHelpAbout_Click(object sender, System.EventArgs e)
		{
			// Display the "About" dialog...
			frmAbout dlg = new frmAbout();
			dlg.ShowDialog();
		}

		private void EnableHandlerMenuItems(bool bEnable)
		{
			// The "handler" menu items include:
			//
			// File|Save
			// File|SaveAs
			// File|Properties
			mnuFileSave.Enabled = bEnable;
			mnuFileSaveAs.Enabled = bEnable;
			mnuFileProps.Enabled = bEnable;
		}

		private void EnableEditingMenuItems(bool bEnable)
		{
			// The "editing" menu items include:
			//
			// Edit|Cut
			// Edit|Copy
			// Edit|Paste
			// Edit|Delete
			mnuEditCut.Enabled = bEnable;
			mnuEditCopy.Enabled = bEnable;
			mnuEditPaste.Enabled = bEnable;
			mnuEditDel.Enabled = bEnable;

			// Override the paste disable if there
			// is something in the card cache
			if ( this._cardCache != null ) mnuEditPaste.Enabled = true;
		}

		private void ResetCardList()
		{
			// Iterate through cards, placing the name and type of card
			// into the listview control
			lvCards.SuspendLayout(); // hold up redraws...
			lvCards.Items.Clear(); // clear existing data...

			if ( this._cards != null )
			{
				// Iterate through each card, adding it to the
				// listview...
				foreach ( CardType card in this._cards.Items )
				{
					string[] texts = new string[2];
					texts[0] = " "; // will not be displayed
					texts[1] = card.Header.Name;
					ListViewItem item = new ListViewItem(texts,Convert.ToInt32(card.Header.Type));
					item.Tag = card.Header.ID;
					lvCards.Items.Add(item);
				} // if
			} // if

			lvCards.ResumeLayout(); // allow redraws...
		}

		private void SaveCards(string fileName)
		{
			// Serialize the cards to a file
			StreamWriter writer = null;
			try
			{
				XmlSerializer ser = new XmlSerializer(typeof(Cards));
				writer = new StreamWriter(fileName);
				ser.Serialize(writer, this._cards);
				this._cards.Dirty = false;
			} // try
			catch (Exception ex)
			{
				string strErr = String.Format("Unable to save cards, error '{0}'",ex.Message);
				MessageBox.Show(strErr,"CardFile2003 File Save Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
			} // catch
			finally
			{
				if (writer != null) writer.Close();
				writer = null;
			} // finally
		}

		private void LoadCards(string fileName)
		{
			StreamReader reader = null;
			try
			{
				// Check for pre-loaded schema
				if ( _xschemaCache == null )
				{
					// Create the XmlSchemaCollection.
					_xschemaCache = new XmlSchemaCollection();

					// Load the schema resource.
					Assembly assem = Assembly.GetExecutingAssembly();
					Stream stream = assem.GetManifestResourceStream(this.GetType(), "Cardfile.xsd");
					XmlTextReader xrdr = new XmlTextReader(stream);
					_xschemaCache.Add("http://tempuri.org/Cardfile.xsd", xrdr);
				} // if

				// Set up the basic file stream reader
				reader = new StreamReader(fileName);

				// Set up validatation
				XmlValidatingReader xval = new XmlValidatingReader(new XmlTextReader(reader));
				xval.ValidationType = ValidationType.Schema;
				xval.Schemas.Add(_xschemaCache);

				// Deserialize
				XmlSerializer ser = new XmlSerializer(typeof(Cards));
				this._cards = (Cards)ser.Deserialize(xval);
				if ( this._cards == null ) throw new NullReferenceException("Invalid card file");
			} // try
			catch (Exception ex)
			{
				string strErr = String.Format("Unable to load cards, error '{0}'",ex.Message);
				MessageBox.Show(strErr,"CardfileSerializationDemo File Open Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
			} // catch
			finally
			{
				if (reader != null) reader.Close();
			} // finally
		}

		private void CreateCard(CardTypeHeaderType type)
		{
			// Create a new card based upon the type
			DialogResult result = DialogResult.Cancel;
			CardType card = new CardType();
			switch ( type )
			{
				case CardTypeHeaderType.Note:
					{
						InitNoteCard(ref card);
						result = EditNoteCard(ref card);
					} // scope
					break;

				case CardTypeHeaderType.Image:
					{
						InitImageCard(ref card);
						result = EditImageCard(ref card);
					} // scope
					break;

				case CardTypeHeaderType.Contact:
					{
						InitContactCard(ref card);
						result = EditContactCard(ref card);
					} // scope
					break;

			} // switch

			// Check for cancel
			if ( result == DialogResult.OK )
			{
				// Add it to our card deck
				this._cards.Items.Add(card);

				// Insert the card into the list view
				string[] texts = new string[2];
				texts[0] = " "; // will not be displayed
				texts[1] = card.Header.Name;
				ListViewItem item = new ListViewItem(texts,Convert.ToInt32(card.Header.Type));
				item.Tag = card.Header.ID;
				lvCards.Items.Add(item);

				// Mark as dirty
				this._cards.Dirty = true;
			} // if
		}

		private void InitNoteCard(ref CardType card)
		{
			// Complete the header
			card.Header.Name = String.Format("New note");
			card.Header.ID = _cards.NextID++;
			card.Header.Type = CardTypeHeaderType.Note;
			card.Header.Created = DateTime.Now;
			card.Header.Updated = DateTime.Now;

			// Initialize the body
			card.Body.Item = String.Format("");
		}

		private DialogResult EditNoteCard(ref CardType card)
		{
			DialogResult result = DialogResult.Cancel;
			frmNote dlg = new frmNote();
			dlg.CardName = card.Header.Name;
			dlg.NoteText = (string)card.Body.Item;
			result = dlg.ShowDialog();
			if ( result == DialogResult.OK )
			{
				// Set the date, note text, and card name
				card.Header.Name = dlg.CardName;
				card.Header.Updated = DateTime.Now;
				card.Body.Item = String.Format("{0}",dlg.NoteText);
			} // if

			return result;
		}

		private void InitImageCard(ref CardType card)
		{
			// Complete the header
			card.Header.Name = String.Format("New image");
			card.Header.ID = _cards.NextID++;
			card.Header.Type = CardTypeHeaderType.Image;
			card.Header.Created = DateTime.Now;
			card.Header.Updated = DateTime.Now;

			// Initialize the body
			card.Body.Item = new Byte[0];
		}

		private DialogResult EditImageCard(ref CardType card)
		{
			DialogResult result = DialogResult.Cancel;
			frmImage dlg = new frmImage();
			dlg.CardName = card.Header.Name;
			dlg.Image = DecodeImage((Byte[])card.Body.Item);
			result = dlg.ShowDialog();
			if ( result == DialogResult.OK )
			{
				// Set the date, image, and card name
				card.Header.Name = dlg.CardName;
				card.Header.Updated = DateTime.Now;
				card.Body.Item = EncodeImage(dlg.Image);
			} // if

			return result;
		}

		private void InitContactCard(ref CardType card)
		{
			// Complete the header
			card.Header.Name = String.Format("New contact");
			card.Header.ID = _cards.NextID++;
			card.Header.Type = CardTypeHeaderType.Contact;
			card.Header.Created = DateTime.Now;
			card.Header.Updated = DateTime.Now;

			// Initialize the body
			card.Body.Item = new CardTypeBodyContact();
		}

		private DialogResult EditContactCard(ref CardType card)
		{
			DialogResult result = DialogResult.Cancel;
			frmContact dlg = new frmContact();
			dlg.CardName = card.Header.Name;
			dlg.ContactInfo = (CardTypeBodyContact)card.Body.Item;
			result = dlg.ShowDialog();
			if ( result == DialogResult.OK )
			{
				// Set the date, contact information, and card name
				card.Header.Name = dlg.CardName;
				card.Header.Updated = DateTime.Now;
				card.Body.Item = dlg.ContactInfo;
			} // if

			return result;
		}

		private Byte[] EncodeImage(Image bitmap)
		{
			// Create a converter
			ImageConverter converter = new ImageConverter();

			// Convert bitmap to a byte array
			return (Byte[])converter.ConvertTo(bitmap, typeof(Byte[]));
			}

		private Image DecodeImage(Byte[] bytes)
		{
			// Extract bitmap from Base64 byte array
			Image img = null;
			if ( bytes.GetLength(0) > 0 )
			{
				ImageConverter converter = new ImageConverter();
				img = (Image)converter.ConvertFrom(bytes);
			} // if

			return img;
		}

		private void tbDeckName_TextChanged(object sender, System.EventArgs e)
		{
			// Name changed...set and mark deck as dirty
			this._cards.Props.Name = tbDeckName.Text;
			this._cards.Dirty = true;
		}

		private void lvCards_DoubleClick(object sender, System.EventArgs e)
		{
			// Edit the given card...
			ListViewItem item = lvCards.SelectedItems[0];
			if ( item != null )
			{
				CardType card = this._cards.Items.FindByID((Int32)item.Tag);
				if ( card != null )
				{
					// Determine the type and edit
					DialogResult result = DialogResult.Cancel;
					switch ( card.Header.Type )
					{
						case CardTypeHeaderType.Note:
						{
							result = EditNoteCard(ref card);
						} // scope
							break;

						case CardTypeHeaderType.Image:
						{
							result = EditImageCard(ref card);
						} // scope
							break;

						case CardTypeHeaderType.Contact:
						{
							result = EditContactCard(ref card);
						} // scope
							break;

					} // switch

					// Revise card name in list control
					if ( result == DialogResult.OK )
					{
						// Reset the text shown in the listview
						item.SubItems[0].Text = card.Header.Name;
						ResetCardList();

						// Mark as dirty
						this._cards.Dirty = true;
					} // if
				} // if
			} // if
		}

		private void lvCards_Resize(object sender, System.EventArgs e)
		{
			// Resize the name column to look nice...
			lvCards.Columns[1].Width = lvCards.Width - lvCards.Columns[0].Width - 4;
		}

		private void lvCards_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if ( lvCards.SelectedItems.Count > 0 )
			{
				// We have a selected card, so we can cut/paste
				EnableEditingMenuItems(true);
			} // if
			else
			{
				// No selected card
				EnableEditingMenuItems(false);
			} // else
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions