| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040 |
- //
- // System.Web.Compilation.AspGenerator
- //
- // Authors:
- // Gonzalo Paniagua Javier ([email protected])
- //
- // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
- //
- using System;
- using System.Collections;
- using System.ComponentModel;
- using System.Drawing;
- using System.Diagnostics;
- using System.IO;
- using System.Reflection;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.Util;
- namespace System.Web.Compilation
- {
- class ControlStack
- {
- private Stack controls;
- private ControlStackData top;
- private bool space_between_tags;
- private bool sbt_valid;
- class ControlStackData
- {
- public Type controlType;
- public string controlID;
- public string tagID;
- public ChildrenKind childKind;
- public string defaultPropertyName;
- public int childrenNumber;
- public Type container;
- public StringBuilder dataBindFunction;
- public StringBuilder codeRenderFunction;
- public bool useCodeRender;
- public int codeRenderIndex;
- public ControlStackData (Type controlType,
- string controlID,
- string tagID,
- ChildrenKind childKind,
- string defaultPropertyName,
- Type container)
- {
- this.controlType = controlType;
- this.controlID = controlID;
- this.tagID = tagID;
- this.childKind = childKind;
- this.defaultPropertyName = defaultPropertyName;
- this.container = container;
- childrenNumber = 0;
- }
- public override string ToString ()
- {
- return controlType + " " + controlID + " " + tagID + " " + childKind + " " + childrenNumber;
- }
- }
-
- public ControlStack ()
- {
- controls = new Stack ();
- }
- private Type GetContainerType (Type type)
- {
- if (type != typeof (System.Web.UI.Control) &&
- !type.IsSubclassOf (typeof (System.Web.UI.Control)))
- return null;
-
- Type container_type;
- if (type == typeof (System.Web.UI.WebControls.DataList))
- container_type = typeof (System.Web.UI.WebControls.DataListItem);
- else if (type == typeof (System.Web.UI.WebControls.DataGrid))
- container_type = typeof (System.Web.UI.WebControls.DataGridItem);
- else if (type == typeof (System.Web.UI.WebControls.Repeater))
- container_type = typeof (System.Web.UI.WebControls.RepeaterItem);
- else if (type == typeof (ListControl) || type.IsSubclassOf (typeof (ListControl)))
- container_type = type;
- else
- container_type = Container;
- return container_type;
- }
- public void Push (object o)
- {
- if (!(o is ControlStackData))
- return;
- controls.Push (o);
- top = (ControlStackData) o;
- sbt_valid = false;
- }
-
- public void Push (Type controlType,
- string controlID,
- string tagID,
- ChildrenKind childKind,
- string defaultPropertyName)
- {
- Type container_type = null;
- if (controlType != null){
- AddChild ();
- container_type = GetContainerType (controlType);
- if (container_type == null)
- container_type = this.Container;
- }
- top = new ControlStackData (controlType,
- controlID,
- tagID,
- childKind,
- defaultPropertyName,
- container_type);
- sbt_valid = false;
- controls.Push (top);
- }
- public object Pop ()
- {
- object item = controls.Pop ();
- if (controls.Count != 0)
- top = (ControlStackData) controls.Peek ();
- sbt_valid = false;
- return item;
- }
- public Type PeekType ()
- {
- return top.controlType;
- }
- public string PeekControlID ()
- {
- return top.controlID;
- }
- public string PeekTagID ()
- {
- return top.tagID;
- }
- public ChildrenKind PeekChildKind ()
- {
- return top.childKind;
- }
- public string PeekDefaultPropertyName ()
- {
- return top.defaultPropertyName;
- }
- public void AddChild ()
- {
- if (top != null)
- top.childrenNumber++;
- }
- public bool HasDataBindFunction ()
- {
- if (top.dataBindFunction == null || top.dataBindFunction.Length == 0)
- return false;
- return true;
- }
-
- public bool UseCodeRender
- {
- get {
- if (top.codeRenderFunction == null || top.codeRenderFunction.Length == 0)
- return false;
- return top.useCodeRender;
- }
- set { top.useCodeRender= value; }
- }
-
- public bool SpaceBetweenTags
- {
- get {
- if (!sbt_valid){
- sbt_valid = true;
- Type type = top.controlType;
- if (type.Namespace == "System.Web.UI.WebControls")
- space_between_tags = true;
- else if (type.IsSubclassOf (typeof (System.Web.UI.WebControls.WebControl)))
- space_between_tags = true;
- else if (type == typeof (System.Web.UI.HtmlControls.HtmlSelect))
- space_between_tags = true;
- else if (type == typeof (System.Web.UI.HtmlControls.HtmlTable))
- space_between_tags = true;
- else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableRow))
- space_between_tags = true;
- else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableCell))
- space_between_tags = true;
- else
- space_between_tags = false;
- }
- return space_between_tags;
- }
- }
-
- public Type Container {
- get {
- if (top == null)
- return null;
-
- return top.container;
- }
- }
-
- public StringBuilder DataBindFunction
- {
- get {
- if (top.dataBindFunction == null)
- top.dataBindFunction = new StringBuilder ();
- return top.dataBindFunction;
- }
- }
- public int CodeRenderIndex {
- get {
- return top.codeRenderIndex++;
- }
- }
-
- public StringBuilder CodeRenderFunction
- {
- get {
- if (top.codeRenderFunction == null)
- top.codeRenderFunction = new StringBuilder ();
- return top.codeRenderFunction;
- }
- }
- public int ChildIndex
- {
- get { return top.childrenNumber - 1; }
- }
-
- public int Count
- {
- get { return controls.Count; }
- }
- public override string ToString ()
- {
- return top.ToString () + " " + top.useCodeRender;
- }
-
- }
- enum ScriptStatus
- {
- Close,
- Open,
- Text
- }
- class AspGenerator
- {
- object [] parts;
- StringBuilder prolog;
- StringBuilder declarations;
- StringBuilder script;
- StringBuilder constructor;
- StringBuilder init_funcs;
- StringBuilder epilog;
- StringBuilder current_function;
- StringBuilder textChunk;
- Stack functions;
- ControlStack controls;
- bool parse_ok;
- bool has_form_tag;
- AspComponentFoundry aspFoundry;
- string classDecl;
- string className;
- string interfaces;
- string basetype;
- string parent;
- Type parentType;
- string fullPath;
- Hashtable options;
- string privateBinPath;
- string main_directive;
- static string app_file_wrong = "The content in the application file is not valid.";
- bool isPage;
- bool isUserControl;
- bool isApplication;
- Element current;
- ScriptStatus sstatus = ScriptStatus.Close;
- string waitClosing;
- HttpContext context;
- SessionState sessionState = SessionState.Enabled;
- static Type styleType = typeof (System.Web.UI.WebControls.Style);
- static Type fontinfoType = typeof (System.Web.UI.WebControls.FontInfo);
- enum UserControlResult
- {
- OK = 0,
- FileNotFound = 1,
- CompilationFailed = 2
- }
- enum SessionState
- {
- Enabled,
- ReadOnly,
- Disabled
- }
-
- public AspGenerator (string pathToFile)
- {
- if (pathToFile == null)
- throw new ArgumentNullException ("pathToFile");
- string filename = Path.GetFileName (pathToFile);
- this.className = filename.Replace ('.', '_'); // Overridden by @ Page classname
- this.className = className.Replace ('-', '_');
- this.className = className.Replace (' ', '_');
- Options ["ClassName"] = this.className;
- this.fullPath = Path.GetFullPath (pathToFile);
- this.has_form_tag = false;
- AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
- privateBinPath = setup.PrivateBinPath;
- // This is a hack until we can run stuff in different domains
- if (privateBinPath == null || privateBinPath.Length == 0)
- privateBinPath = "bin";
-
- if (!Path.IsPathRooted (privateBinPath)) {
- string appbase = setup.ApplicationBase;
- if (appbase.StartsWith ("file://"))
- appbase = appbase.Substring (7);
- privateBinPath = Path.Combine (appbase, privateBinPath);
- }
-
- Init ();
- }
- public string BaseType {
- get { return basetype; }
- set {
- if (parent == null)
- parent = value;
- basetype = value;
- isUserControl = (basetype == "System.Web.UI.UserControl");
- isPage = (basetype == "System.Web.UI.Page");
- isApplication = (basetype == "System.Web.HttpApplication");
- }
- }
- public bool IsUserControl {
- get { return isUserControl; }
- }
-
- public bool IsPage {
- get { return isPage; }
- }
-
- public bool IsApplication {
- get { return isApplication; }
- }
- public string Interfaces {
- get { return interfaces; }
- }
- public Hashtable Options {
- get {
- if (options == null)
- options = new Hashtable ();
- return options;
- }
- }
-
- internal HttpContext Context {
- get { return context; }
- set { context = value; }
- }
-
- bool AddUsing (string nspace)
- {
- string _using = "using " + nspace + ";";
- if (prolog.ToString ().IndexOf (_using) == -1) {
- prolog.AppendFormat ("\t{0}\n", _using);
- return true;
- }
- return false;
- }
- void AddInterface (Type type)
- {
- AddInterface (type.ToString ());
- }
-
- public void AddInterface (string iface)
- {
- if (interfaces == null) {
- interfaces = ", " + iface;
- } else {
- string s = ", " + iface;
- if (interfaces.IndexOf (s) == -1)
- interfaces += s;
- }
- }
- private AspComponentFoundry Foundry
- {
- get {
- if (aspFoundry == null)
- aspFoundry = new AspComponentFoundry ();
- return aspFoundry;
- }
- }
- private void Init ()
- {
- controls = new ControlStack ();
- controls.Push (typeof (System.Web.UI.Control), "Root", null, ChildrenKind.CONTROLS, null);
- prolog = new StringBuilder ();
- declarations = new StringBuilder ();
- script = new StringBuilder ();
- constructor = new StringBuilder ();
- init_funcs = new StringBuilder ();
- epilog = new StringBuilder ();
- textChunk = new StringBuilder ();
- current_function = new StringBuilder ();
- functions = new Stack ();
- functions.Push (current_function);
- parts = new Object [6];
- parts [0] = prolog;
- parts [1] = declarations;
- parts [2] = script;
- parts [3] = constructor;
- parts [4] = init_funcs;
- parts [5] = epilog;
- prolog.Append ("namespace ASP {\n" +
- "\tusing System;\n" +
- "\tusing System.Collections;\n" +
- "\tusing System.Collections.Specialized;\n" +
- "\tusing System.Configuration;\n" +
- "\tusing System.IO;\n" +
- "\tusing System.Text;\n" +
- "\tusing System.Text.RegularExpressions;\n" +
- "\tusing System.Web;\n" +
- "\tusing System.Web.Caching;\n" +
- "\tusing System.Web.Security;\n" +
- "\tusing System.Web.SessionState;\n" +
- "\tusing System.Web.UI;\n" +
- "\tusing System.Web.UI.WebControls;\n" +
- "\tusing System.Web.UI.HtmlControls;\n");
- declarations.Append ("\t\tprivate static int __autoHandlers;\n");
- current_function.Append ("\t\tprivate void __BuildControlTree (System.Web.UI.Control __ctrl)\n\t\t{\n");
- if (!IsUserControl)
- current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
- "(System.Web.UI.IParserAccessor) __ctrl;\n\n");
- else
- controls.UseCodeRender = true;
- }
- public TextReader GetCode ()
- {
- if (!parse_ok)
- throw new InvalidOperationException ("Parsing not done yet! (may be there were errors?)");
- StringBuilder code = new StringBuilder ();
- for (int i = 0; i < parts.Length; i++)
- code.Append ((StringBuilder) parts [i]);
- return new StringReader (code.ToString ());
- }
- // Regex.Escape () make some illegal escape sequences for a C# source.
- private string Escape (string input)
- {
- if (input == null)
- return String.Empty;
- string output = input.Replace ("\\", "\\\\");
- output = output.Replace ("\"", "\\\"");
- output = output.Replace ("\t", "\\t");
- output = output.Replace ("\r", "\\r");
- output = output.Replace ("\n", "\\n");
- output = output.Replace ("\n", "\\n");
- return output;
- }
-
- bool AddProtectedField (Type type, string fieldName)
- {
- if (parentType == null) {
- declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
- return true;
- }
- FieldInfo field = parentType.GetField (fieldName, BindingFlags.Public |
- BindingFlags.NonPublic |
- BindingFlags.Instance |
- BindingFlags.Static);
- if (field == null || (!field.IsPublic && !field.IsFamily)) {
- declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
- return true;
- }
- if (!field.FieldType.IsAssignableFrom (type)) {
- string message = String.Format ("The base class includes the field '{0}', but its " +
- "type '{1}' is not compatible with {2}",
- fieldName, field.FieldType, type);
- throw new ApplicationException (message);
- }
- return false;
- }
-
- private Type LoadParentType (string typeName)
- {
- // First try loaded assemblies, then try assemblies in Bin directory.
- // By now i do this 'by hand' but may be this is a runtime/gac task.
- Type type = null;
- Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
- foreach (Assembly ass in assemblies) {
- type = ass.GetType (typeName);
- if (type != null)
- return type;
- }
- Assembly assembly;
- string [] binDlls = Directory.GetFiles (privateBinPath, "*.dll");
- foreach (string dll in binDlls) {
- string dllPath = Path.Combine (privateBinPath, dll);
- assembly = null;
- try {
- assembly = Assembly.LoadFrom (dllPath);
- type = assembly.GetType (typeName);
- } catch (Exception e) {
- if (assembly != null) {
- Console.WriteLine ("ASP.NET Warning: assembly {0} loaded", dllPath);
- Console.WriteLine ("ASP.NET Warning: but type {0} not found", typeName);
- } else {
- Console.WriteLine ("ASP.NET Warning: unable to load type {0} from {1}",
- typeName, dllPath);
- }
- Console.WriteLine ("ASP.NET Warning: error was: {0}", e.Message);
- }
- if (type != null)
- return type;
- }
- return null;
- }
- private void PageDirective (TagAttributes att)
- {
- if (att ["ClassName"] != null){
- this.className = (string) att ["ClassName"];
- Options ["ClassName"] = className;
- }
- if (att ["EnableSessionState"] != null){
- if (!IsPage)
- throw new ApplicationException ("EnableSessionState not allowed here.");
-
- string est = (string) att ["EnableSessionState"];
- if (0 == String.Compare (est, "false", true))
- sessionState = SessionState.Disabled;
- else if (0 == String.Compare (est, "true", true))
- sessionState = SessionState.Enabled;
- else if (0 == String.Compare (est, "readonly", true))
- sessionState = SessionState.ReadOnly;
- else
- throw new ApplicationException ("EnableSessionState in Page directive not set to " +
- "a correct value: " + est);
- }
- if (att ["Inherits"] != null) {
- parent = (string) att ["Inherits"];
- parentType = LoadParentType (parent);
- if (parentType == null)
- throw new ApplicationException ("The class " + parent + " cannot be found.");
- }
- if (att ["CompilerOptions"] != null)
- Options ["CompilerOptions"] = (string) att ["CompilerOptions"];
- if (att ["AutoEventWireup"] != null) {
- if (options ["AutoEventWireup"] != null)
- throw new ApplicationException ("Already have an AutoEventWireup attribute");
-
- bool autoevent = true;
- string v = att ["AutoEventWireup"] as string;
- try {
- autoevent = Convert.ToBoolean (v);
- } catch (Exception) {
- throw new ApplicationException ("'" + v + "' is not a valid value for AutoEventWireup");
- }
- options ["AutoEventWireup"] = autoevent;
- }
- //FIXME: add support for more attributes.
- }
- void AddReference (string dll)
- {
- string references = Options ["References"] as string;
- if (references == null)
- references = dll;
- else
- references = references + "|" + dll;
- Options ["References"] = references;
- }
- private void RegisterDirective (TagAttributes att)
- {
- string tag_prefix = (string) (att ["tagprefix"] == null ? "" : att ["tagprefix"]);
- string name_space = (string) (att ["namespace"] == null ? "" : att ["namespace"]);
- string assembly_name = (string) (att ["assembly"] == null ? "" : att ["assembly"]);
- string tag_name = (string) (att ["tagname"] == null ? "" : att ["tagname"]);
- string src = (string) (att ["src"] == null ? "" : att ["src"]);
- if (tag_prefix != "" && name_space != "" && assembly_name != ""){
- if (tag_name != "" || src != "")
- throw new ApplicationException ("Invalid attributes for @ Register: " +
- att.ToString ());
- AddUsing (name_space);
- string dll = privateBinPath + Path.DirectorySeparatorChar + assembly_name + ".dll";
- // Hack: it should use assembly.load semantics...
- // may be when we don't run mcs as a external program...
- if (!File.Exists (dll))
- dll = assembly_name;
- Foundry.RegisterFoundry (tag_prefix, dll, name_space);
- AddReference (dll);
- return;
- }
- if (tag_prefix != "" && tag_name != "" && src != ""){
- if (name_space != "" && assembly_name != "")
- throw new ApplicationException ("Invalid attributes for @ Register: " +
- att.ToString ());
-
- if (!src.EndsWith (".ascx"))
- throw new ApplicationException ("Source file extension for controls " +
- "must be .ascx");
- UserControlData data = GenerateUserControl (src, Context);
- switch (data.result) {
- case UserControlResult.OK:
- AddUsing ("ASP");
- Foundry.RegisterFoundry (tag_prefix, tag_name, data.assemblyName, "ASP", data.className);
- AddReference (data.assemblyName);
- break;
- case UserControlResult.FileNotFound:
- throw new ApplicationException ("File '" + src + "' not found.");
- case UserControlResult.CompilationFailed:
- //TODO: should say where the generated .cs file is for the server to
- //show the source and the compiler error
- throw new NotImplementedException ();
- }
- return;
- }
- throw new ApplicationException ("Invalid combination of attributes in " +
- "@ Register: " + att.ToString ());
- }
- private void ProcessDirective ()
- {
- FlushPlainText ();
- Directive directive = (Directive) current;
- TagAttributes att = directive.Attributes;
- if (att == null)
- return;
- string value;
- string id = directive.TagID.ToUpper ();
- switch (id){
- case "APPLICATION":
- if (main_directive != null)
- throw new ApplicationException (id + " not allowed after " + main_directive);
- if (!IsApplication)
- throw new ApplicationException ("@Application not allowed.");
- string inherits = att ["inherits"] as string;
- if (inherits != null)
- Options ["Inherits"] = inherits;
- main_directive = directive.TagID;
- break;
- case "PAGE":
- case "CONTROL":
- if (main_directive != null)
- throw new ApplicationException (id + " not allowed after " + main_directive);
- if (IsUserControl && id != "CONTROL")
- throw new ApplicationException ("@Page not allowed for user controls.");
- else if (IsPage && id != "PAGE")
- throw new ApplicationException ("@Control not allowed here. This is a page!");
- PageDirective (att);
- main_directive = directive.TagID;
- break;
- case "IMPORT":
- value = att ["namespace"] as string;
- if (value == null || att.Count > 1)
- throw new ApplicationException ("Wrong syntax in Import directive.");
- string _using = "using " + value + ";";
- if (AddUsing (value) == true) {
- string imports = Options ["Import"] as string;
- if (imports == null) {
- imports = value;
- } else {
- imports += "," + value;
- }
- Options ["Import"] = imports;
- }
- break;
- case "IMPLEMENTS":
- if (IsApplication)
- throw new ApplicationException ("@ Implements not allowed in an application file.");
- string iface = (string) att ["interface"];
- AddInterface (iface);
- break;
- case "REGISTER":
- if (IsApplication)
- throw new ApplicationException ("@ Register not allowed in an application file.");
- RegisterDirective (att);
- break;
- case "ASSEMBLY":
- if (att.Count > 1)
- throw new ApplicationException ("Wrong syntax in Assembly directive.");
- string name = att ["name"] as string;
- string src = att ["src"] as string;
- if (name == null && src == null)
- throw new ApplicationException ("Wrong syntax in Assembly directive.");
- if (IsApplication && src != null)
- throw new ApplicationException ("'name' attribute expected.");
- value = (name == null) ? src : name;
- string assemblies = Options ["Assembly"] as string;
- if (assemblies == null) {
- assemblies = value;
- } else {
- assemblies += "," + value;
- }
- Options ["Assembly"] = assemblies;
- break;
- }
- }
- private void ProcessPlainText ()
- {
- PlainText asis = (PlainText) current;
- string trimmed = asis.Text.Trim ();
- if (trimmed == String.Empty && controls.SpaceBetweenTags == true)
- return;
- if (IsApplication) {
- if (trimmed != String.Empty)
- throw new ApplicationException (app_file_wrong);
- return;
- }
- if (trimmed != String.Empty && controls.PeekChildKind () != ChildrenKind.CONTROLS){
- string tag_id = controls.PeekTagID ();
- throw new ApplicationException ("Literal content not allowed for " + tag_id);
- }
-
- string escaped_text = Escape (asis.Text);
- current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject (" +
- "new System.Web.UI.LiteralControl (\"{0}\"));\n",
- escaped_text);
- StringBuilder codeRenderFunction = controls.CodeRenderFunction;
- codeRenderFunction.AppendFormat ("\t\t\t__output.Write (\"{0}\");\n", escaped_text);
- }
- private string EnumValueNameToString (Type enum_type, string value_name)
- {
- if (value_name.EndsWith ("*"))
- throw new ApplicationException ("Invalid property value: '" + value_name +
- ". It must be a valid " + enum_type.ToString () + " value.");
- MemberInfo [] nested_types = enum_type.FindMembers (MemberTypes.Field,
- BindingFlags.Public | BindingFlags.Static,
- Type.FilterNameIgnoreCase,
- value_name);
- if (nested_types.Length == 0)
- throw new ApplicationException ("Value " + value_name + " not found in enumeration " +
- enum_type.ToString ());
- if (nested_types.Length > 1)
- throw new ApplicationException ("Value " + value_name + " found " +
- nested_types.Length + " in enumeration " +
- enum_type.ToString ());
- return enum_type.ToString () + "." + nested_types [0].Name;
- }
-
- private void NewControlFunction (string tag_id,
- string control_id,
- Type control_type,
- ChildrenKind children_kind,
- string defaultPropertyName)
- {
- ChildrenKind prev_children_kind = controls.PeekChildKind ();
- if (prev_children_kind == ChildrenKind.NONE ||
- prev_children_kind == ChildrenKind.PROPERTIES){
- string prev_tag_id = controls.PeekTagID ();
- throw new ApplicationException ("Child controls not allowed for " + prev_tag_id);
- }
- Type allowed = null;
- if (prev_children_kind == ChildrenKind.DBCOLUMNS &&
- !typeof (DataGridColumn).IsAssignableFrom (control_type)) {
- allowed = typeof (DataGridColumn);
- } else if (prev_children_kind == ChildrenKind.LISTITEM &&
- control_type != typeof (System.Web.UI.WebControls.ListItem)) {
- allowed = typeof (DataGridColumn);
- } else if (prev_children_kind == ChildrenKind.HTMLROW) {
- Type prevType = controls.PeekType ();
- if (prevType == typeof (HtmlTable) && control_type != typeof (HtmlTableRow))
- allowed = typeof (HtmlTableRow);
- else if (prevType == typeof (Table) && control_type != typeof (TableRow))
- allowed = typeof (TableRow);
- } else if (prev_children_kind == ChildrenKind.HTMLCELL) {
- Type prevType = controls.PeekType ();
- if (prevType == typeof (HtmlTableRow) && control_type != typeof (HtmlTableCell))
- allowed = typeof (HtmlTableCell);
- else if (prevType == typeof (TableRow) && control_type != typeof (TableCell))
- allowed = typeof (TableCell);
- }
-
- if (allowed != null)
- throw new ApplicationException ("Inside " + controls.PeekTagID () + " only " +
- allowed + " objects are allowed");
- StringBuilder func_code = new StringBuilder ();
- current_function = func_code;
- if (0 == String.Compare (tag_id, "form", true)){
- if (has_form_tag)
- throw new ApplicationException ("Only one form server tag allowed.");
- has_form_tag = true;
- }
- controls.Push (control_type, control_id, tag_id, children_kind, defaultPropertyName);
- bool is_generic = control_type == typeof (System.Web.UI.HtmlControls.HtmlGenericControl);
- functions.Push (current_function);
- if (control_type != typeof (System.Web.UI.WebControls.ListItem) &&
- prev_children_kind != ChildrenKind.DBCOLUMNS) {
- current_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_" +
- "{0} ()\n\t\t{{\n\t\t\t{1} __ctrl;\n\n\t\t\t__ctrl" +
- " = new {1} ({2});\n\t\t\tthis.{0} = __ctrl;\n",
- control_id, control_type,
- (is_generic? "\"" + tag_id + "\"" : ""));
- } else {
- current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ()\n\t\t{{" +
- "\n\t\t\t{1} __ctrl;\n\t\t\t__ctrl = new {1} ();" +
- "\n\t\t\tthis.{0} = __ctrl;\n",
- control_id, control_type);
- }
- if (children_kind == ChildrenKind.CONTROLS || children_kind == ChildrenKind.OPTION)
- current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " +
- "(System.Web.UI.IParserAccessor) __ctrl;\n");
- }
-
- private void DataBoundProperty (Type target, string varName, string value)
- {
- if (value == "")
- throw new ApplicationException ("Empty data binding tag.");
- string control_id = controls.PeekControlID ();
- string control_type_string = controls.PeekType ().ToString ();
- StringBuilder db_function = controls.DataBindFunction;
- string container;
- if (controls.Container == null || !typeof (INamingContainer).IsAssignableFrom (controls.Container))
- container = "System.Web.UI.Control";
- else {
- container = controls.Container.ToString ();
- }
- if (db_function.Length == 0)
- db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
- "System.EventArgs e) {{\n" +
- "\t\t\t{1} Container;\n" +
- "\t\t\t{2} target;\n" +
- "\t\t\ttarget = ({2}) sender;\n" +
- "\t\t\tContainer = ({1}) target.BindingContainer;\n",
- control_id, container, control_type_string);
- /* Removes '<%#' and '%>' */
- string real_value = value.Remove (0,3);
- real_value = real_value.Remove (real_value.Length - 2, 2);
- real_value = real_value.Trim ();
- if (target == typeof (string))
- db_function.AppendFormat ("\t\t\ttarget.{0} = System.Convert.ToString ({1});\n",
- varName, real_value);
- else
- db_function.AppendFormat ("\t\t\ttarget.{0} = ({1}) ({2});\n",
- varName, target, real_value);
- }
- /*
- * Returns true if it generates some code for the specified property
- */
- private void AddCodeForPropertyOrField (Type type, string var_name, string att, bool isDataBound)
- {
- /* FIXME: should i check for this or let the compiler fail?
- * if (!prop.CanWrite)
- * ....
- */
- if (isDataBound) {
- DataBoundProperty (type, var_name, att);
- }
- else if (type == typeof (string)){
- if (att == null)
- throw new ApplicationException ("null value for attribute " + var_name );
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = \"{1}\";\n", var_name,
- Escape (att)); // FIXME: really Escape this?
- }
- else if (type.IsEnum){
- if (att == null)
- throw new ApplicationException ("null value for attribute " + var_name );
- string enum_value = EnumValueNameToString (type, att);
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, enum_value);
- }
- else if (type == typeof (bool)){
- string value;
- if (att == null)
- value = "true"; //FIXME: is this ok for non Style properties?
- else if (0 == String.Compare (att, "true", true))
- value = "true";
- else if (0 == String.Compare (att, "false", true))
- value = "false";
- else
- throw new ApplicationException ("Value '" + att + "' is not a valid boolean.");
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
- }
- else if (type == typeof (System.Web.UI.WebControls.Unit)){
- //FIXME: should use the culture specified in Page
- try {
- Unit value = Unit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
- } catch (Exception) {
- throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
- }
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
- "System.Web.UI.WebControls.Unit.Parse (\"{1}\", " +
- "System.Globalization.CultureInfo.InvariantCulture);\n",
- var_name, att);
- }
- else if (type == typeof (System.Web.UI.WebControls.FontUnit)){
- //FIXME: should use the culture specified in Page
- try {
- FontUnit value = FontUnit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
- } catch (Exception) {
- throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
- }
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = " +
- "System.Web.UI.WebControls.FontUnit.Parse (\"{1}\", " +
- "System.Globalization.CultureInfo.InvariantCulture);\n",
- var_name, att);
- }
- else if (type == typeof (Int16) || type == typeof (Int32) || type == typeof (Int64)) {
- long value;
- try {
- value = Int64.Parse (att); //FIXME: should use the culture specified in Page
- } catch (Exception){
- throw new ApplicationException (att + " is not a valid signed number " +
- "or is out of range.");
- }
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
- }
- else if (type == typeof (UInt16) || type == typeof (UInt32) || type == typeof (UInt64)) {
- ulong value;
- try {
- value = UInt64.Parse (att); //FIXME: should use the culture specified in Page
- } catch (Exception){
- throw new ApplicationException (att + " is not a valid unsigned number " +
- "or is out of range.");
- }
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
- }
- else if (type == typeof (float)) {
- float value;
- try {
- value = Single.Parse (att);
- } catch (Exception){
- throw new ApplicationException (att + " is not avalid float number or " +
- "is out of range.");
- }
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
- }
- else if (type == typeof (double)){
- double value;
- try {
- value = Double.Parse (att);
- } catch (Exception){
- throw new ApplicationException (att + " is not avalid double number or " +
- "is out of range.");
- }
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
- }
- else if (type == typeof (System.Drawing.Color)){
- Color c;
- try {
- c = (Color) TypeDescriptor.GetConverter (typeof (Color)).ConvertFromString (att);
- } catch (Exception e){
- throw new ApplicationException ("Color " + att + " is not a valid color.", e);
- }
- // Should i also test for IsSystemColor?
- // Are KnownColor members in System.Drawing.Color?
- if (c.IsKnownColor){
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
- "{1};\n", var_name, c.Name);
- }
- else {
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
- "FromArgb ({1}, {2}, {3}, {4});\n",
- var_name, c.A, c.R, c.G, c.B);
- }
- }
- else if (type == typeof (string [])) {
- string [] subStrings = att.Split (',');
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = new String [] {{\n", var_name);
- int end = subStrings.Length;
- for (int i = 0; i < end; i++) {
- string s = subStrings [i].Trim ();
- current_function.AppendFormat ("\t\t\t\t\"{0}\"", s);
- if (i == end - 1)
- current_function.Append ("\t\t\t\t};\n");
- else
- current_function.Append (",\n");
- }
- } else {
- throw new ApplicationException ("Unsupported type in property: " +
- type.ToString ());
- }
- }
- private bool ProcessPropertiesAndFields (MemberInfo member, string id, TagAttributes att)
- {
- int hyphen = id.IndexOf ('-');
- bool isPropertyInfo = (member is PropertyInfo);
- bool is_processed = false;
- bool isDataBound = att.IsDataBound ((string) att [id]);
- Type type;
- if (isPropertyInfo) {
- type = ((PropertyInfo) member).PropertyType;
- if (hyphen == -1 && ((PropertyInfo) member).CanWrite == false)
- return false;
- } else {
- type = ((FieldInfo) member).FieldType;
- }
- if (0 == String.Compare (member.Name, id, true)){
- AddCodeForPropertyOrField (type, member.Name, (string) att [id], isDataBound);
- is_processed = true;
- } else if (hyphen != -1 && (type == fontinfoType || type == styleType || type.IsSubclassOf (styleType))){
- string prop_field = id.Replace ("-", ".");
- string [] parts = prop_field.Split (new char [] {'.'});
- if (parts.Length != 2 || 0 != String.Compare (member.Name, parts [0], true))
- return false;
- PropertyInfo [] subprops = type.GetProperties ();
- foreach (PropertyInfo subprop in subprops){
- if (0 != String.Compare (subprop.Name, parts [1], true))
- continue;
- if (subprop.CanWrite == false)
- return false;
- bool is_bool = subprop.PropertyType == typeof (bool);
- if (!is_bool && att [id] == null){
- att [id] = ""; // Font-Size -> Font-Size="" as html
- return false;
- }
- string value;
- if (att [id] == null && is_bool)
- value = "true"; // Font-Bold <=> Font-Bold="true"
- else
- value = (string) att [id];
- AddCodeForPropertyOrField (subprop.PropertyType,
- member.Name + "." + subprop.Name,
- value, isDataBound);
- is_processed = true;
- }
- }
- return is_processed;
- }
-
- private void AddCodeForAttributes (Type type, TagAttributes att)
- {
- EventInfo [] ev_info = type.GetEvents ();
- PropertyInfo [] prop_info = type.GetProperties ();
- FieldInfo [] field_info = type.GetFields ();
- bool is_processed = false;
- ArrayList processed = new ArrayList ();
- foreach (string id in att.Keys){
- if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
- continue;
- if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
- string id_as_event = id.Substring (2);
- foreach (EventInfo ev in ev_info){
- if (0 == String.Compare (ev.Name, id_as_event, true)){
- current_function.AppendFormat (
- "\t\t\t__ctrl.{0} += " +
- "new {1} (this.{2});\n",
- ev.Name, ev.EventHandlerType, att [id]);
- is_processed = true;
- break;
- }
- }
- if (is_processed){
- is_processed = false;
- continue;
- }
- }
- foreach (PropertyInfo prop in prop_info){
- is_processed = ProcessPropertiesAndFields (prop, id, att);
- if (is_processed)
- break;
- }
- if (!is_processed) {
- foreach (FieldInfo field in field_info){
- is_processed = ProcessPropertiesAndFields (field, id, att);
- if (is_processed)
- break;
- }
- }
- if (is_processed){
- is_processed = false;
- continue;
- }
- current_function.AppendFormat ("\t\t\t((System.Web.UI.IAttributeAccessor) __ctrl)." +
- "SetAttribute (\"{0}\", \"{1}\");\n",
- id, Escape ((string) att [id]));
- }
- }
-
- private void AddCodeRenderControl (StringBuilder function)
- {
- AddCodeRenderControl (function, controls.CodeRenderIndex);
- }
- private void AddCodeRenderControl (StringBuilder function, int index)
- {
- function.AppendFormat ("\t\t\tparameterContainer.Controls [{0}]." +
- "RenderControl (__output);\n", index);
- }
- private void AddRenderMethodDelegate (StringBuilder function, string control_id)
- {
- function.AppendFormat ("\t\t\t__ctrl.SetRenderMethodDelegate (new System.Web." +
- "UI.RenderMethod (this.__Render_{0}));\n", control_id);
- }
- private void AddCodeRenderFunction (string codeRender, string control_id)
- {
- StringBuilder codeRenderFunction = new StringBuilder ();
- codeRenderFunction.AppendFormat ("\t\tprivate void __Render_{0} " +
- "(System.Web.UI.HtmlTextWriter __output, " +
- "System.Web.UI.Control parameterContainer)\n" +
- "\t\t{{\n", control_id);
- codeRenderFunction.Append (codeRender);
- codeRenderFunction.Append ("\t\t}\n\n");
- init_funcs.Append (codeRenderFunction);
- }
- private void RemoveLiterals (StringBuilder function)
- {
- string no_literals = Regex.Replace (function.ToString (),
- @"\t\t\t__parser.AddParsedSubObject \(" +
- @"new System.Web.UI.LiteralControl \(.+\);\n", "");
- function.Length = 0;
- function.Append (no_literals);
- }
- private bool FinishControlFunction (string tag_id)
- {
- if (functions.Count == 0)
- throw new ApplicationException ("Unbalanced open/close tags");
- if (controls.Count == 0)
- return false;
- string saved_id = controls.PeekTagID ();
- if (0 != String.Compare (saved_id, tag_id, true))
- return false;
- FlushPlainText ();
- StringBuilder old_function = (StringBuilder) functions.Pop ();
- current_function = (StringBuilder) functions.Peek ();
- string control_id = controls.PeekControlID ();
- Type control_type = controls.PeekType ();
- ChildrenKind child_kind = controls.PeekChildKind ();
- bool hasDataBindFunction = controls.HasDataBindFunction ();
- if (hasDataBindFunction)
- old_function.AppendFormat ("\t\t\t__ctrl.DataBinding += new System.EventHandler " +
- "(this.__DataBind_{0});\n", control_id);
- bool useCodeRender = controls.UseCodeRender;
- if (useCodeRender)
- AddRenderMethodDelegate (old_function, control_id);
-
- if (control_type == typeof (System.Web.UI.ITemplate)){
- old_function.Append ("\n\t\t}\n\n");
- current_function.AppendFormat ("\t\t\t__ctrl.{0} = new System.Web.UI." +
- "CompiledTemplateBuilder (new System.Web.UI." +
- "BuildTemplateMethod (this.__BuildControl_{1}));\n",
- saved_id, control_id);
- }
- else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumnCollection)){
- old_function.Append ("\n\t\t}\n\n");
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
- control_id, saved_id);
- }
- else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumn) ||
- control_type.IsSubclassOf (typeof (System.Web.UI.WebControls.DataGridColumn)) ||
- control_type == typeof (System.Web.UI.WebControls.ListItem)){
- old_function.Append ("\n\t\t}\n\n");
- string parsed = "";
- string ctrl_name = "ctrl";
- Type cont = controls.Container;
- if (cont == null || cont == typeof (System.Web.UI.HtmlControls.HtmlSelect)){
- parsed = "ParsedSubObject";
- ctrl_name = "parser";
- }
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
- "\t\t\t__{1}.Add{2} (this.{0});\n\n",
- control_id, ctrl_name, parsed);
- }
- else if (child_kind == ChildrenKind.LISTITEM){
- old_function.Append ("\n\t\t}\n\n");
- init_funcs.Append (old_function); // Closes the BuildList function
- old_function = (StringBuilder) functions.Pop ();
- current_function = (StringBuilder) functions.Peek ();
- old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
- "return __ctrl;\n\t\t}}\n\n",
- control_id, controls.PeekDefaultPropertyName ());
- controls.Pop ();
- control_id = controls.PeekControlID ();
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
- "AddParsedSubObject (this.{0});\n\n", control_id);
- } else if (control_type == typeof (HtmlTableCell) || control_type == typeof (TableCell)) {
- old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
- object top = controls.Pop ();
- Type t = controls.PeekType ();
- controls.Push (top);
- string parsed = "";
- string ctrl_name = "ctrl";
- if (!t.IsSubclassOf (typeof (WebControl)) && t != typeof (HtmlTableRow)) {
- parsed = "ParsedSubObject";
- ctrl_name = "parser";
- }
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
- "\t\t\t__{1}.Add{2} (this.{0});\n\n",
- control_id, ctrl_name, parsed);
- } else if (child_kind == ChildrenKind.HTMLROW || child_kind == ChildrenKind.HTMLCELL) {
- old_function.Append ("\n\t\t}\n\n");
- init_funcs.Append (old_function);
- old_function = (StringBuilder) functions.Pop ();
- current_function = (StringBuilder) functions.Peek ();
- old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
- "return __ctrl;\n\t\t}}\n\n",
- control_id, controls.PeekDefaultPropertyName ());
- controls.Pop ();
- control_id = controls.PeekControlID ();
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n", control_id);
- if (child_kind == ChildrenKind.HTMLROW) {
- current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject ({0});\n",
- control_id);
- } else {
- current_function.AppendFormat ("\t\t\t__ctrl.Add (this.{0});\n", control_id);
- }
- } else {
- old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
- "AddParsedSubObject (this.{0});\n\n", control_id);
- }
- if (useCodeRender)
- RemoveLiterals (old_function);
- init_funcs.Append (old_function);
- if (useCodeRender)
- AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), control_id);
-
- if (hasDataBindFunction){
- StringBuilder db_function = controls.DataBindFunction;
- db_function.Append ("\t\t}\n\n");
- init_funcs.Append (db_function);
- }
- // Avoid getting empty stacks for unbalanced open/close tags
- if (controls.Count > 1){
- controls.Pop ();
- AddCodeRenderControl (controls.CodeRenderFunction, controls.ChildIndex);
- }
- return true;
- }
- private void NewTableElementFunction (HtmlControlTag ctrl)
- {
- string control_id = Tag.GetDefaultID ();
- ChildrenKind child_kind;
- Type t;
- if (ctrl.ControlType == typeof (HtmlTable)) {
- t = typeof (HtmlTableRowCollection);
- child_kind = ChildrenKind.HTMLROW;
- } else {
- t = typeof (HtmlTableCellCollection);
- child_kind = ChildrenKind.HTMLCELL;
- }
- controls.Push (ctrl.ControlType,
- control_id,
- ctrl.TagID,
- child_kind,
- ctrl.ParseChildren);
- current_function = new StringBuilder ();
- functions.Push (current_function);
- current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
- "\t\t{{\n", control_id, t);
- }
- private void ProcessHtmlControlTag ()
- {
- FlushPlainText ();
- HtmlControlTag html_ctrl = (HtmlControlTag) current;
- if (html_ctrl.TagID.ToUpper () == "SCRIPT"){
- //FIXME: if the is script is to be read from disk, do it!
- if (html_ctrl.SelfClosing)
- throw new ApplicationException ("Read script from file not supported yet.");
- sstatus = ScriptStatus.Open;
- return;
- }
-
- if (IsApplication)
- throw new ApplicationException (app_file_wrong);
-
- Type controlType = html_ctrl.ControlType;
- AddProtectedField (controlType, html_ctrl.ControlID);
- ChildrenKind children_kind;
- if (0 == String.Compare (html_ctrl.TagID, "table", true))
- children_kind = ChildrenKind.HTMLROW;
- else if (0 == String.Compare (html_ctrl.TagID, "tr", true))
- children_kind = ChildrenKind.HTMLCELL;
- else if (0 != String.Compare (html_ctrl.TagID, "select", true))
- children_kind = html_ctrl.IsContainer ? ChildrenKind.CONTROLS :
- ChildrenKind.NONE;
- else
- children_kind = ChildrenKind.OPTION;
- NewControlFunction (html_ctrl.TagID, html_ctrl.ControlID, controlType, children_kind, html_ctrl.ParseChildren);
- current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", html_ctrl.ControlID);
- AddCodeForAttributes (html_ctrl.ControlType, html_ctrl.Attributes);
- if (children_kind == ChildrenKind.HTMLROW || children_kind == ChildrenKind.HTMLCELL)
- NewTableElementFunction (html_ctrl);
- if (html_ctrl.SelfClosing)
- FinishControlFunction (html_ctrl.TagID);
- }
- // Closing is performed in FinishControlFunction ()
- private void NewBuildListFunction (AspComponent component)
- {
- string control_id = Tag.GetDefaultID ();
- controls.Push (component.ComponentType,
- control_id,
- component.TagID,
- component.ChildrenKind,
- component.DefaultPropertyName);
- Type childType = component.DefaultPropertyType;
- if (childType == null)
- childType = typeof (ListItemCollection);
- current_function = new StringBuilder ();
- functions.Push (current_function);
- current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
- "({1} __ctrl)\n" +
- "\t\t{{\n", control_id, childType);
- }
- private void ProcessComponent ()
- {
- FlushPlainText ();
- AspComponent component = (AspComponent) current;
- Type component_type = component.ComponentType;
- AddProtectedField (component_type, component.ControlID);
- NewControlFunction (component.TagID, component.ControlID, component_type,
- component.ChildrenKind, component.DefaultPropertyName);
- if (component_type == typeof (UserControl) ||
- component_type.IsSubclassOf (typeof (System.Web.UI.UserControl)))
- current_function.Append ("\t\t\t__ctrl.InitializeAsUserControl (Page);\n");
- if (component_type == typeof (Control) ||
- component_type.IsSubclassOf (typeof (System.Web.UI.Control)))
- current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", component.ControlID);
- AddCodeForAttributes (component.ComponentType, component.Attributes);
- if (component.ChildrenKind == ChildrenKind.LISTITEM || component.DefaultPropertyType != null)
- NewBuildListFunction (component);
- if (component.SelfClosing)
- FinishControlFunction (component.TagID);
- }
- private void ProcessServerObjectTag ()
- {
- FlushPlainText ();
- ServerObjectTag obj = (ServerObjectTag) current;
- declarations.AppendFormat ("\t\tprivate {0} cached{1};\n", obj.ObjectClass, obj.ObjectID);
- constructor.AppendFormat ("\n\t\tprivate {0} {1}\n\t\t{{\n\t\t\tget {{\n\t\t\t\t" +
- "if (this.cached{1} == null)\n\t\t\t\t\tthis.cached{1} = " +
- "new {0} ();\n\t\t\t\treturn cached{1};\n\t\t\t}}\n\t\t}}\n\n",
- obj.ObjectClass, obj.ObjectID);
- }
- // Creates a new function that sets the values of subproperties.
- private void NewStyleFunction (PropertyTag tag)
- {
- current_function = new StringBuilder ();
- string prop_id = tag.PropertyID;
- Type prop_type = tag.PropertyType;
- // begin function
- current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
- "\t\t{{\n", prop_id, prop_type);
-
- // Add property initialization code
- PropertyInfo [] subprop_info = prop_type.GetProperties ();
- TagAttributes att = tag.Attributes;
- string subprop_name = null;
- foreach (string id in att.Keys){
- if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
- continue;
- bool is_processed = false;
- foreach (PropertyInfo subprop in subprop_info){
- is_processed = ProcessPropertiesAndFields (subprop, id, att);
- if (is_processed){
- subprop_name = subprop.Name;
- break;
- }
- }
- if (subprop_name == null)
- throw new ApplicationException ("Property " + tag.TagID + " does not have " +
- "a " + id + " subproperty.");
- }
- // Finish function
- current_function.Append ("\n\t\t}\n\n");
- init_funcs.Append (current_function);
- current_function = (StringBuilder) functions.Peek ();
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
- prop_id, tag.PropertyName);
- if (!tag.SelfClosing){
- // Next tag should be the closing tag
- controls.Push (null, null, null, ChildrenKind.NONE, null);
- waitClosing = tag.TagID;
- }
- }
- // This one just opens the function. Closing is performed in FinishControlFunction ()
- private void NewTemplateFunction (PropertyTag tag)
- {
- /*
- * FIXME
- * This function does almost the same as NewControlFunction.
- * Consider merging.
- */
- string prop_id = tag.PropertyID;
- Type prop_type = tag.PropertyType;
- string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
- controls.Push (prop_type, prop_id, tag_id, ChildrenKind.CONTROLS, null);
- current_function = new StringBuilder ();
- functions.Push (current_function);
- current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
- "(System.Web.UI.Control __ctrl)\n" +
- "\t\t{{\n" +
- "\t\t\tSystem.Web.UI.IParserAccessor __parser " +
- "= (System.Web.UI.IParserAccessor) __ctrl;\n" , prop_id);
- }
- // Closing is performed in FinishControlFunction ()
- private void NewDBColumnFunction (PropertyTag tag)
- {
- /*
- * FIXME
- * This function also does almost the same as NewControlFunction.
- * Consider merging.
- */
- string prop_id = tag.PropertyID;
- Type prop_type = tag.PropertyType;
- string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
- controls.Push (prop_type, prop_id, tag_id, ChildrenKind.DBCOLUMNS, null);
- current_function = new StringBuilder ();
- functions.Push (current_function);
- current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
- "(System.Web.UI.WebControls.DataGridColumnCollection __ctrl)\n" +
- "\t\t{{\n", prop_id);
- }
- private void NewPropertyFunction (PropertyTag tag)
- {
- FlushPlainText ();
- if (tag.PropertyType == typeof (System.Web.UI.WebControls.Style) ||
- tag.PropertyType.IsSubclassOf (typeof (System.Web.UI.WebControls.Style)))
- NewStyleFunction (tag);
- else if (tag.PropertyType == typeof (System.Web.UI.ITemplate))
- NewTemplateFunction (tag);
- else if (tag.PropertyType == typeof (System.Web.UI.WebControls.DataGridColumnCollection))
- NewDBColumnFunction (tag);
- else
- throw new ApplicationException ("Other than Style and ITemplate not supported yet. " +
- tag.PropertyType);
- }
-
- private void ProcessHtmlTag ()
- {
- Tag tag = (Tag) current;
- ChildrenKind child_kind = controls.PeekChildKind ();
- if (child_kind == ChildrenKind.NONE){
- string tag_id = controls.PeekTagID ();
- throw new ApplicationException (tag + " not allowed inside " + tag_id);
- }
-
- if (child_kind == ChildrenKind.OPTION){
- if (0 != String.Compare (tag.TagID, "option", true))
- throw new ApplicationException ("Only <option> tags allowed inside <select>.");
- string default_id = Tag.GetDefaultID ();
- Type type = typeof (System.Web.UI.WebControls.ListItem);
- AddProtectedField (type, default_id);
- NewControlFunction (tag.TagID, default_id, type, ChildrenKind.CONTROLS, null);
- return;
- }
- if (child_kind == ChildrenKind.CONTROLS) {
- ArrayList tag_elements = tag.GetElements ();
- foreach (Element e in tag_elements) {
- if (e is PlainText) {
- current = e;
- textChunk.Append (((PlainText) e).Text);
- } else if (e is CodeRenderTag) {
- current = e;
- ProcessCodeRenderTag ();
- } else if (e is DataBindingTag) {
- current = e;
- ProcessDataBindingLiteral ();
- } else {
- throw new ApplicationException (fullPath + ": unexpected tag type " + e.GetType ());
- }
- }
- return;
- }
- if (child_kind == ChildrenKind.HTMLROW) {
- if (0 == String.Compare (tag.TagID, "tr", true)) {
- current = new HtmlControlTag (tag);
- ProcessHtmlControlTag ();
- return;
- }
- }
- if (child_kind == ChildrenKind.HTMLCELL) {
- if (0 == String.Compare (tag.TagID, "td", true)) {
- current = new HtmlControlTag (tag);
- ProcessHtmlControlTag ();
- return;
- }
- }
- // Now child_kind should be PROPERTIES, so only allow tag_id == property
- Type control_type = controls.PeekType ();
- PropertyInfo [] prop_info = control_type.GetProperties ();
- bool is_processed = false;
- foreach (PropertyInfo prop in prop_info){
- if (0 == String.Compare (prop.Name, tag.TagID, true)){
- PropertyTag prop_tag = new PropertyTag (tag, prop.PropertyType, prop.Name);
- NewPropertyFunction (prop_tag);
- is_processed = true;
- break;
- }
- }
-
- if (!is_processed){
- string tag_id = controls.PeekTagID ();
- throw new ApplicationException (tag.TagID + " is not a property of " + control_type);
- }
- }
- private Tag Map (Tag tag)
- {
- int pos = tag.TagID.IndexOf (":");
- if (pos == -1) {
- ChildrenKind child_kind = controls.PeekChildKind ();
- if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
- tag.Attributes.Add ("runat", "server");
- return new HtmlControlTag (tag);
- } else if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
- tag.Attributes.Add ("runat", "server");
- return new HtmlControlTag (tag);
- }
- }
- if (tag is CloseTag ||
- ((tag.Attributes == null ||
- !tag.Attributes.IsRunAtServer ()) && pos == -1))
- return tag;
- if (pos == -1){
- if (0 == String.Compare (tag.TagID, "object", true))
- return new ServerObjectTag (tag);
- return new HtmlControlTag (tag);
- }
- string foundry_name = tag.TagID.Substring (0, pos);
- string component_name = tag.TagID.Substring (pos + 1);
- if (Foundry.LookupFoundry (foundry_name) == false)
- throw new ApplicationException ("Cannot find foundry for alias'" + foundry_name + "'");
- AspComponent component = Foundry.MakeAspComponent (foundry_name, component_name, tag);
- if (component == null)
- throw new ApplicationException ("Cannot find component '" + component_name +
- "' for alias '" + foundry_name + "'");
- return component;
- }
-
- private void ProcessCloseTag ()
- {
- CloseTag closeTag = (CloseTag) current;
- if (FinishControlFunction (closeTag.TagID))
- return;
- textChunk.Append (closeTag.PlainHtml);
- }
- private void ProcessDataBindingLiteral ()
- {
- FlushPlainText ();
- DataBindingTag dataBinding = (DataBindingTag) current;
- string actual_value = dataBinding.Data;
- if (actual_value == "")
- throw new ApplicationException ("Empty data binding tag.");
- if (controls.PeekChildKind () != ChildrenKind.CONTROLS)
- throw new ApplicationException ("Data bound content not allowed for " +
- controls.PeekTagID ());
- StringBuilder db_function = new StringBuilder ();
- string control_id = Tag.GetDefaultID ();
- string control_type_string = "System.Web.UI.DataBoundLiteralControl";
- AddProtectedField (typeof (System.Web.UI.DataBoundLiteralControl), control_id);
- // Build the control
- db_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_{0} ()\n" +
- "\t\t{{\n\t\t\t{1} __ctrl;\n\n" +
- "\t\t\t__ctrl = new {1} (0, 1);\n" +
- "\t\t\tthis.{0} = __ctrl;\n" +
- "\t\t\t__ctrl.DataBinding += new System.EventHandler " +
- "(this.__DataBind_{0});\n" +
- "\t\t\treturn __ctrl;\n"+
- "\t\t}}\n\n",
- control_id, control_type_string);
- // DataBinding handler
- db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " +
- "System.EventArgs e) {{\n" +
- "\t\t\t{1} Container;\n" +
- "\t\t\t{2} target;\n" +
- "\t\t\ttarget = ({2}) sender;\n" +
- "\t\t\tContainer = ({1}) target.BindingContainer;\n" +
- "\t\t\ttarget.SetDataBoundString (0, System.Convert." +
- "ToString ({3}));\n" +
- "\t\t}}\n\n",
- control_id, controls.Container, control_type_string,
- actual_value);
- init_funcs.Append (db_function);
- current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
- "AddParsedSubObject (this.{0});\n\n", control_id);
- AddCodeRenderControl (controls.CodeRenderFunction);
- }
- private void ProcessCodeRenderTag ()
- {
- FlushPlainText ();
- CodeRenderTag code_tag = (CodeRenderTag) current;
- controls.UseCodeRender = true;
- if (code_tag.IsVarName)
- controls.CodeRenderFunction.AppendFormat ("\t\t\t__output.Write ({0});\n",
- code_tag.Code);
- else
- controls.CodeRenderFunction.AppendFormat ("\t\t\t{0}\n", code_tag.Code);
- }
-
- void FlushPlainText ()
- {
- if (textChunk.Length != 0) {
- Element saved = current;
- current = new PlainText (textChunk.ToString ());
- textChunk.Length = 0;
- ProcessPlainText ();
- current = saved;
- }
- }
-
- void ParseError (string msg, int line, int col)
- {
- throw new ParseException (fullPath, msg, line, col);
- }
- void TagParsed (Tag tag, int line, int col)
- {
- if (waitClosing != null) {
- if (!(tag is CloseTag) || tag.TagID.ToUpper () != waitClosing.ToUpper ())
- throw new HttpException ("Tag " + waitClosing + " not properly closed.");
- waitClosing = null;
- controls.Pop ();
- return;
- }
-
- if ((sstatus == ScriptStatus.Open || sstatus == ScriptStatus.Text) &&
- tag.TagID.ToUpper () == "SCRIPT" && tag is CloseTag) {
- sstatus = ScriptStatus.Close;
- return;
- }
- current = tag;
- if (current is Directive) {
- ProcessDirective ();
- return;
- } else if (current is DataBindingTag) {
- if (IsApplication)
- throw new ApplicationException (app_file_wrong);
- ProcessDataBindingLiteral ();
- return;
- } else if (current is CodeRenderTag) {
- if (IsApplication)
- throw new ApplicationException (app_file_wrong);
- ProcessCodeRenderTag ();
- return;
- }
- current = Map (tag);
- if (current is ServerObjectTag) {
- ProcessServerObjectTag ();
- return;
- } else if (current is HtmlControlTag) {
- ProcessHtmlControlTag ();
- return;
- }
- if (IsApplication)
- throw new ApplicationException (app_file_wrong);
- if (current is AspComponent) {
- ProcessComponent ();
- } else if (current is CloseTag) {
- ProcessCloseTag ();
- } else if (current is Tag) {
- ProcessHtmlTag ();
- } else {
- throw new HttpException ("This place should not be reached.");
- }
- }
- void TextParsed (string text, int line, int col)
- {
- if (sstatus == ScriptStatus.Open) {
- script.Append (text);
- sstatus = ScriptStatus.Text;
- return;
- }
- textChunk.Append (text);
- }
- public void ProcessElements ()
- {
- AspParser parser = new AspParser (fullPath, File.OpenRead (fullPath));
-
- parser.Error += new ParseErrorHandler (ParseError);
- parser.TagParsed += new TagParsedHandler (TagParsed);
- parser.TextParsed += new TextParsedHandler (TextParsed);
- try {
- parser.Parse ();
- } catch (CompilationException e) {
- throw;
- } catch (ParseException e) {
- throw;
- } catch (Exception e) {
- throw new ParseException (fullPath, e.Message, parser.Line, parser.Column, e);
- }
- End ();
- parse_ok = true;
- }
-
- private string GetTemplateDirectory ()
- {
- string templatePath = Path.GetDirectoryName (fullPath);
- string appPath = Path.GetDirectoryName (HttpRuntime.AppDomainAppPath);
- if (templatePath == appPath)
- return "/";
- templatePath = templatePath.Substring (appPath.Length);
- if (Path.DirectorySeparatorChar != '/')
- templatePath = templatePath.Replace (Path.DirectorySeparatorChar, '/');
-
- return templatePath;
- }
- private void End ()
- {
- FlushPlainText ();
- if (isPage) {
- if (sessionState == SessionState.Enabled || sessionState == SessionState.ReadOnly)
- AddInterface (typeof (System.Web.SessionState.IRequiresSessionState));
- if (sessionState == SessionState.ReadOnly)
- AddInterface (typeof (System.Web.SessionState.IReadOnlySessionState));
- }
-
- classDecl = "\tpublic class " + className + " : " + parent + interfaces + " {\n";
- prolog.Append ("\n" + classDecl);
- declarations.Append ("\t\tprivate static bool __intialized = false;\n\n");
- if (IsPage)
- declarations.Append ("\t\tprivate static ArrayList __fileDependencies;\n\n");
- // adds the constructor
- constructor.AppendFormat ("\t\tpublic {0} ()\n\t\t{{\n", className);
- if (!IsApplication)
- constructor.Append ("\t\t\tSystem.Collections.ArrayList dependencies;\n\n");
-
- constructor.AppendFormat ("\t\t\tif (ASP.{0}.__intialized == false){{\n", className);
- if (IsPage) {
- constructor.AppendFormat ("\t\t\t\tdependencies = new System.Collections.ArrayList ();\n" +
- "\t\t\t\tdependencies.Add (@\"{1}\");\n" +
- "\t\t\t\tASP.{0}.__fileDependencies = dependencies;\n",
- className, fullPath);
- }
- constructor.AppendFormat ("\t\t\t\tASP.{0}.__intialized = true;\n\t\t\t}}\n\t\t}}\n\n",
- className);
-
- if (!IsApplication) {
- //FIXME: add AutoHandlers: don't know what for...yet!
- constructor.AppendFormat (
- "\t\tprotected override int AutoHandlers\n\t\t{{\n" +
- "\t\t\tget {{ return ASP.{0}.__autoHandlers; }}\n" +
- "\t\t\tset {{ ASP.{0}.__autoHandlers = value; }}\n" +
- "\t\t}}\n\n", className);
- constructor.Append (
- "\t\tprotected System.Web.HttpApplication ApplicationInstance\n\t\t{\n" +
- "\t\t\tget { return (System.Web.HttpApplication) this.Context.ApplicationInstance; }\n" +
- "\t\t}\n\n");
- constructor.AppendFormat (
- "\t\tpublic override string TemplateSourceDirectory\n\t\t{{\n" +
- "\t\t\tget {{ return \"{0}\"; }}\n" +
- "\t\t}}\n\n", GetTemplateDirectory ());
- epilog.Append ("\n\t\tprotected override void FrameworkInitialize ()\n\t\t{\n" +
- "\t\t\tthis.__BuildControlTree (this);\n");
- if (IsPage) {
- epilog.AppendFormat ("\t\t\tthis.FileDependencies = ASP.{0}.__fileDependencies;\n" +
- "\t\t\tthis.EnableViewStateMac = true;\n", className);
- }
- epilog.Append ("\t\t}\n\n");
- }
- if (IsPage) {
- Random rnd = new Random ();
- epilog.AppendFormat ("\t\tpublic override int GetTypeHashCode ()\n\t\t{{\n" +
- "\t\t\treturn {0};\n" +
- "\t\t}}\n", rnd.Next ());
- }
- epilog.Append ("\t}\n}\n");
- // Closes the currently opened tags
- StringBuilder old_function = current_function;
- string control_id;
- while (functions.Count > 1){
- old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
- init_funcs.Append (old_function);
- control_id = controls.PeekControlID ();
- FinishControlFunction (control_id);
- controls.AddChild ();
- old_function = (StringBuilder) functions.Pop ();
- current_function = (StringBuilder) functions.Peek ();
- controls.Pop ();
- }
- bool useCodeRender = controls.UseCodeRender;
- if (useCodeRender){
- RemoveLiterals (current_function);
- AddRenderMethodDelegate (current_function, controls.PeekControlID ());
- }
-
- current_function.Append ("\t\t}\n\n");
- init_funcs.Append (current_function);
- if (useCodeRender)
- AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), controls.PeekControlID ());
- functions.Pop ();
- }
- //
- // Functions related to compilation of user controls
- //
-
- private static char dirSeparator = Path.DirectorySeparatorChar;
- struct UserControlData
- {
- public UserControlResult result;
- public string className;
- public string assemblyName;
- }
- private static UserControlData GenerateUserControl (string src, HttpContext context)
- {
- UserControlData data = new UserControlData ();
- data.result = UserControlResult.OK;
- UserControlCompiler compiler = new UserControlCompiler (new UserControlParser (src, context));
- Type t = compiler.GetCompiledType ();
- if (t == null) {
- data.result = UserControlResult.CompilationFailed;
- return data;
- }
-
- data.className = t.Name;
- data.assemblyName = compiler.TargetFile;
-
- return data;
- }
- }
- }
|