Click here to Skip to main content
15,892,697 members
Articles / General Programming / Architecture

Binding Web Pages with nHydrate

,
Rate me:
Please Sign up or sign in to vote.
4.71/5 (5 votes)
1 Jun 2011Ms-PL12 min read 20.9K   256   14  
Bind your UI controls to generated objects generically
using System;
using System.Linq;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Collections.Generic;
using Acme.EFExample.EFDAL.Entity;

[assembly: EdmSchemaAttribute()]
#region EDM Relationship Metadata

[assembly: EdmRelationshipAttribute("Acme.EFExample.EFDAL.Entity", "FK__SystemUser_Region", "Region", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(Acme.EFExample.EFDAL.Entity.Region), "SystemUserList", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Acme.EFExample.EFDAL.Entity.SystemUser), true)]
[assembly: EdmRelationshipAttribute("Acme.EFExample.EFDAL.Entity", "FK__Customer_CustomerType", "CustomerType", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Acme.EFExample.EFDAL.Entity.CustomerType), "CustomerList", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Acme.EFExample.EFDAL.Entity.Customer), true)]
[assembly: EdmRelationshipAttribute("Acme.EFExample.EFDAL.Entity", "FK__SystemUser_Country", "Country", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(Acme.EFExample.EFDAL.Entity.Country), "SystemUserList", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Acme.EFExample.EFDAL.Entity.SystemUser), true)]

#endregion

namespace Acme.EFExample.EFDAL
{
	#region EntityMappingConstants Enumeration

	/// <summary>
	/// A map for all entity types in this library
	/// </summary>
	public enum EntityMappingConstants
	{
		/// <summary>
		/// A mapping for the the Country entity
		/// </summary>
		Country,
		/// <summary>
		/// A mapping for the the Customer entity
		/// </summary>
		Customer,
		/// <summary>
		/// A mapping for the the CustomerType entity
		/// </summary>
		CustomerType,
		/// <summary>
		/// A mapping for the the Region entity
		/// </summary>
		Region,
		/// <summary>
		/// A mapping for the the SystemUser entity
		/// </summary>
		SystemUser,
	}

	#endregion

	#region StaticDataConstants Enumeration for 'CustomerType' entity
	/// <summary>
	/// Enumeration to define static data items and their ids 'CustomerType' table.
	/// </summary>
	public enum CustomerTypeConstants
	{
		/// <summary>
		/// Enumeration for the 'BigFish' item
		/// </summary>
		[Description("")]
		BigFish = 1,
		/// <summary>
		/// Enumeration for the 'LittleFish' item
		/// </summary>
		[Description("")]
		LittleFish = 2,
	}
	#endregion

	#region Entity Context

	/// <summary>
	/// There context EFExampleEntities
	/// </summary>
	public partial class EFExampleEntities : System.Data.Objects.ObjectContext, Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities
	{
		/// <summary>
		/// The audit modifier used to mark database edits
		/// </summary>
		protected ContextStartup _contextStartup = new ContextStartup(null);

		/// <summary>
		/// Initializes a new EFExampleEntities object using the connection string found in the 'EFExampleEntities' section of the application configuration file.
		/// </summary>
		public EFExampleEntities() :
			base("name=EFExampleEntities", "EFExampleEntities")
		{
			this.OnContextCreated();
		}

		/// <summary>
		/// Initialize a new EFExampleEntities object with an audit modifier.
		/// </summary>
		public EFExampleEntities(ContextStartup contextStartup) :
			base("name=EFExampleEntities", "EFExampleEntities")
		{
			_contextStartup = contextStartup;
			this.OnContextCreated();
		}

		/// <summary>
		/// Initialize a new EFExampleEntities object.
		/// </summary>
		public EFExampleEntities(string connectionString) :
			base(connectionString, "EFExampleEntities")
		{
			this.OnContextCreated();
		}

		/// <summary>
		/// Initialize a new EFExampleEntities object.
		/// </summary>
		public EFExampleEntities(System.Data.EntityClient.EntityConnection connection) :
			base(connection, "EFExampleEntities")
		{
			this.OnContextCreated();
		}

		partial void OnContextCreated();

		/// <summary>
		/// 
		/// </summary>
		public virtual System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.Country> Country
		{
			get
			{
				if ((this._country == null))
				{
					this._country = base.CreateObjectSet<Acme.EFExample.EFDAL.Entity.Country>("Country");
				}
				return this._country;
			}
		}

		/// <summary>
		/// The internal reference variable for the 'Country' object set
		/// </summary>
		protected System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.Country> _country;

		/// <summary>
		/// 
		/// </summary>
		public virtual System.Data.Objects.ObjectQuery<Customer> Customer
		{
			get { return this.SystemUser.OfType<Customer>(); }
		}

		/// <summary>
		/// 
		/// </summary>
		public virtual System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.CustomerType> CustomerType
		{
			get
			{
				if ((this._customertype == null))
				{
					this._customertype = base.CreateObjectSet<Acme.EFExample.EFDAL.Entity.CustomerType>("CustomerType");
				}
				return this._customertype;
			}
		}

		/// <summary>
		/// The internal reference variable for the 'CustomerType' object set
		/// </summary>
		protected System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.CustomerType> _customertype;

		/// <summary>
		/// 
		/// </summary>
		public virtual System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.Region> Region
		{
			get
			{
				if ((this._region == null))
				{
					this._region = base.CreateObjectSet<Acme.EFExample.EFDAL.Entity.Region>("Region");
				}
				return this._region;
			}
		}

		/// <summary>
		/// The internal reference variable for the 'Region' object set
		/// </summary>
		protected System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.Region> _region;

		/// <summary>
		/// 
		/// </summary>
		public virtual System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.SystemUser> SystemUser
		{
			get
			{
				if ((this._systemuser == null))
				{
					this._systemuser = base.CreateObjectSet<Acme.EFExample.EFDAL.Entity.SystemUser>("SystemUser");
				}
				return this._systemuser;
			}
		}

		/// <summary>
		/// The internal reference variable for the 'SystemUser' object set
		/// </summary>
		protected System.Data.Objects.ObjectSet<Acme.EFExample.EFDAL.Entity.SystemUser> _systemuser;

		#region AddItem Methods

		/// <summary>
		/// Adds an object of type 'Country' to the object context.
		/// </summary>
		/// <param name="entity">The entity to add</param>
		public virtual void AddItem(Acme.EFExample.EFDAL.Entity.Country entity)
		{
			entity.CreatedBy = _contextStartup.Modifer;
			entity.ModifiedBy = _contextStartup.Modifer;
			base.AddObject("Country", entity);
		}

		/// <summary>
		/// Adds an object of type 'Customer' to the object context.
		/// </summary>
		/// <param name="entity">The entity to add</param>
		public virtual void AddItem(Acme.EFExample.EFDAL.Entity.Customer entity)
		{
			entity.CreatedBy = _contextStartup.Modifer;
			entity.ModifiedBy = _contextStartup.Modifer;
			base.AddObject("SystemUser", entity);
		}

		/// <summary>
		/// Adds an object of type 'Region' to the object context.
		/// </summary>
		/// <param name="entity">The entity to add</param>
		public virtual void AddItem(Acme.EFExample.EFDAL.Entity.Region entity)
		{
			entity.CreatedBy = _contextStartup.Modifer;
			entity.ModifiedBy = _contextStartup.Modifer;
			base.AddObject("Region", entity);
		}

		/// <summary>
		/// Adds an object of type 'SystemUser' to the object context.
		/// </summary>
		/// <param name="entity">The entity to add</param>
		public virtual void AddItem(Acme.EFExample.EFDAL.Entity.SystemUser entity)
		{
			entity.CreatedBy = _contextStartup.Modifer;
			entity.ModifiedBy = _contextStartup.Modifer;
			base.AddObject("SystemUser", entity);
		}

		/// <summary>
		/// Adds an object to the object context.
		/// </summary>
		[Obsolete("This method signature is no longer used. Use the AddItem method.", true)]
		[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
		public new void AddObject(string entitySetName, object entity)
		{
			throw new Exception("This method signature is no longer used. Use the AddItem method.");
		}

		#endregion

		#region DeleteItem Methods

		/// <summary>
		/// Marks an object for deletion.
		/// </summary>
		/// <param name="entity">An object that specifies the entity to delete. The object can be in any state except System.Data.EntityState.Detached.</param>
		public virtual void DeleteItem(Widgetsphere.EFCore.DataAccess.NHEntityObject entity)
		{
			if (entity is Acme.EFExample.EFDAL.Entity.Country) base.DeleteObject(entity);
			else if (entity is Acme.EFExample.EFDAL.Entity.Region) base.DeleteObject(entity);
			else if (entity is Acme.EFExample.EFDAL.Entity.SystemUser) base.DeleteObject(entity);
			else if (entity is Acme.EFExample.EFDAL.Entity.Customer) base.DeleteObject(entity);
			else
				throw new Exception("An entity of this type cannot deleted!");
		}

		/// <summary>
		/// Marks an set of objects for deletion.
		/// </summary>
		/// <param name="entityList">A list of NHEntityObject objects to mark for deletion</param>
		public virtual void DeleteItem(IEnumerable<Widgetsphere.EFCore.DataAccess.NHEntityObject> entityList)
		{
			foreach (Widgetsphere.EFCore.DataAccess.NHEntityObject item in entityList)
			{
				this.DeleteItem(item);
			}
		}

		/// <summary>
		/// Marks an object for deletion.
		/// </summary>
		[Obsolete("This method signature is no longer used. Use the AddItem method.", true)]
		[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
		public new void DeleteObject(object entity)
		{
			this.DeleteItem((Widgetsphere.EFCore.DataAccess.NHEntityObject)entity);
		}

		#endregion

		internal static string GetConnectionString()
		{
			string s = System.Configuration.ConfigurationManager.ConnectionStrings["EFExampleEntities"].ConnectionString;
			System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex("provider connection string\\s*=\\s*\"([^\"]*)");
			System.Text.RegularExpressions.Match m = regEx.Match(s);
			string connString = string.Empty;
			if (m != null && m.Groups.Count > 1)
			{
				connString = m.Groups[1].Value;
			}
			return connString;
		}

		private string GetConnString()
		{
			string s = this.Connection.ConnectionString;
			System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex("provider connection string\\s*=\\s*\"([^\"]*)");
			System.Text.RegularExpressions.Match m = regEx.Match(s);
			string connString = string.Empty;
			if (m != null && m.Groups.Count > 1)
			{
				connString = m.Groups[1].Value;
			}
			return connString;
		}

		/// <summary>
		/// The global settings of this context
		/// </summary>
		public ContextStartup ContextStartup
		{
			get { return _contextStartup; }
		}

		#region IEFExample Members

		void Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.AddItem(Widgetsphere.EFCore.DataAccess.IBusinessObject entity)
		{
			if (entity is Acme.EFExample.EFDAL.Entity.Country) this.AddItem((Acme.EFExample.EFDAL.Entity.Country)entity);
			else if (entity is Acme.EFExample.EFDAL.Entity.Customer) this.AddItem((Acme.EFExample.EFDAL.Entity.Customer)entity);
			else if (entity is Acme.EFExample.EFDAL.Entity.Region) this.AddItem((Acme.EFExample.EFDAL.Entity.Region)entity);
			else if (entity is Acme.EFExample.EFDAL.Entity.SystemUser) this.AddItem((Acme.EFExample.EFDAL.Entity.SystemUser)entity);
			else
				throw new Exception("Entity type not found");
		}

		System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ICountry> Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.Country
		{
			get { return (System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ICountry>)this.Country; }
		}

		System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ICustomer> Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.Customer
		{
			get { return (System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ICustomer>)this.Customer; }
		}

		System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ICustomerType> Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.CustomerType
		{
			get { return (System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ICustomerType>)this.CustomerType; }
		}

		System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.IRegion> Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.Region
		{
			get { return (System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.IRegion>)this.Region; }
		}

		System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ISystemUser> Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.SystemUser
		{
			get { return (System.Data.Objects.IObjectSet<Acme.EFExample.EFDAL.Interfaces.Entity.ISystemUser>)this.SystemUser; }
		}

		void Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.DeleteItem(IEnumerable<Widgetsphere.EFCore.DataAccess.IBusinessObject> entityList)
		{
			foreach (var entity in entityList)
			{
				this.DeleteItem((Widgetsphere.EFCore.DataAccess.NHEntityObject)entity);
			}
		}

		void Acme.EFExample.EFDAL.Interfaces.IEFExampleEntities.DeleteItem(Widgetsphere.EFCore.DataAccess.IBusinessObject entity)
		{
			this.DeleteItem((Widgetsphere.EFCore.DataAccess.NHEntityObject)entity);
		}
		#endregion

		/// <summary>
		/// Determines the version of the model that created this library.
		/// </summary>
		public virtual string Version
		{
			get { return "0.0.0.0.25"; }
		}

		/// <summary>
		/// Determines the key of the model that created this library.
		/// </summary>
		public virtual string ModelKey
		{
			get { return "a0c7bf5a-c94a-4ae4-9f2b-f57f3b0e06b9"; }
		}

		/// <summary>
		/// Determines if the API matches the database connection
		/// </summary>
		/// <returns></returns>
		public virtual bool IsValidConnection()
		{
			return IsValidConnection(true);
		}

		/// <summary>
		/// Determines if the API matches the database connection
		/// </summary>
		/// <param name="checkVersion">Determines if the check also includes the exact version of the model</param>
		/// <returns></returns>
		public virtual bool IsValidConnection(bool checkVersion)
		{
			if (string.IsNullOrEmpty(GetConnectionString()))
				return false;

			string modelKey = GetDatabaseExtendedProperty(GetConnectionString(), "ModelKey");
			if (string.Compare(this.ModelKey, modelKey, true) != 0)
				return false;

			if (checkVersion)
			{
				string dbVersion = GetDatabaseExtendedProperty(GetConnectionString(), "dbVersion");
				if (dbVersion != this.Version)
					return false;
			}

			return true;
		}

		private static string GetDatabaseExtendedProperty(string connectionString, string propertyName)
		{
			string returnVal = string.Empty;
			returnVal = SelectExtendedProperty(connectionString, propertyName, string.Empty, string.Empty, string.Empty);
			return returnVal;
		}

		private static string SelectExtendedProperty(string connectionString, string property, string user, string table, string parameter)
		{
			string returnVal = string.Empty;
			string userName = string.Empty;
			string userValue = string.Empty;
			string tableName = string.Empty;
			string tableValue = string.Empty;
			string columnName = string.Empty;
			string columnValue = string.Empty;

			property = "'" + property + "'";
			if (user == string.Empty)
			{
				userName = "NULL";
				userValue = "NULL";
			}
			else
			{
				userName = "'user'";
				userValue = "'" + user + "'";
			}
			if (table == string.Empty)
			{
				tableName = "NULL";
				tableValue = "NULL";
			}
			else
			{
				tableName = "'table'";
				tableValue = "'" + table + "'";
			}
			if (parameter == string.Empty)
			{
				columnName = "NULL";
				columnValue = "NULL";
			}
			else
			{
				columnName = "'parameter'";
				columnValue = "'" + parameter + "'";
			}

			System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
			System.Data.SqlClient.SqlDataReader externalReader = null;
			try
			{
				conn.ConnectionString = connectionString;
				conn.Open();
				var cmdGetExtProp = new System.Data.SqlClient.SqlCommand();
				cmdGetExtProp.CommandText = String.Format("SELECT value FROM ::fn_listextendedproperty({0}, {1}, {2}, {3}, {4}, {5}, {6})", new object[] { property, userName, userValue, tableName, tableValue, columnName, columnValue });
				cmdGetExtProp.CommandType = System.Data.CommandType.Text;
				cmdGetExtProp.Connection = conn;
				externalReader = cmdGetExtProp.ExecuteReader();
				if (externalReader.Read())
				{
					if (externalReader[0] != System.DBNull.Value)
					{
						returnVal = externalReader.GetString(0);
					}
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				if (externalReader != null)
					externalReader.Close();
				if (conn != null)
					conn.Close();
			}
			return returnVal;
		}

	}

	#endregion

}

namespace Acme.EFExample.EFDAL.Entity
{
}

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 Microsoft Public License (Ms-PL)



Written By
Software Developer (Senior) Hewlett Packard
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