Created
July 7, 2010 19:06
-
-
Save statianzo/467112 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Dynamic; | |
using System.Linq; | |
using System.Text; | |
namespace CSharpFourScratch | |
{ | |
internal class Program | |
{ | |
private static void Main() | |
{ | |
var table = new HtmlTag | |
{ | |
Name = "table", | |
Children = | |
{ | |
new HtmlTag | |
{ | |
Name = "tr", | |
Children = | |
{ | |
new HtmlTag {Name = "td"}, | |
new HtmlTag {Name = "td"} | |
} | |
} | |
} | |
}.Dynamic.Attr( | |
border: 1, | |
width: 360, | |
height: 180, | |
padding: "5px" | |
); | |
Console.WriteLine(table.ToString()); | |
Console.ReadLine(); | |
} | |
} | |
internal class DynamicHtmlTag : DynamicObject | |
{ | |
private readonly HtmlTag _tag; | |
public DynamicHtmlTag(HtmlTag tag) | |
{ | |
_tag = tag; | |
} | |
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) | |
{ | |
if (binder.Name == "Attr") | |
{ | |
IEnumerable<Tuple<string, string>> pairs = binder. | |
CallInfo | |
.ArgumentNames | |
.Zip(args, | |
(x, y) => | |
new Tuple<string, string> | |
(x, y.ToString())); | |
foreach (var pair in pairs) | |
_tag[pair.Item1] = pair.Item2; | |
result = this; | |
return true; | |
} | |
return base.TryInvokeMember(binder, args, out result); | |
} | |
public override string ToString() | |
{ | |
return _tag.ToString(); | |
} | |
} | |
internal class HtmlTag | |
{ | |
private dynamic _dynamic; | |
public dynamic Dynamic { get { return _dynamic ?? (_dynamic = new DynamicHtmlTag(this)); } } | |
private readonly IDictionary<string, string> _attributes = new Dictionary<string, string>(); | |
private IList<HtmlTag> _children = new List<HtmlTag>(); | |
public string Name { get; set; } | |
public string this[string attr] | |
{ | |
get { return _attributes[attr]; } | |
set { _attributes[attr] = value; } | |
} | |
public IList<HtmlTag> Children | |
{ | |
get { return _children; } | |
set { _children = value; } | |
} | |
public override string ToString() | |
{ | |
var builder = new StringBuilder(); | |
builder.AppendFormat("<{0} ", Name); | |
foreach (var attribute in _attributes) | |
builder.AppendFormat("{0}=\"{1}\" ", attribute.Key, attribute.Value); | |
if (_children.Any()) | |
{ | |
builder.AppendLine(">"); | |
foreach (HtmlTag child in Children) | |
builder.AppendFormat("\t{0}", child); | |
builder.AppendFormat("</{0}>\n", Name); | |
} | |
else | |
builder.AppendLine("/>"); | |
return builder.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment