public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { Hashtable msgs = new Hashtable(); foreach (ModelErrorMessage mem in modelType.GetCustomAttributes(typeof(ModelErrorMessage), false)) { Hashtable ht = new Hashtable(); if (msgs.Contains(mem.language)) { ht = (Hashtable)msgs[mem.language]; msgs.Remove(mem.language); } _RecurAdd(mem.MessageName.Split('.'), mem.Message, 0, ref ht); msgs.Add(mem.language, ht); } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (msgs.Count > 0) { sb.AppendLine((!minimize ? "//Org.Reddragonit.BackBoneDotNet.JSGenerators.ErrorMessageGenerator\n" : "") + "_.extend(true,Backbone.ErrorMessages,{"); _RecurWrite(sb, msgs, (minimize ? "" : "\t"), minimize); sb.AppendLine("});"); } return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{Model:Backbone.Model.extend({{initialize:function(){{if(this._revertReadonlyFields!=undefined){{this.on(\"change\",this._revertReadonlyFields);}}}}," :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.ModelDefinitionGenerator {0} = _.extend(true,{0}, {{Model : Backbone.Model.extend({{ initialize : function() {{ if (this._revertReadonlyFields != undefined){{ this.on(""change"",this._revertReadonlyFields); }} }},"), ModelNamespace.GetFullNameForModel(modelType, host)); _AppendDefaults(modelType, properties, sb, minimize); if (!hasDelete) { _AppendBlockDestroy(sb, minimize); } if (!hasAdd && !hasUpdate) { _AppendBlockSave(sb, minimize); } else if (!hasAdd) { _AppendBlockAdd(sb, minimize); } else if (!hasUpdate) { _AppendBlockUpdate(sb, minimize); } _AppendReadonly(readOnlyProperties, sb, minimize); _AppendValidate(modelType, properties, sb, minimize); _AppendParse(modelType, host, properties, readOnlyProperties, sb, minimize); string urlRoot = ""; foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == host) { urlRoot = mr.Path; break; } } if (urlRoot == "") { foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == "*") { urlRoot = mr.Path; break; } } } _AppendExposedMethods(modelType, urlRoot, host, sb, minimize); sb.AppendLine(string.Format((minimize ? "urlRoot:\"{0}\"}})}});" : "\turlRoot : \"{0}\"}})}});"), urlRoot)); return(sb.ToString()); }
public Task HandleRequest(string url, RequestHandler.RequestMethods method, string formData, HttpContext context, ISecureSession session, IsValidCall securityCheck) { if (!HandlesRequest(url, method)) { throw new CallNotFoundException(); } else { Type model = null; if (_types != null) { foreach (Type t in _types) { foreach (ModelJSFilePath mjsfp in t.GetCustomAttributes(typeof(ModelJSFilePath), false)) { if (mjsfp.IsMatch(url)) { model = t; break; } } } if (model != null) { if (!securityCheck.Invoke(model, null, session, null, url, null)) { throw new InsecureAccessException(); } } } string ret = null; context.Response.ContentType = "text/javascript"; context.Response.StatusCode = 200; lock (_cache) { if (_cache.ContainsKey(url)) { ret = _cache[url]; } } if (ret == null && model != null) { WrappedStringBuilder builder = new WrappedStringBuilder(url.ToLower().EndsWith(".min.js")); foreach (IJSGenerator gen in _generators) { gen.GeneratorJS(ref builder, url.ToLower().EndsWith(".min.js"), model); } ret = builder.ToString(); lock (_cache) { if (!_cache.ContainsKey(url)) { _cache.Add(url, ret); } } } return(context.Response.WriteAsync(ret)); } }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (!minimize) sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.RouterGenerator"); Dictionary<string, List<BackboneHashRoute>> routes = new Dictionary<string, List<BackboneHashRoute>>(); foreach (BackboneHashRoute bhr in modelType.GetCustomAttributes(typeof(BackboneHashRoute), false)) { List<BackboneHashRoute> rts = new List<BackboneHashRoute>(); if (routes.ContainsKey(bhr.RouterName)) { rts = routes[bhr.RouterName]; routes.Remove(bhr.RouterName); } rts.Add(bhr); routes.Add(bhr.RouterName, rts); } if (routes.Count > 0) { foreach (string routerName in routes.Keys) { if (routerName.Contains(".")) { string tmp = ""; foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.')) { sb.AppendLine(string.Format((minimize ? "{1}{0}={2}{0}||{{}};" : "{1}{0} = {2}{0} || {{}};"), str, (tmp.Length == 0 ? "var " : tmp+"."), (tmp.Length == 0 ? "" : tmp + "."))); tmp += (tmp.Length == 0 ? "" : ".") + str; } } else sb.AppendLine(string.Format((minimize ? "var {0}={0}||{{}};" : "var {0} = {0} || {{}};"), routerName)); sb.AppendLine(string.Format((minimize ? "if(!Backbone.History.started){{Backbone.history.start({{pushState:false}});}}if({0}.navigate==undefined){{{0}=new Backbone.Router();}}" : @"if (!Backbone.History.started){{ Backbone.history.start({{ pushState: false }}); }} if ({0}.navigate == undefined){{ {0} = new Backbone.Router(); }}"), routerName)); foreach (BackboneHashRoute bhr in routes[routerName]) { sb.AppendFormat(@"{0}.route('{1}','{2}',function(",routerName,bhr.Path,bhr.FunctionName); if (bhr.Path.Contains(":")) { foreach (Match m in _REG_PARS.Matches(bhr.Path)) sb.Append(m.Groups[1].Value + ","); sb.Length = sb.Length - 1; } sb.AppendLine(string.Format((minimize ? "){{{0}}});" : "){{ {0} }});"), bhr.Code)); } } } return sb.ToString(); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); string urlRoot = ""; foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == host) { urlRoot = mr.Path; break; } } if (urlRoot == "") { foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == "*") { urlRoot = mr.Path; break; } } } sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.StaticExposedMethodGenerator {0} = _.extend(true,{0}, {{"), ModelNamespace.GetFullNameForModel(modelType, host)); foreach (MethodInfo mi in modelType.GetMethods(BindingFlags.Public | BindingFlags.Static)) { if (mi.GetCustomAttributes(typeof(ExposedMethod), false).Length > 0) { AppendMethodCall(urlRoot, host, mi, ((ExposedMethod)mi.GetCustomAttributes(typeof(ExposedMethod), false)[0]).AllowNullResponse, ref sb, minimize); } } while (sb.ToString().TrimEnd().EndsWith(",")) { sb.Length = sb.Length - 1; } sb.AppendLine("});"); return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { if (!hasUpdate) { return(""); } else if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.EditForm) == (int)ModelBlockJavascriptGenerations.EditForm) { return(""); } } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{editModel:function(view){{" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.EditAddFormGenerator {0} = _.extend(true,{0},{{editModel : function(view){{"), ModelNamespace.GetFullNameForModel(modelType, host)); ModelEditAddTypes meat = ModelEditAddTypes.dialog; if (modelType.GetCustomAttributes(typeof(ModelEditAddType), false).Length > 0) { meat = ((ModelEditAddType)modelType.GetCustomAttributes(typeof(ModelEditAddType), false)[0]).Type; } switch (meat) { case ModelEditAddTypes.dialog: _RenderDialogCode(modelType, host, readOnlyProperties, properties, sb, minimize); break; case ModelEditAddTypes.inline: _RenderInlineCode(modelType, host, readOnlyProperties, properties, viewIgnoreProperties, sb, minimize); break; } sb.AppendLine("}});"); return(sb.ToString()); }
private void _AppendDefaults(Type modelType, List <string> properties, WrappedStringBuilder sb, bool minimize) { if (modelType.GetConstructor(Type.EmptyTypes) != null) { sb.AppendLine((minimize ? "" : "\t") + "defaults:{"); object obj = modelType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); if (obj != null) { WrappedStringBuilder sbProps = new WrappedStringBuilder(minimize); foreach (string propName in properties) { if (propName != "id") { object pobj = modelType.GetProperty(propName).GetValue(obj, new object[0]); sbProps.AppendLine((minimize ? "" : "\t\t") + propName + ":" + (pobj == null ? "null" : JSON.JsonEncode(pobj)) + (properties.IndexOf(propName) == properties.Count - 1 ? "" : ",")); } } sb.Append(sbProps.ToString().TrimEnd(",\r\n".ToCharArray())); } sb.AppendLine((minimize ? "" : "\t") + "},"); } }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.View) == (int)ModelBlockJavascriptGenerations.View) { return(""); } } string editImage = null; string deleteImage = null; EditButtonDefinition edDef; DeleteButtonDefinition delDef; _LocateButtonImages(modelType, host, out editImage, out deleteImage, out edDef, out delDef); WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{View : Backbone.View.extend({{" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.ViewGenerator {0} = _.extend(true,{0},{{View : Backbone.View.extend({{ "), ModelNamespace.GetFullNameForModel(modelType, host)); string tag = "div"; if (modelType.GetCustomAttributes(typeof(ModelViewTag), false).Length > 0) { tag = ((ModelViewTag)modelType.GetCustomAttributes(typeof(ModelViewTag), false)[0]).TagName; } sb.AppendLine(string.Format((minimize ? "tagName:\"{0}\",":"\ttagName : \"{0}\","), tag)); _AppendClassName(modelType, host, sb, minimize); _AppendAttributes(modelType, sb, minimize); _AppendRenderFunction(modelType, host, tag, properties, hasUpdate, hasDelete, sb, viewIgnoreProperties, editImage, deleteImage, edDef, delDef, minimize); sb.AppendLine("})});"); return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { Hashtable msgs = new Hashtable(); foreach (ModelErrorMessage mem in modelType.GetCustomAttributes(typeof(ModelErrorMessage), false)) { Hashtable ht = new Hashtable(); if (msgs.Contains(mem.language)) { ht = (Hashtable)msgs[mem.language]; msgs.Remove(mem.language); } _RecurAdd(mem.MessageName.Split('.'), mem.Message, 0, ref ht); msgs.Add(mem.language, ht); } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (msgs.Count > 0) { sb.AppendLine((!minimize ? "//Org.Reddragonit.BackBoneDotNet.JSGenerators.ErrorMessageGenerator\n" : "")+ "_.extend(true,Backbone.ErrorMessages,{"); _RecurWrite(sb, msgs,(minimize ? "" : "\t"),minimize); sb.AppendLine("});"); } return sb.ToString(); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { string urlRoot = ""; foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == host) { urlRoot = mr.Path; break; } } if (urlRoot == "") { foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == "*") { urlRoot = mr.Path; break; } } } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (!minimize) { sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.SelectListCallGenerator"); } List <MethodInfo> methods = new List <MethodInfo>(); foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelSelectListMethod), false).Length > 0) { methods.Add(mi); } } int curLen = 0; for (int x = 0; x < methods.Count; x++) { curLen = Math.Max(methods[x].GetParameters().Length, curLen); } int index = 0; while (index < methods.Count) { for (int x = index; x < methods.Count; x++) { if (curLen == methods[x].GetParameters().Length) { MethodInfo mi = methods[x]; methods.RemoveAt(x); methods.Insert(index, mi); index++; x = index - 1; } } curLen = 0; for (int x = index; x < methods.Count; x++) { curLen = Math.Max(methods[x].GetParameters().Length, curLen); } } if (methods.Count > 0) { sb.AppendLine(string.Format((minimize ? "{0}=_.extend(true,{0},{{SelectList:function(pars){{" : "{0} = _.extend(true,{0},{{SelectList : function(pars){{" ), ModelNamespace.GetFullNameForModel(modelType, host))); for (int x = 0; x < methods.Count; x++) { sb.Append((minimize ? "" : "\t") + (x == 0 ? "" : "else ") + "if("); if (methods[x].GetParameters().Length == 0) { sb.AppendLine((minimize? "pars==undefined||pars==null){url='';" : @"pars==undefined || pars==null){ url='';")); } else { ParameterInfo[] pars = methods[x].GetParameters(); WrappedStringBuilder code = new WrappedStringBuilder(minimize); code.AppendLine((minimize ? "url='?';" : "\t\turl='?';")); sb.Append((minimize ? "pars!=undefined&&pars!=null&&(" : "pars!=undefined && pars!=null && (")); for (int y = 0; y < pars.Length; y++) { sb.Append((y != 0 ? (minimize ? "&&" : " && ") : "") + "pars." + pars[y].Name + "!=undefined"); code.AppendLine(string.Format((minimize? "pars.{0}=(pars.{0}==null?'NULL':pars.{0});" :"\t\tpars.{0} = (pars.{0} == null ? 'NULL' : pars.{0});"), pars[y].Name)); if (pars[y].ParameterType == typeof(bool)) { code.AppendLine(string.Format((minimize? "pars.{0}=(pars.{0}==null?'false':(pars.{0}?'true':'false'));" :"\t\tpars.{0} = (pars.{0} == null ? 'false' : (pars.{0} ? 'true' : 'false'));"), pars[y].Name)); } else if (pars[y].ParameterType == typeof(DateTime) || pars[y].ParameterType == typeof(DateTime?)) { code.AppendLine(string.Format((minimize ? "if(pars.{0}!='NULL'){{if(!(pars.{0} instanceof Date)){{pars.{0}=new Date(pars.{0});}}pars.{0}=Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds());}}" : @"if (pars.{0} != 'NULL'){{ if (!(pars.{0} instanceof Date)){{ pars.{0} = new Date(pars.{0}); }} pars.{0} = Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds()); }}"), pars[y].Name)); } code.AppendLine((minimize ? "" : "\t\t") + "url+='" + (y == 0 ? "" : "&") + pars[y].Name + "='+pars." + pars[y].Name + ".toString();"); } sb.AppendLine(")){"); sb.Append(code.ToString()); } sb.AppendLine("}"); } sb.AppendLine(string.Format((minimize ? "else{{return null;}}var ret=$.ajax('{0}'+url,{{async:false,cache:false,type : 'SELECT'}}).responseText;var response=JSON.parse(ret);if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);response=response.response;}}return response;}}}});" :@" else{{ return null; }} var ret=$.ajax( '{0}'+url,{{ async:false, cache:false, type : 'SELECT' }}).responseText; var response = JSON.parse(ret); if(response.Backbone!=undefined){{ _.extend(Backbone,response.Backbone); response=response.response; }} return response; }}}});"), urlRoot)); } return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (!minimize) { sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.RouterGenerator"); } Dictionary <string, List <BackboneHashRoute> > routes = new Dictionary <string, List <BackboneHashRoute> >(); foreach (BackboneHashRoute bhr in modelType.GetCustomAttributes(typeof(BackboneHashRoute), false)) { List <BackboneHashRoute> rts = new List <BackboneHashRoute>(); if (routes.ContainsKey(bhr.RouterName)) { rts = routes[bhr.RouterName]; routes.Remove(bhr.RouterName); } rts.Add(bhr); routes.Add(bhr.RouterName, rts); } if (routes.Count > 0) { foreach (string routerName in routes.Keys) { if (routerName.Contains(".")) { string tmp = ""; foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.')) { sb.AppendLine(string.Format((minimize ? "{1}{0}={2}{0}||{{}};" : "{1}{0} = {2}{0} || {{}};"), str, (tmp.Length == 0 ? "var " : tmp + "."), (tmp.Length == 0 ? "" : tmp + "."))); tmp += (tmp.Length == 0 ? "" : ".") + str; } } else { sb.AppendLine(string.Format((minimize ? "var {0}={0}||{{}};" : "var {0} = {0} || {{}};"), routerName)); } sb.AppendLine(string.Format((minimize ? "if(!Backbone.History.started){{Backbone.history.start({{pushState:false}});}}if({0}.navigate==undefined){{{0}=new Backbone.Router();}}" : @"if (!Backbone.History.started){{ Backbone.history.start({{ pushState: false }}); }} if ({0}.navigate == undefined){{ {0} = new Backbone.Router(); }}"), routerName)); foreach (BackboneHashRoute bhr in routes[routerName]) { sb.AppendFormat(@"{0}.route('{1}','{2}',function(", routerName, bhr.Path, bhr.FunctionName); if (bhr.Path.Contains(":")) { foreach (Match m in _REG_PARS.Matches(bhr.Path)) { sb.Append(m.Groups[1].Value + ","); } sb.Length = sb.Length - 1; } sb.AppendLine(string.Format((minimize ? "){{{0}}});" : "){{ {0} }});"), bhr.Code)); } } } return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); string urlRoot = ""; foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == host) { urlRoot = mr.Path; break; } } if (urlRoot == "") { foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == "*") { urlRoot = mr.Path; break; } } } sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.StaticExposedMethodGenerator {0} = _.extend(true,{0}, {{"), ModelNamespace.GetFullNameForModel(modelType, host)); foreach (MethodInfo mi in modelType.GetMethods(BindingFlags.Public | BindingFlags.Static)) { if (mi.GetCustomAttributes(typeof(ExposedMethod), false).Length > 0) AppendMethodCall(urlRoot,host, mi,((ExposedMethod)mi.GetCustomAttributes(typeof(ExposedMethod), false)[0]).AllowNullResponse, ref sb,minimize); } while (sb.ToString().TrimEnd().EndsWith(",")) sb.Length = sb.Length - 1; sb.AppendLine("});"); return sb.ToString(); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.CollectionView) == (int)ModelBlockJavascriptGenerations.CollectionView) { return(""); } } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{CollectionView:Backbone.View.extend({{" : @"//Org.Reddragonit.BackBoneDotNet.JSGenerators.CollectionViewGenerator {0} = _.extend(true,{0}, {{CollectionView : Backbone.View.extend({{ "), ModelNamespace.GetFullNameForModel(modelType, host)); string tag = "div"; if (modelType.GetCustomAttributes(typeof(ModelViewTag), false).Length > 0) { tag = ((ModelViewTag)modelType.GetCustomAttributes(typeof(ModelViewTag), false)[0]).TagName; } switch (tag) { case "tr": sb.AppendLine((minimize ? "tagName:\"table\"," : "\ttagName : \"table\",")); break; default: sb.AppendLine((minimize ? "tagName:\"" + tag + "\"," : "\ttagName : \"" + tag + "\",")); break; } _AppendClassName(modelType, host, sb, minimize); _AppendAttributes(modelType, sb, minimize); sb.AppendLine((minimize ? "render:function(){var el=this.$el;el.html('');" :@" render : function(){ var el = this.$el; el.html('');")); if (tag.ToLower() == "tr") { sb.AppendLine((minimize ? "var thead=$('<thead class=\"'+this.className+' header\"></thead>');el.append(thead);thead.append('<tr></tr>');thead=$(thead.children()[0]);" :@" var thead = $('<thead class=""'+this.className+' header""></thead>'); el.append(thead); thead.append('<tr></tr>'); thead = $(thead.children()[0]);")); foreach (string str in properties) { if (str != "id" && !viewIgnoreProperties.Contains(str)) { sb.AppendLine((minimize ? "" : "\t\t") + "thead.append('<th className=\"'+this.className+' " + str + "\">" + str + "</th>');"); } } sb.AppendLine((minimize ? "el.append('<tbody></tbody>');el=$(el.children()[1]);" : @" el.append('<tbody></tbody>'); el = $(el.children()[1]);")); } sb.AppendFormat((minimize ? "if(this.collection.length==0){{this.trigger('pre_render_complete',this);this.trigger('render',this);}}else{{var alt=false;for(var x=0;x<this.collection.length;x++){{var vw=new {0}.View({{model:this.collection.at(x)}});if(alt){{vw.$el.addClass('Alt');}}alt=!alt;if(x+1==this.collection.length){{vw.on('render',function(){{this.col.trigger('item_render',this.view);this.col.trigger('pre_render_complete',this.col);this.col.trigger('render',this.col);}},{{col:this,view:vw}});}}else{{vw.on('render',function(){{this.col.trigger('item_render',this.view);}},{{col:this,view:vw}});}}el.append(vw.$el);vw.render();}}}}}}}})}});" : @" if(this.collection.length==0){{ this.trigger('pre_render_complete',this); this.trigger('render',this); }}else{{ var alt=false; for(var x=0;x<this.collection.length;x++){{ var vw = new {0}.View({{model:this.collection.at(x)}}); if (alt){{ vw.$el.addClass('Alt'); }} alt=!alt; if(x+1==this.collection.length){{ vw.on('render',function(){{this.col.trigger('item_render',this.view);this.col.trigger('pre_render_complete',this.col);this.col.trigger('render',this.col);}},{{col:this,view:vw}}); }}else{{ vw.on('render',function(){{this.col.trigger('item_render',this.view);}},{{col:this,view:vw}}); }} el.append(vw.$el); vw.render(); }} }} }} }})}});"), ModelNamespace.GetFullNameForModel(modelType, host)); return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.View) == (int)ModelBlockJavascriptGenerations.View) return ""; } string editImage = null; string deleteImage = null; EditButtonDefinition edDef; DeleteButtonDefinition delDef; _LocateButtonImages(modelType, host, out editImage, out deleteImage,out edDef,out delDef); WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{View : Backbone.View.extend({{" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.ViewGenerator {0} = _.extend(true,{0},{{View : Backbone.View.extend({{ "),ModelNamespace.GetFullNameForModel(modelType, host)); string tag = "div"; if (modelType.GetCustomAttributes(typeof(ModelViewTag), false).Length > 0) tag = ((ModelViewTag)modelType.GetCustomAttributes(typeof(ModelViewTag), false)[0]).TagName; sb.AppendLine(string.Format((minimize ? "tagName:\"{0}\",":"\ttagName : \"{0}\","),tag)); _AppendClassName(modelType,host, sb,minimize); _AppendAttributes(modelType, sb,minimize); _AppendRenderFunction(modelType,host,tag, properties, hasUpdate, hasDelete, sb,viewIgnoreProperties,editImage,deleteImage,edDef,delDef,minimize); sb.AppendLine("})});"); return sb.ToString(); }
private void _AppendRenderFunction(Type modelType,string host,string tag,List<string> properties,bool hasUpdate,bool hasDelete, WrappedStringBuilder sb, List<string> viewIgnoreProperties,string editImage,string deleteImage,EditButtonDefinition edDef,DeleteButtonDefinition delDef,bool minimize) { bool hasUpdateFunction = true; if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.EditForm) == (int)ModelBlockJavascriptGenerations.EditForm) hasUpdateFunction = false; } sb.AppendLine((minimize ? "render:function(){" : "\trender : function(){")); string fstring = ""; switch (tag.ToLower()) { case "tr": fstring = "'<td class=\"'+this.className+' {0}\">'+{1}+'</td>'{2}"; break; case "ul": case "ol": fstring = "'<li class=\"'+this.className+' {0}\">'+{1}+'</li>'{2}"; break; default: fstring = "'<" + tag + " class=\"'+this.className+' {0}\">'+{1}+'</" + tag + ">'{2}"; break; } int arIndex = 0; WrappedStringBuilder sbHtml = new WrappedStringBuilder(minimize); sbHtml.Append((minimize ? "" : "\t\t")+"$(this.el).html("); foreach (string prop in properties) { if (!viewIgnoreProperties.Contains(prop)&&prop!="id") { Type PropType = modelType.GetProperty(prop).PropertyType; bool array = false; if (PropType.FullName.StartsWith("System.Nullable")) { if (PropType.IsGenericType) PropType = PropType.GetGenericArguments()[0]; else PropType = PropType.GetElementType(); } if (PropType.IsArray) { array = true; PropType = PropType.GetElementType(); } else if (PropType.IsGenericType) { if (PropType.GetGenericTypeDefinition() == typeof(List<>)) { array = true; PropType = PropType.GetGenericArguments()[0]; } } if (new List<Type>(PropType.GetInterfaces()).Contains(typeof(IModel))) { if (array) { string tsets = ""; string tcode = _RecurAddRenderModelPropertyCode(prop, PropType,host, "this.model.get('" + prop + "').at(x).get('{0}')", out tsets, true,minimize); if (tsets != "") sb.Append(tsets); sb.AppendFormat((minimize ? "var ars{0}='';if(this.model.get('{1}')!=null){{for(var x=0;x<this.model.get('{1}').length;x++){{ars{0}+={2};}}}}" :@" var ars{0} = ''; if(this.model.get('{1}')!=null){{ for(var x=0;x<this.model.get('{1}').length;x++){{ ars{0}+={2}; }} }}"), arIndex, prop, string.Format(tcode, prop)); sbHtml.Append(string.Format(fstring, prop, "ars" + arIndex.ToString(), (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); arIndex++; } else { string tsets = ""; string code = _RecurAddRenderModelPropertyCode(prop, PropType,host, "this.model.get('" + prop + "').get('{0}')", out tsets, false,minimize); if (tsets != "") sb.Append(tsets); sbHtml.Append(string.Format(fstring, prop, "(this.model.get('" + prop + "') == null ? '' : "+code+")", (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); } } else { if (array) { sb.AppendFormat((minimize? "var ars{0}='';if(this.model.get('{1}')!=null){{for(x in this.model.get('{1}')){{if(this.model.get('{1}')[x]!=null){{ars{0}+='<span class=\"'+this.className+' {1} els\">'+this.model.get('{1}')[x]+'</span>';}}}}}}" :@" var ars{0} = ''; if(this.model.get('{1}')!=null){{ for(x in this.model.get('{1}')){{ if(this.model.get('{1}')[x]!=null){{ ars{0}+='<span class=""'+this.className+' {1} els"">'+this.model.get('{1}')[x]+'</span>'; }} }} }}"),arIndex,prop); sbHtml.Append(string.Format(fstring, prop, "ars" + arIndex.ToString(), (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); arIndex++; } else sbHtml.Append(string.Format(fstring, prop, string.Format((minimize ? "(this.model.get('{0}')==null?'':this.model.get('{0}'))":"(this.model.get('{0}')==null ? '' : this.model.get('{0}'))"), prop), (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); } } } sb.Append(sbHtml.ToString().Trim('+')); if (hasUpdate || hasDelete) { switch (tag.ToLower()) { case "tr": sb.Append("+'<td class=\"'+this.className+' buttons\">'"); break; case "ul": case "ol": sb.Append("+'<li class=\"'+this.className+' buttons\">'"); break; default: sb.Append("+'<"+tag+" class=\"'+this.className+' buttons\">'"); break; } } if (hasUpdate) { if (edDef == null) sb.Append("+'<span class=\"'+this.className+' button edit\">" + (editImage == null ? "Edit" : "<img src=\"" + editImage + "\"/>") + "</span>'"); else { sb.Append("+'<"+edDef.Tag+" class=\"'+this.className+' button edit"); if (edDef.Class != null) { foreach (string str in edDef.Class) sb.Append(" "+str); } sb.Append("\">" + (editImage == null ? "" : "<img src=\"" + editImage + "\"/>") + (edDef.Text == null ? "" : edDef.Text) + "</" + edDef.Tag+">'"); } } if (hasDelete) { if (delDef == null) sb.Append("+'<span class=\"'+this.className+' button delete\">" + (deleteImage == null ? "Delete" : "<img src=\"" + deleteImage + "\"/>") + "</span>'"); else { sb.Append("+'<" + delDef.Tag + " class=\"'+this.className+' button edit"); if (delDef.Class != null) { foreach (string str in delDef.Class) sb.Append(" " + str); } sb.Append("\">" + (deleteImage == null ? "" : "<img src=\"" + deleteImage + "\"/>") + (delDef.Text == null ? "" : delDef.Text) + "</" + delDef.Tag + ">'"); } } if (hasUpdate || hasDelete) { switch (tag.ToLower()) { case "tr": sb.Append("+'</td>'"); break; case "ul": case "ol": sb.Append("+'</li>'"); break; default: sb.Append("+'</" + tag + ">'"); break; } } sb.AppendLine((minimize ? ");$(this.el).attr('name',this.model.id);this.trigger('pre_render_complete',this);this.trigger('render',this);return this;}" : @"); $(this.el).attr('name',this.model.id); this.trigger('pre_render_complete',this); this.trigger('render',this); return this; }") + (hasUpdate || hasDelete ? "," : "")); if ((hasUpdate&&hasUpdateFunction) || hasDelete) { sb.AppendLine((minimize ? "events:{" : "\tevents : {")); if (hasUpdate && hasUpdateFunction) sb.AppendLine((minimize ? "'click .button.edit':'editModel'" : "\t\t'click .button.edit' : 'editModel'") + (hasDelete ? "," : "")); if (hasDelete) sb.AppendLine((minimize ? "'click .button.delete':'deleteModel'" : "\t\t'click .button.delete' : 'deleteModel'")); sb.AppendLine((minimize ? "" : "\t")+"},"); if (hasUpdate && hasUpdateFunction) { sb.AppendLine(string.Format((minimize ? "editModel:function(){{{0}.editModel(this);}}" : @" editModel : function(){{ {0}.editModel(this); }}"),ModelNamespace.GetFullNameForModel(modelType, host)) + (hasDelete ? "," : "")); } if (hasDelete) { sb.AppendLine((minimize ? "deleteModel:function(){this.model.destroy();}" :@" deleteModel : function(){ this.model.destroy(); }")); } } }
private string _RecurAddRenderModelPropertyCode(string prop, Type PropType, string host, string modelstring, out string arstring, bool addEls, bool minimize) { string className = ModelNamespace.GetFullNameForModel(PropType, host).Replace(".", " ") + (addEls ? " els " : ""); foreach (ModelViewClass mvc in PropType.GetCustomAttributes(typeof(ModelViewClass), false)) { className += mvc.ClassName + " "; } string code = ""; int arIndex = 0; WrappedStringBuilder sb = new WrappedStringBuilder(minimize); foreach (PropertyInfo pi in PropType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (pi.GetCustomAttributes(typeof(ModelIgnoreProperty), false).Length == 0) { if (pi.GetCustomAttributes(typeof(ReadOnlyModelProperty), false).Length == 0 && pi.GetCustomAttributes(typeof(ViewIgnoreField), false).Length == 0) { Type ptype = pi.PropertyType; bool array = false; if (ptype.FullName.StartsWith("System.Nullable")) { if (ptype.IsGenericType) { ptype = ptype.GetGenericArguments()[0]; } else { ptype = ptype.GetElementType(); } } if (ptype.IsArray) { array = true; ptype = ptype.GetElementType(); } else if (ptype.IsGenericType) { if (ptype.GetGenericTypeDefinition() == typeof(List <>)) { array = true; ptype = ptype.GetGenericArguments()[0]; } } if (new List <Type>(ptype.GetInterfaces()).Contains(typeof(IModel))) { if (array) { string tsets = ""; string tcode = _RecurAddRenderModelPropertyCode(pi.Name, ptype, host, string.Format(modelstring, pi.Name) + ".at(x).get('{0}')", out tsets, true, minimize); if (tsets != "") { sb.Append(tsets); } sb.AppendLine(string.Format((minimize ? "var ars{0}{1}='';if({2}!=null{{for(var x=0;x<{2}).length;x++){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{5}+'</span>'}}}}" :@" var ars{0}{1} = ''; if({2}!=null{{ for(var x=0;x<{2}.length;x++){{ ars{0}{1} += '<span class=""{3} {4} els"">'+{5}+'</span>' }} }}" ), new object[] { prop, arIndex, string.Format(modelstring, pi.Name), className, pi.Name, tcode })); code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'"; arIndex++; } else { string tsets = ""; code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "(" + string.Format(modelstring, prop) + "==null ? '' : '<span class=\"" + className + " " + pi.Name + "\">'+" + _RecurAddRenderModelPropertyCode(pi.Name, ptype, host, string.Format(modelstring, pi.Name) + ".get('{0}')", out tsets, false, minimize) + "+'</span>')"; if (tsets != "") { sb.Append(tsets); } } } else { if (array) { sb.AppendLine(string.Format((minimize ? "var ars{0}{1}='';if ({2}!=null){{for(x in {2}){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{2}[x]+'</span>';}}}}" : @" var ars{0}{1} = ''; if ({2}!=null){{ for(x in {2}){{ ars{0}{1} += '<span class=""{3} {4} els"">'+{2}[x]+'</span>'; }} }}"), new object[] { prop, arIndex, string.Format(modelstring, pi.Name), className, pi.Name })); code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'"; arIndex++; } else { code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+(" + string.Format(modelstring, pi.Name) + "==null ? '' : " + string.Format(modelstring, pi.Name) + ")+'</span>'"; } } } } } arstring = sb.ToString(); return(code); }
public Task HandleRequest(string url, RequestHandler.RequestMethods method, Hashtable formData, HttpContext context, ISecureSession session, IsValidCall securityCheck) { if (!HandlesRequest(url, method)) { throw new CallNotFoundException(); } else { List <Type> models = new List <Type>(); if (_types != null) { foreach (Type t in _types) { foreach (ModelJSFilePath mjsfp in t.GetCustomAttributes(typeof(ModelJSFilePath), false)) { if (mjsfp.IsMatch(url)) { models.Add(t); } } } foreach (Type model in models) { if (!securityCheck.Invoke(model, null, session, null, url, null)) { throw new InsecureAccessException(); } } } DateTime modDate = DateTime.MinValue; foreach (Type model in models) { try { FileInfo fi = new FileInfo(model.Assembly.Location); if (fi.Exists) { modDate = new DateTime(Math.Max(modDate.Ticks, fi.LastWriteTime.Ticks)); } } catch (Exception e) { } } if (modDate == DateTime.MinValue) { modDate = RequestHandler.StartTime; } if (context.Request.Headers.ContainsKey("If-Modified-Since")) { DateTime lastModified = DateTime.Parse(context.Request.Headers["If-Modified-Since"]); if (modDate.ToString() == lastModified.ToString()) { context.Response.StatusCode = 304; return(Task.CompletedTask); } } string ret = null; context.Response.ContentType = "text/javascript"; context.Response.StatusCode = 200; lock (_cache) { if (_cache.ContainsKey(url)) { ret = _cache[url]; } } if (ret == null && models.Count > 0) { WrappedStringBuilder builder = new WrappedStringBuilder(url.ToLower().EndsWith(".min.js")); foreach (IBasicJSGenerator gen in _oneTimeInitialGenerators) { gen.GeneratorJS(ref builder); } foreach (Type model in models) { foreach (IJSGenerator gen in _instanceGenerators) { gen.GeneratorJS(ref builder, model); } foreach (IJSGenerator gen in _globalGenerators) { gen.GeneratorJS(ref builder, model); } } foreach (IBasicJSGenerator gen in _oneTimeFinishGenerators) { gen.GeneratorJS(ref builder); } ret = builder.ToString(); lock (_cache) { if (!_cache.ContainsKey(url)) { _cache.Add(url, ret); } } } context.Response.Headers.Add("Last-Modified", modDate.ToUniversalTime().ToString("R")); context.Response.Headers.Add("Cache-Control", "public"); return(context.Response.WriteAsync(ret)); } }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { if (!hasUpdate) return ""; else if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.EditForm) == (int)ModelBlockJavascriptGenerations.EditForm) return ""; } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{editModel:function(view){{" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.EditAddFormGenerator {0} = _.extend(true,{0},{{editModel : function(view){{"), ModelNamespace.GetFullNameForModel(modelType, host)); ModelEditAddTypes meat = ModelEditAddTypes.dialog; if (modelType.GetCustomAttributes(typeof(ModelEditAddType), false).Length > 0) meat = ((ModelEditAddType)modelType.GetCustomAttributes(typeof(ModelEditAddType), false)[0]).Type; switch (meat) { case ModelEditAddTypes.dialog: _RenderDialogCode(modelType,host, readOnlyProperties, properties,sb,minimize); break; case ModelEditAddTypes.inline: _RenderInlineCode(modelType,host, readOnlyProperties, properties,viewIgnoreProperties, sb,minimize); break; } sb.AppendLine("}});"); return sb.ToString(); }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { string urlRoot = ""; foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == host) { urlRoot = mr.Path; break; } } if (urlRoot == "") { foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false)) { if (mr.Host == "*") { urlRoot = mr.Path; break; } } } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (!minimize) sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.SelectListCallGenerator"); List<MethodInfo> methods = new List<MethodInfo>(); foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelSelectListMethod), false).Length > 0) methods.Add(mi); } int curLen = 0; for (int x = 0; x < methods.Count; x++) curLen = Math.Max(methods[x].GetParameters().Length, curLen); int index = 0; while (index < methods.Count) { for (int x = index; x < methods.Count; x++) { if (curLen == methods[x].GetParameters().Length) { MethodInfo mi = methods[x]; methods.RemoveAt(x); methods.Insert(index, mi); index++; x = index - 1; } } curLen = 0; for (int x = index; x < methods.Count; x++) curLen = Math.Max(methods[x].GetParameters().Length, curLen); } if (methods.Count > 0) { sb.AppendLine(string.Format((minimize ? "{0}=_.extend(true,{0},{{SelectList:function(pars){{" : "{0} = _.extend(true,{0},{{SelectList : function(pars){{" ),ModelNamespace.GetFullNameForModel(modelType, host))); for (int x = 0; x < methods.Count; x++) { sb.Append((minimize ? "" : "\t") + (x == 0 ? "" : "else ") + "if("); if (methods[x].GetParameters().Length == 0) { sb.AppendLine((minimize? "pars==undefined||pars==null){url='';" : @"pars==undefined || pars==null){ url='';")); } else { ParameterInfo[] pars = methods[x].GetParameters(); WrappedStringBuilder code = new WrappedStringBuilder(minimize); code.AppendLine((minimize ? "url='?';" : "\t\turl='?';")); sb.Append((minimize ? "pars!=undefined&&pars!=null&&(" : "pars!=undefined && pars!=null && (")); for (int y = 0; y < pars.Length; y++) { sb.Append((y != 0 ? (minimize ? "&&" : " && ") : "") + "pars." + pars[y].Name + "!=undefined"); code.AppendLine(string.Format((minimize? "pars.{0}=(pars.{0}==null?'NULL':pars.{0});" :"\t\tpars.{0} = (pars.{0} == null ? 'NULL' : pars.{0});"), pars[y].Name)); if (pars[y].ParameterType == typeof(bool)) code.AppendLine(string.Format((minimize? "pars.{0}=(pars.{0}==null?'false':(pars.{0}?'true':'false'));" :"\t\tpars.{0} = (pars.{0} == null ? 'false' : (pars.{0} ? 'true' : 'false'));"), pars[y].Name)); else if (pars[y].ParameterType == typeof(DateTime)||pars[y].ParameterType == typeof(DateTime?)) { code.AppendLine(string.Format((minimize ? "if(pars.{0}!='NULL'){{if(!(pars.{0} instanceof Date)){{pars.{0}=new Date(pars.{0});}}pars.{0}=Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds());}}" : @"if (pars.{0} != 'NULL'){{ if (!(pars.{0} instanceof Date)){{ pars.{0} = new Date(pars.{0}); }} pars.{0} = Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds()); }}"),pars[y].Name)); } code.AppendLine((minimize ? "" : "\t\t")+"url+='" + (y == 0 ? "" : "&") + pars[y].Name + "='+pars." + pars[y].Name + ".toString();"); } sb.AppendLine(")){"); sb.Append(code.ToString()); } sb.AppendLine("}"); } sb.AppendLine(string.Format((minimize ? "else{{return null;}}var ret=$.ajax('{0}'+url,{{async:false,cache:false,type : 'SELECT'}}).responseText;var response=JSON.parse(ret);if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);response=response.response;}}return response;}}}});" :@" else{{ return null; }} var ret=$.ajax( '{0}'+url,{{ async:false, cache:false, type : 'SELECT' }}).responseText; var response = JSON.parse(ret); if(response.Backbone!=undefined){{ _.extend(Backbone,response.Backbone); response=response.response; }} return response; }}}});"),urlRoot)); } return sb.ToString(); }
private void _AppendRenderFunction(Type modelType, string host, string tag, List <string> properties, bool hasUpdate, bool hasDelete, WrappedStringBuilder sb, List <string> viewIgnoreProperties, string editImage, string deleteImage, EditButtonDefinition edDef, DeleteButtonDefinition delDef, bool minimize) { bool hasUpdateFunction = true; if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.EditForm) == (int)ModelBlockJavascriptGenerations.EditForm) { hasUpdateFunction = false; } } sb.AppendLine((minimize ? "render:function(){" : "\trender : function(){")); string fstring = ""; switch (tag.ToLower()) { case "tr": fstring = "'<td class=\"'+this.className+' {0}\">'+{1}+'</td>'{2}"; break; case "ul": case "ol": fstring = "'<li class=\"'+this.className+' {0}\">'+{1}+'</li>'{2}"; break; default: fstring = "'<" + tag + " class=\"'+this.className+' {0}\">'+{1}+'</" + tag + ">'{2}"; break; } int arIndex = 0; WrappedStringBuilder sbHtml = new WrappedStringBuilder(minimize); sbHtml.Append((minimize ? "" : "\t\t") + "$(this.el).html("); foreach (string prop in properties) { if (!viewIgnoreProperties.Contains(prop) && prop != "id") { Type PropType = modelType.GetProperty(prop).PropertyType; bool array = false; if (PropType.FullName.StartsWith("System.Nullable")) { if (PropType.IsGenericType) { PropType = PropType.GetGenericArguments()[0]; } else { PropType = PropType.GetElementType(); } } if (PropType.IsArray) { array = true; PropType = PropType.GetElementType(); } else if (PropType.IsGenericType) { if (PropType.GetGenericTypeDefinition() == typeof(List <>)) { array = true; PropType = PropType.GetGenericArguments()[0]; } } if (new List <Type>(PropType.GetInterfaces()).Contains(typeof(IModel))) { if (array) { string tsets = ""; string tcode = _RecurAddRenderModelPropertyCode(prop, PropType, host, "this.model.get('" + prop + "').at(x).get('{0}')", out tsets, true, minimize); if (tsets != "") { sb.Append(tsets); } sb.AppendFormat((minimize ? "var ars{0}='';if(this.model.get('{1}')!=null){{for(var x=0;x<this.model.get('{1}').length;x++){{ars{0}+={2};}}}}" :@" var ars{0} = ''; if(this.model.get('{1}')!=null){{ for(var x=0;x<this.model.get('{1}').length;x++){{ ars{0}+={2}; }} }}"), arIndex, prop, string.Format(tcode, prop)); sbHtml.Append(string.Format(fstring, prop, "ars" + arIndex.ToString(), (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); arIndex++; } else { string tsets = ""; string code = _RecurAddRenderModelPropertyCode(prop, PropType, host, "this.model.get('" + prop + "').get('{0}')", out tsets, false, minimize); if (tsets != "") { sb.Append(tsets); } sbHtml.Append(string.Format(fstring, prop, "(this.model.get('" + prop + "') == null ? '' : " + code + ")", (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); } } else { if (array) { sb.AppendFormat((minimize? "var ars{0}='';if(this.model.get('{1}')!=null){{for(x in this.model.get('{1}')){{if(this.model.get('{1}')[x]!=null){{ars{0}+='<span class=\"'+this.className+' {1} els\">'+this.model.get('{1}')[x]+'</span>';}}}}}}" :@" var ars{0} = ''; if(this.model.get('{1}')!=null){{ for(x in this.model.get('{1}')){{ if(this.model.get('{1}')[x]!=null){{ ars{0}+='<span class=""'+this.className+' {1} els"">'+this.model.get('{1}')[x]+'</span>'; }} }} }}"), arIndex, prop); sbHtml.Append(string.Format(fstring, prop, "ars" + arIndex.ToString(), (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); arIndex++; } else { sbHtml.Append(string.Format(fstring, prop, string.Format((minimize ? "(this.model.get('{0}')==null?'':this.model.get('{0}'))":"(this.model.get('{0}')==null ? '' : this.model.get('{0}'))"), prop), (properties.IndexOf(prop) == properties.Count - 1 ? "" : "+"))); } } } } sb.Append(sbHtml.ToString().Trim('+')); if (hasUpdate || hasDelete) { switch (tag.ToLower()) { case "tr": sb.Append("+'<td class=\"'+this.className+' buttons\">'"); break; case "ul": case "ol": sb.Append("+'<li class=\"'+this.className+' buttons\">'"); break; default: sb.Append("+'<" + tag + " class=\"'+this.className+' buttons\">'"); break; } } if (hasUpdate) { if (edDef == null) { sb.Append("+'<span class=\"'+this.className+' button edit\">" + (editImage == null ? "Edit" : "<img src=\"" + editImage + "\"/>") + "</span>'"); } else { sb.Append("+'<" + edDef.Tag + " class=\"'+this.className+' button edit"); if (edDef.Class != null) { foreach (string str in edDef.Class) { sb.Append(" " + str); } } sb.Append("\">" + (editImage == null ? "" : "<img src=\"" + editImage + "\"/>") + (edDef.Text == null ? "" : edDef.Text) + "</" + edDef.Tag + ">'"); } } if (hasDelete) { if (delDef == null) { sb.Append("+'<span class=\"'+this.className+' button delete\">" + (deleteImage == null ? "Delete" : "<img src=\"" + deleteImage + "\"/>") + "</span>'"); } else { sb.Append("+'<" + delDef.Tag + " class=\"'+this.className+' button edit"); if (delDef.Class != null) { foreach (string str in delDef.Class) { sb.Append(" " + str); } } sb.Append("\">" + (deleteImage == null ? "" : "<img src=\"" + deleteImage + "\"/>") + (delDef.Text == null ? "" : delDef.Text) + "</" + delDef.Tag + ">'"); } } if (hasUpdate || hasDelete) { switch (tag.ToLower()) { case "tr": sb.Append("+'</td>'"); break; case "ul": case "ol": sb.Append("+'</li>'"); break; default: sb.Append("+'</" + tag + ">'"); break; } } sb.AppendLine((minimize ? ");$(this.el).attr('name',this.model.id);this.trigger('pre_render_complete',this);this.trigger('render',this);return this;}" : @"); $(this.el).attr('name',this.model.id); this.trigger('pre_render_complete',this); this.trigger('render',this); return this; }") + (hasUpdate || hasDelete ? "," : "")); if ((hasUpdate && hasUpdateFunction) || hasDelete) { sb.AppendLine((minimize ? "events:{" : "\tevents : {")); if (hasUpdate && hasUpdateFunction) { sb.AppendLine((minimize ? "'click .button.edit':'editModel'" : "\t\t'click .button.edit' : 'editModel'") + (hasDelete ? "," : "")); } if (hasDelete) { sb.AppendLine((minimize ? "'click .button.delete':'deleteModel'" : "\t\t'click .button.delete' : 'deleteModel'")); } sb.AppendLine((minimize ? "" : "\t") + "},"); if (hasUpdate && hasUpdateFunction) { sb.AppendLine(string.Format((minimize ? "editModel:function(){{{0}.editModel(this);}}" : @" editModel : function(){{ {0}.editModel(this); }}"), ModelNamespace.GetFullNameForModel(modelType, host)) + (hasDelete ? "," : "")); } if (hasDelete) { sb.AppendLine((minimize ? "deleteModel:function(){this.model.destroy();}" :@" deleteModel : function(){ this.model.destroy(); }")); } } }
private void _AppendParse(Type modelType, string host, List <string> properties, List <string> readOnlyProperties, WrappedStringBuilder sb, bool minimize) { bool add = false; foreach (string str in properties) { Type propType = modelType.GetProperty(str).PropertyType; if (propType.FullName.StartsWith("System.Nullable")) { if (propType.IsGenericType) { propType = propType.GetGenericArguments()[0]; } else { propType = propType.GetElementType(); } } if (propType.IsArray) { propType = propType.GetElementType(); } else if (propType.IsGenericType) { if (propType.GetGenericTypeDefinition() == typeof(List <>)) { propType = propType.GetGenericArguments()[0]; } } if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel)) || (propType == typeof(DateTime))) { add = true; break; } else if (readOnlyProperties.Contains(str)) { add = true; break; } } if (add) { WrappedStringBuilder jsonb = new WrappedStringBuilder(minimize); string lazyLoads = ""; jsonb.AppendLine((minimize ? "toJSON:function(){var attrs={};this._changedFields=(this._changedFields==undefined?[]:this._changedFields);" :@" toJSON : function(){ var attrs = {}; this._changedFields = (this._changedFields == undefined ? [] : this._changedFields);")); sb.AppendLine((minimize ? "parse:function(response){var attrs={};this._origAttributes=(this._origAttributes==undefined?{}:this._origAttributes);if(response.Backbone!=undefined){_.extend(Backbone,response.Backbone);response=response.response;}if(response!=true){" :@" parse: function(response) { var attrs = {}; this._origAttributes = (this._origAttributes==undefined ? {} : this._origAttributes); if(response.Backbone!=undefined){ _.extend(Backbone,response.Backbone); response=response.response; } if (response!=true){")); foreach (string str in properties) { bool isReadOnly = modelType.GetProperty(str).GetCustomAttributes(typeof(ReadOnlyModelProperty), false).Length > 0 || !modelType.GetProperty(str).CanWrite; Type propType = modelType.GetProperty(str).PropertyType; bool array = false; if (propType.FullName.StartsWith("System.Nullable")) { if (propType.IsGenericType) { propType = propType.GetGenericArguments()[0]; } else { propType = propType.GetElementType(); } } if (propType.IsArray) { array = true; propType = propType.GetElementType(); } else if (propType.IsGenericType) { if (propType.GetGenericTypeDefinition() == typeof(List <>)) { array = true; propType = propType.GetGenericArguments()[0]; } } if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel))) { bool isLazy = modelType.GetProperty(str).GetCustomAttributes(typeof(ModelPropertyLazyLoadExternalModel), false).Length > 0; if (isLazy) { lazyLoads += ",'" + str + "'"; } sb.AppendLine(string.Format((minimize ? "if(response.{0}!=undefined){{" : "\t\tif (response.{0} != undefined){{"), str)); if (array) { sb.AppendFormat((minimize ? "if({0}.Collection!=undefined){{attrs.{1}=new {0}.Collection();for(var x=0;x<response.{1}.length;x++){{attrs.{1}.add(new {0}.Model({{'id':response.{1}[x].id}}));attrs.{1}.at(x).attributes=attrs.{1}.at(x).parse(response.{1}[x]);}}}}else{{attrs.{1}=[];for(var x=0;x<response.{1}.length;x++){{attrs.{1}.push(new {0}.Model({{'id':response.{1}[x].id}}));attrs.{1}[x].attributes=attrs.{1}[x].parse(response.{1}[x]);}}}}" :@" if({0}.Collection!=undefined){{ attrs.{1} = new {0}.Collection(); for (var x=0;x<response.{1}.length;x++){{ attrs.{1}.add(new {0}.Model({{'id':response.{1}[x].id}})); attrs.{1}.at(x).attributes=attrs.{1}.at(x).parse(response.{1}[x]); }} }}else{{ attrs.{1}=[]; for (var x=0;x<response.{1}.length;x++){{ attrs.{1}.push(new {0}.Model({{'id':response.{1}[x].id}})); attrs.{1}[x].attributes=attrs.{1}[x].parse(response.{1}[x]); }} }}"), ModelNamespace.GetFullNameForModel(propType, host), str); if (isReadOnly) { jsonb.AppendLine((minimize ? "if(this.isNew()){" : "if (this.isNew()){")); } jsonb.AppendFormat((minimize ? "if(this._changedFields.indexOf('{0}')>=0||this.isNew()){{attrs.{0}=[];if(this.attributes['{0}']!=null){{for(var x=0;x<this.attributes['{0}'].length;x++){{if(this.attributes['{0}'].at!=undefined){{attrs.{0}.push({{id:this.attributes['{0}'].at(x).id}});}}else{{attrs.{0}.push({{id:this.attributes['{0}'][x].id}});}}}}}}}}" :@" if(this._changedFields.indexOf('{0}')>=0||this.isNew()){{ attrs.{0} = []; if (this.attributes['{0}']!=null){{ for(var x=0;x<this.attributes['{0}'].length;x++){{ if(this.attributes['{0}'].at!=undefined){{ attrs.{0}.push({{id:this.attributes['{0}'].at(x).id}}); }}else{{ attrs.{0}.push({{id:this.attributes['{0}'][x].id}}); }} }} }} }}"), str); if (isReadOnly) { jsonb.AppendLine("}"); } } else { sb.AppendFormat((minimize ? "attrs.{0}=new {1}.Model({{'id':response.{0}.id}});attrs.{0}.attributes=attrs.{0}.parse(response.{0});" :@" attrs.{0} = new {1}.Model({{'id':response.{0}.id}}); attrs.{0}.attributes=attrs.{0}.parse(response.{0});"), str, ModelNamespace.GetFullNameForModel(propType, host)); if (isReadOnly) { jsonb.AppendLine((minimize? "if(this.isNew()){": "if (this.isNew()){")); } jsonb.AppendFormat((minimize ? "if(this._changedFields.indexOf('{0}')>=0||this.isNew()){{if(this.attributes['{0}']!=null){{attrs.{0}={{id:this.attributes['{0}'].id}};}}else{{attrs.{0}=null;}}}}" :@" if(this._changedFields.indexOf('{0}')>=0||this.isNew()){{ if (this.attributes['{0}']!=null){{ attrs.{0} = {{id : this.attributes['{0}'].id}}; }}else{{ attrs.{0} = null; }} }}"), str); if (isReadOnly) { jsonb.AppendLine("}"); } } sb.AppendLine((minimize ? "" : "\t\t") + "}"); } else { sb.AppendLine(string.Format((minimize ? "if(response.{0}!=undefined){{" : "\t\tif (response.{0} != undefined){{"), str)); if (propType == typeof(DateTime)) { sb.AppendLine(string.Format((minimize ? "attrs.{0}=new Date(response.{0});" :"\t\tattrs.{0} = new Date(response.{0});"), str)); } else { sb.AppendLine(string.Format((minimize ? "attrs.{0}=response.{0};":"\t\tattrs.{0} = response.{0};"), str)); } sb.AppendLine((minimize ? "" : "\t\t") + "}"); if (isReadOnly) { jsonb.AppendLine((minimize ? "if(this.isNew()){":"if (this.isNew()){")); } jsonb.AppendFormat((minimize ? "if(this._changedFields.indexOf('{0}')>=0||this.isNew()){{attrs.{0}=this.attributes['{0}'];}}" :@" if(this._changedFields.indexOf('{0}')>=0||this.isNew()){{ attrs.{0} = this.attributes['{0}']; }}"), str); if (isReadOnly) { jsonb.AppendLine("}"); } } } sb.AppendFormat((minimize ? "}}return attrs;}},{0}return attrs;}}," :@" }} return attrs; }},{0} return attrs; }},"), jsonb.ToString()); if (lazyLoads.Length > 0) { sb.AppendLine(string.Format((minimize ? "LazyLoadAttributes:[{0}],": "\tLazyLoadAttributes : [{0}],"), lazyLoads.Substring(1))); } } else { sb.AppendLine((minimize ? "parse:function(response){if(response.Backbone!=undefined){_.extend(Backbone,response.Backbone);response=response.response;}return response;}," :@" parse: function(response) { if(response.Backbone!=undefined){ _.extend(Backbone,response.Backbone); response=response.response; } return response; },")); } }
private string _RecurAddRenderModelPropertyCode(string prop,Type PropType,string host,string modelstring,out string arstring,bool addEls,bool minimize) { string className = ModelNamespace.GetFullNameForModel(PropType, host).Replace(".", " ") + (addEls ? " els " : ""); foreach (ModelViewClass mvc in PropType.GetCustomAttributes(typeof(ModelViewClass), false)) className += mvc.ClassName + " "; string code = ""; int arIndex = 0; WrappedStringBuilder sb = new WrappedStringBuilder(minimize); foreach (PropertyInfo pi in PropType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (pi.GetCustomAttributes(typeof(ModelIgnoreProperty), false).Length == 0) { if (pi.GetCustomAttributes(typeof(ReadOnlyModelProperty), false).Length == 0 && pi.GetCustomAttributes(typeof(ViewIgnoreField), false).Length == 0) { Type ptype = pi.PropertyType; bool array = false; if (ptype.FullName.StartsWith("System.Nullable")) { if (ptype.IsGenericType) ptype = ptype.GetGenericArguments()[0]; else ptype = ptype.GetElementType(); } if (ptype.IsArray) { array = true; ptype = ptype.GetElementType(); } else if (ptype.IsGenericType) { if (ptype.GetGenericTypeDefinition() == typeof(List<>)) { array = true; ptype = ptype.GetGenericArguments()[0]; } } if (new List<Type>(ptype.GetInterfaces()).Contains(typeof(IModel))){ if (array) { string tsets = ""; string tcode = _RecurAddRenderModelPropertyCode(pi.Name, ptype,host, string.Format(modelstring, pi.Name) + ".at(x).get('{0}')", out tsets,true,minimize); if (tsets != "") sb.Append(tsets); sb.AppendLine(string.Format((minimize ? "var ars{0}{1}='';if({2}!=null{{for(var x=0;x<{2}).length;x++){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{5}+'</span>'}}}}" :@" var ars{0}{1} = ''; if({2}!=null{{ for(var x=0;x<{2}.length;x++){{ ars{0}{1} += '<span class=""{3} {4} els"">'+{5}+'</span>' }} }}" ),new object[]{ prop, arIndex, string.Format(modelstring, pi.Name), className, pi.Name, tcode })); code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'"; arIndex++; } else { string tsets = ""; code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "("+string.Format(modelstring,prop)+"==null ? '' : '<span class=\"" + className + " " + pi.Name + "\">'+" + _RecurAddRenderModelPropertyCode(pi.Name, ptype,host, string.Format(modelstring, pi.Name) + ".get('{0}')",out tsets,false,minimize) + "+'</span>')"; if (tsets != "") sb.Append(tsets); } }else{ if (array) { sb.AppendLine(string.Format((minimize ? "var ars{0}{1}='';if ({2}!=null){{for(x in {2}){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{2}[x]+'</span>';}}}}" : @" var ars{0}{1} = ''; if ({2}!=null){{ for(x in {2}){{ ars{0}{1} += '<span class=""{3} {4} els"">'+{2}[x]+'</span>'; }} }}"), new object[]{ prop, arIndex, string.Format(modelstring, pi.Name), className, pi.Name })); code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'"; arIndex++; }else code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "")+"'<span class=\"" + className + " " + pi.Name + "\">'+(" + string.Format(modelstring, pi.Name) + "==null ? '' : "+string.Format(modelstring,pi.Name)+")+'</span>'"; } } } } arstring = sb.ToString(); return code; }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (!minimize) sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.ModelListCallGenerators"); foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelListMethod), false).Length > 0) { foreach (ModelListMethod mlm in mi.GetCustomAttributes(typeof(ModelListMethod), false)) { if (mlm.Host == host || mlm.Host == "*") { WrappedStringBuilder sbCurParameters = new WrappedStringBuilder(minimize); sbCurParameters.Append((minimize ? "function(){return{":"function(){return {")); sb.Append(string.Format((minimize ? "{0}=_.extend({0},{{{1}:function(" : "{0} = _.extend({0}, {{{1}:function("),ModelNamespace.GetFullNameForModel(modelType, host),mi.Name)); for (int x = 0; x < (mlm.Paged ? mi.GetParameters().Length-3 : mi.GetParameters().Length); x++) { sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name); sbCurParameters.AppendLine((x == 0 ? "" : ",") + string.Format("'{0}':{0}", mi.GetParameters()[x].Name)); } sbCurParameters.Append("};}"); if (mlm.Paged) { if (mi.GetParameters().Length != 3) sb.Append(","); sb.Append("pageStartIndex,pageSize"); } sb.AppendLine("){"); string urlCode = URLUtility.CreateJavacriptUrlCode(mlm, mi, modelType); sb.Append(urlCode); if (mlm.Paged) { sb.AppendLine(string.Format((minimize ? "pageStartIndex=(pageStartIndex==undefined?0:(pageStartIndex==null?0:pageStartIndex));pageSize=(pageSize==undefined?10:(pageSize==null?10:pageSize));var ret=Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize,CurrentParameters:{1},currentIndex:pageStartIndex*pageSize,currentPageSize:pageSize,CurrentPage:Math.floor(pageStartIndex/pageSize),parse:function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);}}response=response.response;this.TotalPages=response.Pager.TotalPages;return response.response;}},MoveToPage:function(pageNumber){{if(pageNumber>=0&&pageNumber<this.TotalPages){{this.currentIndex=pageNumber*this.currentPageSize;{2}this.fetch();this.CurrentPage=pageNumber;}}}},ChangePageSize:function(pageSize){{this.currentPageSize=pageSize;this.MoveToPage(Math.floor(this.currentIndex/pageSize));}},MoveToNextPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1);}}}},MoveToPreviousPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1);}}}}," :@"pageStartIndex = (pageStartIndex == undefined ? 0 : (pageStartIndex == null ? 0 : pageStartIndex)); pageSize = (pageSize == undefined ? 10 : (pageSize == null ? 10 : pageSize)); var ret = Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize, CurrentParameters:{1}, currentIndex : pageStartIndex*pageSize, currentPageSize : pageSize, CurrentPage : Math.floor(pageStartIndex/pageSize), parse : function(response){{ if(response.Backbone!=undefined){{ _.extend(Backbone,response.Backbone); }} response = response.response; this.TotalPages = response.Pager.TotalPages; return response.response; }}, MoveToPage : function(pageNumber){{ if (pageNumber>=0 && pageNumber<this.TotalPages){{ this.currentIndex = pageNumber*this.currentPageSize; {2} this.fetch(); this.CurrentPage=pageNumber; }} }}, ChangePageSize : function(pageSize){{ this.currentPageSize = pageSize; this.MoveToPage(Math.floor(this.currentIndex/pageSize)); }}, MoveToNextPage : function(){{ if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{ this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1); }} }}, MoveToPreviousPage : function(){{ if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{ this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1); }} }},"),new object[]{ (mlm.Path.Contains("?") ? "&" : "?"), sbCurParameters.ToString(), (mlm.Path.Contains("?") ? (minimize ? "" : "\t\t\t")+"this.url = this.url.substring(0,this.url.indexOf('&PageStartIndex='))+'&PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;" : (minimize ? "" : "\t\t\t")+"this.url = this.url.substring(0,this.url.indexOf('?'))+'?PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;") })); if (mi.GetParameters().Length > 0) { sb.Append((minimize ? "" : "\t")+"ChangeParameters: function("); for (int x = 0; x < mi.GetParameters().Length - 3; x++) { sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name); } sb.AppendLine(string.Format((minimize ? "){{{0}url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;this.CurrentParameters={2};this.currentIndex=0;this.url=url;this.fetch();}}," :@"){{{0} url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize; this.CurrentParameters = {2}; this.currentIndex=0; this.url=url; this.fetch(); }},"),new object[]{urlCode,(mlm.Path.Contains("?") ? "&" : "?"),sbCurParameters.ToString()})); } sb.AppendLine(string.Format((minimize ? "model:{0}.Model}});" :@" model:{0}.Model }});"),ModelNamespace.GetFullNameForModel(modelType, host))); } else { sb.AppendLine(string.Format((minimize ? "var ret=Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);return response.response;}}else{{return response;}}}}," :@" var ret = Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{ if(response.Backbone!=undefined){{ _.extend(Backbone,response.Backbone); return response.response; }}else{{ return response; }} }},"),sbCurParameters.ToString())); if (mi.GetParameters().Length > 0) { sb.Append((minimize ? "" : "\t")+"ChangeParameters: function("); for (int x = 0; x < mi.GetParameters().Length; x++) { sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name); } sb.AppendLine(string.Format((minimize ? "){{{0}this.CurrentParameters={1};this.currentIndex=0;this.url=url;this.fetch();}}," :@"){{{0} this.CurrentParameters = {1}; this.currentIndex=0; this.url=url; this.fetch(); }},"),urlCode,sbCurParameters.ToString())); } sb.AppendLine("model:" + ModelNamespace.GetFullNameForModel(modelType, host) + ".Model});"); } sb.AppendLine((minimize ? "ret=new ret();return ret;}});" :@"ret = new ret(); return ret; }});")); break; } } } } return sb.ToString(); }
public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize) { WrappedStringBuilder sb = new WrappedStringBuilder(minimize); if (!minimize) { sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.ModelListCallGenerators"); } foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelListMethod), false).Length > 0) { foreach (ModelListMethod mlm in mi.GetCustomAttributes(typeof(ModelListMethod), false)) { if (mlm.Host == host || mlm.Host == "*") { WrappedStringBuilder sbCurParameters = new WrappedStringBuilder(minimize); sbCurParameters.Append((minimize ? "function(){return{":"function(){return {")); sb.Append(string.Format((minimize ? "{0}=_.extend({0},{{{1}:function(" : "{0} = _.extend({0}, {{{1}:function("), ModelNamespace.GetFullNameForModel(modelType, host), mi.Name)); for (int x = 0; x < (mlm.Paged ? mi.GetParameters().Length - 3 : mi.GetParameters().Length); x++) { sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name); sbCurParameters.AppendLine((x == 0 ? "" : ",") + string.Format("'{0}':{0}", mi.GetParameters()[x].Name)); } sbCurParameters.Append("};}"); if (mlm.Paged) { if (mi.GetParameters().Length != 3) { sb.Append(","); } sb.Append("pageStartIndex,pageSize"); } sb.AppendLine("){"); string urlCode = URLUtility.CreateJavacriptUrlCode(mlm, mi, modelType); sb.Append(urlCode); if (mlm.Paged) { sb.AppendLine(string.Format((minimize ? "pageStartIndex=(pageStartIndex==undefined?0:(pageStartIndex==null?0:pageStartIndex));pageSize=(pageSize==undefined?10:(pageSize==null?10:pageSize));var ret=Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize,CurrentParameters:{1},currentIndex:pageStartIndex*pageSize,currentPageSize:pageSize,CurrentPage:Math.floor(pageStartIndex/pageSize),parse:function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);}}response=response.response;this.TotalPages=response.Pager.TotalPages;return response.response;}},MoveToPage:function(pageNumber){{if(pageNumber>=0&&pageNumber<this.TotalPages){{this.currentIndex=pageNumber*this.currentPageSize;{2}this.fetch();this.CurrentPage=pageNumber;}}}},ChangePageSize:function(pageSize){{this.currentPageSize=pageSize;this.MoveToPage(Math.floor(this.currentIndex/pageSize));}},MoveToNextPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1);}}}},MoveToPreviousPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1);}}}}," :@"pageStartIndex = (pageStartIndex == undefined ? 0 : (pageStartIndex == null ? 0 : pageStartIndex)); pageSize = (pageSize == undefined ? 10 : (pageSize == null ? 10 : pageSize)); var ret = Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize, CurrentParameters:{1}, currentIndex : pageStartIndex*pageSize, currentPageSize : pageSize, CurrentPage : Math.floor(pageStartIndex/pageSize), parse : function(response){{ if(response.Backbone!=undefined){{ _.extend(Backbone,response.Backbone); }} response = response.response; this.TotalPages = response.Pager.TotalPages; return response.response; }}, MoveToPage : function(pageNumber){{ if (pageNumber>=0 && pageNumber<this.TotalPages){{ this.currentIndex = pageNumber*this.currentPageSize; {2} this.fetch(); this.CurrentPage=pageNumber; }} }}, ChangePageSize : function(pageSize){{ this.currentPageSize = pageSize; this.MoveToPage(Math.floor(this.currentIndex/pageSize)); }}, MoveToNextPage : function(){{ if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{ this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1); }} }}, MoveToPreviousPage : function(){{ if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{ this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1); }} }},"), new object[] { (mlm.Path.Contains("?") ? "&" : "?"), sbCurParameters.ToString(), (mlm.Path.Contains("?") ? (minimize ? "" : "\t\t\t") + "this.url = this.url.substring(0,this.url.indexOf('&PageStartIndex='))+'&PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;" : (minimize ? "" : "\t\t\t") + "this.url = this.url.substring(0,this.url.indexOf('?'))+'?PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;") })); if (mi.GetParameters().Length > 0) { sb.Append((minimize ? "" : "\t") + "ChangeParameters: function("); for (int x = 0; x < mi.GetParameters().Length - 3; x++) { sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name); } sb.AppendLine(string.Format((minimize ? "){{{0}url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;this.CurrentParameters={2};this.currentIndex=0;this.url=url;this.fetch();}}," :@"){{{0} url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize; this.CurrentParameters = {2}; this.currentIndex=0; this.url=url; this.fetch(); }},"), new object[] { urlCode, (mlm.Path.Contains("?") ? "&" : "?"), sbCurParameters.ToString() })); } sb.AppendLine(string.Format((minimize ? "model:{0}.Model}});" :@" model:{0}.Model }});"), ModelNamespace.GetFullNameForModel(modelType, host))); } else { sb.AppendLine(string.Format((minimize ? "var ret=Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);return response.response;}}else{{return response;}}}}," :@" var ret = Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{ if(response.Backbone!=undefined){{ _.extend(Backbone,response.Backbone); return response.response; }}else{{ return response; }} }},"), sbCurParameters.ToString())); if (mi.GetParameters().Length > 0) { sb.Append((minimize ? "" : "\t") + "ChangeParameters: function("); for (int x = 0; x < mi.GetParameters().Length; x++) { sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name); } sb.AppendLine(string.Format((minimize ? "){{{0}this.CurrentParameters={1};this.currentIndex=0;this.url=url;this.fetch();}}," :@"){{{0} this.CurrentParameters = {1}; this.currentIndex=0; this.url=url; this.fetch(); }},"), urlCode, sbCurParameters.ToString())); } sb.AppendLine("model:" + ModelNamespace.GetFullNameForModel(modelType, host) + ".Model});"); } sb.AppendLine((minimize ? "ret=new ret();return ret;}});" :@"ret = new ret(); return ret; }});")); break; } } } } return(sb.ToString()); }
public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize) { if (modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false).Length > 0) { if (((int)((ModelBlockJavascriptGeneration)modelType.GetCustomAttributes(typeof(ModelBlockJavascriptGeneration), false)[0]).BlockType & (int)ModelBlockJavascriptGenerations.CollectionView) == (int)ModelBlockJavascriptGenerations.CollectionView) return ""; } WrappedStringBuilder sb = new WrappedStringBuilder(minimize); sb.AppendFormat((minimize ? "{0}=_.extend(true,{0},{{CollectionView:Backbone.View.extend({{" : @"//Org.Reddragonit.BackBoneDotNet.JSGenerators.CollectionViewGenerator {0} = _.extend(true,{0}, {{CollectionView : Backbone.View.extend({{ "), ModelNamespace.GetFullNameForModel(modelType, host)); string tag = "div"; if (modelType.GetCustomAttributes(typeof(ModelViewTag), false).Length > 0) tag = ((ModelViewTag)modelType.GetCustomAttributes(typeof(ModelViewTag), false)[0]).TagName; switch (tag) { case "tr": sb.AppendLine((minimize ? "tagName:\"table\"," : "\ttagName : \"table\",")); break; default: sb.AppendLine((minimize ? "tagName:\""+tag+"\"," : "\ttagName : \""+tag+"\",")); break; } _AppendClassName(modelType,host, sb,minimize); _AppendAttributes(modelType, sb,minimize); sb.AppendLine((minimize ? "render:function(){var el=this.$el;el.html('');" :@" render : function(){ var el = this.$el; el.html('');")); if (tag.ToLower() == "tr") { sb.AppendLine((minimize ? "var thead=$('<thead class=\"'+this.className+' header\"></thead>');el.append(thead);thead.append('<tr></tr>');thead=$(thead.children()[0]);" :@" var thead = $('<thead class=""'+this.className+' header""></thead>'); el.append(thead); thead.append('<tr></tr>'); thead = $(thead.children()[0]);")); foreach (string str in properties) { if (str != "id" && !viewIgnoreProperties.Contains(str)) sb.AppendLine((minimize ? "" : "\t\t")+"thead.append('<th className=\"'+this.className+' " + str + "\">" + str + "</th>');"); } sb.AppendLine((minimize ? "el.append('<tbody></tbody>');el=$(el.children()[1]);" : @" el.append('<tbody></tbody>'); el = $(el.children()[1]);")); } sb.AppendFormat((minimize ? "if(this.collection.length==0){{this.trigger('pre_render_complete',this);this.trigger('render',this);}}else{{var alt=false;for(var x=0;x<this.collection.length;x++){{var vw=new {0}.View({{model:this.collection.at(x)}});if(alt){{vw.$el.addClass('Alt');}}alt=!alt;if(x+1==this.collection.length){{vw.on('render',function(){{this.col.trigger('item_render',this.view);this.col.trigger('pre_render_complete',this.col);this.col.trigger('render',this.col);}},{{col:this,view:vw}});}}else{{vw.on('render',function(){{this.col.trigger('item_render',this.view);}},{{col:this,view:vw}});}}el.append(vw.$el);vw.render();}}}}}}}})}});" : @" if(this.collection.length==0){{ this.trigger('pre_render_complete',this); this.trigger('render',this); }}else{{ var alt=false; for(var x=0;x<this.collection.length;x++){{ var vw = new {0}.View({{model:this.collection.at(x)}}); if (alt){{ vw.$el.addClass('Alt'); }} alt=!alt; if(x+1==this.collection.length){{ vw.on('render',function(){{this.col.trigger('item_render',this.view);this.col.trigger('pre_render_complete',this.col);this.col.trigger('render',this.col);}},{{col:this,view:vw}}); }}else{{ vw.on('render',function(){{this.col.trigger('item_render',this.view);}},{{col:this,view:vw}}); }} el.append(vw.$el); vw.render(); }} }} }} }})}});"), ModelNamespace.GetFullNameForModel(modelType, host)); return sb.ToString(); }