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;
306 ArrayList dependencies;
310 SessionState sessionState = SessionState.Enabled;
312 static Type styleType = typeof (System.Web.UI.WebControls.Style);
313 static Type fontinfoType = typeof (System.Web.UI.WebControls.FontInfo);
315 enum UserControlResult
319 CompilationFailed = 2
329 public AspGenerator (string pathToFile)
331 if (pathToFile == null)
332 throw new ArgumentNullException ("pathToFile");
334 string filename = Path.GetFileName (pathToFile);
335 this.className = filename.Replace ('.', '_'); // Overridden by @ Page classname
336 this.className = className.Replace ('-', '_');
337 this.className = className.Replace (' ', '_');
338 Options ["ClassName"] = this.className;
339 this.fullPath = Path.GetFullPath (pathToFile);
341 this.has_form_tag = false;
342 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
343 privateBinPath = setup.PrivateBinPath;
344 // This is a hack until we can run stuff in different domains
345 if (privateBinPath == null || privateBinPath.Length == 0)
346 privateBinPath = "bin";
348 if (!Path.IsPathRooted (privateBinPath)) {
349 string appbase = setup.ApplicationBase;
350 if (appbase.StartsWith ("file://"))
351 appbase = appbase.Substring (7);
352 privateBinPath = Path.Combine (appbase, privateBinPath);
358 public string BaseType {
359 get { return basetype; }
366 isUserControl = (basetype == "System.Web.UI.UserControl");
367 isPage = (basetype == "System.Web.UI.Page");
368 isApplication = (basetype == "System.Web.HttpApplication");
372 public bool IsUserControl {
373 get { return isUserControl; }
377 get { return isPage; }
380 public bool IsApplication {
381 get { return isApplication; }
384 public string Interfaces {
385 get { return interfaces; }
388 public Hashtable Options {
391 options = new Hashtable ();
397 public ArrayList Dependencies {
398 get { return dependencies; }
401 internal HttpContext Context {
402 get { return context; }
403 set { context = value; }
406 bool AddUsing (string nspace)
408 string _using = "using " + nspace + ";";
409 if (prolog.ToString ().IndexOf (_using) == -1) {
410 prolog.AppendFormat ("\t{0}\n", _using);
417 void AddInterface (Type type)
419 AddInterface (type.ToString ());
422 public void AddInterface (string iface)
424 if (interfaces == null) {
425 interfaces = ", " + iface;
427 string s = ", " + iface;
428 if (interfaces.IndexOf (s) == -1)
433 private AspComponentFoundry Foundry
436 if (aspFoundry == null)
437 aspFoundry = new AspComponentFoundry ();
445 dependencies = new ArrayList ();
446 dependencies.Add (fullPath);
448 controls = new ControlStack ();
449 controls.Push (typeof (System.Web.UI.Control), "Root", null, ChildrenKind.CONTROLS, null);
450 prolog = new StringBuilder ();
451 declarations = new StringBuilder ();
452 script = new StringBuilder ();
453 constructor = new StringBuilder ();
454 init_funcs = new StringBuilder ();
455 epilog = new StringBuilder ();
456 textChunk = new StringBuilder ();
458 current_function = new StringBuilder ();
459 functions = new Stack ();
460 functions.Push (current_function);
462 parts = new Object [6];
464 parts [1] = declarations;
466 parts [3] = constructor;
467 parts [4] = init_funcs;
470 prolog.Append ("namespace ASP {\n" +
471 "\tusing System;\n" +
472 "\tusing System.Collections;\n" +
473 "\tusing System.Collections.Specialized;\n" +
474 "\tusing System.Configuration;\n" +
475 "\tusing System.IO;\n" +
476 "\tusing System.Text;\n" +
477 "\tusing System.Text.RegularExpressions;\n" +
478 "\tusing System.Web;\n" +
479 "\tusing System.Web.Caching;\n" +
480 "\tusing System.Web.Security;\n" +
481 "\tusing System.Web.SessionState;\n" +
482 "\tusing System.Web.UI;\n" +
483 "\tusing System.Web.UI.WebControls;\n" +
484 "\tusing System.Web.UI.HtmlControls;\n");
486 declarations.Append ("\t\tprivate static int __autoHandlers;\n");
488 current_function.Append ("\t\tprivate void __BuildControlTree (System.Web.UI.Control __ctrl)\n\t\t{\n");
490 current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
491 "(System.Web.UI.IParserAccessor) __ctrl;\n\n");
493 controls.UseCodeRender = true;
496 public TextReader GetCode ()
499 throw new InvalidOperationException ("Parsing not done yet! (may be there were errors?)");
501 StringBuilder code = new StringBuilder ();
502 for (int i = 0; i < parts.Length; i++)
503 code.Append ((StringBuilder) parts [i]);
505 return new StringReader (code.ToString ());
508 // Regex.Escape () make some illegal escape sequences for a C# source.
509 private string Escape (string input)
514 string output = input.Replace ("\\", "\\\\");
515 output = output.Replace ("\"", "\\\"");
516 output = output.Replace ("\t", "\\t");
517 output = output.Replace ("\r", "\\r");
518 output = output.Replace ("\n", "\\n");
519 output = output.Replace ("\n", "\\n");
523 bool AddProtectedField (Type type, string fieldName)
525 if (parentType == null) {
526 declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
530 FieldInfo field = parentType.GetField (fieldName, BindingFlags.Public |
531 BindingFlags.NonPublic |
532 BindingFlags.Instance |
533 BindingFlags.Static);
535 if (field == null || (!field.IsPublic && !field.IsFamily)) {
536 declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
540 if (!field.FieldType.IsAssignableFrom (type)) {
541 string message = String.Format ("The base class includes the field '{0}', but its " +
542 "type '{1}' is not compatible with {2}",
543 fieldName, field.FieldType, type);
545 throw new ApplicationException (message);
551 private Type LoadParentType (string typeName)
553 // First try loaded assemblies, then try assemblies in Bin directory.
554 // By now i do this 'by hand' but may be this is a runtime/gac task.
556 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
557 foreach (Assembly ass in assemblies) {
558 type = ass.GetType (typeName);
564 string [] binDlls = Directory.GetFiles (privateBinPath, "*.dll");
565 foreach (string dll in binDlls) {
566 string dllPath = Path.Combine (privateBinPath, dll);
569 assembly = Assembly.LoadFrom (dllPath);
570 type = assembly.GetType (typeName);
571 } catch (Exception e) {
572 if (assembly != null) {
573 Console.WriteLine ("ASP.NET Warning: assembly {0} loaded", dllPath);
574 Console.WriteLine ("ASP.NET Warning: but type {0} not found", typeName);
576 Console.WriteLine ("ASP.NET Warning: unable to load type {0} from {1}",
579 Console.WriteLine ("ASP.NET Warning: error was: {0}", e.Message);
583 dependencies.Add (dllPath);
591 private void PageDirective (TagAttributes att)
593 if (att ["ClassName"] != null){
594 this.className = (string) att ["ClassName"];
595 Options ["ClassName"] = className;
598 if (att ["EnableSessionState"] != null){
600 throw new ApplicationException ("EnableSessionState not allowed here.");
602 string est = (string) att ["EnableSessionState"];
603 if (0 == String.Compare (est, "false", true))
604 sessionState = SessionState.Disabled;
605 else if (0 == String.Compare (est, "true", true))
606 sessionState = SessionState.Enabled;
607 else if (0 == String.Compare (est, "readonly", true))
608 sessionState = SessionState.ReadOnly;
610 throw new ApplicationException ("EnableSessionState in Page directive not set to " +
611 "a correct value: " + est);
614 if (att ["Inherits"] != null) {
615 parent = (string) att ["Inherits"];
616 parentType = LoadParentType (parent);
617 if (parentType == null)
618 throw new ApplicationException ("The class " + parent + " cannot be found.");
621 if (att ["CompilerOptions"] != null)
622 Options ["CompilerOptions"] = (string) att ["CompilerOptions"];
624 if (att ["AutoEventWireup"] != null) {
625 if (options ["AutoEventWireup"] != null)
626 throw new ApplicationException ("Already have an AutoEventWireup attribute");
628 bool autoevent = true;
629 string v = att ["AutoEventWireup"] as string;
631 autoevent = Convert.ToBoolean (v);
632 } catch (Exception) {
633 throw new ApplicationException ("'" + v + "' is not a valid value for AutoEventWireup");
635 options ["AutoEventWireup"] = autoevent;
638 //FIXME: add support for more attributes.
641 void AddReference (string dll)
643 string references = Options ["References"] as string;
644 if (references == null)
647 references = references + "|" + dll;
649 Options ["References"] = references;
652 private void RegisterDirective (TagAttributes att)
654 string tag_prefix = (string) (att ["tagprefix"] == null ? "" : att ["tagprefix"]);
655 string name_space = (string) (att ["namespace"] == null ? "" : att ["namespace"]);
656 string assembly_name = (string) (att ["assembly"] == null ? "" : att ["assembly"]);
657 string tag_name = (string) (att ["tagname"] == null ? "" : att ["tagname"]);
658 string src = (string) (att ["src"] == null ? "" : att ["src"]);
660 if (tag_prefix != "" && name_space != "" && assembly_name != ""){
661 if (tag_name != "" || src != "")
662 throw new ApplicationException ("Invalid attributes for @ Register: " +
665 AddUsing (name_space);
666 string dll = Path.Combine (privateBinPath, assembly_name + ".dll");
667 // Hack: it should use assembly.load semantics...
668 // may be when we don't run mcs as a external program...
669 if (!File.Exists (dll))
672 dependencies.Add (dll);
674 Foundry.RegisterFoundry (tag_prefix, dll, name_space);
679 if (tag_prefix != "" && tag_name != "" && src != ""){
680 if (name_space != "" && assembly_name != "")
681 throw new ApplicationException ("Invalid attributes for @ Register: " +
684 if (!src.EndsWith (".ascx"))
685 throw new ApplicationException ("Source file extension for controls " +
688 UserControlData data = GenerateUserControl (src, Context);
689 switch (data.result) {
690 case UserControlResult.OK:
692 Foundry.RegisterFoundry (tag_prefix, tag_name, data.assemblyName, "ASP", data.className);
693 AddReference (data.assemblyName);
695 case UserControlResult.FileNotFound:
696 throw new ApplicationException ("File '" + src + "' not found.");
697 case UserControlResult.CompilationFailed:
698 //TODO: should say where the generated .cs file is for the server to
699 //show the source and the compiler error
700 throw new NotImplementedException ();
705 throw new ApplicationException ("Invalid combination of attributes in " +
706 "@ Register: " + att.ToString ());
709 private void ProcessDirective ()
712 Directive directive = (Directive) current;
713 TagAttributes att = directive.Attributes;
718 string id = directive.TagID.ToUpper ();
721 if (main_directive != null)
722 throw new ApplicationException (id + " not allowed after " + main_directive);
725 throw new ApplicationException ("@Application not allowed.");
727 string inherits = att ["inherits"] as string;
728 if (inherits != null)
729 Options ["Inherits"] = inherits;
731 main_directive = directive.TagID;
735 if (main_directive != null)
736 throw new ApplicationException (id + " not allowed after " + main_directive);
738 if (IsUserControl && id != "CONTROL")
739 throw new ApplicationException ("@Page not allowed for user controls.");
740 else if (IsPage && id != "PAGE")
741 throw new ApplicationException ("@Control not allowed here. This is a page!");
744 main_directive = directive.TagID;
747 value = att ["namespace"] as string;
748 if (value == null || att.Count > 1)
749 throw new ApplicationException ("Wrong syntax in Import directive.");
751 string _using = "using " + value + ";";
752 if (AddUsing (value) == true) {
753 string imports = Options ["Import"] as string;
754 if (imports == null) {
757 imports += "," + value;
760 Options ["Import"] = imports;
765 throw new ApplicationException ("@ Implements not allowed in an application file.");
767 string iface = (string) att ["interface"];
768 AddInterface (iface);
772 throw new ApplicationException ("@ Register not allowed in an application file.");
774 RegisterDirective (att);
778 throw new ApplicationException ("Wrong syntax in Assembly directive.");
780 string name = att ["name"] as string;
781 string src = att ["src"] as string;
783 if (name == null && src == null)
784 throw new ApplicationException ("Wrong syntax in Assembly directive.");
786 if (IsApplication && src != null)
787 throw new ApplicationException ("'name' attribute expected.");
789 value = (name == null) ? src : name;
790 string assemblies = Options ["Assembly"] as string;
791 if (assemblies == null) {
794 assemblies += "," + value;
797 Options ["Assembly"] = assemblies;
802 private void ProcessPlainText ()
804 PlainText asis = (PlainText) current;
805 string trimmed = asis.Text.Trim ();
806 if (trimmed == String.Empty && controls.SpaceBetweenTags == true)
810 if (trimmed != String.Empty)
811 throw new ApplicationException (app_file_wrong);
815 if (trimmed != String.Empty && controls.PeekChildKind () != ChildrenKind.CONTROLS){
816 string tag_id = controls.PeekTagID ();
817 throw new ApplicationException ("Literal content not allowed for " + tag_id);
820 string escaped_text = Escape (asis.Text);
821 current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject (" +
822 "new System.Web.UI.LiteralControl (\"{0}\"));\n",
824 StringBuilder codeRenderFunction = controls.CodeRenderFunction;
825 codeRenderFunction.AppendFormat ("\t\t\t__output.Write (\"{0}\");\n", escaped_text);
828 private string EnumValueNameToString (Type enum_type, string value_name)
830 if (value_name.EndsWith ("*"))
831 throw new ApplicationException ("Invalid property value: '" + value_name +
832 ". It must be a valid " + enum_type.ToString () + " value.");
834 MemberInfo [] nested_types = enum_type.FindMembers (MemberTypes.Field,
835 BindingFlags.Public | BindingFlags.Static,
836 Type.FilterNameIgnoreCase,
839 if (nested_types.Length == 0)
840 throw new ApplicationException ("Value " + value_name + " not found in enumeration " +
841 enum_type.ToString ());
842 if (nested_types.Length > 1)
843 throw new ApplicationException ("Value " + value_name + " found " +
844 nested_types.Length + " in enumeration " +
845 enum_type.ToString ());
847 return enum_type.ToString () + "." + nested_types [0].Name;
850 private void NewControlFunction (string tag_id,
853 ChildrenKind children_kind,
854 string defaultPropertyName)
856 ChildrenKind prev_children_kind = controls.PeekChildKind ();
857 if (prev_children_kind == ChildrenKind.NONE ||
858 prev_children_kind == ChildrenKind.PROPERTIES){
859 string prev_tag_id = controls.PeekTagID ();
860 throw new ApplicationException ("Child controls not allowed for " + prev_tag_id);
864 if (prev_children_kind == ChildrenKind.DBCOLUMNS &&
865 !typeof (DataGridColumn).IsAssignableFrom (control_type)) {
866 allowed = typeof (DataGridColumn);
867 } else if (prev_children_kind == ChildrenKind.LISTITEM &&
868 control_type != typeof (System.Web.UI.WebControls.ListItem)) {
869 allowed = typeof (DataGridColumn);
870 } else if (prev_children_kind == ChildrenKind.HTMLROW) {
871 Type prevType = controls.PeekType ();
872 if (prevType == typeof (HtmlTable) && control_type != typeof (HtmlTableRow))
873 allowed = typeof (HtmlTableRow);
874 else if (prevType == typeof (Table) && control_type != typeof (TableRow))
875 allowed = typeof (TableRow);
876 } else if (prev_children_kind == ChildrenKind.HTMLCELL) {
877 Type prevType = controls.PeekType ();
878 if (prevType == typeof (HtmlTableRow) && control_type != typeof (HtmlTableCell))
879 allowed = typeof (HtmlTableCell);
880 else if (prevType == typeof (TableRow) && control_type != typeof (TableCell))
881 allowed = typeof (TableCell);
885 throw new ApplicationException ("Inside " + controls.PeekTagID () + " only " +
886 allowed + " objects are allowed");
888 StringBuilder func_code = new StringBuilder ();
889 current_function = func_code;
890 if (0 == String.Compare (tag_id, "form", true)){
892 throw new ApplicationException ("Only one form server tag allowed.");
896 controls.Push (control_type, control_id, tag_id, children_kind, defaultPropertyName);
897 bool is_generic = control_type == typeof (System.Web.UI.HtmlControls.HtmlGenericControl);
898 functions.Push (current_function);
899 if (control_type != typeof (System.Web.UI.WebControls.ListItem) &&
900 prev_children_kind != ChildrenKind.DBCOLUMNS) {
901 current_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_" +
902 "{0} ()\n\t\t{{\n\t\t\t{1} __ctrl;\n\n\t\t\t__ctrl" +
903 " = new {1} ({2});\n\t\t\tthis.{0} = __ctrl;\n",
904 control_id, control_type,
905 (is_generic? "\"" + tag_id + "\"" : ""));
907 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ()\n\t\t{{" +
908 "\n\t\t\t{1} __ctrl;\n\t\t\t__ctrl = new {1} ();" +
909 "\n\t\t\tthis.{0} = __ctrl;\n",
910 control_id, control_type);
913 if (children_kind == ChildrenKind.CONTROLS || children_kind == ChildrenKind.OPTION)
914 current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
915 "(System.Web.UI.IParserAccessor) __ctrl;\n");
918 private void DataBoundProperty (Type target, string varName, string value)
921 throw new ApplicationException ("Empty data binding tag.");
923 string control_id = controls.PeekControlID ();
924 string control_type_string = controls.PeekType ().ToString ();
925 StringBuilder db_function = controls.DataBindFunction;
927 if (controls.Container == null || !typeof (INamingContainer).IsAssignableFrom (controls.Container))
928 container = "System.Web.UI.Control";
930 container = controls.Container.ToString ();
933 if (db_function.Length == 0)
934 db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
935 "System.EventArgs e) {{\n" +
936 "\t\t\t{1} Container;\n" +
937 "\t\t\t{2} target;\n" +
938 "\t\t\ttarget = ({2}) sender;\n" +
939 "\t\t\tContainer = ({1}) target.BindingContainer;\n",
940 control_id, container, control_type_string);
942 /* Removes '<%#' and '%>' */
943 string real_value = value.Remove (0,3);
944 real_value = real_value.Remove (real_value.Length - 2, 2);
945 real_value = real_value.Trim ();
947 if (target == typeof (string))
948 db_function.AppendFormat ("\t\t\ttarget.{0} = System.Convert.ToString ({1});\n",
949 varName, real_value);
951 db_function.AppendFormat ("\t\t\ttarget.{0} = ({1}) ({2});\n",
952 varName, target, real_value);
956 * Returns true if it generates some code for the specified property
958 private void AddCodeForPropertyOrField (Type type, string var_name, string att, bool isDataBound)
960 /* FIXME: should i check for this or let the compiler fail?
961 * if (!prop.CanWrite)
965 DataBoundProperty (type, var_name, att);
967 else if (type == typeof (string)){
969 throw new ApplicationException ("null value for attribute " + var_name );
971 current_function.AppendFormat ("\t\t\t__ctrl.{0} = \"{1}\";\n", var_name,
972 Escape (att)); // FIXME: really Escape this?
974 else if (type.IsEnum){
976 throw new ApplicationException ("null value for attribute " + var_name );
978 string enum_value = EnumValueNameToString (type, att);
980 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, enum_value);
982 else if (type == typeof (bool)){
985 value = "true"; //FIXME: is this ok for non Style properties?
986 else if (0 == String.Compare (att, "true", true))
988 else if (0 == String.Compare (att, "false", true))
991 throw new ApplicationException ("Value '" + att + "' is not a valid boolean.");
993 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
995 else if (type == typeof (System.Web.UI.WebControls.Unit)){
996 //FIXME: should use the culture specified in Page
998 Unit value = Unit.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.Unit.Parse (\"{1}\", " +
1004 "System.Globalization.CultureInfo.InvariantCulture);\n",
1007 else if (type == typeof (System.Web.UI.WebControls.FontUnit)){
1008 //FIXME: should use the culture specified in Page
1010 FontUnit value = FontUnit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
1011 } catch (Exception) {
1012 throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
1014 current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
1015 "System.Web.UI.WebControls.FontUnit.Parse (\"{1}\", " +
1016 "System.Globalization.CultureInfo.InvariantCulture);\n",
1019 else if (type == typeof (Int16) || type == typeof (Int32) || type == typeof (Int64)) {
1022 value = Int64.Parse (att); //FIXME: should use the culture specified in Page
1023 } catch (Exception){
1024 throw new ApplicationException (att + " is not a valid signed number " +
1025 "or is out of range.");
1028 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1030 else if (type == typeof (UInt16) || type == typeof (UInt32) || type == typeof (UInt64)) {
1033 value = UInt64.Parse (att); //FIXME: should use the culture specified in Page
1034 } catch (Exception){
1035 throw new ApplicationException (att + " is not a valid unsigned number " +
1036 "or is out of range.");
1039 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1041 else if (type == typeof (float)) {
1044 value = Single.Parse (att);
1045 } catch (Exception){
1046 throw new ApplicationException (att + " is not avalid float number or " +
1047 "is out of range.");
1050 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1052 else if (type == typeof (double)){
1055 value = Double.Parse (att);
1056 } catch (Exception){
1057 throw new ApplicationException (att + " is not avalid double number or " +
1058 "is out of range.");
1061 current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1063 else if (type == typeof (System.Drawing.Color)){
1066 c = (Color) TypeDescriptor.GetConverter (typeof (Color)).ConvertFromString (att);
1067 } catch (Exception e){
1068 throw new ApplicationException ("Color " + att + " is not a valid color.", e);
1071 // Should i also test for IsSystemColor?
1072 // Are KnownColor members in System.Drawing.Color?
1073 if (c.IsKnownColor){
1074 current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
1075 "{1};\n", var_name, c.Name);
1078 current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
1079 "FromArgb ({1}, {2}, {3}, {4});\n",
1080 var_name, c.A, c.R, c.G, c.B);
1083 else if (type == typeof (string [])) {
1084 string [] subStrings = att.Split (',');
1085 current_function.AppendFormat ("\t\t\t__ctrl.{0} = new String [] {{\n", var_name);
1086 int end = subStrings.Length;
1087 for (int i = 0; i < end; i++) {
1088 string s = subStrings [i].Trim ();
1089 current_function.AppendFormat ("\t\t\t\t\"{0}\"", s);
1091 current_function.Append ("\t\t\t\t};\n");
1093 current_function.Append (",\n");
1096 throw new ApplicationException ("Unsupported type in property: " +
1101 private bool ProcessPropertiesAndFields (MemberInfo member, string id, TagAttributes att)
1103 int hyphen = id.IndexOf ('-');
1105 bool isPropertyInfo = (member is PropertyInfo);
1107 bool is_processed = false;
1108 bool isDataBound = att.IsDataBound ((string) att [id]);
1110 if (isPropertyInfo) {
1111 type = ((PropertyInfo) member).PropertyType;
1112 if (hyphen == -1 && ((PropertyInfo) member).CanWrite == false)
1115 type = ((FieldInfo) member).FieldType;
1118 if (0 == String.Compare (member.Name, id, true)){
1119 AddCodeForPropertyOrField (type, member.Name, (string) att [id], isDataBound);
1120 is_processed = true;
1121 } else if (hyphen != -1 && (type == fontinfoType || type == styleType || type.IsSubclassOf (styleType))){
1122 string prop_field = id.Replace ("-", ".");
1123 string [] parts = prop_field.Split (new char [] {'.'});
1124 if (parts.Length != 2 || 0 != String.Compare (member.Name, parts [0], true))
1127 PropertyInfo [] subprops = type.GetProperties ();
1128 foreach (PropertyInfo subprop in subprops){
1129 if (0 != String.Compare (subprop.Name, parts [1], true))
1132 if (subprop.CanWrite == false)
1135 bool is_bool = subprop.PropertyType == typeof (bool);
1136 if (!is_bool && att [id] == null){
1137 att [id] = ""; // Font-Size -> Font-Size="" as html
1142 if (att [id] == null && is_bool)
1143 value = "true"; // Font-Bold <=> Font-Bold="true"
1145 value = (string) att [id];
1147 AddCodeForPropertyOrField (subprop.PropertyType,
1148 member.Name + "." + subprop.Name,
1149 value, isDataBound);
1150 is_processed = true;
1154 return is_processed;
1157 private void AddCodeForAttributes (Type type, TagAttributes att)
1159 EventInfo [] ev_info = type.GetEvents ();
1160 PropertyInfo [] prop_info = type.GetProperties ();
1161 FieldInfo [] field_info = type.GetFields ();
1162 bool is_processed = false;
1163 ArrayList processed = new ArrayList ();
1165 foreach (string id in att.Keys){
1166 if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
1169 if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
1170 string id_as_event = id.Substring (2);
1171 foreach (EventInfo ev in ev_info){
1172 if (0 == String.Compare (ev.Name, id_as_event, true)){
1173 current_function.AppendFormat (
1174 "\t\t\t__ctrl.{0} += " +
1175 "new {1} (this.{2});\n",
1176 ev.Name, ev.EventHandlerType, att [id]);
1177 is_processed = true;
1182 is_processed = false;
1187 foreach (PropertyInfo prop in prop_info){
1188 is_processed = ProcessPropertiesAndFields (prop, id, att);
1193 if (!is_processed) {
1194 foreach (FieldInfo field in field_info){
1195 is_processed = ProcessPropertiesAndFields (field, id, att);
1202 is_processed = false;
1206 current_function.AppendFormat ("\t\t\t((System.Web.UI.IAttributeAccessor) __ctrl)." +
1207 "SetAttribute (\"{0}\", \"{1}\");\n",
1208 id, Escape ((string) att [id]));
1212 private void AddCodeRenderControl (StringBuilder function)
1214 AddCodeRenderControl (function, controls.CodeRenderIndex);
1217 private void AddCodeRenderControl (StringBuilder function, int index)
1219 function.AppendFormat ("\t\t\tparameterContainer.Controls [{0}]." +
1220 "RenderControl (__output);\n", index);
1223 private void AddRenderMethodDelegate (StringBuilder function, string control_id)
1225 function.AppendFormat ("\t\t\t__ctrl.SetRenderMethodDelegate (new System.Web." +
1226 "UI.RenderMethod (this.__Render_{0}));\n", control_id);
1229 private void AddCodeRenderFunction (string codeRender, string control_id)
1231 StringBuilder codeRenderFunction = new StringBuilder ();
1232 codeRenderFunction.AppendFormat ("\t\tprivate void __Render_{0} " +
1233 "(System.Web.UI.HtmlTextWriter __output, " +
1234 "System.Web.UI.Control parameterContainer)\n" +
1235 "\t\t{{\n", control_id);
1236 codeRenderFunction.Append (codeRender);
1237 codeRenderFunction.Append ("\t\t}\n\n");
1238 init_funcs.Append (codeRenderFunction);
1241 private void RemoveLiterals (StringBuilder function)
1243 string no_literals = Regex.Replace (function.ToString (),
1244 @"\t\t\t__parser.AddParsedSubObject \(" +
1245 @"new System.Web.UI.LiteralControl \(.+\);\n", "");
1246 function.Length = 0;
1247 function.Append (no_literals);
1250 private bool FinishControlFunction (string tag_id)
1252 if (functions.Count == 0)
1253 throw new ApplicationException ("Unbalanced open/close tags");
1255 if (controls.Count == 0)
1258 string saved_id = controls.PeekTagID ();
1259 if (0 != String.Compare (saved_id, tag_id, true))
1263 StringBuilder old_function = (StringBuilder) functions.Pop ();
1264 current_function = (StringBuilder) functions.Peek ();
1266 string control_id = controls.PeekControlID ();
1267 Type control_type = controls.PeekType ();
1268 ChildrenKind child_kind = controls.PeekChildKind ();
1270 bool hasDataBindFunction = controls.HasDataBindFunction ();
1271 if (hasDataBindFunction)
1272 old_function.AppendFormat ("\t\t\t__ctrl.DataBinding += new System.EventHandler " +
1273 "(this.__DataBind_{0});\n", control_id);
1275 bool useCodeRender = controls.UseCodeRender;
1277 AddRenderMethodDelegate (old_function, control_id);
1279 if (control_type == typeof (System.Web.UI.ITemplate)){
1280 old_function.Append ("\n\t\t}\n\n");
1281 current_function.AppendFormat ("\t\t\t__ctrl.{0} = new System.Web.UI." +
1282 "CompiledTemplateBuilder (new System.Web.UI." +
1283 "BuildTemplateMethod (this.__BuildControl_{1}));\n",
1284 saved_id, control_id);
1286 else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumnCollection)){
1287 old_function.Append ("\n\t\t}\n\n");
1288 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
1289 control_id, saved_id);
1291 else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumn) ||
1292 control_type.IsSubclassOf (typeof (System.Web.UI.WebControls.DataGridColumn)) ||
1293 control_type == typeof (System.Web.UI.WebControls.ListItem)){
1294 old_function.Append ("\n\t\t}\n\n");
1296 string ctrl_name = "ctrl";
1297 Type cont = controls.Container;
1298 if (cont == null || cont == typeof (System.Web.UI.HtmlControls.HtmlSelect)){
1299 parsed = "ParsedSubObject";
1300 ctrl_name = "parser";
1303 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
1304 "\t\t\t__{1}.Add{2} (this.{0});\n\n",
1305 control_id, ctrl_name, parsed);
1307 else if (child_kind == ChildrenKind.LISTITEM){
1308 old_function.Append ("\n\t\t}\n\n");
1309 init_funcs.Append (old_function); // Closes the BuildList function
1310 old_function = (StringBuilder) functions.Pop ();
1311 current_function = (StringBuilder) functions.Peek ();
1312 old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
1313 "return __ctrl;\n\t\t}}\n\n",
1314 control_id, controls.PeekDefaultPropertyName ());
1317 control_id = controls.PeekControlID ();
1318 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1319 "AddParsedSubObject (this.{0});\n\n", control_id);
1320 } else if (control_type == typeof (HtmlTableCell) || control_type == typeof (TableCell)) {
1321 old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1322 object top = controls.Pop ();
1323 Type t = controls.PeekType ();
1324 controls.Push (top);
1326 string ctrl_name = "ctrl";
1327 if (!t.IsSubclassOf (typeof (WebControl)) && t != typeof (HtmlTableRow)) {
1328 parsed = "ParsedSubObject";
1329 ctrl_name = "parser";
1332 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
1333 "\t\t\t__{1}.Add{2} (this.{0});\n\n",
1334 control_id, ctrl_name, parsed);
1335 } else if (child_kind == ChildrenKind.HTMLROW || child_kind == ChildrenKind.HTMLCELL) {
1336 old_function.Append ("\n\t\t}\n\n");
1337 init_funcs.Append (old_function);
1338 old_function = (StringBuilder) functions.Pop ();
1339 current_function = (StringBuilder) functions.Peek ();
1340 old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
1341 "return __ctrl;\n\t\t}}\n\n",
1342 control_id, controls.PeekDefaultPropertyName ());
1345 control_id = controls.PeekControlID ();
1346 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n", control_id);
1347 if (child_kind == ChildrenKind.HTMLROW) {
1348 current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject ({0});\n",
1351 current_function.AppendFormat ("\t\t\t__ctrl.Add (this.{0});\n", control_id);
1354 old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1355 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1356 "AddParsedSubObject (this.{0});\n\n", control_id);
1360 RemoveLiterals (old_function);
1362 init_funcs.Append (old_function);
1364 AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), control_id);
1366 if (hasDataBindFunction){
1367 StringBuilder db_function = controls.DataBindFunction;
1368 db_function.Append ("\t\t}\n\n");
1369 init_funcs.Append (db_function);
1372 // Avoid getting empty stacks for unbalanced open/close tags
1373 if (controls.Count > 1){
1375 AddCodeRenderControl (controls.CodeRenderFunction, controls.ChildIndex);
1381 private void NewTableElementFunction (HtmlControlTag ctrl)
1383 string control_id = Tag.GetDefaultID ();
1384 ChildrenKind child_kind;
1387 if (ctrl.ControlType == typeof (HtmlTable)) {
1388 t = typeof (HtmlTableRowCollection);
1389 child_kind = ChildrenKind.HTMLROW;
1391 t = typeof (HtmlTableCellCollection);
1392 child_kind = ChildrenKind.HTMLCELL;
1395 controls.Push (ctrl.ControlType,
1399 ctrl.ParseChildren);
1401 current_function = new StringBuilder ();
1402 functions.Push (current_function);
1403 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
1404 "\t\t{{\n", control_id, t);
1407 private void ProcessHtmlControlTag ()
1410 HtmlControlTag html_ctrl = (HtmlControlTag) current;
1411 if (html_ctrl.TagID.ToUpper () == "SCRIPT"){
1412 //FIXME: if the is script is to be read from disk, do it!
1413 if (html_ctrl.SelfClosing)
1414 throw new ApplicationException ("Read script from file not supported yet.");
1416 sstatus = ScriptStatus.Open;
1421 throw new ApplicationException (app_file_wrong);
1423 Type controlType = html_ctrl.ControlType;
1424 AddProtectedField (controlType, html_ctrl.ControlID);
1426 ChildrenKind children_kind;
1427 if (0 == String.Compare (html_ctrl.TagID, "table", true))
1428 children_kind = ChildrenKind.HTMLROW;
1429 else if (0 == String.Compare (html_ctrl.TagID, "tr", true))
1430 children_kind = ChildrenKind.HTMLCELL;
1431 else if (0 != String.Compare (html_ctrl.TagID, "select", true))
1432 children_kind = html_ctrl.IsContainer ? ChildrenKind.CONTROLS :
1435 children_kind = ChildrenKind.OPTION;
1437 NewControlFunction (html_ctrl.TagID, html_ctrl.ControlID, controlType, children_kind, html_ctrl.ParseChildren);
1439 current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", html_ctrl.ControlID);
1440 AddCodeForAttributes (html_ctrl.ControlType, html_ctrl.Attributes);
1442 if (children_kind == ChildrenKind.HTMLROW || children_kind == ChildrenKind.HTMLCELL)
1443 NewTableElementFunction (html_ctrl);
1445 if (html_ctrl.SelfClosing)
1446 FinishControlFunction (html_ctrl.TagID);
1449 // Closing is performed in FinishControlFunction ()
1450 private void NewBuildListFunction (AspComponent component)
1452 string control_id = Tag.GetDefaultID ();
1454 controls.Push (component.ComponentType,
1457 component.ChildrenKind,
1458 component.DefaultPropertyName);
1460 Type childType = component.DefaultPropertyType;
1461 if (childType == null)
1462 childType = typeof (ListItemCollection);
1464 current_function = new StringBuilder ();
1465 functions.Push (current_function);
1466 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1468 "\t\t{{\n", control_id, childType);
1471 private void ProcessComponent ()
1474 AspComponent component = (AspComponent) current;
1475 Type component_type = component.ComponentType;
1476 AddProtectedField (component_type, component.ControlID);
1478 NewControlFunction (component.TagID, component.ControlID, component_type,
1479 component.ChildrenKind, component.DefaultPropertyName);
1481 if (component_type == typeof (UserControl) ||
1482 component_type.IsSubclassOf (typeof (System.Web.UI.UserControl)))
1483 current_function.Append ("\t\t\t__ctrl.InitializeAsUserControl (Page);\n");
1485 if (component_type == typeof (Control) ||
1486 component_type.IsSubclassOf (typeof (System.Web.UI.Control)))
1487 current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", component.ControlID);
1489 AddCodeForAttributes (component.ComponentType, component.Attributes);
1490 if (component.ChildrenKind == ChildrenKind.LISTITEM || component.DefaultPropertyType != null)
1491 NewBuildListFunction (component);
1493 if (component.SelfClosing)
1494 FinishControlFunction (component.TagID);
1497 private void ProcessServerObjectTag ()
1500 ServerObjectTag obj = (ServerObjectTag) current;
1501 declarations.AppendFormat ("\t\tprivate {0} cached{1};\n", obj.ObjectClass, obj.ObjectID);
1502 constructor.AppendFormat ("\n\t\tprivate {0} {1}\n\t\t{{\n\t\t\tget {{\n\t\t\t\t" +
1503 "if (this.cached{1} == null)\n\t\t\t\t\tthis.cached{1} = " +
1504 "new {0} ();\n\t\t\t\treturn cached{1};\n\t\t\t}}\n\t\t}}\n\n",
1505 obj.ObjectClass, obj.ObjectID);
1508 // Creates a new function that sets the values of subproperties.
1509 private void NewStyleFunction (PropertyTag tag)
1511 current_function = new StringBuilder ();
1513 string prop_id = tag.PropertyID;
1514 Type prop_type = tag.PropertyType;
1516 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
1517 "\t\t{{\n", prop_id, prop_type);
1519 // Add property initialization code
1520 PropertyInfo [] subprop_info = prop_type.GetProperties ();
1521 TagAttributes att = tag.Attributes;
1523 string subprop_name = null;
1524 foreach (string id in att.Keys){
1525 if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
1528 bool is_processed = false;
1529 foreach (PropertyInfo subprop in subprop_info){
1530 is_processed = ProcessPropertiesAndFields (subprop, id, att);
1532 subprop_name = subprop.Name;
1537 if (subprop_name == null)
1538 throw new ApplicationException ("Property " + tag.TagID + " does not have " +
1539 "a " + id + " subproperty.");
1543 current_function.Append ("\n\t\t}\n\n");
1544 init_funcs.Append (current_function);
1545 current_function = (StringBuilder) functions.Peek ();
1546 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
1547 prop_id, tag.PropertyName);
1549 if (!tag.SelfClosing){
1550 // Next tag should be the closing tag
1551 controls.Push (null, null, null, ChildrenKind.NONE, null);
1552 waitClosing = tag.TagID;
1556 // This one just opens the function. Closing is performed in FinishControlFunction ()
1557 private void NewTemplateFunction (PropertyTag tag)
1561 * This function does almost the same as NewControlFunction.
1564 string prop_id = tag.PropertyID;
1565 Type prop_type = tag.PropertyType;
1566 string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
1568 controls.Push (prop_type, prop_id, tag_id, ChildrenKind.CONTROLS, null);
1569 current_function = new StringBuilder ();
1570 functions.Push (current_function);
1571 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1572 "(System.Web.UI.Control __ctrl)\n" +
1574 "\t\t\tSystem.Web.UI.IParserAccessor __parser " +
1575 "= (System.Web.UI.IParserAccessor) __ctrl;\n" , prop_id);
1578 // Closing is performed in FinishControlFunction ()
1579 private void NewDBColumnFunction (PropertyTag tag)
1583 * This function also does almost the same as NewControlFunction.
1586 string prop_id = tag.PropertyID;
1587 Type prop_type = tag.PropertyType;
1588 string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
1590 controls.Push (prop_type, prop_id, tag_id, ChildrenKind.DBCOLUMNS, null);
1591 current_function = new StringBuilder ();
1592 functions.Push (current_function);
1593 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1594 "(System.Web.UI.WebControls.DataGridColumnCollection __ctrl)\n" +
1595 "\t\t{{\n", prop_id);
1598 private void NewPropertyFunction (PropertyTag tag)
1601 if (tag.PropertyType == typeof (System.Web.UI.WebControls.Style) ||
1602 tag.PropertyType.IsSubclassOf (typeof (System.Web.UI.WebControls.Style)))
1603 NewStyleFunction (tag);
1604 else if (tag.PropertyType == typeof (System.Web.UI.ITemplate))
1605 NewTemplateFunction (tag);
1606 else if (tag.PropertyType == typeof (System.Web.UI.WebControls.DataGridColumnCollection))
1607 NewDBColumnFunction (tag);
1609 throw new ApplicationException ("Other than Style and ITemplate not supported yet. " +
1613 private void ProcessHtmlTag ()
1615 Tag tag = (Tag) current;
1616 ChildrenKind child_kind = controls.PeekChildKind ();
1617 if (child_kind == ChildrenKind.NONE){
1618 string tag_id = controls.PeekTagID ();
1619 throw new ApplicationException (tag + " not allowed inside " + tag_id);
1622 if (child_kind == ChildrenKind.OPTION){
1623 if (0 != String.Compare (tag.TagID, "option", true))
1624 throw new ApplicationException ("Only <option> tags allowed inside <select>.");
1626 string default_id = Tag.GetDefaultID ();
1627 Type type = typeof (System.Web.UI.WebControls.ListItem);
1628 AddProtectedField (type, default_id);
1629 NewControlFunction (tag.TagID, default_id, type, ChildrenKind.CONTROLS, null);
1633 if (child_kind == ChildrenKind.CONTROLS) {
1634 ArrayList tag_elements = tag.GetElements ();
1635 foreach (Element e in tag_elements) {
1636 if (e is PlainText) {
1638 textChunk.Append (((PlainText) e).Text);
1639 } else if (e is CodeRenderTag) {
1641 ProcessCodeRenderTag ();
1642 } else if (e is DataBindingTag) {
1644 ProcessDataBindingLiteral ();
1646 throw new ApplicationException (fullPath + ": unexpected tag type " + e.GetType ());
1652 if (child_kind == ChildrenKind.HTMLROW) {
1653 if (0 == String.Compare (tag.TagID, "tr", true)) {
1654 current = new HtmlControlTag (tag);
1655 ProcessHtmlControlTag ();
1660 if (child_kind == ChildrenKind.HTMLCELL) {
1661 if (0 == String.Compare (tag.TagID, "td", true)) {
1662 current = new HtmlControlTag (tag);
1663 ProcessHtmlControlTag ();
1668 // Now child_kind should be PROPERTIES, so only allow tag_id == property
1669 Type control_type = controls.PeekType ();
1670 PropertyInfo [] prop_info = control_type.GetProperties ();
1671 bool is_processed = false;
1672 foreach (PropertyInfo prop in prop_info){
1673 if (0 == String.Compare (prop.Name, tag.TagID, true)){
1674 PropertyTag prop_tag = new PropertyTag (tag, prop.PropertyType, prop.Name);
1675 NewPropertyFunction (prop_tag);
1676 is_processed = true;
1682 string tag_id = controls.PeekTagID ();
1683 throw new ApplicationException (tag.TagID + " is not a property of " + control_type);
1687 private Tag Map (Tag tag)
1689 int pos = tag.TagID.IndexOf (":");
1691 ChildrenKind child_kind = controls.PeekChildKind ();
1692 if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
1693 tag.Attributes.Add ("runat", "server");
1694 return new HtmlControlTag (tag);
1695 } else if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
1696 tag.Attributes.Add ("runat", "server");
1697 return new HtmlControlTag (tag);
1701 if (tag is CloseTag ||
1702 ((tag.Attributes == null ||
1703 !tag.Attributes.IsRunAtServer ()) && pos == -1))
1707 if (0 == String.Compare (tag.TagID, "object", true))
1708 return new ServerObjectTag (tag);
1710 return new HtmlControlTag (tag);
1713 string foundry_name = tag.TagID.Substring (0, pos);
1714 string component_name = tag.TagID.Substring (pos + 1);
1716 if (Foundry.LookupFoundry (foundry_name) == false)
1717 throw new ApplicationException ("Cannot find foundry for alias'" + foundry_name + "'");
1719 AspComponent component = Foundry.MakeAspComponent (foundry_name, component_name, tag);
1720 if (component == null)
1721 throw new ApplicationException ("Cannot find component '" + component_name +
1722 "' for alias '" + foundry_name + "'");
1727 private void ProcessCloseTag ()
1729 CloseTag closeTag = (CloseTag) current;
1730 if (FinishControlFunction (closeTag.TagID))
1733 textChunk.Append (closeTag.PlainHtml);
1736 private void ProcessDataBindingLiteral ()
1739 DataBindingTag dataBinding = (DataBindingTag) current;
1740 string actual_value = dataBinding.Data;
1741 if (actual_value == "")
1742 throw new ApplicationException ("Empty data binding tag.");
1744 if (controls.PeekChildKind () != ChildrenKind.CONTROLS)
1745 throw new ApplicationException ("Data bound content not allowed for " +
1746 controls.PeekTagID ());
1748 StringBuilder db_function = new StringBuilder ();
1749 string control_id = Tag.GetDefaultID ();
1750 string control_type_string = "System.Web.UI.DataBoundLiteralControl";
1751 AddProtectedField (typeof (System.Web.UI.DataBoundLiteralControl), control_id);
1752 // Build the control
1753 db_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_{0} ()\n" +
1754 "\t\t{{\n\t\t\t{1} __ctrl;\n\n" +
1755 "\t\t\t__ctrl = new {1} (0, 1);\n" +
1756 "\t\t\tthis.{0} = __ctrl;\n" +
1757 "\t\t\t__ctrl.DataBinding += new System.EventHandler " +
1758 "(this.__DataBind_{0});\n" +
1759 "\t\t\treturn __ctrl;\n"+
1761 control_id, control_type_string);
1762 // DataBinding handler
1763 db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
1764 "System.EventArgs e) {{\n" +
1765 "\t\t\t{1} Container;\n" +
1766 "\t\t\t{2} target;\n" +
1767 "\t\t\ttarget = ({2}) sender;\n" +
1768 "\t\t\tContainer = ({1}) target.BindingContainer;\n" +
1769 "\t\t\ttarget.SetDataBoundString (0, System.Convert." +
1770 "ToString ({3}));\n" +
1772 control_id, controls.Container, control_type_string,
1775 init_funcs.Append (db_function);
1776 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1777 "AddParsedSubObject (this.{0});\n\n", control_id);
1779 AddCodeRenderControl (controls.CodeRenderFunction);
1782 private void ProcessCodeRenderTag ()
1785 CodeRenderTag code_tag = (CodeRenderTag) current;
1787 controls.UseCodeRender = true;
1788 if (code_tag.IsVarName)
1789 controls.CodeRenderFunction.AppendFormat ("\t\t\t__output.Write ({0});\n",
1792 controls.CodeRenderFunction.AppendFormat ("\t\t\t{0}\n", code_tag.Code);
1795 void FlushPlainText ()
1797 if (textChunk.Length != 0) {
1798 Element saved = current;
1799 current = new PlainText (textChunk.ToString ());
1800 textChunk.Length = 0;
1801 ProcessPlainText ();
1806 void ParseError (string msg, int line, int col)
1808 throw new ParseException (fullPath, msg, line, col);
1811 void TagParsed (Tag tag, int line, int col)
1813 if (waitClosing != null) {
1814 if (!(tag is CloseTag) || tag.TagID.ToUpper () != waitClosing.ToUpper ())
1815 throw new HttpException ("Tag " + waitClosing + " not properly closed.");
1822 if ((sstatus == ScriptStatus.Open || sstatus == ScriptStatus.Text) &&
1823 tag.TagID.ToUpper () == "SCRIPT" && tag is CloseTag) {
1824 sstatus = ScriptStatus.Close;
1830 if (current is Directive) {
1831 ProcessDirective ();
1833 } else if (current is DataBindingTag) {
1835 throw new ApplicationException (app_file_wrong);
1837 ProcessDataBindingLiteral ();
1839 } else if (current is CodeRenderTag) {
1841 throw new ApplicationException (app_file_wrong);
1843 ProcessCodeRenderTag ();
1847 current = Map (tag);
1849 if (current is ServerObjectTag) {
1850 ProcessServerObjectTag ();
1852 } else if (current is HtmlControlTag) {
1853 ProcessHtmlControlTag ();
1858 throw new ApplicationException (app_file_wrong);
1860 if (current is AspComponent) {
1861 ProcessComponent ();
1862 } else if (current is CloseTag) {
1864 } else if (current is Tag) {
1867 throw new HttpException ("This place should not be reached.");
1871 void TextParsed (string text, int line, int col)
1873 if (sstatus == ScriptStatus.Open) {
1874 script.Append (text);
1875 sstatus = ScriptStatus.Text;
1879 textChunk.Append (text);
1882 public void ProcessElements ()
1884 AspParser parser = new AspParser (fullPath, File.OpenRead (fullPath));
1886 parser.Error += new ParseErrorHandler (ParseError);
1887 parser.TagParsed += new TagParsedHandler (TagParsed);
1888 parser.TextParsed += new TextParsedHandler (TextParsed);
1892 } catch (CompilationException e) {
1894 } catch (ParseException e) {
1896 } catch (Exception e) {
1897 throw new ParseException (fullPath, e.Message, parser.Line, parser.Column, e);
1904 private string GetTemplateDirectory ()
1906 string templatePath = Path.GetDirectoryName (fullPath);
1907 string appPath = Path.GetDirectoryName (HttpRuntime.AppDomainAppPath);
1909 if (templatePath == appPath)
1912 templatePath = templatePath.Substring (appPath.Length);
1913 if (Path.DirectorySeparatorChar != '/')
1914 templatePath = templatePath.Replace (Path.DirectorySeparatorChar, '/');
1916 return templatePath;
1924 if (sessionState == SessionState.Enabled || sessionState == SessionState.ReadOnly)
1925 AddInterface (typeof (System.Web.SessionState.IRequiresSessionState));
1927 if (sessionState == SessionState.ReadOnly)
1928 AddInterface (typeof (System.Web.SessionState.IReadOnlySessionState));
1931 classDecl = "\tpublic class " + className + " : " + parent + interfaces + " {\n";
1932 prolog.Append ("\n" + classDecl);
1933 declarations.Append ("\t\tprivate static bool __intialized = false;\n\n");
1935 declarations.Append ("\t\tprivate static ArrayList __fileDependencies;\n\n");
1937 // adds the constructor
1938 constructor.AppendFormat ("\t\tpublic {0} ()\n\t\t{{\n", className);
1940 constructor.Append ("\t\t\tSystem.Collections.ArrayList dependencies;\n\n");
1942 constructor.AppendFormat ("\t\t\tif (ASP.{0}.__intialized == false){{\n", className);
1945 constructor.AppendFormat ("\t\t\t\tdependencies = new System.Collections.ArrayList ();\n" +
1946 "\t\t\t\tdependencies.Add (@\"{1}\");\n" +
1947 "\t\t\t\tASP.{0}.__fileDependencies = dependencies;\n",
1948 className, fullPath);
1951 constructor.AppendFormat ("\t\t\t\tASP.{0}.__intialized = true;\n\t\t\t}}\n\t\t}}\n\n",
1954 if (!IsApplication) {
1955 //FIXME: add AutoHandlers: don't know what for...yet!
1956 constructor.AppendFormat (
1957 "\t\tprotected override int AutoHandlers\n\t\t{{\n" +
1958 "\t\t\tget {{ return ASP.{0}.__autoHandlers; }}\n" +
1959 "\t\t\tset {{ ASP.{0}.__autoHandlers = value; }}\n" +
1960 "\t\t}}\n\n", className);
1962 constructor.Append (
1963 "\t\tprotected System.Web.HttpApplication ApplicationInstance\n\t\t{\n" +
1964 "\t\t\tget { return (System.Web.HttpApplication) this.Context.ApplicationInstance; }\n" +
1967 constructor.AppendFormat (
1968 "\t\tpublic override string TemplateSourceDirectory\n\t\t{{\n" +
1969 "\t\t\tget {{ return \"{0}\"; }}\n" +
1970 "\t\t}}\n\n", GetTemplateDirectory ());
1972 epilog.Append ("\n\t\tprotected override void FrameworkInitialize ()\n\t\t{\n" +
1973 "\t\t\tthis.__BuildControlTree (this);\n");
1976 epilog.AppendFormat ("\t\t\tthis.FileDependencies = ASP.{0}.__fileDependencies;\n" +
1977 "\t\t\tthis.EnableViewStateMac = true;\n", className);
1980 epilog.Append ("\t\t}\n\n");
1984 Random rnd = new Random ();
1985 epilog.AppendFormat ("\t\tpublic override int GetTypeHashCode ()\n\t\t{{\n" +
1986 "\t\t\treturn {0};\n" +
1987 "\t\t}}\n", rnd.Next ());
1990 epilog.Append ("\t}\n}\n");
1992 // Closes the currently opened tags
1993 StringBuilder old_function = current_function;
1995 while (functions.Count > 1){
1996 old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1997 init_funcs.Append (old_function);
1998 control_id = controls.PeekControlID ();
1999 FinishControlFunction (control_id);
2000 controls.AddChild ();
2001 old_function = (StringBuilder) functions.Pop ();
2002 current_function = (StringBuilder) functions.Peek ();
2006 bool useCodeRender = controls.UseCodeRender;
2008 RemoveLiterals (current_function);
2009 AddRenderMethodDelegate (current_function, controls.PeekControlID ());
2012 current_function.Append ("\t\t}\n\n");
2013 init_funcs.Append (current_function);
2015 AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), controls.PeekControlID ());
2021 // Functions related to compilation of user controls
2024 private static char dirSeparator = Path.DirectorySeparatorChar;
2025 struct UserControlData
2027 public UserControlResult result;
2028 public string className;
2029 public string assemblyName;
2032 private UserControlData GenerateUserControl (string src, HttpContext context)
2034 UserControlData data = new UserControlData ();
2035 data.result = UserControlResult.OK;
2037 UserControlCompiler compiler = new UserControlCompiler (new UserControlParser (src, context));
2038 Type t = compiler.GetCompiledType ();
2040 data.result = UserControlResult.CompilationFailed;
2044 data.className = t.Name;
2045 data.assemblyName = compiler.TargetFile;
2046 dependencies.Add (src);
2047 foreach (string s in compiler.Dependencies)
2048 dependencies.Add (s);