Click here to Skip to main content
15,894,646 members
Articles / Mobile Apps

Compact Framework Project Manager

Rate me:
Please Sign up or sign in to vote.
3.77/5 (18 votes)
2 Jun 2004CPOL5 min read 61.4K   156   31  
A real world example of storing and retrieving XML files and sending them across IR ports.
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Xml;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace CF_Proj_Mgr
{
	/// <summary>
	/// Summary description for FileIO.
	/// </summary>
	public class FileIO
	{
		private bool IsRunning;


		public FileIO()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public FileIO( bool isRun )
		{
			isRunning = isRun;
		}
		
		public bool isRunning
		{
			get { return this.IsRunning; }
			set { this.IsRunning = value; }
		}
		public void SaveFile( string fileToSaveTo, ArrayList myProjects )
		{
			XmlTextWriter fileWriter = new XmlTextWriter( fileToSaveTo, Encoding.ASCII);
			fileWriter.Formatting = Formatting.Indented;
			fileWriter.WriteStartDocument();
			fileWriter.WriteStartElement("Projects");

			foreach (project p in (myProjects) )
			{
				WriteProject( fileWriter, p);
			}
			fileWriter.WriteEndDocument();
			fileWriter.Close();
		}

		private void WriteProject( XmlTextWriter fileWriter, project p )
		{
			// write out the project information
			fileWriter.WriteStartElement("Project");
			fileWriter.WriteAttributeString("Name", p.Name );
			fileWriter.WriteAttributeString("Description", p.Description );
			fileWriter.WriteAttributeString("DueDate", p.DueDate );
			fileWriter.WriteAttributeString("Manager", p.Resource );
			fileWriter.WriteAttributeString("SalesGuy", p.SalesGuy );
			fileWriter.WriteAttributeString("TER", p.TER );
			fileWriter.WriteAttributeString("SONumber", p.SOnum );
			fileWriter.WriteAttributeString("PONumber1", p.POnum1 );
			fileWriter.WriteAttributeString("POValue1", p.POamt1.ToString() );
			fileWriter.WriteAttributeString("PONumber2", p.POnum2 );
			fileWriter.WriteAttributeString("POValue2", p.POamt2.ToString() );
			// write out the customer
			fileWriter.WriteStartElement("Customer");
			fileWriter.WriteAttributeString("Name", p.Customer.Name);
			fileWriter.WriteAttributeString("Phone", p.Customer.Phone);
			fileWriter.WriteAttributeString("Email", p.Customer.EMail);
			fileWriter.WriteAttributeString("Contact", p.Customer.Contact);
			fileWriter.WriteEndElement();	// customer

			// write out the list of tasks.
			fileWriter.WriteStartElement("Tasks");
			foreach( task t in p.Tasks )
			{
				fileWriter.WriteStartElement("Task");
				fileWriter.WriteAttributeString( "Name", t.Name);
				fileWriter.WriteAttributeString( "Resource", t.Resource);
				fileWriter.WriteAttributeString( "PrevTask", t.PrevTask);
				fileWriter.WriteEndElement();
			}
			fileWriter.WriteEndElement();	// end Tasks

			// write out the list of to do's
			fileWriter.WriteStartElement("ToDos");
			foreach( todo td in p.ToDos )
			{
				fileWriter.WriteStartElement("ToDo");
				fileWriter.WriteAttributeString( "Name", td.Name );
				if ( td.Done )
					fileWriter.WriteAttributeString( "Done", "1" );
				else
					fileWriter.WriteAttributeString( "Done", "0" );
				fileWriter.WriteAttributeString( "DueDate", td.DueDate.ToLongDateString() );
				fileWriter.WriteEndElement();
			}
			fileWriter.WriteEndElement();	// end ToDos

			fileWriter.WriteStartElement("Notes");
			foreach( note n in p.Notes )
			{
				fileWriter.WriteStartElement("Note");
				fileWriter.WriteAttributeString( "Text", n.Text);
				fileWriter.WriteAttributeString( "Date", n.Date.ToString() );
				fileWriter.WriteEndElement();
			}
			fileWriter.WriteEndElement();	// end Notes

			fileWriter.WriteEndElement();	// end Project
		}

		public void LoadFile( string fileToReadFrom, ArrayList myProjects )
		{
			XmlDocument xmlDoc = new XmlDocument();
			XmlTextReader reader = new XmlTextReader( fileToReadFrom);
			try 
			{
				xmlDoc.Load( reader );
				XmlNode rootElement = xmlDoc.DocumentElement;
				XmlNodeList xNodes = rootElement.ChildNodes;
				foreach( XmlNode childNode in xNodes )
				{
					project pr = new project();
					foreach( XmlAttribute attrib in childNode.Attributes )
					{
						switch ( attrib.Name )
						{
							case "Name" :
								pr.Name = attrib.Value;
								break;
							case "Description" :
								pr.Description = attrib.Value;
								break;
							case "DueDate" :
								pr.DueDate = attrib.Value;
								break;
							case "Manager" :
								pr.Resource = attrib.Value;
								break;
							case "SalesGuy" :
								pr.SalesGuy = attrib.Value;
								break;
							case "TER" :
								pr.TER = attrib.Value;
								break;
							case "SONumber" :
								pr.SOnum = attrib.Value;
								break;
							case "PONumber1" :
								pr.POnum1 = attrib.Value;
								break;
							case "POValue1" :
								pr.POamt1 = Convert.ToInt32( attrib.Value);
								break;
							case "PONumber2" :
								pr.POnum2 = attrib.Value;
								break;
							case "POValue2" :
								pr.POamt2 = Convert.ToInt32( attrib.Value);
								break;
						}
					}
					foreach( XmlNode child in childNode.ChildNodes )
					{
						switch ( child.Name )
						{
							case "Customer" :
								foreach( XmlAttribute attrib in child.Attributes )
								{
									switch ( attrib.Name )
									{
										case "Name" :
											pr.Customer.Name = attrib.Value;
											break;
										case "Contact" :
											pr.Customer.Contact = attrib.Value;
											break;
										case "Phone" :
											pr.Customer.Phone = attrib.Value;
											break;
										case "Email" :
											pr.Customer.EMail = attrib.Value;
											break;
									}
								}
								break;
							case "Tasks" :
								foreach( XmlNode tsks in child.ChildNodes )
								{
									task t = new task();
									foreach( XmlAttribute attrib in tsks.Attributes )
									{
										switch ( attrib.Name )
										{
											case "Name" :
												t.Name = attrib.Value;
												break;
											case "Resource" :
												t.Resource = attrib.Value;
												break;
											case "StartDate" :
												t.StartDate = DateTime.Parse(attrib.Value);
												break;
											case "EndDate" :
												t.EndDate = DateTime.Parse(attrib.Value);
												break;
											case "PrevTask" :
												t.PrevTask = attrib.Value;
												break;
										}
									}
									pr.Tasks.Add(t);
								}
								break;
							case "ToDos" :
								foreach( XmlNode tdos in child.ChildNodes)
								{
									todo t = new todo();
									foreach( XmlAttribute attrib in tdos.Attributes )
									{
										switch ( attrib.Name )
										{
											case "Name" :
												t.Name = attrib.Value;
												break;
											case "Done" :
												t.Done =false;
												if ( attrib.Value == "1")
													t.Done = true;
												break;
											case "DueDate" :
												t.DueDate = DateTime.Parse(attrib.Value);
												break;
										}
									}
									pr.ToDos.Add(t);
								}
								break;
							case "Notes" :
								foreach( XmlNode notes in child.ChildNodes)
								{
									note n = new note();
									foreach( XmlAttribute attrib in notes.Attributes )
									{
										switch ( attrib.Name )
										{
											case "Text" :
												n.Text = attrib.Value;
												break;
											case "Date" :
												n.Date = DateTime.Parse(attrib.Value);
												break;
										}
									}
									pr.Notes.Add(n);
								}
								break;
						}
					}
					myProjects.Add( pr);
				}
			}
			catch ( Exception exc ) 
			{
				Console.WriteLine ("Exception: {0}", exc.ToString());
			}
			finally 
			{
				reader.Close();
			}
		}

		private void StringOut (string str)
		{
			//this.listOut.Items.Add (str);
			return;
		}

		public void SendFileToIR (string strFileName)
		{
			Stream s;
			FileStream fs;
			int rc;
			IrDAClient irClient;

			try
			{
				fs = new FileStream (strFileName, FileMode.Open,
					FileAccess.Read);
			}
			catch (IOException ex)
			{
				StringOut (string.Format("Error opening file {0}",
					ex.Message));
				return;
			}
			StringOut ("File opened");

			irClient = new IrDAClient ();
			//
			// Connect to service
			//
			StringOut ("Waiting at connect");
			try
			{
				irClient.Connect("PrjMgr");

			}
			catch (SocketException ex)
			{
				StringOut (string.Format ("Sock connect exception {0}",
					ex.ErrorCode));
				fs.Close();
				return;
			}
			StringOut ("Connected");

			//
			// Start transfer
			//
			try
			{
				s = irClient.GetStream();
			}
			catch (SocketException ex)
			{
				StringOut (string.Format ("Sock GetStream exception {0}",
					ex.ErrorCode));
				fs.Close();
				irClient.Close();
				return;
			}
			// Parse path to get only the file name and extension
			char[]  parse = "\\".ToCharArray();
			string[] fnParts = strFileName.Split (parse);
			string strNameOnly = fnParts[fnParts.Length-1];
			int nLen = strNameOnly.Length;

			// Allocate transfer buffer
			byte[] buff = new byte[4096];

			// Send name length
			StringOut ("Sending file name");
			if (!SendDWord (s, nLen+1))
			{
				StringOut (string.Format ("Error sending name length"));
				return;
			}
			// Send name
			UTF8Encoding UTF8enc = new UTF8Encoding();
			UTF8enc.GetBytes (strNameOnly, 0, nLen, buff, 0);
			buff[nLen] = 0;
			try
			{
				s.Write (buff, 0, nLen+1);
			}
			catch (SocketException ex)
			{
				StringOut (string.Format ("Sock Write exception {0}",
					ex.ErrorCode));
			}
			StringOut ("Sending file");
			// Send file length
			nLen = (int)fs.Length;
			if (!SendDWord (s, nLen))
			{
				StringOut ("Error sending file list");
			}

			// Read back file open return code
			StringOut ("Reading file create ack");
			RecvDWord (s, out rc);
			if (rc != 0)
			{
				StringOut (string.Format ("Bad Ack code {0}", rc));
				fs.Close();
				irClient.Close();
				s.Close();
				return;
			}
			StringOut ("ack received");

			// Send file data
			while (nLen > 0)
			{
				int j = -1;
				try
				{
					j = (nLen > buff.Length) ? buff.Length : nLen;
					StringOut (string.Format("Sending {0} bytes", j));
					fs.Read (buff, 0, j);
					s.Write (buff, 0, j);
					nLen -= j;

					if (!RecvDWord (s, out j))
						break;
					if (j != 0)
					{
						StringOut ("Error ack");
						break;
					}
				}
				catch (SocketException socex)
				{
					StringOut (string.Format ("5 Sock Err {0} ({1},{2}",
						socex.ErrorCode, nLen, j));
					break;
				}
				catch (IOException ioex)
				{
					StringOut (string.Format ("File Error {0}",
						ioex.Message));
					break;
				}
				// Allow other events to happen during loop
				Application.DoEvents();
			}
			StringOut (string.Format("File sent"));

			s.Close();          // Close the stream
			irClient.Close();   // Close the socket
			fs.Close();         // Close the file
			return;
		}
		/// <summary>
		/// Sends a DWORD to the other device
		/// </summary>
		/// <param name="s"></param>
		/// <param name="i"></param>
		/// <returns></returns>
		bool SendDWord (Stream s, int i)
		{
			byte[] b = BitConverter.GetBytes (i);
			try
			{
				s.Write (b, 0, 4);
			}
			catch (SocketException ex)
			{
				StringOut (string.Format ("Err {0} writing dword",
					ex.ErrorCode));
				return false;
			}
			return true;
		}
		/// <summary>
		/// Receiveds a DWORD from the other device
		/// </summary>
		/// <param name="s"></param>
		/// <param name="i"></param>
		/// <returns></returns>
		bool RecvDWord (Stream s, out int i)
		{
			byte[] b = new byte[4];
			try
			{
				s.Read (b, 0, 4);
			}
			catch (SocketException ex)
			{
				StringOut (string.Format ("Err {0} reading dword",
					ex.ErrorCode));
				i = 0;
				return false;
			}
			i = BitConverter.ToInt32 (b, 0);
			return true;
		}
		/// <summary>
		/// Server thread
		/// </summary>
		public void SrvRoutine()
		{
			IrDAListener irListen;
			FileStream fs;
			string strFileName;
			int nLen;
			IrDAClient irClientSrv;
			Stream s;
			byte[] buff = new byte[4096];

			try
			{
				irListen = new IrDAListener("PrjMgr");
				irListen.Start();
			}
			catch (SocketException ex)
			{
				StringOut (string.Format("Err {0} creating IrDAListener",
					ex.ErrorCode));
				return;
			}
			StringOut ("IrdaListener created");

			while (isRunning)
			{
				if (irListen.Pending())
				{
					try
					{
						StringOut ("Calling AcceptIrDAClient");
						irClientSrv = irListen.AcceptIrDAClient();
						StringOut ("AcceptIrDAClient returned");
						s = irClientSrv.GetStream();
					}
					catch (SocketException ex)
					{
						StringOut (string.Format ("Sock exception {0}",
							ex.ErrorCode));
						continue;
					}

					// Get name length
					StringOut ("Getting file name");
					if (!RecvDWord (s, out nLen))
					{
						StringOut ("Error getting name length");
						s.Close();
						continue;
					}
					// Read name
					try
					{
						s.Read (buff, 0, nLen);
					}
					catch (SocketException ex)
					{
						StringOut (string.Format ("Read exception {0}",
							ex.ErrorCode));
						s.Close();
						continue;
					}
					UTF8Encoding UTF8enc = new UTF8Encoding();
					//Trim terminating zero
					char[] ch = UTF8enc.GetChars (buff, 0, nLen-1);
					strFileName = new string (ch);
					StringOut ("Receiving file " + strFileName);

					// Get file length
					if (!RecvDWord (s, out nLen))
					{
						StringOut ("Error getting file length");
					}
					StringOut (string.Format ("File len: {0}", nLen));
					try
					{
						fs = new FileStream (strFileName,
							FileMode.Create,
							FileAccess.Read|FileAccess.Write);
					}
					catch (IOException ioex)
					{
						StringOut (string.Format("Error opening file"));
						StringOut (ioex.Message);
						SendDWord (s, -3);
						s.Close();
						continue;
					}
					StringOut ("File opened");

					// Send file open return code
					StringOut ("Send file create ack");
					if (!SendDWord (s, 0))
					{
						StringOut ("fail sending ack code");
						fs.Close();
						s.Close();
						break;
					}
					int nTotal = 0;
					// Send file data
					while (nLen > 0)
					{
						int BlkSize = -1;
						try
						{
							BlkSize = (nLen > buff.Length) ?
								buff.Length : nLen;
							int k = 0, BytesRead = 0;
							while (BlkSize > k) 
							{
								// Wait for data
								if (!((NetworkStream)s).DataAvailable)
									Thread.Sleep(100);
								// Read it
								BytesRead = s.Read (buff, k, BlkSize-k);
								StringOut (string.Format ("Bytes: {0}",
									BytesRead));
								k += BytesRead;
							}
							fs.Write (buff, 0, BlkSize);
							StringOut ("Send Ack");
							if (!SendDWord (s, 0))
							{
								StringOut ("Error sending ack");
								break;
							}
							nLen -= BlkSize;
							nTotal += BlkSize;
						}
						catch (SocketException socex)
						{
							StringOut (string.Format ("Sock Err {0}",
								socex.ErrorCode));
							break;
						}
						catch (IOException ioex)
						{
							StringOut (string.Format ("File Err {0}",
								ioex.Message));
							StringOut (ioex.Message);
							break;
						}
					}
					StringOut (string.Format("File received {0} bytes.",
						nTotal));
					RecvDWord (s, out nLen);
					fs.Close();
					s.Close();
					ArrayList al= new ArrayList(1);
					LoadFile(strFileName,al);
					foreach( project p in al )
					{
						CF_Proj_Mgr.MainForm.AddProject(p);
						//this
					}
				}
				if (isRunning)
					Thread.Sleep (500);
			}
			irListen.Stop();
			return;
		}




	}
}

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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