Click here to Skip to main content
15,886,795 members
Articles / Programming Languages / C#

The Power of a POC

Rate me:
Please Sign up or sign in to vote.
4.42/5 (6 votes)
26 Apr 2011CPOL13 min read 49.9K   358   19  
The importance of creating a POC as the first step to your next adventure
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="EdmxLibrary" #>
<#@ import namespace="EdmxLibrary.DataObjects" #>
<#+
// <copyright file="ServerModel.generated.tt" company="Webbert Solutions, LLC">
//  Copyright © Webbert Solutions, LLC. All Rights Reserved.
// </copyright>

/// <summary>
/// 
/// </summary>
public class ServerModelDesigner : Template
{
	public List<Entity> EntitySetList;
	public Entity entity;
	
    /// <summary>
    /// 
    /// </summary>
    public override string TransformText()
    {
#>
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Runtime.Serialization;

using EntityModel = AdventureWorksEntityModel;


namespace <#= entity.Namespace #>
{
    [DataContract(IsReference = true)]
    public partial class <#= entity.Name #> : PocoBase, IExtensibleDataObject
    {
<#+ 
		ClassName();
		PropertyNames();
		
		DataMemberKeys();
		DataMemberScalar();
		DataMemberSingleReference();
		DataMemberMultipleReferences();
		DataMemberMisc();
#>
		//
		// Public Class Methods
		//

<#+
		GetKeys();
		GetReference();

#>
		//
		// Repository Calls
		//
		
<#+
		EntitySetName();
		Find();
		Add();
		Update();
		Delete();
		
		return this.GenerationEnvironment.ToString();
	}
	
	public void ClassName()
	{
#>
   		// Class Name
		public const string <#= CreateMethodName(entity.Name) #> = "<#= entity.Name #>";
		
<#+
	}

	public void PropertyNames()
	{
#>
		// Property Names
<#+
		foreach (Scalar key in entity.Keys)
		{
#>
        public const string <#= CreateMethodName(key.Name) #> = "<#= key.Name #>";
<#+
		}

		foreach (Scalar scalar in entity.Scalars)
		{
#>
        public const string <#= CreateMethodName(scalar.Name) #> = "<#= scalar.Name #>";
<#+
		}
	}

	public void DataMemberKeys()
	{
#>

		// Data Members - Keys
<#+
		foreach (Scalar key in entity.Keys)
		{
#>
        [DataMember(EmitDefaultValue = false)] public <#= GetPropertyType(key) #> <#= key.Name #> { get; private set; }
<#+
		}
		
		Write("\r\n");
	}
	
	public void DataMemberScalar()
	{
#>
		// Data Members
<#+
		foreach (Scalar scalar in entity.Scalars)
		{
#>
        [DataMember(EmitDefaultValue = false)] public <#= GetPropertyType(scalar) #> <#= scalar.Name #> { get; set; }
<#+
		}
		
		Write("\r\n");
	}

	public void DataMemberSingleReference()
	{
		if (entity.SingleReferences.Count == 0)
			return;
#>
		// Reference (FK) to other Table (PK)	
<#+
		foreach (Reference reference in entity.SingleReferences)
		{
#>
		[DataMember(EmitDefaultValue = false)] public <#= GetPropertyType(reference) #> <#= reference.Name #> { get; set; }
		[DataMember(EmitDefaultValue = false)] public PocoReference<<#= GetPropertyType(reference) #>> <#= reference.Name #>Reference { get; set; }
		
<#+
		}
	}
	
	public void DataMemberMultipleReferences()
	{
		if (entity.MultipleReferences.Count == 0)
			return;
#>
		// References back to <#= entity.Name #>
<#+
		foreach (Reference reference in entity.MultipleReferences)
		{
#>
        [DataMember(EmitDefaultValue = false)] public <#= GetPropertyType(reference) #> <#= reference.Name #> { get; set; }
<#+
		}
	}
	
	public void DataMemberMisc()
	{
#>

		public ExtensionDataObject ExtensionData { get; set; }

<#+
	}

	public void GetKeys()
	{
#>
   		public override IList<KeyValuePair<string, object>> GetKeys()
    	{
			return new List<KeyValuePair<string, object>> 
			{ 
<#+
		for (int index = 0; index < entity.Keys.Count; index++)
		{
			Scalar key = entity.Keys[index];
			
			 string keyText = string.Format("new KeyValuePair<string, object>({0}, {1}){2}",
                CreateMethodName(key.Name), key.Name, 
                ((index < entity.Keys.Count - 1) ? "," : string.Empty));
#>
				<#= keyText #>
<#+
		}
#>
			};
    	}

<#+
	}

	public void GetReference()
	{
#>
    	public PocoReference<<#= entity.Name #>> GetReference()
		{
			PocoReference<<#= entity.Name #>> reference = GetReference(<#= GetMethodParameterToPassName(entity.Keys, false) #>);
			reference.PocoKey.ID = ObjectID;
			return reference; 
		}

		public static PocoReference<<#= entity.Name #>> GetReference(<#= GetMethodParameterName(entity.Keys) #>)
		{
			List<KeyValuePair<string, object>> pairs = new List<KeyValuePair<string, object>> 
			{ 
<#+
	
		for (int index = 0; index < entity.Keys.Count; index++)
		{
			Scalar key = entity.Keys[index];
			
			string pair = string.Format("new KeyValuePair<string, object>({0}, {1}){2}",
                CreateMethodName(key.Name), LowercaseName(key.Name), 
                ((index < entity.Keys.Count - 1) ? "," : string.Empty));
#>
				<#= pair #>
<#+
		}
#>
			};

			return GetReference(new PocoKey { Name = <#= CreateMethodName(entity.Name) #>, KeyValues = pairs });
		}		
    	
    	private static PocoReference<<#= entity.Name #>> GetReference(PocoKey pocoKey)
		{
			return new PocoReference<<#= entity.Name #>>
			{
				PocoKey = pocoKey
			};
		}

<#+
	}

	public void EntitySetName()
	{
#>
		public override string EntitySetName()
    	{
			return Repository.EntitySetName<<#= entity.Name #>, EntityModel.<#= entity.Name #>>(false);
    	}

<#+
	}

	public void Find()
	{
#>
		public override IQueryable<PocoBase> Find()
    	{
			return Repository.Find<<#= entity.Name #>, EntityModel.<#= entity.Name #>>(SearchOptions, MergeOption.NoTracking).Cast<PocoBase>();
    	}

<#+
	}

	public void Add()
	{
#>
		public override PocoKey Add()
    	{
			PocoKey key = Repository.Add<<#= entity.Name #>, EntityModel.<#= entity.Name #>>(this);
			PocoReference<<#= entity.Name #>> reference = GetReference(key);
			
<#+
		foreach (Scalar key in entity.Keys)
		{
#>
			<#= key.Name #> = (<#= GetPropertyType(key) #>)key.KeyValues.FirstOrDefault(k=> k.Key.Equals(<#= CreateMethodName(key.Name) #>)).Value;
<#+
		}
		
		Write("\r\n");
		
		foreach (Reference reference in entity.MultipleReferences)
	    {
#>
			if (<#= reference.Name #> != null)
			{
				foreach (<#= reference.ReferenceType.Name #> <#= LowercaseName(reference.Name) #> in <#= reference.Name #>)
				{
<#+
		List<Reference> relatedProperties = GetRelatedProperties(EntitySetList, entity, reference.ReferenceType);
		for (int i = 0; i < relatedProperties.Count; i++)
		{ 
			Reference relatedProperty = relatedProperties[i];
#>
					if (<#= LowercaseName(reference.Name) #>.<#= relatedProperty.Name #> != null && <#= LowercaseName(reference.Name) #>.<#= relatedProperty.Name #>.ObjectID == ObjectID)
						<#= LowercaseName(reference.Name) #>.<#= relatedProperty.Name #>Reference = reference;
<#+ 
			if (i < relatedProperties.Count - 1)
				Write("\r\n");
		}
#>
				}
			}
			
<#+
	}
#>
			return key;
    	}
    	
<#+
	}

	public void Update()
	{
#>
		public override void Update()
    	{
			Repository.Update<<#= entity.Name #>, EntityModel.<#= entity.Name #>>(this);
    	}
    	
<#+
	}

	public void Delete()
	{
#>
		public override void Delete()
		{
			Repository.Delete<<#= entity.Name #>, EntityModel.<#= entity.Name #>>(this);
<#+
	foreach (Reference reference in entity.MultipleReferences)
    {
#>	
			if (<#= reference.Name #> != null)
			{
				foreach (<#= reference.ReferenceType.Name #> <#= LowercaseName(reference.Name) #> in <#= reference.Name #>)
				{
<#+
		List<Reference> relatedProperties = GetRelatedProperties(EntitySetList, entity, reference.ReferenceType);
		for (int i = 0; i < relatedProperties.Count; i++)
		{ 
			Reference relatedProperty = relatedProperties[i];
#>
					if (<#= LowercaseName(reference.Name) #>.<#= relatedProperty.Name #> == this)
					{
						<#= LowercaseName(reference.Name) #>.<#= relatedProperty.Name #> = null;
						<#= LowercaseName(reference.Name) #>.<#= relatedProperty.Name #>Reference = null;
					}
<#+ 
			if (i < relatedProperties.Count - 1)
				Write("\r\n");
		}
#>
				}
			}
<#+
	}
#>
		}
	}
}
<#+
	}

	public string GetPropertyType(Scalar property)
	{
		Type t = Type.GetType(property.ScalarType.Namespace + "." + property.ScalarType.Name);
		
		return (t != null && t.IsValueType && property.ScalarType.IsNullable)
			? property.ScalarType.Name + "?"
			: property.ScalarType.Name;
	}
	
	public string GetMethodParameterName(List<Scalar> keyProperties)
	{
		StringBuilder sb = new StringBuilder(2048);
		
		foreach (Scalar property in keyProperties)
		{
			if (sb.Length > 0)
				sb.Append(", ");
			sb.AppendFormat("{0} {1}", GetPropertyType(property), LowercaseName(property.Name));
		}
		
		return sb.ToString();
	}
	
	public string GetMethodParameterToPassName(List<Scalar> keyProperties, bool lowercase)
	{
		StringBuilder sb = new StringBuilder(2048);
		
		foreach (Scalar property in keyProperties)
		{
			if (sb.Length > 0)
				sb.Append(", ");
			
			if (lowercase)
				sb.AppendFormat("{0}", LowercaseName(property.Name));
			else
				sb.AppendFormat("{0}", property.Name);
		}
		
		return sb.ToString();
	}
	
	public static string LowercaseName(string name)
	{
		return char.ToLower(name[0]) + name.Substring(1);
	}
	
	public string GetPropertyType(Reference property)
	{
		return (property.DstDataType.Multiplicity == Multiplicity.Many)
			? string.Format("IList<{0}>", property.ReferenceType.Name)
			: string.Format("{0}", property.ReferenceType.Name);
	}
	
	public static string CreateMethodName(string methodName)
	{
		StringBuilder sb = new StringBuilder(methodName.Length + 10);
		bool lastWasUpper = true;
		bool lastWasLetter = false;
		
		foreach (char ch in methodName)
		{
			bool isUpper = char.IsUpper(ch);
			bool isLetter = char.IsLetter(ch);
			
			if (lastWasUpper)
			{
				sb.Append(char.ToUpper(ch));
			}
			else 
			{
				if (lastWasLetter && isUpper)
					sb.Append('_');
				
				sb.Append(char.ToUpper(ch));
			}
			
			lastWasUpper = isUpper;
			lastWasLetter = isLetter;
		}
		
		return sb.ToString();
	}
	
    private static List<Reference> GetRelatedProperties(List<Entity> entities, Entity entity, DataType dataType)
    {
//        Entity foundEntity = entities.Find(e => e.Name.Equals(dataType.Name));
//        return foundEntity.MultipleReferences.FindAll(e => e.ReferenceType.Name.Equals(entity.Name));
		Entity foundEntity = entities.Find(e => e.Name.Equals(dataType.Name));
		return foundEntity.SingleReferences.FindAll(e => e.ReferenceType.Name.Equals(entity.Name));
    }
}
#>

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) Webbert Solutions
United States United States
Dave is an independent consultant working in a variety of industries utilizing Microsoft .NET technologies.

Comments and Discussions