Skip to content

Instantly share code, notes, and snippets.

@janhebnes
Last active December 16, 2015 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janhebnes/6b4516d5b4d37d5ba4a1 to your computer and use it in GitHub Desktop.
Save janhebnes/6b4516d5b4d37d5ba4a1 to your computer and use it in GitHub Desktop.
Sitecore Code Generation based on T4 and extending the sitecore base template fields with class information for mapping the c# code to correct types.
namespace Client.Logic.Entities.Client.Pages.Blog
{
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using global::System.Text;
using FemtenNulOtte.Core.Entities;
using FemtenNulOtte.Core.Entities.Context;
public partial class Blog : global::Client.Logic.Entities.Document
{
#region Navigation
public bool ShowBreadcrumbMenu { get { return GetValue<bool>("ShowBreadcrumbMenu"); } set { SetValue("ShowBreadcrumbMenu", value); } }
public bool ShowInBreadcrumb { get { return GetValue<bool>("ShowInBreadcrumb"); } set { SetValue("ShowInBreadcrumb", value); } }
#endregion
#region Blogger Info
public string FirstName { get { return GetValue<string>("FirstName"); } set { SetValue("FirstName", value); } }
public string LastName { get { return GetValue<string>("LastName"); } set { SetValue("LastName", value); } }
public string Job { get { return GetValue<string>("Job"); } set { SetValue("Job", value); } }
public string Email { get { return GetValue<string>("Email"); } set { SetValue("Email", value); } }
public string Phone { get { return GetValue<string>("Phone"); } set { SetValue("Phone", value); } }
public string MobilePhone { get { return GetValue<string>("MobilePhone"); } set { SetValue("MobilePhone", value); } }
public Image Image { get { return GetValue<Image>("Image"); } set { SetValue("Image", value); } }
public Html CitatText { get { return GetValue<Html>("CitatText"); } set { SetValue("CitatText", value); } }
#endregion
#region Context Elements
public string TopContext { get { return GetValue<string>("TopContext"); } set { SetValue("TopContext", value); } }
public string RightContext { get { return GetValue<string>("RightContext"); } set { SetValue("RightContext", value); } }
public string ContentContext { get { return GetValue<string>("ContentContext"); } set { SetValue("ContentContext", value); } }
public string BottomContext { get { return GetValue<string>("BottomContext"); } set { SetValue("BottomContext", value); } }
#endregion
#region Meta
public string BodyCssClass { get { return GetValue<string>("BodyCssClass"); } set { SetValue("BodyCssClass", value); } }
#endregion
public override string TemplateName { get { return "Blog"; } }
public override string TemplatePath { get { return "/sitecore/templates/Client/Pages/Blog/Blog"; } }
public override Id TemplateId { get { return new Id("{BAFD0C2E-D6BF-4D74-ABB6-EC767C9962FD}"); } }
}
public partial class Post : global::Client.Logic.Entities.Document
{
#region Comments
public bool AllowComments { get { return GetValue<bool>("AllowComments"); } set { SetValue("AllowComments", value); } }
#endregion
#region Data
public string Headline { get { return GetValue<string>("Headline"); } set { SetValue("Headline", value); } }
public Html Content { get { return GetValue<Html>("Content"); } set { SetValue("Content", value); } }
public DateTime? CreatedDate { get { return GetValue<DateTime?>("CreatedDate"); } set { SetValue("CreatedDate", value); } }
#endregion
#region Context Elements
public string RightContext { get { return GetValue<string>("RightContext"); } set { SetValue("RightContext", value); } }
#endregion
public override string TemplateName { get { return "Post"; } }
public override string TemplatePath { get { return "/sitecore/templates/Client/Pages/Blog/Post"; } }
public override Id TemplateId { get { return new Id("{E4966B6A-5ADF-48E3-BEB8-C2760B394BAF}"); } }
}
}
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
// <autogenerated>
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// </autogenerated>
<#
XmlDocument doc = new XmlDocument();
doc.Load("http://localhost/Services/T4XmlProvider.ashx?configuration=Logic");
foreach (XmlElement nameSpace in doc.DocumentElement.ChildNodes)
{
#>
namespace Client.Logic.Entities<#= string.IsNullOrEmpty(nameSpace.GetAttribute("name"))? "" : "." + nameSpace.GetAttribute("name") #>
{
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using global::System.Text;
using FemtenNulOtte.Core.Entities;
using FemtenNulOtte.Core.Entities.Context;
<# foreach (XmlElement template in nameSpace.ChildNodes) { #>
public partial class <#= template.GetAttribute("csname") #> : <#= template.GetAttribute("base") #>
{
<# foreach (XmlElement section in template["sections"].ChildNodes) { #>
#region <#= section.GetAttribute("name") #>
<# foreach (XmlElement field in section.ChildNodes) {
if (string.IsNullOrEmpty(field.GetAttribute("typeTable"))) {
#>
<#= field.GetAttribute("access") #> <#= field.GetAttribute("cstype") #> <#= field.GetAttribute("csname") #> { get { return <#= field.GetAttribute("method") #>("<#= field.GetAttribute("name") #>"); } set { SetValue("<#= field.GetAttribute("name") #>", value); } }
<#
} else {
#>
<#= field.GetAttribute("access") #> <#= field.GetAttribute("cstype") #> <#= field.GetAttribute("csname") #> { get { return <#= field.GetAttribute("method") #>(); } set { SetValue("<#= field.GetAttribute("name") #>", value); } }
<#
}} // End of field loop #>
#endregion
<# } // End of section loop #>
public override string TemplateName { get { return "<#= template.GetAttribute("name") #>"; } }
public override string TemplatePath { get { return "<#= template.GetAttribute("path") #>"; } }
public override Id TemplateId { get { return new Id("<#= template.GetAttribute("id") #>"); } }
}
<# } // End of template loop #>
}
<# } // End of namespace loop #>
namespace Client.Logic.Entities
{
public class ClientEntityTypeTable : FemtenNulOtte.Core.Entities.EntityTypeTable
{
public ClientEntityTypeTable()
{
<#
foreach (XmlElement nameSpace in doc.DocumentElement.ChildNodes)
foreach (XmlElement template in nameSpace.ChildNodes)
{
#>
AddType("<#= template.GetAttribute("path") #>",typeof(global::Client.Logic.Entities<#= string.IsNullOrEmpty(nameSpace.GetAttribute("name"))? "" : "." + nameSpace.GetAttribute("name") #>.<#= template.GetAttribute("csname") #>));
<#
}
#>
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<CodeGeneration>
<Configuration name="Logic">
<IncludePaths root="/sitecore/templates/">
<Path>/sitecore/templates/Client/Pages/*</Path>
<Path>/sitecore/templates/Client/Elements/*</Path>
<Path>/sitecore/templates/Client/SystemTemplates/*</Path>
</IncludePaths>
<ExcludePaths root="/sitecore/templates/">
<Path>/sitecore/templates/Client/Pages/BaseTemplates/*</Path>
<Path>/sitecore/templates/Client/Elements/BaseTemplates/*</Path>
<Path>/sitecore/templates/Client/SystemTemplates/BaseTemplates/*</Path>
</ExcludePaths>
<DefaultSettings>
<FieldSetting cmstype="Rich Text" cstype="Html" />
<FieldSetting cmstype="Checkbox" cstype="bool" />
<FieldSetting cmstype="Date" cstype="DateTime?" />
<FieldSetting cmstype="Datetime" cstype="DateTime?" />
<FieldSetting cmstype="Droplink" cstype="Entity" />
<FieldSetting cmstype="Droplist" cstype="string" />
<FieldSetting cmstype="Droptree" cstype="Entity" />
<FieldSetting cmstype="File" cstype="File" />
<FieldSetting cmstype="General Link" cstype="Link" />
<FieldSetting cmstype="Image" cstype="Image" />
<FieldSetting cmstype="Integer" cstype="int?" />
<FieldSetting cmstype="Internal Link" cstype="Link" />
<FieldSetting cmstype="Multi-Line Text" cstype="Text" />
<FieldSetting cmstype="Multilist" cstype="Entity[]" />
<FieldSetting cmstype="Number" cstype="decimal?" />
<FieldSetting cmstype="Treelist" cstype="Entity[]" />
<FieldSetting cmstype="tree" cstype="Entity" />
<FieldSetting cmstype="text" cstype="Text" />
<FieldSetting cmstype="server file" cstype="string" />
<FieldSetting cmstype="TreelistEx" cstype="string" />
<FieldSetting cmstype="link" cstype="Link" />
<FieldSetting cmstype="checkbox" cstype="bool" />
<FieldSetting cmstype="icon" cstype="string" />
<FieldSetting cmstype="memo" cstype="Text" />
<FieldSetting cmstype="lookup" cstype="string" />
<FieldSetting cmstype="datetime" cstype="DateTime?" />
<FieldSetting cmstype="reference" cstype="string" />
<FieldSetting cmstype="layout" cstype="string" />
<FieldSetting cmstype="checklist" cstype="string" />
<FieldSetting cmstype="Single-Line Text" cstype="string" />
<FieldSetting cmstype="security" cstype="string" />
<FieldSetting cmstype="Tracking" cstype="string" />
<!-- XPAC Field Types -->
<FieldSetting cmstype="Context List" cstype="ContextList" method="GetEntity&lt;ContextList&gt;" />
<FieldSetting cmstype="Thumbnail" cstype="string" />
<FieldSetting cmstype="Version Link" cstype="string" />
<FieldSetting cmstype="date" cstype="string" />
<FieldSetting cmstype="valuelookup" cstype="string" />
<FieldSetting cmstype="image" cstype="string" />
<FieldSetting cmstype="rich text" cstype="string" />
<FieldSetting cmstype="multilist" cstype="string" />
<FieldSetting cmstype="tree list" cstype="string" />
<FieldSetting cmstype="tree list with query" cstype="string" />
<FieldSetting cmstype="" cstype="string" />
<FieldSetting cmstype="Draggable Context" cstype="string" />
<FieldSetting cmstype="Childlist" cstype="Entity[UNVEntityTypeTable]" />
<FieldSetting cmstype="CustomDropDownList" cstype="?" />
<FieldSetting cmstype="CustomMultiSelect" cstype="?[]" />
<FieldSetting cmstype="LinkListBox" cstype="LinkList" />
<FieldSetting cmstype="CustomTreeList" cstype="?[]" />
<FieldSetting cmstype="SystemLinkedDropLink" cstype="?" />
<FieldSetting cmstype="SystemLinkedTreeList" cstype="?[]" />
<FieldSetting cmstype="SystemLinkedMultiList" cstype="?[]" />
<FieldSetting cmstype="CustomTreePicker" cstype="?" />
<FieldSetting cmstype="Tristate" cstype="bool?" method="GetTristate" />
<FieldSetting cmstype="DeviceRenderingsPicker" cstype="string" />
<FieldSetting cmstype="Datasource" cstype="string" />
<FieldSetting cmstype="Page Preview" cstype="string" />
</DefaultSettings>
<BaseClasses>
<BaseClass type="global::Client.Logic.Entities.Document">
<SearchPaths>
<Path>/sitecore/templates/Client/Pages/*</Path>
<Path>/sitecore/templates/Client/SystemTemplates/Consultant/*</Path>
</SearchPaths>
<CustomFields>
</CustomFields>
</BaseClass>
<BaseClass type="global::Client.Logic.Entities.ContextElement">
<SearchPaths>
<Path>/sitecore/templates/Client/Elements/*</Path>
<CustomFields>
</CustomFields>
</SearchPaths>
</BaseClass>
<BaseClass type="global::Client.Logic.Entities.FormField">
<SearchPaths>
<Path>/sitecore/templates/Client/SystemTemplates/Form Module/Fields/*</Path>
</SearchPaths>
</BaseClass>
<BaseClass type="global::Client.Logic.Entities.FormAction">
<SearchPaths>
<Path>/sitecore/templates/Client/SystemTemplates/Form Module/Actions/*</Path>
</SearchPaths>
</BaseClass>
<BaseClass type="global::Client.Logic.Entities.FocusItem">
<SearchPaths>
<Path>/sitecore/templates/Client/SystemTemplates/Focus/Items/*</Path>
</SearchPaths>
</BaseClass>
<BaseClass type="global::Client.Logic.Entities.Client.SystemTemplates.Contacts.Contact">
<SearchPaths>
<Path>/sitecore/templates/Client/SystemTemplates/Contacts/Profile</Path>
</SearchPaths>
</BaseClass>
<BaseClass type="global::Client.Logic.Entities.Client.Pages.SubPages.PublicationChapter">
<SearchPaths>
<Path>/sitecore/templates/Client/Pages/SubPages/SharedGoalsPage</Path>
</SearchPaths>
<CustomFields>
</CustomFields>
</BaseClass>
</BaseClasses>
<CustomSettings>
</CustomSettings>
</Configuration>
<CsTypeConversions defaultValue="Single-Line Text">
<type name="Int32" convertsTo="Integer" />
<type name="DateTime" convertsTo="Date" />
<type name="Boolean" convertsTo="Checkbox" />
<type name="String" convertsTo="?" />
</CsTypeConversions>
</CodeGeneration>
namespace FemtenNulOtte.Core.Configuration
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using FemtenNulOtte.Core.Entities;
using FemtenNulOtte.Core.Utilities;
using FemtenNulOtte.Core.Web.Services;
public class CodeGenerationConfiguration
{
#region Fields
private readonly string _name;
private readonly CodeGenerationSettings _settings;
private readonly Dictionary<string, TemplateSetting> _templateSettings;
#endregion Fields
#region Constructors
internal CodeGenerationConfiguration(CodeGenerationSettings settings, string name, XmlElement root)
{
this._name = name;
this._settings = settings;
this._templateSettings = new Dictionary<string, TemplateSetting>();
InitializeSettings();
if (root != null)
{
IncludePathRoot = root.SelectSingleNode("IncludePaths/@root").Value;
TrimTemplatesByIncludePaths(root);
TrimTemplatesByExcludePaths(root);
ApplyNameSpaces();
LoadDefaultFieldSettings(root);
LoadBaseClasses(root);
OverrideByCustomSettings(root);
RemoveSystemFields();
ApplyPropertyNames();
}
}
#endregion Constructors
#region Properties
public string IncludePathRoot
{
get; private set;
}
#endregion Properties
#region Methods
public IEnumerable<TemplateSetting> GetTemplateSettings()
{
return this._templateSettings.Values;
}
internal static string GetCsName(string name)
{
string value = Regex.Replace(name, "[^a-zA-Z0-9_]", "");
return char.ToUpper(value[0]) + value.Substring(1);
}
private void ApplyNameSpaces()
{
foreach (var template in this._templateSettings.Values)
{
var parts = template.Path.Substring(this.IncludePathRoot.Length).Split('/').Select(GetCsName).ToArray();
template.NameSpace = parts.Take(parts.Length - 1).ToSeparatedString(".");
}
}
private void ApplyPropertyNames()
{
foreach (var template in this._templateSettings.Values)
{
foreach (var field in template.FieldSettings.Values)
{
string propertyName = GetCsName(field.Name);
if (propertyName == template.ClassName)
propertyName += "Field";
field.PropertyName = propertyName;
}
}
}
private string GetFullClassNameFromTemplatePath(string path)
{
if (path.StartsWith("/") && this._templateSettings.ContainsKey(path))
{
var template = this._templateSettings[path];
return template.NameSpace + "." + template.ClassName;
}
else
{
try
{
Guid id = new Guid(path);
var template = _templateSettings.Values.Where(t => t.Id == new Id(id)).FirstOrDefault();
if (template != null)
return template.NameSpace + "." + template.ClassName;
}
catch (Exception)
{
}
}
return path;
}
private void InitializeSettings()
{
foreach (var template in CmsService.Instance.GetTemplates())
{
TemplateSetting templateSetting = new TemplateSetting(template);
this._templateSettings.Add(templateSetting.Path, templateSetting);
}
}
private void LoadBaseClasses(XmlElement root)
{
foreach (XmlElement element in root.SelectNodes("BaseClasses/BaseClass"))
{
string[] fieldNames = element.SelectNodes("CustomFields/Field").Cast<XmlElement>().Select(e => e.GetAttribute("name")).ToArray();
string[] searchPaths = element.SelectNodes("SearchPaths/Path").Cast<XmlElement>().Select(e => e.InnerText).ToArray();
foreach (string key in this._templateSettings.Keys.Where(k => searchPaths.Where(s => k.IsWildcardMatch(s)).Any()))
{
TemplateSetting setting = this._templateSettings[key];
setting.BaseClass = element.GetAttribute("type");
foreach (string fieldName in fieldNames)
{
if (setting.FieldSettings.ContainsKey(fieldName))
setting.FieldSettings.Remove(fieldName);
}
}
}
}
private void LoadDefaultFieldSettings(XmlElement root)
{
Dictionary<string, string> csTypes = root.SelectNodes("DefaultSettings/FieldSetting").Cast<XmlElement>().ToDictionary(e => e.GetAttribute("cmstype"), e => e.GetAttribute("cstype"));
Dictionary<string, string> methods = root.SelectNodes("DefaultSettings/FieldSetting").Cast<XmlElement>().ToDictionary(e => e.GetAttribute("cmstype"), e => e.GetAttribute("method"));
foreach (var templateSetting in this._templateSettings.Values)
foreach (var fieldSetting in templateSetting.FieldSettings.Values)
{
if (csTypes.ContainsKey(fieldSetting.CmsType))
{
string csType = csTypes[fieldSetting.CmsType];
Match enumTypeTableMatch = Regex.Match(csType, @"Entity\[(?<typetable>[^\]]+)\]");
if (csType == "?")
{
fieldSetting.CsType = GetFullClassNameFromTemplatePath(fieldSetting.ContainedType);
fieldSetting.Method = "GetValue<" + GetFullClassNameFromTemplatePath(fieldSetting.ContainedType) + ">";
}
else if (csType == "?[]")
{
fieldSetting.CsType = "IEnumerable<" + GetFullClassNameFromTemplatePath(fieldSetting.ContainedType) + ">";
fieldSetting.Method = "GetListValue<" + GetFullClassNameFromTemplatePath(fieldSetting.ContainedType) + ">";
}
else if (enumTypeTableMatch.Success)
{
fieldSetting.TypeTable = enumTypeTableMatch.Groups["typetable"].Value;
string innerType = !string.IsNullOrEmpty(fieldSetting.ContainedType) ? GetFullClassNameFromTemplatePath(fieldSetting.ContainedType) : "Entity";
fieldSetting.CsType = "IEnumerable<" + innerType + ">";
fieldSetting.Method = "GetDescendantsOfType<" + innerType + "," + fieldSetting.TypeTable + ">";
}
else
{
switch (csType)
{
case "Entity":
fieldSetting.CsType = !string.IsNullOrEmpty(fieldSetting.ContainedType) ? GetFullClassNameFromTemplatePath(fieldSetting.ContainedType) : csType;
fieldSetting.Method = "GetEntity<" + fieldSetting.CsType + ">";
break;
case "Entity[]":
string containedType = !string.IsNullOrEmpty(fieldSetting.ContainedType) ? GetFullClassNameFromTemplatePath(fieldSetting.ContainedType) : "Entity";
fieldSetting.CsType = "IEnumerable<" + containedType + ">";
fieldSetting.Method = "GetEntities<" + containedType + ">";
break;
default:
fieldSetting.CsType = csTypes[fieldSetting.CmsType];
fieldSetting.Method = "GetValue<" + fieldSetting.CsType + ">";
break;
}
}
}
else
{
csTypes.Add(fieldSetting.CmsType, "string");
// Add the unknown type to the configuration xml file, so it's easier to create the correct conversion.
this._settings.AddDefaultCmsTypeConversion(this._name, fieldSetting.CmsType);
}
if (methods.ContainsKey(fieldSetting.CmsType) && !string.IsNullOrEmpty(methods[fieldSetting.CmsType]))
fieldSetting.Method = methods[fieldSetting.CmsType];
}
}
private void OverrideByCustomSettings(XmlElement root)
{
foreach (XmlElement template in root.SelectNodes("CustomSettings/Template"))
{
string path = template.GetAttribute("path");
if (this._templateSettings.ContainsKey(path))
{
TemplateSetting setting = this._templateSettings[path];
foreach (XmlElement fieldSetting in template.ChildNodes)
{
string name = fieldSetting.GetAttribute("name");
if (setting.FieldSettings.ContainsKey(name))
{
var f = setting.FieldSettings[name];
bool skip = fieldSetting.GetAttribute("skip") == "true";
if (skip)
setting.FieldSettings.Remove(name);
else
{
f.CsType = fieldSetting.GetAttribute("cstype");
string method = fieldSetting.GetAttribute("method");
if (string.IsNullOrEmpty(method))
f.Method = "GetValue<" + f.CsType + ">";
else
f.Method = method;
}
}
}
}
}
}
private void RemoveSystemFields()
{
foreach (var template in this._templateSettings.Values)
{
string[] removedKeys = template.FieldSettings.Keys.Where(k => k.StartsWith("__")).ToArray();
foreach (string key in removedKeys)
template.FieldSettings.Remove(key);
}
}
private void TrimTemplatesByIncludePaths(XmlElement root)
{
string[] paths = root.SelectNodes("IncludePaths/Path").Cast<XmlElement>().Select(e => e.InnerText).ToArray();
string[] keys = this._templateSettings.Keys.ToArray();
foreach (string key in keys)
{
if (!paths.Where(p => key.IsWildcardMatch(p)).Any())
this._templateSettings.Remove(key);
}
}
private void TrimTemplatesByExcludePaths(XmlElement root)
{
string[] paths = root.SelectNodes("ExcludePaths/Path").Cast<XmlElement>().Select(e => e.InnerText).ToArray();
string[] keys = this._templateSettings.Keys.ToArray();
foreach (string key in keys)
{
if (paths.Where(p => key.IsWildcardMatch(p)).Any())
this._templateSettings.Remove(key);
}
}
#endregion Methods
#region Nested Types
public class FieldSetting
{
#region Constructors
public FieldSetting(Entities.TemplateField field)
{
this.Name = field.Name;
this.CmsType = field.Type;
this.AccessModifier = "public";
this.CsType = "string";
this.Method = "GetValue<" + CsType + ">";
this.Section = field.Section;
if (field.CodeGenerationSettings != null)
{
this.ContainedType = field.CodeGenerationSettings.ContainedType;
this.Skip = field.CodeGenerationSettings.Skip;
}
}
#endregion Constructors
#region Properties
public string AccessModifier
{
get; set;
}
public string CmsType
{
get; set;
}
public string ContainedType
{
get; private set;
}
public string CsType
{
get; set;
}
public string Method
{
get; set;
}
public string Name
{
get; set;
}
public string PropertyName
{
get; set;
}
public string Section
{
get; private set;
}
public bool Skip
{
get; private set;
}
#endregion Properties
public string TypeTable { get; set; }
}
public class TemplateSetting
{
#region Fields
private readonly Dictionary<string, FieldSetting> _FieldSettings;
#endregion Fields
#region Constructors
public TemplateSetting(Entities.Template template)
{
Name = template.Name;
Path = template.Path;
Id = template.Id;
BaseClass = "Entity";
AccessModifier = "public";
_FieldSettings = new Dictionary<string, FieldSetting>();
ClassName = GetCsName(Name);
foreach (var field in template.AllFields)
{
if (!_FieldSettings.ContainsKey(field.Name))
{
FieldSetting fieldSetting = new FieldSetting(field);
if (!fieldSetting.Skip)
_FieldSettings.Add(fieldSetting.Name, fieldSetting);
}
}
}
#endregion Constructors
#region Properties
public string AccessModifier
{
get; set;
}
public string BaseClass
{
get; set;
}
public string ClassName
{
get; private set;
}
public Dictionary<string, FieldSetting> FieldSettings
{
get { return _FieldSettings; }
}
public Id Id
{
get; private set;
}
public string Name
{
get; private set;
}
public string NameSpace
{
get; set;
}
public string Path
{
get; private set;
}
#endregion Properties
#region Methods
public FieldSetting GetFieldSetting(string fieldName)
{
return _FieldSettings[fieldName];
}
#endregion Methods
}
#endregion Nested Types
}
public class CodeGenerationSettings
{
#region Fields
private Dictionary<string, CodeGenerationConfiguration> _Configurations;
private Dictionary<string, string> _CsTypeConversions;
private string _DefaultCsTypeConversion;
#endregion Fields
#region Constructors
private CodeGenerationSettings()
{
XmlDocument doc = GetXml();
_Configurations = new Dictionary<string, CodeGenerationConfiguration>();
foreach (XmlElement config in doc.SelectNodes("CodeGeneration/Configuration"))
{
string name = config.GetAttribute("name");
CodeGenerationConfiguration configuration = new CodeGenerationConfiguration(this, name, config);
_Configurations.Add(name, configuration);
}
_CsTypeConversions = new Dictionary<string, string>();
XmlElement csConversion = (XmlElement)doc.SelectSingleNode("CodeGeneration/CsTypeConversions");
_DefaultCsTypeConversion = csConversion.GetAttribute("defaultValue");
foreach (XmlElement type in csConversion.ChildNodes)
{
string typeName = type.GetAttribute("name");
if (_CsTypeConversions.ContainsKey(typeName))
continue;
string convertsTo = type.GetAttribute("convertsTo");
if (convertsTo == "?")
_CsTypeConversions.Add(typeName, _DefaultCsTypeConversion);
else
_CsTypeConversions.Add(typeName, convertsTo);
}
}
#endregion Constructors
#region Properties
public static CodeGenerationSettings Instance
{
get { return Cache.Get("CodeGenerationSettings", CacheScope.Request, () => new CodeGenerationSettings()); }
}
public string[] Configurations
{
get { return _Configurations.Keys.ToArray(); }
}
#endregion Properties
#region Indexers
public CodeGenerationConfiguration this[string key]
{
get { return _Configurations[key]; }
}
#endregion Indexers
#region Methods
public CodeGenerationConfiguration GetConfiguration(string name)
{
return _Configurations[name];
}
public string GetCsTypeConversion<T>()
{
string typeName = typeof (T).Name;
if (_CsTypeConversions.ContainsKey(typeName))
return _CsTypeConversions[typeName];
AddDefaultCsTypeConversion(typeName);
_CsTypeConversions.Add(typeName, _DefaultCsTypeConversion);
return _DefaultCsTypeConversion;
}
internal void AddDefaultCmsTypeConversion(string configuration, string cmsType)
{
XmlDocument doc = GetXml();
XmlElement conversions = (XmlElement)doc.SelectSingleNode("CodeGeneration/Configuration[@name='" + configuration + "']/DefaultSettings");
XmlElement typeElement = doc.CreateElement("FieldSetting");
conversions.AppendChild(typeElement);
typeElement.SetAttribute("cmstype", cmsType);
typeElement.SetAttribute("cstype", "string");
doc.Save(GetFilename());
}
private void AddDefaultCsTypeConversion(string typeName)
{
XmlDocument doc = GetXml();
XmlElement conversions = (XmlElement) doc.SelectSingleNode("CodeGeneration/CsTypeConversions");
XmlElement typeElement = doc.CreateElement("type");
conversions.AppendChild(typeElement);
typeElement.SetAttribute("name", typeName);
typeElement.SetAttribute("convertsTo", "?");
doc.Save(GetFilename());
}
private string GetFilename()
{
return ApplicationSettings.MapPath("~/App_Data/CodeGeneration.xml");
}
private XmlDocument GetXml()
{
XmlDocument doc = new XmlDocument();
doc.Load(GetFilename());
return doc;
}
#endregion Methods
}
}
namespace FemtenNulOtte.Core.Entities
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using FemtenNulOtte.Core.Utilities;
using FemtenNulOtte.Core.Web.Services;
using FemtenNulOtte.Core.Xsl;
public class Entity : IComparable, IXPathNavigable
{
private readonly Dictionary<string, object> _fields = new Dictionary<string, object>();
private Object _lock = new Object();
#region Properties
/// <summary>
/// Returns the encapsulated items displayname
/// </summary>
public string DisplayName
{
get { return CmsService.Instance.GetDisplayName(this); }
}
/// <summary>
/// Returns the encapsulated items's Name
/// </summary>
public string EntityName
{
get { return CmsService.Instance.GetName(this); }
}
public bool HasVersion
{
get { return CmsService.Instance.HasVersion(this); }
}
/// <summary>
/// Returns the encapsulated item's ID
/// </summary>
public Id Id
{
get { return CmsService.Instance.GetId(this); }
}
public string Path
{
get
{
if (WrappedItem == null)
{
throw new ApplicationException("Wrapped item is null");
}
return CmsService.Instance.GetPath(this);
}
}
public virtual Id TemplateId
{
get { return null; }
}
public virtual string TemplateName
{
get { return GetType().Name; }
}
public virtual string TemplatePath
{
get { return string.Empty; }
}
public object WrappedItem
{
get; set;
}
#endregion Properties
#region Methods
public T CastAs<T>() where T:Entity, new()
{
return new T() { WrappedItem = this.WrappedItem };
}
public int CompareTo(object obj)
{
Entity entity = obj as Entity;
if (entity == null)
throw new ArgumentException("Cannot compare Entity with " + obj.GetType().Name);
return this.Id.CompareTo(entity.Id);
}
public XPathNavigator CreateNavigator()
{
return new EntityXPathNavigator(this);
}
public XPathNodeIterator GetChildNodeIterator()
{
return CmsService.Instance.GetChildNodeIterator(this);
}
private T Get<T>(string key, Func<T> resolver)
{
lock (_lock)
{
if (_fields.ContainsKey(key))
{
return (T) _fields[key];
}
var result = resolver();
_fields.Add(key, result);
return result;
}
}
protected bool HasValue(string key)
{
return CmsService.Instance.HasValue(this, key);
}
#region Get Children
public IEnumerable<T> GetChildren<T>() where T : Entity, new()
{
string key = "GetChildren" + typeof(T).Name;
return Get<IEnumerable<T>>(key, () => CmsService.Instance.GetChildren<T>(this).ToArray());
}
public IEnumerable<T> GetChildrenOfType<T,TE>()
where T : Entity, new()
where TE : EntityTypeTable, new()
{
string key = "GetChildren" + typeof(T).Name;
return Get<IEnumerable<T>>(key, () => CmsService.Instance.GetChildrenOfType<T,TE>(this).ToArray());
}
public IEnumerable<T> GetChildrenOfType<T>()
where T : Entity, new()
{
string key = "GetChildrenOfType" + typeof(T).Name;
return Get<IEnumerable<T>>(key, () => CmsService.Instance.GetChildrenOfType<T>(this).ToArray());
}
#endregion
#region Get Descendants
public IEnumerable<T> GetDescendantsOfType<T>()
where T : Entity, new()
{
string key = "GetDescendantsOfType" + typeof(T).Name;
return Get<IEnumerable<T>>(key, () => CmsService.Instance.GetDescendantsOfType<T>(this).ToArray());
}
public IEnumerable<T> GetDescendantsOfType<T, TE>()
where T : Entity, new()
where TE : EntityTypeTable, new()
{
string key = "GetDescendandtsOfType" + typeof(T).Name + typeof(TE).Name;
return Get<IEnumerable<T>>(key, () => CmsService.Instance.GetDescendantsOfType<T,TE>(this).ToArray());
}
#endregion
public XPathNodeIterator GetNodeIterator()
{
return CmsService.Instance.GetNodeIterator(this);
}
public string this[string key]
{
get
{
return CmsService.Instance.GetFieldValue<string>(this, key);
}
//set
//{
// this.SetValue(key, value);
//}
}
public T GetParent<T>()
where T : Entity, new()
{
return CmsService.Instance.GetParent<T>(this);
}
public bool? GetTristate(string fieldName)
{
if (string.IsNullOrEmpty(this[fieldName]))
return null;
return this.GetValue<bool>(fieldName);
}
public T GetValue<T>(string fieldName)
{
return Get<T>(fieldName, () => CmsService.Instance.GetFieldValue<T>(this, fieldName));
}
public IEnumerable<T> GetListValue<T>(string fieldName)
{
return this.Get<IEnumerable<T>>(fieldName, () => CmsService.Instance.GetFieldValues<T>(this, fieldName));
}
public void Initialize(object wrappedItem)
{
WrappedItem = wrappedItem;
}
public bool Is(string templateName)
{
return string.Compare(TemplateName, templateName, true) == 0;
}
public bool Save()
{
return CmsService.Instance.SaveItem(this);
}
public bool TemplateIs(string templateName)
{
return CmsService.Instance.TemplateIs(this, templateName);
}
internal NameValueCollection GetAttributes()
{
return CmsService.Instance.GetFields(this);
}
protected bool GetBool(string fieldName)
{
return Get<bool>(fieldName, () => CmsService.Instance.GetBool(this, fieldName));
}
protected IEnumerable<T> GetEntities<T>(string fieldName) where T : Entity, new()
{
IdList ids = this.GetValue<IdList>(fieldName);
return CmsService.Instance.GetItems<T>(ids);
}
protected IEnumerable<T> GetEntities<T, TE>(string fieldName) where T : Entity, new() where TE:EntityTypeTable,new()
{
IdList ids = this.GetValue<IdList>(fieldName);
return CmsService.Instance.GetItemsOfType<T,TE>(ids);
}
protected T GetEntity<T>(string fieldName) where T : Entity, new()
{
Id id = this.GetValue<Id>(fieldName);
return CmsService.Instance.GetItem<T>(id);
}
protected void SetValue(string fieldName, object value)
{
CmsService.Instance.SetFieldValue(this, fieldName, value);
}
public T GetAnchestorOfType<T>() where T:Entity, new()
{
return CmsService.Instance.GetAnchestorOfType<T>(this);
}
protected Entity GetEntityOrParentWithValue(string fieldName)
{
var result = this;
bool done = false;
while (!done && result != null)
{
if (!string.IsNullOrEmpty(result[fieldName]))
done = true;
else
result = result.GetParent<Entity>();
}
return result;
}
#endregion Methods
public void Publish()
{
CmsService.Instance.PublishItem(this);
}
}
}
namespace FemtenNulOtte.Core.Entities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class EntityTypeTable
{
#region Fields
private Dictionary<string, Type> _types;
#endregion Fields
#region Constructors
public EntityTypeTable()
{
_types = new Dictionary<string, Type>();
}
#endregion Constructors
#region Methods
public void AddType<T>()
where T : Entity, new()
{
T item = new T();
_types.Add(item.TemplatePath, typeof(T));
}
public void AddType(string templatePath, Type type)
{
_types.Add(templatePath, type);
}
public Type GetType(string templatePath)
{
if (_types.ContainsKey(templatePath))
return _types[templatePath];
return typeof (Entity);
}
#endregion Methods
}
}
<%@ WebHandler Language="C#" Class="FemtenNulOtte.Core.T4.T4XmlProvider,FemtenNulOtte.Core" %>
namespace FemtenNulOtte.Core.T4
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;
using System.Xml;
using FemtenNulOtte.Core.Configuration;
using FemtenNulOtte.Core.Entities;
using FemtenNulOtte.Core.Web.Services;
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class T4XmlProvider : IHttpHandler
{
#region Fields
private CodeGenerationConfiguration _configuration;
private Dictionary<string, CodeGenerationConfiguration.TemplateSetting> _templates;
#endregion Fields
#region Properties
public bool IsReusable
{
get
{
return false;
}
}
#endregion Properties
#region Methods
public void ProcessRequest(HttpContext context)
{
string configName = context.Request.QueryString["configuration"];
_configuration = CodeGenerationSettings.Instance.GetConfiguration(configName);
context.Response.ContentType = "text/plain";
using (XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
writer.WriteStartElement("namespaces");
_templates = _configuration.GetTemplateSettings().ToDictionary(t => t.Path);
foreach (var nameSpace in _templates.Values.GroupBy(c => c.NameSpace))
{
writer.WriteStartElement("namespace");
writer.WriteAttributeString("name", nameSpace.Key);
foreach (var template in nameSpace)
WriteTemplate(template, writer);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
private void WriteTemplate(CodeGenerationConfiguration.TemplateSetting template, XmlTextWriter writer)
{
writer.WriteStartElement("template");
writer.WriteAttributeString("name", template.Name);
writer.WriteAttributeString("id", template.Id.ToString());
writer.WriteAttributeString("base", template.BaseClass);
writer.WriteAttributeString("csname", template.ClassName);
writer.WriteAttributeString("access", template.AccessModifier);
writer.WriteAttributeString("path", template.Path);
writer.WriteStartElement("sections");
foreach (var section in template.FieldSettings.Values.GroupBy(f => f.Section))
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", section.Key);
foreach (var field in section)
{
writer.WriteStartElement("field");
writer.WriteAttributeString("name", field.Name);
writer.WriteAttributeString("csname", field.PropertyName);
writer.WriteAttributeString("cstype", field.CsType);
writer.WriteAttributeString("method", field.Method);
writer.WriteAttributeString("access", field.AccessModifier);
writer.WriteAttributeString("typeTable", field.TypeTable);
writer.WriteEndElement(); // field
}
writer.WriteEndElement();
}
writer.WriteEndElement(); // fields
writer.WriteEndElement(); // template
}
#endregion Methods
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment