2 // System.Web.Compilation.AspGenerator
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
10 using System.Collections;
11 using System.ComponentModel;
13 using System.Diagnostics;
15 using System.Reflection;
17 using System.Text.RegularExpressions;
19 using System.Web.UI.HtmlControls;
20 using System.Web.UI.WebControls;
21 using System.Web.Util;
23 namespace System.Web.Compilation
28 private Stack controls;
29 private ControlStackData top;
30 private bool space_between_tags;
31 private bool sbt_valid;
33 class ControlStackData
35 public Type controlType;
36 public string controlID;
38 public ChildrenKind childKind;
39 public string defaultPropertyName;
40 public int childrenNumber;
41 public Type container;
42 public StringBuilder dataBindFunction;
43 public StringBuilder codeRenderFunction;
44 public bool useCodeRender;
45 public int codeRenderIndex;
47 public ControlStackData (Type controlType,
50 ChildrenKind childKind,
51 string defaultPropertyName,
54 this.controlType = controlType;
55 this.controlID = controlID;
57 this.childKind = childKind;
58 this.defaultPropertyName = defaultPropertyName;
59 this.container = container;
63 public override string ToString ()
65 return controlType + " " + controlID + " " + tagID + " " + childKind + " " + childrenNumber;
69 public ControlStack ()
71 controls = new Stack ();
74 private Type GetContainerType (Type type)
76 if (type != typeof (System.Web.UI.Control) &&
77 !type.IsSubclassOf (typeof (System.Web.UI.Control)))
81 if (type == typeof (System.Web.UI.WebControls.DataList))
82 container_type = typeof (System.Web.UI.WebControls.DataListItem);
83 else if (type == typeof (System.Web.UI.WebControls.DataGrid))
84 container_type = typeof (System.Web.UI.WebControls.DataGridItem);
85 else if (type == typeof (System.Web.UI.WebControls.Repeater))
86 container_type = typeof (System.Web.UI.WebControls.RepeaterItem);
87 else if (type == typeof (ListControl) || type.IsSubclassOf (typeof (ListControl)))
88 container_type = type;
90 container_type = Container;
92 return container_type;
95 public void Push (object o)
97 if (!(o is ControlStackData))
101 top = (ControlStackData) o;
105 public void Push (Type controlType,
108 ChildrenKind childKind,
109 string defaultPropertyName)
111 Type container_type = null;
112 if (controlType != null){
114 container_type = GetContainerType (controlType);
115 if (container_type == null)
116 container_type = this.Container;
119 top = new ControlStackData (controlType,
131 object item = controls.Pop ();
132 if (controls.Count != 0)
133 top = (ControlStackData) controls.Peek ();
138 public Type PeekType ()
140 return top.controlType;
143 public string PeekControlID ()
145 return top.controlID;
148 public string PeekTagID ()
153 public ChildrenKind PeekChildKind ()
155 return top.childKind;
158 public string PeekDefaultPropertyName ()
160 return top.defaultPropertyName;
163 public void AddChild ()
166 top.childrenNumber++;
169 public bool HasDataBindFunction ()
171 if (top.dataBindFunction == null || top.dataBindFunction.Length == 0)
176 public bool UseCodeRender
179 if (top.codeRenderFunction == null || top.codeRenderFunction.Length == 0)
181 return top.useCodeRender;
184 set { top.useCodeRender= value; }
187 public bool SpaceBetweenTags
192 Type type = top.controlType;
193 if (type.Namespace == "System.Web.UI.WebControls")
194 space_between_tags = true;
195 else if (type.IsSubclassOf (typeof (System.Web.UI.WebControls.WebControl)))
196 space_between_tags = true;
197 else if (type == typeof (System.Web.UI.HtmlControls.HtmlSelect))
198 space_between_tags = true;
199 else if (type == typeof (System.Web.UI.HtmlControls.HtmlTable))
200 space_between_tags = true;
201 else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableRow))
202 space_between_tags = true;
203 else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableCell))
204 space_between_tags = true;
206 space_between_tags = false;
208 return space_between_tags;
212 public Type Container {
217 return top.container;
221 public StringBuilder DataBindFunction
224 if (top.dataBindFunction == null)
225 top.dataBindFunction = new StringBuilder ();
226 return top.dataBindFunction;
230 public int CodeRenderIndex {
232 return top.codeRenderIndex++;
236 public StringBuilder CodeRenderFunction
239 if (top.codeRenderFunction == null)
240 top.codeRenderFunction = new StringBuilder ();
241 return top.codeRenderFunction;
245 public int ChildIndex
247 get { return top.childrenNumber - 1; }
252 get { return controls.Count; }
255 public override string ToString ()
257 return top.ToString () + " " + top.useCodeRender;
272 StringBuilder prolog;
273 StringBuilder declarations;
274 StringBuilder script;
275 StringBuilder constructor;
276 StringBuilder init_funcs;
277 StringBuilder epilog;
278 StringBuilder current_function;
279 StringBuilder textChunk;
281 ControlStack controls;
284 AspComponentFoundry aspFoundry;
295 string privateBinPath;
296 string main_directive;
297 static string app_file_wrong = "The content in the application file is not valid.";
304 ScriptStatus sstatus = ScriptStatus.Close;
309 SessionState sessionState = SessionState.Enabled;
311 static Type styleType = typeof (System.Web.UI.WebControls.Style);
312 static Type fontinfoType = typeof (System.Web.UI.WebControls.FontInfo);
314 enum UserControlResult
318 CompilationFailed = 2
328 public AspGenerator (string pathToFile)
330 if (pathToFile == null)
331 throw new ArgumentNullException ("pathToFile");
333 string filename = Path.GetFileName (pathToFile);
334 this.className = filename.Replace ('.', '_'); // Overridden by @ Page classname
335 this.className = className.Replace ('-', '_');
336 this.className = className.Replace (' ', '_');
337 Options ["ClassName"] = this.className;
338 this.fullPath = Path.GetFullPath (pathToFile);
340 this.has_form_tag = false;
341 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
342 privateBinPath = setup.PrivateBinPath;
343 // This is a hack until we can run stuff in different domains
344 if (privateBinPath == null || privateBinPath.Length == 0)
345 privateBinPath = "bin";
347 if (!Path.IsPathRooted (privateBinPath)) {
348 string appbase = setup.ApplicationBase;
349 if (appbase.StartsWith ("file://"))
350 appbase = appbase.Substring (7);
351 privateBinPath = Path.Combine (appbase, privateBinPath);
357 public string BaseType {
358 get { return basetype; }
365 isUserControl = (basetype == "System.Web.UI.UserControl");
366 isPage = (basetype == "System.Web.UI.Page");
367 isApplication = (basetype == "System.Web.HttpApplication");
371 public bool IsUserControl {
372 get { return isUserControl; }
376 get { return isPage; }
379 public bool IsApplication {
380 get { return isApplication; }
383 public string Interfaces {
384 get { return interfaces; }
387 public Hashtable Options {
390 options = new Hashtable ();
396 internal HttpContext Context {
397 get { return context; }
398 set { context = value; }
401 bool AddUsing (string nspace)
403 string _using = "using " + nspace + ";";
404 if (prolog.ToString ().IndexOf (_using) == -1) {
405 prolog.AppendFormat ("\t{0}\n", _using);
412 void AddInterface (Type type)
414 AddInterface (type.ToString ());
417 public void AddInterface (string iface)
419 if (interfaces == null) {
420 interfaces = ", " + iface;
422 string s = ", " + iface;
423 if (interfaces.IndexOf (s) == -1)
428 private AspComponentFoundry Foundry
431 if (aspFoundry == null)
432 aspFoundry = new AspComponentFoundry ();
440 controls = new ControlStack ();
441 controls.Push (typeof (System.Web.UI.Control), "Root", null, ChildrenKind.CONTROLS, null);
442 prolog = new StringBuilder ();
443 declarations = new StringBuilder ();
444 script = new StringBuilder ();
445 constructor = new StringBuilder ();
446 init_funcs = new StringBuilder ();
447 epilog = new StringBuilder ();
448 textChunk = new StringBuilder ();
450 current_function = new StringBuilder ();
451 functions = new Stack ();
452 functions.Push (current_function);
454 parts = new Object [6];
456 parts [1] = declarations;
458 parts [3] = constructor;
459 parts [4] = init_funcs;
462 prolog.Append ("namespace ASP {\n" +
463 "\tusing System;\n" +
464 "\tusing System.Collections;\n" +
465 "\tusing System.Collections.Specialized;\n" +
466 "\tusing System.Configuration;\n" +
467 "\tusing System.IO;\n" +
468 "\tusing System.Text;\n" +
469 "\tusing System.Text.RegularExpressions;\n" +
470 "\tusing System.Web;\n" +
471 "\tusing System.Web.Caching;\n" +
472 "\tusing System.Web.Security;\n" +
473 "\tusing System.Web.SessionState;\n" +
474 "\tusing System.Web.UI;\n" +
475 "\tusing System.Web.UI.WebControls;\n" +
476 "\tusing System.Web.UI.HtmlControls;\n");
478 declarations.Append ("\t\tprivate static int __autoHandlers;\n");
480 current_function.Append ("\t\tprivate void __BuildControlTree (System.Web.UI.Control __ctrl)\n\t\t{\n");
482 current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
483 "(System.Web.UI.IParserAccessor) __ctrl;\n\n");
485 controls.UseCodeRender = true;
488 public TextReader GetCode ()
491 throw new InvalidOperationException ("Parsing not done yet! (may be there were errors?)");
493 StringBuilder code = new StringBuilder ();
494 for (int i = 0; i < parts.Length; i++)
495 code.Append ((StringBuilder) parts [i]);
497 return new StringReader (code.ToString ());
500 // Regex.Escape () make some illegal escape sequences for a C# source.
501 private string Escape (string input)
506 string output = input.Replace ("\\", "\\\\");
507 output = output.Replace ("\"", "\\\"");
508 output = output.Replace ("\t", "\\t");
509 output = output.Replace ("\r", "\\r");
510 output = output.Replace ("\n", "\\n");
511 output = output.Replace ("\n", "\\n");
515 bool AddProtectedField (Type type, string fieldName)
517 if (parentType == null) {
518 declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
522 FieldInfo field = parentType.GetField (fieldName, BindingFlags.Public |
523 BindingFlags.NonPublic |
524 BindingFlags.Instance |
525 BindingFlags.Static);
527 if (field == null || (!field.IsPublic && !field.IsFamily)) {
528 declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
532 if (!field.FieldType.IsAssignableFrom (type)) {
533 string message = String.Format ("The base class includes the field '{0}', but its " +
534 "type '{1}' is not compatible with {2}",
535 fieldName, field.FieldType, type);
537 throw new ApplicationException (message);
543 private Type LoadParentType (string typeName)
545 // First try loaded assemblies, then try assemblies in Bin directory.
546 // By now i do this 'by hand' but may be this is a runtime/gac task.
548 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
549 foreach (Assembly ass in assemblies) {
550 type = ass.GetType (typeName);
556 string [] binDlls = Directory.GetFiles (privateBinPath, "*.dll");
557 foreach (string dll in binDlls) {
558 string dllPath = Path.Combine (privateBinPath, dll);
561 assembly = Assembly.LoadFrom (dllPath);
562 type = assembly.GetType (typeName);
563 } catch (Exception e) {
564 if (assembly != null) {
565 Console.WriteLine ("ASP.NET Warning: assembly {0} loaded", dllPath);
566 Console.WriteLine ("ASP.NET Warning: but type {0} not found", typeName);
568 Console.WriteLine ("ASP.NET Warning: unable to load type {0} from {1}",
571 Console.WriteLine ("ASP.NET Warning: error was: {0}", e.Message);
581 private void PageDirective (TagAttributes att)
583 if (att ["ClassName"] != null){
584 this.className = (string) att ["ClassName"];
585 Options ["ClassName"] = className;
588 if (att ["EnableSessionState"] != null){
590 throw new ApplicationException ("EnableSessionState not allowed here.");
592 string est = (string) att ["EnableSessionState"];
593 if (0 == String.Compare (est, "false", true))
594 sessionState = SessionState.Disabled;
595 else if (0 == String.Compare (est, "true", true))
596 sessionState = SessionState.Enabled;
597 else if (0 == String.Compare (est, "readonly", true))
598 sessionState = SessionState.ReadOnly;
600 throw new ApplicationException ("EnableSessionState in Page directive not set to " +
601 "a correct value: " + est);
604 if (att ["Inherits"] != null) {
605 parent = (string) att ["Inherits"];
606 parentType = LoadParentType (parent);
607 if (parentType == null)
608 throw new ApplicationException ("The class " + parent + " cannot be found.");
611 if (att ["CompilerOptions"] != null)
612 Options ["CompilerOptions"] = (string) att ["CompilerOptions"];
614 if (att ["AutoEventWireup"] != null) {
615 if (options ["AutoEventWireup"] != null)
616 throw new ApplicationException ("Already have an AutoEventWireup attribute");
618 bool autoevent = true;
619 string v = att ["AutoEventWireup"] as string;
621 autoevent = Convert.ToBoolean (v);
622 } catch (Exception) {
623 throw new ApplicationException ("'" + v + "' is not a valid value for AutoEventWireup");
625 options ["AutoEventWireup"] = autoevent;
628 //FIXME: add support for more attributes.
631 void AddReference (string dll)
633 string references = Options ["References"] as string;
634 if (references == null)
637 references = references + "|" + dll;
639 Options ["References"] = references;
642 private void RegisterDirective (TagAttributes att)
644 string tag_prefix = (string) (att ["tagprefix"] == null ? "" : att ["tagprefix"]);
645 string name_space = (string) (att ["namespace"] == null ? "" : att ["namespace"]);
646 string assembly_name = (string) (att ["assembly"] == null ? "" : att ["assembly"]);
647 string tag_name = (string) (att ["tagname"] == null ? "" : att ["tagname"]);
648 string src = (string) (att ["src"] == null ? "" : att ["src"]);
650 if (tag_prefix != "" && name_space != "" && assembly_name != ""){
651 if (tag_name != "" || src != "")
652 throw new ApplicationException ("Invalid attributes for @ Register: " +
655 AddUsing (name_space);
656 string dll = privateBinPath + Path.DirectorySeparatorChar + assembly_name + ".dll";
657 // Hack: it should use assembly.load semantics...
658 // may be when we don't run mcs as a external program...
659 if (!File.Exists (dll))
662 Foundry.RegisterFoundry (tag_prefix, dll, name_space);
667 if (tag_prefix != "" && tag_name != "" && src != ""){
668 if (name_space != "" && assembly_name != "")
669 throw new ApplicationException ("Invalid attributes for @ Register: " +
672 if (!src.EndsWith (".ascx"))
673 throw new ApplicationException ("Source file extension for controls " +
676 UserControlData data = GenerateUserControl (src, Context);
677 switch (data.result) {
678 case UserControlResult.OK:
680 Foundry.RegisterFoundry (tag_prefix, tag_name, data.assemblyName, "ASP", data.className);
681 AddReference (data.assemblyName);
683 case UserControlResult.FileNotFound:
684 throw new ApplicationException ("File '" + src + "' not found.");
685 case UserControlResult.CompilationFailed:
686 //TODO: should say where the generated .cs file is for the server to
687 //show the source and the compiler error
688 throw new NotImplementedException ();
693 throw new ApplicationException ("Invalid combination of attributes in " +
694 "@ Register: " + att.ToString ());
697 private void ProcessDirective ()
700 Directive directive = (Directive) current;
701 TagAttributes att = directive.Attributes;
706 string id = directive.TagID.ToUpper ();
709 if (main_directive != null)
710 throw new ApplicationException (id + " not allowed after " + main_directive);
713 throw new ApplicationException ("@Application not allowed.");
715 string inherits = att ["inherits"] as string;
716 if (inherits != null)
717 Options ["Inherits"] = inherits;
719 main_directive = directive.TagID;
723 if (main_directive != null)
724 throw new ApplicationException (id + " not allowed after " + main_directive);
726 if (IsUserControl && id != "CONTROL")
727 throw new ApplicationException ("@Page not allowed for user controls.");
728 else if (IsPage && id != "PAGE")
729 throw new ApplicationException ("@Control not allowed here. This is a page!");
732 main_directive = directive.TagID;
735 value = att ["namespace"] as string;
736 if (value == null || att.Count > 1)
737 throw new ApplicationException ("Wrong syntax in Import directive.");
739 string _using = "using " + value + ";";
740 if (AddUsing (value) == true) {
741 string imports = Options ["Import"] as string;
742 if (imports == null) {
745 imports += "," + value;
748 Options ["Import"] = imports;
753 throw new ApplicationException ("@ Implements not allowed in an application file.");
755 string iface = (string) att ["interface"];
756 AddInterface (iface);
760 throw new ApplicationException ("@ Register not allowed in an application file.");
762 RegisterDirective (att);
766 throw new ApplicationException ("Wrong syntax in Assembly directive.");
768 string name = att ["name"] as string;
769 string src = att ["src"] as string;
771 if (name == null && src == null)
772 throw new ApplicationException ("Wrong syntax in Assembly directive.");
774 if (IsApplication && src != null)
775 throw new ApplicationException ("'name' attribute expected.");
777 value = (name == null) ? src : name;
778 string assemblies = Options ["Assembly"] as string;
779 if (assemblies == null) {
782 assemblies += "," + value;
785 Options ["Assembly"] = assemblies;
790 private void ProcessPlainText ()
792 PlainText asis = (PlainText) current;
793 string trimmed = asis.Text.Trim ();
794 if (trimmed == String.Empty && controls.SpaceBetweenTags == true)
798 if (trimmed != String.Empty)
799 throw new ApplicationException (app_file_wrong);
803 if (trimmed != String.Empty && controls.PeekChildKind () != ChildrenKind.CONTROLS){
804 string tag_id = controls.PeekTagID ();
805 throw new ApplicationException ("Literal content not allowed for " + tag_id);
808 string escaped_text = Escape (asis.Text);
809 current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject (" +
810 "new System.Web.UI.LiteralControl (\"{0}\"));\n",
812 StringBuilder codeRenderFunction = controls.CodeRenderFunction;
813 codeRenderFunction.AppendFormat ("\t\t\t__output.Write (\"{0}\");\n", escaped_text);
816 private string EnumValueNameToString (Type enum_type, string value_name)
818 if (value_name.EndsWith ("*"))
819 throw new ApplicationException ("Invalid property value: '" + value_name +
820 ". It must be a valid " + enum_type.ToString () + " value.");
822 MemberInfo [] nested_types = enum_type.FindMembers (MemberTypes.Field,
823 BindingFlags.Public | BindingFlags.Static,
824 Type.FilterNameIgnoreCase,
827 if (nested_types.Length == 0)
828 throw new ApplicationException ("Value " + value_name + " not found in enumeration " +
829 enum_type.ToString ());
830 if (nested_types.Length > 1)
831 throw new ApplicationException ("Value " + value_name + " found " +
832 nested_types.Length + " in enumeration " +
833 enum_type.ToString ());
835 return enum_type.ToString () + "." + nested_types [0].Name;
838 private void NewControlFunction (string tag_id,
841 ChildrenKind children_kind,
842 string defaultPropertyName)
844 ChildrenKind prev_children_kind = controls.PeekChildKind ();
845 if (prev_children_kind == ChildrenKind.NONE ||
846 prev_children_kind == ChildrenKind.PROPERTIES){
847 string prev_tag_id = controls.PeekTagID ();
848 throw new ApplicationException ("Child controls not allowed for " + prev_tag_id);
852 if (prev_children_kind == ChildrenKind.DBCOLUMNS &&
853 !typeof (DataGridColumn).IsAssignableFrom (control_type)) {
854 allowed = typeof (DataGridColumn);
855 } else if (prev_children_kind == ChildrenKind.LISTITEM &&
856 control_type != typeof (System.Web.UI.WebControls.ListItem)) {
857 allowed = typeof (DataGridColumn);
858 } else if (prev_children_kind == ChildrenKind.HTMLROW) {
859 Type prevType = controls.PeekType ();
860 if (prevType == typeof (HtmlTable) && control_type != typeof (HtmlTableRow))
861 allowed = typeof (HtmlTableRow);
862 else if (prevType == typeof (Table) && control_type != typeof (TableRow))
863 allowed = typeof (TableRow);
864 } else if (prev_children_kind == ChildrenKind.HTMLCELL) {
865 Type prevType = controls.PeekType ();
866 if (prevType == typeof (HtmlTableRow) && control_type != typeof (HtmlTableCell))
867 allowed = typeof (HtmlTableCell);
868 else if (prevType == typeof (TableRow) && control_type != typeof (TableCell))
869 allowed = typeof (TableCell);
873 throw new ApplicationException ("Inside " + controls.PeekTagID () + " only " +
874 allowed + " objects are allowed");
876 StringBuilder func_code = new StringBuilder ();
877 current_function = func_code;
878 if (0 == String.Compare (tag_id, "form", true)){
880 throw new ApplicationException ("Only one form server tag allowed.");
884 controls.Push (control_type, control_id, tag_id, children_kind, defaultPropertyName);
885 bool is_generic = control_type == typeof (System.Web.UI.HtmlControls.HtmlGenericControl);
886 functions.Push (current_function);
887 if (control_type != typeof (System.Web.UI.WebControls.ListItem) &&
888 prev_children_kind != ChildrenKind.DBCOLUMNS) {
889 current_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_" +
890 "{0} ()\n\t\t{{\n\t\t\t{1} __ctrl;\n\n\t\t\t__ctrl" +
891 " = new {1} ({2});\n\t\t\tthis.{0} = __ctrl;\n",
892 control_id, control_type,
893 (is_generic? "\"" + tag_id + "\"" : ""));
895 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ()\n\t\t{{" +
896 "\n\t\t\t{1} __ctrl;\n\t\t\t__ctrl = new {1} ();" +
897 "\n\t\t\tthis.{0} = __ctrl;\n",
898 control_id, control_type);
901 if (children_kind == ChildrenKind.CONTROLS || children_kind == ChildrenKind.OPTION)
902 current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
903 "(System.Web.UI.IParserAccessor) __ctrl;\n");
906 private void DataBoundProperty (Type target, string varName, string value)
909 throw new ApplicationException ("Empty data binding tag.");
911 string control_id = controls.PeekControlID ();
912 string control_type_string = controls.PeekType ().ToString ();
913 StringBuilder db_function = controls.DataBindFunction;
915 if (controls.Container == null || !typeof (INamingContainer).IsAssignableFrom (controls.Container))
916 container = "System.Web.UI.Control";
918 container = controls.Container.ToString ();
921 if (db_function.Length == 0)
922 db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
923 "System.EventArgs e) {{\n" +
924 "\t\t\t{1} Container;\n" +
925 "\t\t\t{2} target;\n" +
926 "\t\t\ttarget = ({2}) sender;\n" +
927 "\t\t\tContainer = ({1}) target.BindingContainer;\n",
928 control_id, container, control_type_string);
930 /* Removes '<%#' and '%>' */
931 string real_value = value.Remove (0,3);
932 real_value = real_value.Remove (real_value.Length - 2, 2);
933 real_value = real_value.Trim ();
935 if (target == typeof (string))
936 db_function.AppendFormat ("\t\t\ttarget.{0} = System.Convert.ToString ({1});\n",
937 varName, real_value);
939 db_function.AppendFormat ("\t\t\ttarget.{0} = ({1}) ({2});\n",
940 varName, target, real_value);
944 * Returns true if it generates some code for the specified property
946 private void AddCodeForPropertyOrField (Type type, string var_name, string att, bool isDataBound)
948 /* FIXME: should i check for this or let the compiler fail?
949 * if (!prop.CanWrite)
953 DataBoundProperty (type, var_name, att);
955 else if (type == typeof (string)){
957 throw new ApplicationException ("null value for attribute " + var_name );
959 current_function.AppendFormat ("\t\t\t__ctrl.{0} = \"{1}\";\n", var_name,
960 Escape (att)); // FIXME: really Escape this?
962 else if (type.IsEnum){
964 throw new ApplicationException ("null value for attribute " + var_name );
966 string enum_value = EnumValueNameToString (type, att);
968 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, enum_value);
970 else if (type == typeof (bool)){
973 value = "true"; //FIXME: is this ok for non Style properties?
974 else if (0 == String.Compare (att, "true", true))
976 else if (0 == String.Compare (att, "false", true))
979 throw new ApplicationException ("Value '" + att + "' is not a valid boolean.");
981 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
983 else if (type == typeof (System.Web.UI.WebControls.Unit)){
984 //FIXME: should use the culture specified in Page
986 Unit value = Unit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
987 } catch (Exception) {
988 throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
990 current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
991 "System.Web.UI.WebControls.Unit.Parse (\"{1}\", " +
992 "System.Globalization.CultureInfo.InvariantCulture);\n",
995 else if (type == typeof (System.Web.UI.WebControls.FontUnit)){
996 //FIXME: should use the culture specified in Page
998 FontUnit value = FontUnit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
999 } catch (Exception) {
1000 throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
1002 current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
1003 "System.Web.UI.WebControls.FontUnit.Parse (\"{1}\", " +
1004 "System.Globalization.CultureInfo.InvariantCulture);\n",
1007 else if (type == typeof (Int16) || type == typeof (Int32) || type == typeof (Int64)) {
1010 value = Int64.Parse (att); //FIXME: should use the culture specified in Page
1011 } catch (Exception){
1012 throw new ApplicationException (att + " is not a valid signed number " +
1013 "or is out of range.");
1016 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1018 else if (type == typeof (UInt16) || type == typeof (UInt32) || type == typeof (UInt64)) {
1021 value = UInt64.Parse (att); //FIXME: should use the culture specified in Page
1022 } catch (Exception){
1023 throw new ApplicationException (att + " is not a valid unsigned number " +
1024 "or is out of range.");
1027 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1029 else if (type == typeof (float)) {
1032 value = Single.Parse (att);
1033 } catch (Exception){
1034 throw new ApplicationException (att + " is not avalid float number or " +
1035 "is out of range.");
1038 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1040 else if (type == typeof (double)){
1043 value = Double.Parse (att);
1044 } catch (Exception){
1045 throw new ApplicationException (att + " is not avalid double number or " +
1046 "is out of range.");
1049 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1051 else if (type == typeof (System.Drawing.Color)){
1054 c = (Color) TypeDescriptor.GetConverter (typeof (Color)).ConvertFromString (att);
1055 } catch (Exception e){
1056 throw new ApplicationException ("Color " + att + " is not a valid color.", e);
1059 // Should i also test for IsSystemColor?
1060 // Are KnownColor members in System.Drawing.Color?
1061 if (c.IsKnownColor){
1062 current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
1063 "{1};\n", var_name, c.Name);
1066 current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
1067 "FromArgb ({1}, {2}, {3}, {4});\n",
1068 var_name, c.A, c.R, c.G, c.B);
1071 else if (type == typeof (string [])) {
1072 string [] subStrings = att.Split (',');
1073 current_function.AppendFormat ("\t\t\t__ctrl.{0} = new String [] {{\n", var_name);
1074 int end = subStrings.Length;
1075 for (int i = 0; i < end; i++) {
1076 string s = subStrings [i].Trim ();
1077 current_function.AppendFormat ("\t\t\t\t\"{0}\"", s);
1079 current_function.Append ("\t\t\t\t};\n");
1081 current_function.Append (",\n");
1084 throw new ApplicationException ("Unsupported type in property: " +
1089 private bool ProcessPropertiesAndFields (MemberInfo member, string id, TagAttributes att)
1091 int hyphen = id.IndexOf ('-');
1093 bool isPropertyInfo = (member is PropertyInfo);
1095 bool is_processed = false;
1096 bool isDataBound = att.IsDataBound ((string) att [id]);
1098 if (isPropertyInfo) {
1099 type = ((PropertyInfo) member).PropertyType;
1100 if (hyphen == -1 && ((PropertyInfo) member).CanWrite == false)
1103 type = ((FieldInfo) member).FieldType;
1106 if (0 == String.Compare (member.Name, id, true)){
1107 AddCodeForPropertyOrField (type, member.Name, (string) att [id], isDataBound);
1108 is_processed = true;
1109 } else if (hyphen != -1 && (type == fontinfoType || type == styleType || type.IsSubclassOf (styleType))){
1110 string prop_field = id.Replace ("-", ".");
1111 string [] parts = prop_field.Split (new char [] {'.'});
1112 if (parts.Length != 2 || 0 != String.Compare (member.Name, parts [0], true))
1115 PropertyInfo [] subprops = type.GetProperties ();
1116 foreach (PropertyInfo subprop in subprops){
1117 if (0 != String.Compare (subprop.Name, parts [1], true))
1120 if (subprop.CanWrite == false)
1123 bool is_bool = subprop.PropertyType == typeof (bool);
1124 if (!is_bool && att [id] == null){
1125 att [id] = ""; // Font-Size -> Font-Size="" as html
1130 if (att [id] == null && is_bool)
1131 value = "true"; // Font-Bold <=> Font-Bold="true"
1133 value = (string) att [id];
1135 AddCodeForPropertyOrField (subprop.PropertyType,
1136 member.Name + "." + subprop.Name,
1137 value, isDataBound);
1138 is_processed = true;
1142 return is_processed;
1145 private void AddCodeForAttributes (Type type, TagAttributes att)
1147 EventInfo [] ev_info = type.GetEvents ();
1148 PropertyInfo [] prop_info = type.GetProperties ();
1149 FieldInfo [] field_info = type.GetFields ();
1150 bool is_processed = false;
1151 ArrayList processed = new ArrayList ();
1153 foreach (string id in att.Keys){
1154 if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
1157 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
1158 string id_as_event = id.Substring (2);
1159 foreach (EventInfo ev in ev_info){
1160 if (0 == String.Compare (ev.Name, id_as_event, true)){
1161 current_function.AppendFormat (
1162 "\t\t\t__ctrl.{0} += " +
1163 "new {1} (this.{2});\n",
1164 ev.Name, ev.EventHandlerType, att [id]);
1165 is_processed = true;
1170 is_processed = false;
1175 foreach (PropertyInfo prop in prop_info){
1176 is_processed = ProcessPropertiesAndFields (prop, id, att);
1181 if (!is_processed) {
1182 foreach (FieldInfo field in field_info){
1183 is_processed = ProcessPropertiesAndFields (field, id, att);
1190 is_processed = false;
1194 current_function.AppendFormat ("\t\t\t((System.Web.UI.IAttributeAccessor) __ctrl)." +
1195 "SetAttribute (\"{0}\", \"{1}\");\n",
1196 id, Escape ((string) att [id]));
1200 private void AddCodeRenderControl (StringBuilder function)
1202 AddCodeRenderControl (function, controls.CodeRenderIndex);
1205 private void AddCodeRenderControl (StringBuilder function, int index)
1207 function.AppendFormat ("\t\t\tparameterContainer.Controls [{0}]." +
1208 "RenderControl (__output);\n", index);
1211 private void AddRenderMethodDelegate (StringBuilder function, string control_id)
1213 function.AppendFormat ("\t\t\t__ctrl.SetRenderMethodDelegate (new System.Web." +
1214 "UI.RenderMethod (this.__Render_{0}));\n", control_id);
1217 private void AddCodeRenderFunction (string codeRender, string control_id)
1219 StringBuilder codeRenderFunction = new StringBuilder ();
1220 codeRenderFunction.AppendFormat ("\t\tprivate void __Render_{0} " +
1221 "(System.Web.UI.HtmlTextWriter __output, " +
1222 "System.Web.UI.Control parameterContainer)\n" +
1223 "\t\t{{\n", control_id);
1224 codeRenderFunction.Append (codeRender);
1225 codeRenderFunction.Append ("\t\t}\n\n");
1226 init_funcs.Append (codeRenderFunction);
1229 private void RemoveLiterals (StringBuilder function)
1231 string no_literals = Regex.Replace (function.ToString (),
1232 @"\t\t\t__parser.AddParsedSubObject \(" +
1233 @"new System.Web.UI.LiteralControl \(.+\);\n", "");
1234 function.Length = 0;
1235 function.Append (no_literals);
1238 private bool FinishControlFunction (string tag_id)
1240 if (functions.Count == 0)
1241 throw new ApplicationException ("Unbalanced open/close tags");
1243 if (controls.Count == 0)
1246 string saved_id = controls.PeekTagID ();
1247 if (0 != String.Compare (saved_id, tag_id, true))
1251 StringBuilder old_function = (StringBuilder) functions.Pop ();
1252 current_function = (StringBuilder) functions.Peek ();
1254 string control_id = controls.PeekControlID ();
1255 Type control_type = controls.PeekType ();
1256 ChildrenKind child_kind = controls.PeekChildKind ();
1258 bool hasDataBindFunction = controls.HasDataBindFunction ();
1259 if (hasDataBindFunction)
1260 old_function.AppendFormat ("\t\t\t__ctrl.DataBinding += new System.EventHandler " +
1261 "(this.__DataBind_{0});\n", control_id);
1263 bool useCodeRender = controls.UseCodeRender;
1265 AddRenderMethodDelegate (old_function, control_id);
1267 if (control_type == typeof (System.Web.UI.ITemplate)){
1268 old_function.Append ("\n\t\t}\n\n");
1269 current_function.AppendFormat ("\t\t\t__ctrl.{0} = new System.Web.UI." +
1270 "CompiledTemplateBuilder (new System.Web.UI." +
1271 "BuildTemplateMethod (this.__BuildControl_{1}));\n",
1272 saved_id, control_id);
1274 else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumnCollection)){
1275 old_function.Append ("\n\t\t}\n\n");
1276 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
1277 control_id, saved_id);
1279 else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumn) ||
1280 control_type.IsSubclassOf (typeof (System.Web.UI.WebControls.DataGridColumn)) ||
1281 control_type == typeof (System.Web.UI.WebControls.ListItem)){
1282 old_function.Append ("\n\t\t}\n\n");
1284 string ctrl_name = "ctrl";
1285 Type cont = controls.Container;
1286 if (cont == null || cont == typeof (System.Web.UI.HtmlControls.HtmlSelect)){
1287 parsed = "ParsedSubObject";
1288 ctrl_name = "parser";
1291 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
1292 "\t\t\t__{1}.Add{2} (this.{0});\n\n",
1293 control_id, ctrl_name, parsed);
1295 else if (child_kind == ChildrenKind.LISTITEM){
1296 old_function.Append ("\n\t\t}\n\n");
1297 init_funcs.Append (old_function); // Closes the BuildList function
1298 old_function = (StringBuilder) functions.Pop ();
1299 current_function = (StringBuilder) functions.Peek ();
1300 old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
1301 "return __ctrl;\n\t\t}}\n\n",
1302 control_id, controls.PeekDefaultPropertyName ());
1305 control_id = controls.PeekControlID ();
1306 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1307 "AddParsedSubObject (this.{0});\n\n", control_id);
1308 } else if (control_type == typeof (HtmlTableCell) || control_type == typeof (TableCell)) {
1309 old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1310 object top = controls.Pop ();
1311 Type t = controls.PeekType ();
1312 controls.Push (top);
1314 string ctrl_name = "ctrl";
1315 if (!t.IsSubclassOf (typeof (WebControl)) && t != typeof (HtmlTableRow)) {
1316 parsed = "ParsedSubObject";
1317 ctrl_name = "parser";
1320 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
1321 "\t\t\t__{1}.Add{2} (this.{0});\n\n",
1322 control_id, ctrl_name, parsed);
1323 } else if (child_kind == ChildrenKind.HTMLROW || child_kind == ChildrenKind.HTMLCELL) {
1324 old_function.Append ("\n\t\t}\n\n");
1325 init_funcs.Append (old_function);
1326 old_function = (StringBuilder) functions.Pop ();
1327 current_function = (StringBuilder) functions.Peek ();
1328 old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
1329 "return __ctrl;\n\t\t}}\n\n",
1330 control_id, controls.PeekDefaultPropertyName ());
1333 control_id = controls.PeekControlID ();
1334 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n", control_id);
1335 if (child_kind == ChildrenKind.HTMLROW) {
1336 current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject ({0});\n",
1339 current_function.AppendFormat ("\t\t\t__ctrl.Add (this.{0});\n", control_id);
1342 old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1343 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1344 "AddParsedSubObject (this.{0});\n\n", control_id);
1348 RemoveLiterals (old_function);
1350 init_funcs.Append (old_function);
1352 AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), control_id);
1354 if (hasDataBindFunction){
1355 StringBuilder db_function = controls.DataBindFunction;
1356 db_function.Append ("\t\t}\n\n");
1357 init_funcs.Append (db_function);
1360 // Avoid getting empty stacks for unbalanced open/close tags
1361 if (controls.Count > 1){
1363 AddCodeRenderControl (controls.CodeRenderFunction, controls.ChildIndex);
1369 private void NewTableElementFunction (HtmlControlTag ctrl)
1371 string control_id = Tag.GetDefaultID ();
1372 ChildrenKind child_kind;
1375 if (ctrl.ControlType == typeof (HtmlTable)) {
1376 t = typeof (HtmlTableRowCollection);
1377 child_kind = ChildrenKind.HTMLROW;
1379 t = typeof (HtmlTableCellCollection);
1380 child_kind = ChildrenKind.HTMLCELL;
1383 controls.Push (ctrl.ControlType,
1387 ctrl.ParseChildren);
1389 current_function = new StringBuilder ();
1390 functions.Push (current_function);
1391 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
1392 "\t\t{{\n", control_id, t);
1395 private void ProcessHtmlControlTag ()
1398 HtmlControlTag html_ctrl = (HtmlControlTag) current;
1399 if (html_ctrl.TagID.ToUpper () == "SCRIPT"){
1400 //FIXME: if the is script is to be read from disk, do it!
1401 if (html_ctrl.SelfClosing)
1402 throw new ApplicationException ("Read script from file not supported yet.");
1404 sstatus = ScriptStatus.Open;
1409 throw new ApplicationException (app_file_wrong);
1411 Type controlType = html_ctrl.ControlType;
1412 AddProtectedField (controlType, html_ctrl.ControlID);
1414 ChildrenKind children_kind;
1415 if (0 == String.Compare (html_ctrl.TagID, "table", true))
1416 children_kind = ChildrenKind.HTMLROW;
1417 else if (0 == String.Compare (html_ctrl.TagID, "tr", true))
1418 children_kind = ChildrenKind.HTMLCELL;
1419 else if (0 != String.Compare (html_ctrl.TagID, "select", true))
1420 children_kind = html_ctrl.IsContainer ? ChildrenKind.CONTROLS :
1423 children_kind = ChildrenKind.OPTION;
1425 NewControlFunction (html_ctrl.TagID, html_ctrl.ControlID, controlType, children_kind, html_ctrl.ParseChildren);
1427 current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", html_ctrl.ControlID);
1428 AddCodeForAttributes (html_ctrl.ControlType, html_ctrl.Attributes);
1430 if (children_kind == ChildrenKind.HTMLROW || children_kind == ChildrenKind.HTMLCELL)
1431 NewTableElementFunction (html_ctrl);
1433 if (html_ctrl.SelfClosing)
1434 FinishControlFunction (html_ctrl.TagID);
1437 // Closing is performed in FinishControlFunction ()
1438 private void NewBuildListFunction (AspComponent component)
1440 string control_id = Tag.GetDefaultID ();
1442 controls.Push (component.ComponentType,
1445 component.ChildrenKind,
1446 component.DefaultPropertyName);
1448 Type childType = component.DefaultPropertyType;
1449 if (childType == null)
1450 childType = typeof (ListItemCollection);
1452 current_function = new StringBuilder ();
1453 functions.Push (current_function);
1454 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1456 "\t\t{{\n", control_id, childType);
1459 private void ProcessComponent ()
1462 AspComponent component = (AspComponent) current;
1463 Type component_type = component.ComponentType;
1464 AddProtectedField (component_type, component.ControlID);
1466 NewControlFunction (component.TagID, component.ControlID, component_type,
1467 component.ChildrenKind, component.DefaultPropertyName);
1469 if (component_type == typeof (UserControl) ||
1470 component_type.IsSubclassOf (typeof (System.Web.UI.UserControl)))
1471 current_function.Append ("\t\t\t__ctrl.InitializeAsUserControl (Page);\n");
1473 if (component_type == typeof (Control) ||
1474 component_type.IsSubclassOf (typeof (System.Web.UI.Control)))
1475 current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", component.ControlID);
1477 AddCodeForAttributes (component.ComponentType, component.Attributes);
1478 if (component.ChildrenKind == ChildrenKind.LISTITEM || component.DefaultPropertyType != null)
1479 NewBuildListFunction (component);
1481 if (component.SelfClosing)
1482 FinishControlFunction (component.TagID);
1485 private void ProcessServerObjectTag ()
1488 ServerObjectTag obj = (ServerObjectTag) current;
1489 declarations.AppendFormat ("\t\tprivate {0} cached{1};\n", obj.ObjectClass, obj.ObjectID);
1490 constructor.AppendFormat ("\n\t\tprivate {0} {1}\n\t\t{{\n\t\t\tget {{\n\t\t\t\t" +
1491 "if (this.cached{1} == null)\n\t\t\t\t\tthis.cached{1} = " +
1492 "new {0} ();\n\t\t\t\treturn cached{1};\n\t\t\t}}\n\t\t}}\n\n",
1493 obj.ObjectClass, obj.ObjectID);
1496 // Creates a new function that sets the values of subproperties.
1497 private void NewStyleFunction (PropertyTag tag)
1499 current_function = new StringBuilder ();
1501 string prop_id = tag.PropertyID;
1502 Type prop_type = tag.PropertyType;
1504 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
1505 "\t\t{{\n", prop_id, prop_type);
1507 // Add property initialization code
1508 PropertyInfo [] subprop_info = prop_type.GetProperties ();
1509 TagAttributes att = tag.Attributes;
1511 string subprop_name = null;
1512 foreach (string id in att.Keys){
1513 if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
1516 bool is_processed = false;
1517 foreach (PropertyInfo subprop in subprop_info){
1518 is_processed = ProcessPropertiesAndFields (subprop, id, att);
1520 subprop_name = subprop.Name;
1525 if (subprop_name == null)
1526 throw new ApplicationException ("Property " + tag.TagID + " does not have " +
1527 "a " + id + " subproperty.");
1531 current_function.Append ("\n\t\t}\n\n");
1532 init_funcs.Append (current_function);
1533 current_function = (StringBuilder) functions.Peek ();
1534 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
1535 prop_id, tag.PropertyName);
1537 if (!tag.SelfClosing){
1538 // Next tag should be the closing tag
1539 controls.Push (null, null, null, ChildrenKind.NONE, null);
1540 waitClosing = tag.TagID;
1544 // This one just opens the function. Closing is performed in FinishControlFunction ()
1545 private void NewTemplateFunction (PropertyTag tag)
1549 * This function does almost the same as NewControlFunction.
1552 string prop_id = tag.PropertyID;
1553 Type prop_type = tag.PropertyType;
1554 string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
1556 controls.Push (prop_type, prop_id, tag_id, ChildrenKind.CONTROLS, null);
1557 current_function = new StringBuilder ();
1558 functions.Push (current_function);
1559 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1560 "(System.Web.UI.Control __ctrl)\n" +
1562 "\t\t\tSystem.Web.UI.IParserAccessor __parser " +
1563 "= (System.Web.UI.IParserAccessor) __ctrl;\n" , prop_id);
1566 // Closing is performed in FinishControlFunction ()
1567 private void NewDBColumnFunction (PropertyTag tag)
1571 * This function also does almost the same as NewControlFunction.
1574 string prop_id = tag.PropertyID;
1575 Type prop_type = tag.PropertyType;
1576 string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
1578 controls.Push (prop_type, prop_id, tag_id, ChildrenKind.DBCOLUMNS, null);
1579 current_function = new StringBuilder ();
1580 functions.Push (current_function);
1581 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1582 "(System.Web.UI.WebControls.DataGridColumnCollection __ctrl)\n" +
1583 "\t\t{{\n", prop_id);
1586 private void NewPropertyFunction (PropertyTag tag)
1589 if (tag.PropertyType == typeof (System.Web.UI.WebControls.Style) ||
1590 tag.PropertyType.IsSubclassOf (typeof (System.Web.UI.WebControls.Style)))
1591 NewStyleFunction (tag);
1592 else if (tag.PropertyType == typeof (System.Web.UI.ITemplate))
1593 NewTemplateFunction (tag);
1594 else if (tag.PropertyType == typeof (System.Web.UI.WebControls.DataGridColumnCollection))
1595 NewDBColumnFunction (tag);
1597 throw new ApplicationException ("Other than Style and ITemplate not supported yet. " +
1601 private void ProcessHtmlTag ()
1603 Tag tag = (Tag) current;
1604 ChildrenKind child_kind = controls.PeekChildKind ();
1605 if (child_kind == ChildrenKind.NONE){
1606 string tag_id = controls.PeekTagID ();
1607 throw new ApplicationException (tag + " not allowed inside " + tag_id);
1610 if (child_kind == ChildrenKind.OPTION){
1611 if (0 != String.Compare (tag.TagID, "option", true))
1612 throw new ApplicationException ("Only <option> tags allowed inside <select>.");
1614 string default_id = Tag.GetDefaultID ();
1615 Type type = typeof (System.Web.UI.WebControls.ListItem);
1616 AddProtectedField (type, default_id);
1617 NewControlFunction (tag.TagID, default_id, type, ChildrenKind.CONTROLS, null);
1621 if (child_kind == ChildrenKind.CONTROLS) {
1622 ArrayList tag_elements = tag.GetElements ();
1623 foreach (Element e in tag_elements) {
1624 if (e is PlainText) {
1626 textChunk.Append (((PlainText) e).Text);
1627 } else if (e is CodeRenderTag) {
1629 ProcessCodeRenderTag ();
1630 } else if (e is DataBindingTag) {
1632 ProcessDataBindingLiteral ();
1634 throw new ApplicationException (fullPath + ": unexpected tag type " + e.GetType ());
1640 if (child_kind == ChildrenKind.HTMLROW) {
1641 if (0 == String.Compare (tag.TagID, "tr", true)) {
1642 current = new HtmlControlTag (tag);
1643 ProcessHtmlControlTag ();
1648 if (child_kind == ChildrenKind.HTMLCELL) {
1649 if (0 == String.Compare (tag.TagID, "td", true)) {
1650 current = new HtmlControlTag (tag);
1651 ProcessHtmlControlTag ();
1656 // Now child_kind should be PROPERTIES, so only allow tag_id == property
1657 Type control_type = controls.PeekType ();
1658 PropertyInfo [] prop_info = control_type.GetProperties ();
1659 bool is_processed = false;
1660 foreach (PropertyInfo prop in prop_info){
1661 if (0 == String.Compare (prop.Name, tag.TagID, true)){
1662 PropertyTag prop_tag = new PropertyTag (tag, prop.PropertyType, prop.Name);
1663 NewPropertyFunction (prop_tag);
1664 is_processed = true;
1670 string tag_id = controls.PeekTagID ();
1671 throw new ApplicationException (tag.TagID + " is not a property of " + control_type);
1675 private Tag Map (Tag tag)
1677 int pos = tag.TagID.IndexOf (":");
1679 ChildrenKind child_kind = controls.PeekChildKind ();
1680 if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
1681 tag.Attributes.Add ("runat", "server");
1682 return new HtmlControlTag (tag);
1683 } else if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
1684 tag.Attributes.Add ("runat", "server");
1685 return new HtmlControlTag (tag);
1689 if (tag is CloseTag ||
1690 ((tag.Attributes == null ||
1691 !tag.Attributes.IsRunAtServer ()) && pos == -1))
1695 if (0 == String.Compare (tag.TagID, "object", true))
1696 return new ServerObjectTag (tag);
1698 return new HtmlControlTag (tag);
1701 string foundry_name = tag.TagID.Substring (0, pos);
1702 string component_name = tag.TagID.Substring (pos + 1);
1704 if (Foundry.LookupFoundry (foundry_name) == false)
1705 throw new ApplicationException ("Cannot find foundry for alias'" + foundry_name + "'");
1707 AspComponent component = Foundry.MakeAspComponent (foundry_name, component_name, tag);
1708 if (component == null)
1709 throw new ApplicationException ("Cannot find component '" + component_name +
1710 "' for alias '" + foundry_name + "'");
1715 private void ProcessCloseTag ()
1717 CloseTag closeTag = (CloseTag) current;
1718 if (FinishControlFunction (closeTag.TagID))
1721 textChunk.Append (closeTag.PlainHtml);
1724 private void ProcessDataBindingLiteral ()
1727 DataBindingTag dataBinding = (DataBindingTag) current;
1728 string actual_value = dataBinding.Data;
1729 if (actual_value == "")
1730 throw new ApplicationException ("Empty data binding tag.");
1732 if (controls.PeekChildKind () != ChildrenKind.CONTROLS)
1733 throw new ApplicationException ("Data bound content not allowed for " +
1734 controls.PeekTagID ());
1736 StringBuilder db_function = new StringBuilder ();
1737 string control_id = Tag.GetDefaultID ();
1738 string control_type_string = "System.Web.UI.DataBoundLiteralControl";
1739 AddProtectedField (typeof (System.Web.UI.DataBoundLiteralControl), control_id);
1740 // Build the control
1741 db_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_{0} ()\n" +
1742 "\t\t{{\n\t\t\t{1} __ctrl;\n\n" +
1743 "\t\t\t__ctrl = new {1} (0, 1);\n" +
1744 "\t\t\tthis.{0} = __ctrl;\n" +
1745 "\t\t\t__ctrl.DataBinding += new System.EventHandler " +
1746 "(this.__DataBind_{0});\n" +
1747 "\t\t\treturn __ctrl;\n"+
1749 control_id, control_type_string);
1750 // DataBinding handler
1751 db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
1752 "System.EventArgs e) {{\n" +
1753 "\t\t\t{1} Container;\n" +
1754 "\t\t\t{2} target;\n" +
1755 "\t\t\ttarget = ({2}) sender;\n" +
1756 "\t\t\tContainer = ({1}) target.BindingContainer;\n" +
1757 "\t\t\ttarget.SetDataBoundString (0, System.Convert." +
1758 "ToString ({3}));\n" +
1760 control_id, controls.Container, control_type_string,
1763 init_funcs.Append (db_function);
1764 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1765 "AddParsedSubObject (this.{0});\n\n", control_id);
1767 AddCodeRenderControl (controls.CodeRenderFunction);
1770 private void ProcessCodeRenderTag ()
1773 CodeRenderTag code_tag = (CodeRenderTag) current;
1775 controls.UseCodeRender = true;
1776 if (code_tag.IsVarName)
1777 controls.CodeRenderFunction.AppendFormat ("\t\t\t__output.Write ({0});\n",
1780 controls.CodeRenderFunction.AppendFormat ("\t\t\t{0}\n", code_tag.Code);
1783 void FlushPlainText ()
1785 if (textChunk.Length != 0) {
1786 Element saved = current;
1787 current = new PlainText (textChunk.ToString ());
1788 textChunk.Length = 0;
1789 ProcessPlainText ();
1794 void ParseError (string msg, int line, int col)
1796 throw new ParseException (fullPath, msg, line, col);
1799 void TagParsed (Tag tag, int line, int col)
1801 if (waitClosing != null) {
1802 if (!(tag is CloseTag) || tag.TagID.ToUpper () != waitClosing.ToUpper ())
1803 throw new HttpException ("Tag " + waitClosing + " not properly closed.");
1810 if ((sstatus == ScriptStatus.Open || sstatus == ScriptStatus.Text) &&
1811 tag.TagID.ToUpper () == "SCRIPT" && tag is CloseTag) {
1812 sstatus = ScriptStatus.Close;
1818 if (current is Directive) {
1819 ProcessDirective ();
1821 } else if (current is DataBindingTag) {
1823 throw new ApplicationException (app_file_wrong);
1825 ProcessDataBindingLiteral ();
1827 } else if (current is CodeRenderTag) {
1829 throw new ApplicationException (app_file_wrong);
1831 ProcessCodeRenderTag ();
1835 current = Map (tag);
1837 if (current is ServerObjectTag) {
1838 ProcessServerObjectTag ();
1840 } else if (current is HtmlControlTag) {
1841 ProcessHtmlControlTag ();
1846 throw new ApplicationException (app_file_wrong);
1848 if (current is AspComponent) {
1849 ProcessComponent ();
1850 } else if (current is CloseTag) {
1852 } else if (current is Tag) {
1855 throw new HttpException ("This place should not be reached.");
1859 void TextParsed (string text, int line, int col)
1861 if (sstatus == ScriptStatus.Open) {
1862 script.Append (text);
1863 sstatus = ScriptStatus.Text;
1867 textChunk.Append (text);
1870 public void ProcessElements ()
1872 AspParser parser = new AspParser (fullPath, File.OpenRead (fullPath));
1874 parser.Error += new ParseErrorHandler (ParseError);
1875 parser.TagParsed += new TagParsedHandler (TagParsed);
1876 parser.TextParsed += new TextParsedHandler (TextParsed);
1880 } catch (CompilationException e) {
1882 } catch (ParseException e) {
1884 } catch (Exception e) {
1885 throw new ParseException (fullPath, e.Message, parser.Line, parser.Column, e);
1892 private string GetTemplateDirectory ()
1894 string templatePath = Path.GetDirectoryName (fullPath);
1895 string appPath = Path.GetDirectoryName (HttpRuntime.AppDomainAppPath);
1897 if (templatePath == appPath)
1900 templatePath = templatePath.Substring (appPath.Length);
1901 if (Path.DirectorySeparatorChar != '/')
1902 templatePath = templatePath.Replace (Path.DirectorySeparatorChar, '/');
1904 return templatePath;
1912 if (sessionState == SessionState.Enabled || sessionState == SessionState.ReadOnly)
1913 AddInterface (typeof (System.Web.SessionState.IRequiresSessionState));
1915 if (sessionState == SessionState.ReadOnly)
1916 AddInterface (typeof (System.Web.SessionState.IReadOnlySessionState));
1919 classDecl = "\tpublic class " + className + " : " + parent + interfaces + " {\n";
1920 prolog.Append ("\n" + classDecl);
1921 declarations.Append ("\t\tprivate static bool __intialized = false;\n\n");
1923 declarations.Append ("\t\tprivate static ArrayList __fileDependencies;\n\n");
1925 // adds the constructor
1926 constructor.AppendFormat ("\t\tpublic {0} ()\n\t\t{{\n", className);
1928 constructor.Append ("\t\t\tSystem.Collections.ArrayList dependencies;\n\n");
1930 constructor.AppendFormat ("\t\t\tif (ASP.{0}.__intialized == false){{\n", className);
1933 constructor.AppendFormat ("\t\t\t\tdependencies = new System.Collections.ArrayList ();\n" +
1934 "\t\t\t\tdependencies.Add (@\"{1}\");\n" +
1935 "\t\t\t\tASP.{0}.__fileDependencies = dependencies;\n",
1936 className, fullPath);
1939 constructor.AppendFormat ("\t\t\t\tASP.{0}.__intialized = true;\n\t\t\t}}\n\t\t}}\n\n",
1942 if (!IsApplication) {
1943 //FIXME: add AutoHandlers: don't know what for...yet!
1944 constructor.AppendFormat (
1945 "\t\tprotected override int AutoHandlers\n\t\t{{\n" +
1946 "\t\t\tget {{ return ASP.{0}.__autoHandlers; }}\n" +
1947 "\t\t\tset {{ ASP.{0}.__autoHandlers = value; }}\n" +
1948 "\t\t}}\n\n", className);
1950 constructor.Append (
1951 "\t\tprotected System.Web.HttpApplication ApplicationInstance\n\t\t{\n" +
1952 "\t\t\tget { return (System.Web.HttpApplication) this.Context.ApplicationInstance; }\n" +
1955 constructor.AppendFormat (
1956 "\t\tpublic override string TemplateSourceDirectory\n\t\t{{\n" +
1957 "\t\t\tget {{ return \"{0}\"; }}\n" +
1958 "\t\t}}\n\n", GetTemplateDirectory ());
1960 epilog.Append ("\n\t\tprotected override void FrameworkInitialize ()\n\t\t{\n" +
1961 "\t\t\tthis.__BuildControlTree (this);\n");
1964 epilog.AppendFormat ("\t\t\tthis.FileDependencies = ASP.{0}.__fileDependencies;\n" +
1965 "\t\t\tthis.EnableViewStateMac = true;\n", className);
1968 epilog.Append ("\t\t}\n\n");
1972 Random rnd = new Random ();
1973 epilog.AppendFormat ("\t\tpublic override int GetTypeHashCode ()\n\t\t{{\n" +
1974 "\t\t\treturn {0};\n" +
1975 "\t\t}}\n", rnd.Next ());
1978 epilog.Append ("\t}\n}\n");
1980 // Closes the currently opened tags
1981 StringBuilder old_function = current_function;
1983 while (functions.Count > 1){
1984 old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1985 init_funcs.Append (old_function);
1986 control_id = controls.PeekControlID ();
1987 FinishControlFunction (control_id);
1988 controls.AddChild ();
1989 old_function = (StringBuilder) functions.Pop ();
1990 current_function = (StringBuilder) functions.Peek ();
1994 bool useCodeRender = controls.UseCodeRender;
1996 RemoveLiterals (current_function);
1997 AddRenderMethodDelegate (current_function, controls.PeekControlID ());
2000 current_function.Append ("\t\t}\n\n");
2001 init_funcs.Append (current_function);
2003 AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), controls.PeekControlID ());
2009 // Functions related to compilation of user controls
2012 private static char dirSeparator = Path.DirectorySeparatorChar;
2013 struct UserControlData
2015 public UserControlResult result;
2016 public string className;
2017 public string assemblyName;
2020 private static UserControlData GenerateUserControl (string src, HttpContext context)
2022 UserControlData data = new UserControlData ();
2023 data.result = UserControlResult.OK;
2025 UserControlCompiler compiler = new UserControlCompiler (new UserControlParser (src, context));
2026 Type t = compiler.GetCompiledType ();
2028 data.result = UserControlResult.CompilationFailed;
2032 data.className = t.Name;
2033 data.assemblyName = compiler.TargetFile;