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()); }
private void _AppendClassName(Type modelType, string host, WrappedStringBuilder sb, bool minimize) { sb.Append((minimize ? "className:\"" : "\tclassName : \"")); foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.')) { sb.Append(str + " "); } foreach (ModelViewClass mvc in modelType.GetCustomAttributes(typeof(ModelViewClass), false)) { sb.Append(mvc.ClassName + " "); } sb.AppendLine(" CollectionView\","); }
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 ret = ""; string tmp = ""; foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.')) { ret += (minimize ? (tmp.Length == 0 ? "window." + str : tmp + "." + str) + "=" + (tmp.Length == 0 ? "window." : tmp + ".") + str + "||{};" : (tmp.Length == 0 ? "window." + str : tmp + "." + str) + " = " + (tmp.Length == 0 ? "window." : tmp + ".") + str + " || {};" + Environment.NewLine); tmp += (tmp.Length == 0 ? "" : ".") + str; } return(ret); }
private void _RenderDialogCode(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, WrappedStringBuilder sb, bool minimize) { _RenderDialogConstructCode(modelType, host, readOnlyProperties, properties, sb, minimize); sb.AppendLine((minimize ? "if($('#Org_Reddragonit_BackBoneDotNet_DialogBackground').length==0){$(document.body).append($('<div id=\"Org_Reddragonit_BackBoneDotNet._DialogBackground\" class=\"Org Reddragonit BackBoneDotNet DialogBackground\"></div>'));}$('#Org_Reddragonit_BackBoneDotNet_DialogBackground').show();var frm=$('#" :@" if($('#Org_Reddragonit_BackBoneDotNet_DialogBackground').length==0){ $(document.body).append($('<div id=""Org_Reddragonit_BackBoneDotNet._DialogBackground"" class=""Org Reddragonit BackBoneDotNet DialogBackground""></div>')); } $('#Org_Reddragonit_BackBoneDotNet_DialogBackground').show(); var frm = $('#") + ModelNamespace.GetFullNameForModel(modelType, host).Replace(".", "_") + "_dialog');"); _AppendInputSetupCode(sb, host, properties, readOnlyProperties, modelType, minimize); _AppendAcceptCode(sb, minimize); sb.AppendLine((minimize ? "" : "\t\t") + "frm.show();"); }
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.Collection) == (int)ModelBlockJavascriptGenerations.Collection) { return(""); } } 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; } } } return(string.Format((minimize ? "{0}=_.extend(true,{0},{{Collection:Backbone.Collection.extend({{model:{0}.Model,parse:function(response){{return (response.Backbone==undefined?response:response.response);}},url:\"{1}\"}})}});" :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.CollectionGenerator {0} = _.extend(true,{0},{{Collection: Backbone.Collection.extend({{ model : {0}.Model, parse : function(response){{return (response.Backbone == undefined ? response : response.response);}}, url : ""{1}"" }}) }});"), new object[] { ModelNamespace.GetFullNameForModel(modelType, host), (urlRoot.StartsWith("/") ? "" : "/") + urlRoot })); }
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 _RenderDialogConstructCode(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, WrappedStringBuilder sb, bool minimize) { sb.AppendFormat((minimize ? "if($('#{0}_dialog').length==0){{var dlog=$('<div></div>');dlog.attr('id','{0}_dialog');dlog.attr('class',view.className+' dialog');var frm=$('<table></table>');dlog.append(frm);frm.append('<thead><tr><th colspan=\"2\"></th></tr></thead>');frm.append('<tbody></tbody>');frm=$(frm.children()[1]);" :@" if($('#{0}_dialog').length==0){{ var dlog = $('<div></div>'); dlog.attr('id','{0}_dialog'); dlog.attr('class',view.className+' dialog'); var frm = $('<table></table>'); dlog.append(frm); frm.append('<thead><tr><th colspan=""2""></th></tr></thead>'); frm.append('<tbody></tbody>'); frm = $(frm.children()[1]);"), ModelNamespace.GetFullNameForModel(modelType, host).Replace(".", "_")); foreach (string propName in properties) { if (propName != "id") { if (!readOnlyProperties.Contains(propName)) { Type propType = modelType.GetProperty(propName).PropertyType; sb.Append((minimize ? "" : "\t\t\t") + "frm.append($('<tr><td class=\"fieldName\">" + propName + "</td><td class=\"fieldInput " + propType.Name + "\" proptype=\"" + propType.Name + "\">"); _RenderFieldInput(propName, propType, host, sb); sb.AppendLine("</td></tr>'));"); } } } _AppendArrayInputsCode(sb, minimize); sb.AppendFormat((minimize ? "frm.append($('<tr><td colspan=\"2\" style=\"text-align:center\"><span class=\"button accept\">Okay</span><span class=\"button cancel\">Cancel</span></td></tr>'));var butCancel=$(dlog.find('tr>td>span.cancel')[0]);butCancel.bind('click',function(){{$('#{0}_dialog').hide();$('#Org_Reddragonit_BackBoneDotNet_DialogBackground').hide();}});$(document.body).append(dlog);}}" :@" frm.append($('<tr><td colspan=""2"" style=""text-align:center""><span class=""button accept"">Okay</span><span class=""button cancel"">Cancel</span></td></tr>')); var butCancel = $(dlog.find('tr>td>span.cancel')[0]); butCancel.bind('click',function(){{ $('#{0}_dialog').hide(); $('#Org_Reddragonit_BackBoneDotNet_DialogBackground').hide(); }}); $(document.body).append(dlog); }}"), ModelNamespace.GetFullNameForModel(modelType, host).Replace(".", "_")); }
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 _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; },")); } }
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) { 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()); }
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); }
private void _AppendInputSetupCode(WrappedStringBuilder sb, string host, List <string> properties, List <string> readOnlyProperties, Type modelType, bool minimize) { foreach (string propName in properties) { if (propName != "id") { if (!readOnlyProperties.Contains(propName)) { Type propType = modelType.GetProperty(propName).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))) { sb.AppendFormat((minimize ? "var sel{0}=$(frm.find('select[name=\"{0}\"]')[0]);var opts={1}.SelectList();for(var x=0;x<opts.length;x++){{var opt=opts[x];sel{0}.append($('<option value=\"'+opt.ID+'\">'+opt.Text+'</option>'));}}" :@" var sel{0} = $(frm.find('select[name=""{0}""]')[0]); var opts = {1}.SelectList(); for(var x=0;x<opts.length;x++){{ var opt = opts[x]; sel{0}.append($('<option value=""'+opt.ID+'"">'+opt.Text+'</option>')); }}"), propName, ModelNamespace.GetFullNameForModel(propType, host)); if (array) { sb.AppendFormat((minimize ? "for(var x=0;x<view.model.get('{0}').length;x++){{;$(sel{0}.find('option[value=\"'+view.model.get('{0}')[x].get('id')+'\"]')[0]).attr('selected', 'selected');}}" :@" for(var x=0;x<view.model.get('{0}').length;x++){{; $(sel{0}.find('option[value=""'+view.model.get('{0}')[x].get('id')+'""]')[0]).attr('selected', 'selected'); }}"), propName); } else { sb.AppendLine("\t\tsel.val(view.model.get('" + propName + "').id);"); } } else if (propType.IsEnum) { if (array) { sb.AppendFormat((minimize ? "var sel{0}=$(frm.find('select[name=\"{0}\"]')[0]);for(var x=0;x<view.model.get('{0}').length;x++){{$(sel.find('option[value=\"'+view.model.get('{0}')[x]+'\"]')[0]).attr('selected', 'selected');}}" :@" var sel{0} = $(frm.find('select[name=""{0}""]')[0]); for(var x=0;x<view.model.get('{0}').length;x++){{ $(sel.find('option[value=""'+view.model.get('{0}')[x]+'""]')[0]).attr('selected', 'selected'); }}"), propName); } else { sb.AppendLine((minimize ? "" : "\t\t") + "$(frm.find('select[name=\"" + propName + "\"]')[0]).val(view.model.get('" + propName + "'));"); } } else { if (array) { sb.AppendFormat((minimize ? "var ins=frm.find('input[name={0}');for(var x=1;x<ins.length;x++){{$(ins[x]).remove();}}var inp=$(ins[0]);for(var x=0;x<view.model.get('{0}').length;x++){{inp.val(view.model.get('{0}'));if (x<model.get('{0}').length-1){{var newInp=inp.clone();inp.after(newInp);inp.after('<br/>');inp=newInp;}}}}" :@" var ins = frm.find('input[name={0}'); for(var x=1;x<ins.length;x++){{ $(ins[x]).remove(); }} var inp = $(ins[0]); for(var x=0;x<view.model.get('{0}').length;x++){{ inp.val(view.model.get('{0}')); if (x<model.get('{0}').length-1){{ var newInp = inp.clone(); inp.after(newInp); inp.after('<br/>'); inp = newInp; }} }}"), propName); } else if (propType == typeof(bool)) { sb.AppendLine(string.Format((minimize ? "$(frm.find('input[name=\"{0}\"][value=\"'+view.model.get('{0}')+'\"]')[0]).prop('checked',true);" :"\t\t$(frm.find('input[name=\"{0}\"][value=\"'+view.model.get('{0}')+'\"]')[0]).prop('checked', true);"), propName)); } else { sb.AppendLine(string.Format((minimize ? "$(frm.find('input[name=\"{0}\"]')[0]).val(view.model.get('{0}'));" :"\t\t$(frm.find('input[name=\"{0}\"]')[0]).val(view.model.get('{0}'));"), propName)); } } } } } _AppendAcceptCode(sb, minimize); }
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 _RenderFieldInput(string propName, Type propType, string host, WrappedStringBuilder sb) { 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))) { sb.Append("<select class=\"'+view.className+' " + propName + "\" name=\"" + propName + "\" modeltype=\"" + ModelNamespace.GetFullNameForModel(propType, host) + "\" " + (array ? "multiple=\"multiple\"" : "") + "></select>"); } else if (propType.IsEnum) { sb.Append("<select class=\"'+view.className+' " + propName + "\" name=\"" + propName + "\" " + (array ? "multiple=\"multiple\"" : "") + ">"); foreach (string str in Enum.GetNames(propType)) { sb.Append("<option value=\"" + str + "\">" + str + "</option>"); } sb.Append("</select>"); } else { if (array) { sb.Append("<input class=\"'+view.className+' " + propName + "\" type=\"text\" name=\"" + propName + "\" isarray=\"true\" proptype=\"" + propType.FullName + "\"/><span class=\"button add\">+</span>"); } else if (propType == typeof(bool)) { sb.Append("<input class=\"'+view.className+' " + propName + " radTrue\" type=\"radio\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\" value=\"true\"/><label class=\"'+view.className+' " + propName + " lblTrue\">True</label><input class=\"'+view.className+' " + propName + " radFalse\" type=\"radio\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\" value=\"false\"/><label class=\"'+view.className+' " + propName + " lblFalse\">False</label>"); } else { sb.Append("<input class=\"'+view.className+' " + propName + "\" type=\"text\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\"/>"); } } }
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()); }
internal static void AppendMethodCall(string urlRoot, string host, MethodInfo mi, bool allowNull, ref WrappedStringBuilder sb, bool minimize) { sb.Append(string.Format((minimize ? "" : "\t") + "{0}:function(", mi.Name)); ParameterInfo[] pars = mi.GetParameters(); for (int x = 0; x < pars.Length; x++) { sb.Append(pars[x].Name + (x + 1 == pars.Length ? "" : ",")); } sb.Append((minimize ? "){var function_data={};":"){var function_data = {};")); foreach (ParameterInfo par in pars) { Type propType = par.ParameterType; 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) { sb.AppendLine(string.Format((minimize ? "function_data.{0}=[];for(var x=0;x<{0}.length;x++){{function_data.{0}.push(({0}.at!=undefined?{0}.at(x).id:{0}[x].id));}}" :@"function_data.{0}=[]; for(var x=0;x<{0}.length;x++){{ function_data.{0}.push(({0}.at!=undefined ? {0}.at(x).id : {0}[x].id)); }}"), par.Name)); } else { sb.AppendLine(string.Format((minimize ?"function_data.{0}={0}.id;" :"function_data.{0} = {0}.id;"), par.Name)); } } else { sb.AppendLine(string.Format((minimize ? "function_data.{0}={0};": "function_data.{0} = {0};"), par.Name)); } } sb.AppendLine(string.Format((minimize ? "var response = $.ajax({{type:'{4}',url:'{0}/{3}{1}',processData:false,data:escape(JSON.stringify(function_data)),content_type:'application/json; charset=utf-8',dataType:'json',async:false,cache:false}});if(response.status==200){{{2}}}else{{throw new Exception(response.responseText);}}" :@"var response = $.ajax({{ type:'{4}', url:'{0}/{3}{1}', processData:false, data:escape(JSON.stringify(function_data)), content_type:'application/json; charset=utf-8', dataType:'json', async:false, cache:false }}); if (response.status==200){{ {2} }}else{{ throw new Exception(response.responseText); }} "), new object[] { urlRoot, mi.Name, (mi.ReturnType == typeof(void) ? "" : (minimize ? "var ret=response.responseText; if(ret!=undefined){var response=JSON.parse(ret);if(response.Backbone!=undefined){_.extend(Backbone,response.Backbone);response=response.response;}" : @"var ret=response.responseText; if (ret!=undefined){ var response = JSON.parse(ret); if(response.Backbone!=undefined){ _.extend(Backbone,response.Backbone); response=response.response; }")), (mi.IsStatic ? "" : "'+this.id+'/"), (mi.IsStatic ? "SMETHOD" : "METHOD") })); if (mi.ReturnType != typeof(void)) { Type propType = mi.ReturnType; 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]; } } sb.AppendLine((minimize ? "if(response==null){":"if (response==null){")); if (!allowNull) { sb.AppendLine("throw \"A null response was returned by the server which is invalid.\";"); } else { sb.AppendLine("return response;"); } sb.AppendLine("}else{"); if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel))) { if (array) { sb.AppendLine(string.Format((minimize ? "if({0}.Collection!=undefined){{ret = new {0}.Collection();for(var x=0;x<response.length;x++){{ret.add(new {0}.Model({{'id':response[x].id}}));ret.at(x).attributes=ret.at(x).parse(response[x]);}}}}else{{ret=[];for(var x=0;x<response.length;x++){{ret.push(new {0}.Model({{'id':response[x].id}}));ret[x].attributes=ret[x].parse(response[x]);}}}}response=ret;" : @" if({0}.Collection!=undefined){{ ret = new {0}.Collection(); for (var x=0;x<response.length;x++){{ ret.add(new {0}.Model({{'id':response[x].id}})); ret.at(x).attributes=ret.at(x).parse(response[x]); }} }}else{{ ret=[]; for (var x=0;x<response.length;x++){{ ret.push(new {0}.Model({{'id':response[x].id}})); ret[x].attributes=ret[x].parse(response[x]); }} }} response = ret;"), ModelNamespace.GetFullNameForModel(propType, host))); } else { sb.AppendLine(string.Format((minimize ? "ret=new {0}.Model({{id:response.id}});ret.attributes=ret.parse(response);response=ret;" :@"ret = new {0}.Model({{id:response.id}}); ret.attributes = ret.parse(response); response=ret;"), ModelNamespace.GetFullNameForModel(propType, host))); } } sb.AppendLine((minimize ? "}return response;}else{return null;}" :@"} return response;}else{return null;}")); } sb.AppendLine("},"); }