Click here to Skip to main content
15,896,154 members
Articles / Web Development / ASP.NET

Web User Forms for ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.90/5 (52 votes)
18 Sep 2012CPOL12 min read 135.6K   4.5K   187  
User driven runtime dynamic ASP.NET Web Forms
// -- FILE ------------------------------------------------------------------
// name       : XmlBase.cs
// project    : Itenso Web User Forms
// created    : Jani Giannoudis - 2008.10.30
// language   : c#
// environment: .NET 2.0
// copyright  : (c) 2008-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;
using System.Globalization;

namespace Itenso.WebUserForms.Data
{

	// ------------------------------------------------------------------------
	// TC must be a referential type which implements T and which provides a public no-arg c'tor
	public abstract class XmlBase<T, TC> where TC : class, T, new() where T : class
	{

		// ----------------------------------------------------------------------
		public const string NoPrefix = "";
		public const string WufPrefix = "wuf";
		public const string WufNamespace = "http://www.itenso.com/xml/schema/webuserforms";

		public const string XmlDateFormat = "yyyy'-'MM'-'dd";
		public const string XmlTimeFormat = "HH':'mm':'ss";
		public const string XmlDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss";

		// ----------------------------------------------------------------------
		protected XmlBase( string docTag, XmlReaderSettings xmlReadSettings )
		{
			if ( string.IsNullOrEmpty( docTag ) )
			{
				throw new ArgumentNullException( "docTag" );
			}
			if ( xmlReadSettings == null )
			{
				throw new ArgumentNullException( "xmlReadSettings" );
			}
			this.docTag = docTag;
			this.xmlReadSettings = xmlReadSettings;
		} // XmlBase

		// ----------------------------------------------------------------------
		public string ToXmlString( T content )
		{
			string formatted = null;
			if ( content != null )
			{
				using ( StringWriter stringWriter = new StringWriter( CultureInfo.InvariantCulture ) )
				{
					Save( content, stringWriter );
					stringWriter.Flush();
					formatted = stringWriter.ToString();
				}
			}
			return formatted;
		} // ToXmlString

		// ----------------------------------------------------------------------
		public TC FromXmlString( string contentXml )
		{
			TC loaded = null;
			if ( !string.IsNullOrEmpty( contentXml ) )
			{
				using ( StringReader stringReader = new StringReader( contentXml ) )
				{
					loaded = Load( stringReader );
				}
			}
			return loaded;
		} // FromXmlString

		// ----------------------------------------------------------------------
		public void Save( T content, Stream stream )
		{
			XmlDocument saved = Save( content );
			Write( saved, stream );
		} // Save

		// ----------------------------------------------------------------------
		public TC Load( Stream contentXml )
		{
			TC loaded = null;
			if ( contentXml != null )
			{
				using ( XmlReader xmlReader = XmlReader.Create( contentXml, xmlReadSettings ) )
				{
					loaded = Load( xmlReader );
				}
			}
			return loaded;
		} // Load

		// ----------------------------------------------------------------------
		public void Save( T content, TextWriter writer )
		{
			XmlDocument saved = Save( content );
			Write( saved, writer );
		} // Save

		// ----------------------------------------------------------------------
		public TC Load( TextReader contentXml )
		{
			TC loaded = null;
			if ( contentXml != null )
			{
				using ( XmlReader xmlReader = XmlReader.Create( contentXml, xmlReadSettings ) )
				{
					loaded = Load( xmlReader );
				}
			}
			return loaded;
		} // Load

		// ----------------------------------------------------------------------
		private TC Load( XmlReader contentXml )
		{
			TC loaded;
			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load( contentXml );
				XmlElement docElement = doc.DocumentElement;
				if ( docElement == null )
				{
					throw new XmlException( string.Format(
						"invalid document tag {0}", docTag ) );
				}

				if ( docTag.Equals( docElement.LocalName ) )
				{
					loaded = Load( docElement );
				}
				else
				{
					throw new XmlException( string.Format(
						"invalid document tag {1}, was expecting {0}", docTag, docElement.LocalName ) );
				}
			}
			catch ( XmlSchemaException e )
			{
				throw new XmlException( e.Message, e );
			}
			return loaded;
		} // Load

		// ----------------------------------------------------------------------
		public XmlDocument Save( T content )
		{
			if ( content == null )
			{
				throw new ArgumentNullException( "content" );
			}

			XmlDocument doc = new XmlDocument();

			XmlElement docElement = AppendTag( doc, docTag );
			Save( content, docElement );

			return doc;
		} // Save

		// ----------------------------------------------------------------------
		public TC Load( XmlElement contentXml )
		{
			TC loaded;
			try
			{
				loaded = new TC();
				Load( loaded, contentXml );
			}
			catch ( XmlSchemaException e )
			{
				throw new XmlException( e.Message, e );
			}
			return loaded;
		} // Load

		// ----------------------------------------------------------------------
		public void Load( T content, XmlElement contentXml )
		{
			if ( content == null )
			{
				throw new ArgumentNullException( "content" );
			}
			if ( contentXml == null )
			{
				throw new ArgumentNullException( "contentXml" );
			}
			DoLoad( content, contentXml );
		} // Load

		// ----------------------------------------------------------------------
		protected abstract void DoLoad( T content, XmlElement contentXml );

		// ----------------------------------------------------------------------
		public void Save( T content, XmlElement element )
		{
			if ( content == null )
			{
				throw new ArgumentNullException( "content" );
			}
			if ( element == null )
			{
				throw new ArgumentNullException( "element" );
			}
			DoSave( content, element );
		} // Save

		// ----------------------------------------------------------------------
		protected abstract void DoSave( T content, XmlElement element );

		// ----------------------------------------------------------------------
		protected static XmlElement AppendTag( XmlDocument doc, string childTagName )
		{
			if ( doc == null )
			{
				throw new ArgumentNullException( "doc" );
			}

			XmlElement childElement = doc.CreateElement( NoPrefix, childTagName, WufNamespace );
			doc.AppendChild( childElement );
			return childElement;
		} // AppendTag

		// ----------------------------------------------------------------------
		protected static XmlElement AppendTag( XmlElement parent, string childTagName )
		{
			if ( parent == null )
			{
				throw new ArgumentNullException( "parent" );
			}

			if ( parent.OwnerDocument != null )
			{
				XmlElement childElement = parent.OwnerDocument.CreateElement(
					NoPrefix, childTagName, WufNamespace );
				parent.AppendChild( childElement );
				return childElement;
			}
			return null;
		} // AppendTag

		// ----------------------------------------------------------------------
		protected static XmlElement AppendTextContentTag( XmlElement parent, string childTagName,
			string textContent )
		{
			XmlElement childElement = AppendTag( parent, childTagName );
			childElement.InnerText = textContent;
			return childElement;
		} // AppendTag

		// ----------------------------------------------------------------------
		protected static string GetAttribute( XmlElement node, string attrName )
		{
			if ( node == null )
			{
				throw new ArgumentNullException( "node" );
			}

			string attrValue = null;
			if ( node.HasAttribute( attrName ) )
			{
				attrValue = node.GetAttribute( attrName );
			}
			return attrValue;
		} // GetAttribute

		// ----------------------------------------------------------------------
		protected static void SetAttribute( XmlElement node, string attrName, string attrValue )
		{
			if ( node == null )
			{
				throw new ArgumentNullException( "node" );
			}

			if ( attrValue != null )
			{
				node.SetAttribute( attrName, attrValue );
			}
			else if ( node.HasAttribute( attrName ) )
			{
				node.RemoveAttribute( attrName );
			}
		} // SetAttribute

		// ----------------------------------------------------------------------
		protected static DateTime? GetDateAttribute( XmlElement node, string attrName )
		{
			return GetDateTimeAttribute( node, attrName, XmlDateFormat );
		} // GetDateAttribute

		// ----------------------------------------------------------------------
		protected static void SetDateAttribute( XmlElement node, string attrName, DateTime? attrValue )
		{
			SetDateTimeAttribute( node, attrName, XmlDateFormat, attrValue );
		} // SetDateAttribute

		// ----------------------------------------------------------------------
		protected static DateTime? GetTimeAttribute( XmlElement node, string attrName )
		{
			return GetDateTimeAttribute( node, attrName, XmlTimeFormat );
		} // GetTimeAttribute

		// ----------------------------------------------------------------------
		protected static void SetTimeAttribute( XmlElement node, string attrName, DateTime? attrValue )
		{
			SetDateTimeAttribute( node, attrName, XmlTimeFormat, attrValue );
		} // SetTimeAttribute

		// ----------------------------------------------------------------------
		protected static DateTime? GetDateTimeAttribute( XmlElement node, string attrName )
		{
			return GetDateTimeAttribute( node, attrName, XmlDateTimeFormat );
		} // GetDateTimeAttribute

		// ----------------------------------------------------------------------
		protected static void SetDateTimeAttribute( XmlElement node, string attrName, DateTime? attrValue )
		{
			SetDateTimeAttribute( node, attrName, XmlDateTimeFormat, attrValue );
		} // SetDateTimeAttribute

		// ----------------------------------------------------------------------
		private static DateTime? GetDateTimeAttribute( XmlElement node, string attrName, string format )
		{
			DateTime? attrValue = null;
			if ( node.HasAttribute( attrName ) )
			{
				attrValue = DateTime.ParseExact( node.GetAttribute( attrName ),
					format, DateTimeFormatInfo.InvariantInfo );
			}
			return attrValue;
		} // GetDateTimeAttribute

		// ----------------------------------------------------------------------
		private static void SetDateTimeAttribute( XmlElement node, string attrName, string format, DateTime? attrValue )
		{
			string attribute = null;
			if ( attrValue != null )
			{
				attribute = attrValue.Value.ToString( format, DateTimeFormatInfo.InvariantInfo );
			}
			SetAttribute( node, attrName, attribute );
		} // SetDateTimeAttribute

		// ----------------------------------------------------------------------
		protected static double GetDoubleAttribute( XmlElement node, string attrName )
		{
			return Double.Parse( GetAttribute( node, attrName ), NumberFormatInfo.InvariantInfo );
		} // GetDoubleAttribute

		// ----------------------------------------------------------------------
		protected static void SetDoubleAttribute( XmlElement node, string attrName, double attrValue )
		{
			SetAttribute( node, attrName, attrValue.ToString( NumberFormatInfo.InvariantInfo ) );
		} // SetDoubleAttribute

		// ----------------------------------------------------------------------
		protected static string GetTextContentFromTag( XmlElement parent, string childTagName )
		{
			string textContent = null;
			XmlElement childElement = GetFirstChildElement( parent, childTagName );
			if ( childElement != null )
			{
				textContent = childElement.InnerText;
			}
			return textContent;
		} // GetTextContentFromTag

		// ----------------------------------------------------------------------
		protected static XmlElement GetFirstChildElement( XmlNode node )
		{
			return GetFirstChildElement( node, null );
		} // GetFirstChildElement

		// ----------------------------------------------------------------------
		protected static XmlElement GetFirstChildElement( XmlNode node, string elementLocalName )
		{
			XmlElement firstChild = null;
			if ( node != null )
			{
				XmlNode firstChildNode = node.FirstChild;
				if ( firstChildNode != null )
				{
					firstChild = firstChildNode as XmlElement;
					if ( firstChild == null ||
						( elementLocalName != null && !elementLocalName.Equals( firstChild.LocalName ) ) )
					{
						firstChild = GetNextSiblingElement( firstChildNode, elementLocalName );
					}
				}
			}
			return firstChild;
		} // GetFirstChildElement

		// ----------------------------------------------------------------------
		protected static XmlElement GetNextSiblingElement( XmlNode node )
		{
			return GetNextSiblingElement( node, null );
		} // GetNextSiblingElement

		// ----------------------------------------------------------------------
		protected static XmlElement GetNextSiblingElement( XmlNode node, string elementLocalName )
		{
			XmlElement nextSibling = null;
			if ( node != null )
			{
				XmlNode nextNode = node.NextSibling;
				while ( nextNode != null && nextSibling == null )
				{
					nextSibling = nextNode as XmlElement;
					if ( nextSibling == null ||
						( elementLocalName != null && !elementLocalName.Equals( nextSibling.LocalName ) ) )
					{
						nextSibling = null;
						nextNode = nextNode.NextSibling;
					}
				}
			}
			return nextSibling;
		} // GetNextSiblingElement

		// ----------------------------------------------------------------------
		public static XmlDocument Read( XmlReader reader )
		{
			if ( reader == null )
			{
				throw new ArgumentNullException( "reader" );
			}
			XmlDocument doc = new XmlDocument();
			using ( reader )
			{
				doc.Load( reader );
			}
			return doc;
		} // Read

		// ----------------------------------------------------------------------
		public static void Write( XmlDocument doc, Stream output )
		{
			Write( doc, output, true );
		} // Write

		// ----------------------------------------------------------------------
		public static void Write( XmlDocument doc, Stream output, bool disposeOutput )
		{
			if ( output == null )
			{
				throw new ArgumentNullException( "output" );
			}
			try
			{
				using ( StreamWriter writer = new StreamWriter( output ) )
				{
					Write( doc, writer, disposeOutput );
					if ( !disposeOutput )
					{
						writer.Flush();
					}
				}
			}
			finally
			{
				if ( disposeOutput )
				{
					( (IDisposable)output ).Dispose();
				}
				else
				{
					output.Flush();
				}
			}
		} // Write

		// ----------------------------------------------------------------------
		public static void Write( XmlDocument doc, TextWriter output )
		{
			Write( doc, output, true );
		} // Write

		// ----------------------------------------------------------------------
		public static void Write( XmlDocument doc, TextWriter output, bool disposeOutput )
		{
			if ( output == null )
			{
				throw new ArgumentNullException( "output" );
			}
			Write( doc, XmlWriter.Create( output, CreateSerializationSettings() ), disposeOutput );
		} // Write

		// ----------------------------------------------------------------------
		public static void Write( XmlDocument doc, XmlWriter output )
		{
			Write( doc, output, true );
		} // Write

		// ----------------------------------------------------------------------
		public static void Write( XmlDocument doc, XmlWriter writer, bool disposeOutput )
		{
			if ( doc == null )
			{
				throw new ArgumentNullException( "doc" );
			}
			if ( writer == null )
			{
				throw new ArgumentNullException( "writer" );
			}
			try
			{
				XmlWriterSettings settings = writer.Settings;
				if ( settings != null && !settings.OmitXmlDeclaration )
				{
					string encoding = settings.Encoding != null ? settings.Encoding.WebName : "utf-8";
					XmlDeclaration declaration = doc.FirstChild as XmlDeclaration;
					if ( declaration == null )
					{
						declaration = doc.CreateXmlDeclaration( "1.0", encoding, null );
						declaration.WriteTo( writer );
					}
					else if ( declaration.Encoding == null )
					{
						declaration.Encoding = encoding;
					}
				}
				doc.WriteTo( writer );
			}
			finally
			{
				writer.Flush();
				if ( disposeOutput )
				{
					( (IDisposable)writer ).Dispose();
				}
			}
		} // Write

		// ----------------------------------------------------------------------
		public static XmlWriterSettings CreateSerializationSettings()
		{
			return CreateSerializationSettings( true );
		} // CreateSerializationSettings

		// ----------------------------------------------------------------------
		public static XmlWriterSettings CreateSerializationSettings( bool closeOutput )
		{
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.OmitXmlDeclaration = false;
			settings.CloseOutput = closeOutput;
			settings.NewLineHandling = NewLineHandling.None;
			settings.IndentChars = "  ";
			settings.Indent = true;
			settings.ConformanceLevel = ConformanceLevel.Fragment;
			settings.Encoding = new UTF8Encoding( false );
			return settings;
		} // CreateSerializationSettings

		// ----------------------------------------------------------------------
		// members
		private readonly XmlReaderSettings xmlReadSettings;
		private readonly string docTag;

	} // class XmlBase

} // namespace Itenso.WebUserForms.Data
// -- EOF -------------------------------------------------------------------

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
Software Developer (Senior)
Switzerland Switzerland
👨 Senior .NET Software Engineer

🚀 My Open Source Projects
- Time Period Library 👉 GitHub
- Payroll Engine 👉 GitHub

Feedback and contributions are welcome.



Comments and Discussions