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()); }
private void _AppendData(Type modelType, List <PropertyInfo> props, ref WrappedStringBuilder builder) { IModel m = null; if (modelType.GetConstructor(Type.EmptyTypes) != null) { m = (IModel)modelType.GetConstructor(Type.EmptyTypes).Invoke(new object[] { }); } builder.AppendLine(@" data = {"); bool isFirst = true; foreach (PropertyInfo pi in props) { if (pi.CanRead && pi.CanWrite) { builder.Append(string.Format(@"{2} {0}:{1}", new object[] { pi.Name, (m == null ? "null" : (pi.GetValue(m, new object[0]) == null ? "null" : JSON.JsonEncode(pi.GetValue(m, new object[0])))), (isFirst ? "" : ",") })); isFirst = false; } } builder.AppendLine(@" };"); }
public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType) { string urlRoot = Utility.GetModelUrlRoot(modelType); List <PropertyInfo> props = Utility.GetModelProperties(modelType); _AppendData(modelType, props, ref builder); _AppendComputed(props, ref builder); builder.AppendLine(string.Format(@" methods = extend(methods,{{ isNew:function(){{ return (getMap(this)==undefined ? true : (getMap(this).{0} == undefined ? true : (this.id==undefined? true : this.id==undefined||this.id==null)));}},", Constants.INITIAL_DATA_KEY)); _AppendInstanceMethods(modelType, urlRoot, ref builder); foreach (MethodInfo mi in modelType.GetMethods(Constants.STORE_DATA_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelSaveMethod), false).Length > 0) { _AppendSave(urlRoot, ref builder, (mi.GetCustomAttributes(typeof(UseFormData), false).Length == 0)); } else if (mi.GetCustomAttributes(typeof(ModelUpdateMethod), false).Length > 0) { _AppendUpdate(urlRoot, ref builder, (mi.GetCustomAttributes(typeof(UseFormData), false).Length == 0)); } else if (mi.GetCustomAttributes(typeof(ModelDeleteMethod), false).Length > 0) { _AppendDelete(urlRoot, ref builder); } } _AppendReloadMethod(modelType, urlRoot, ref builder); builder.AppendLine(" });"); }
public void GeneratorJS(ref WrappedStringBuilder builder, bool minimize, Type modelType) { string urlRoot = Utility.GetModelUrlRoot(modelType); builder.AppendLine(string.Format(@"App.Models.{0}=Vue.extend({{", modelType.Name)); List <PropertyInfo> props = Utility.GetModelProperties(modelType); IModel m = (IModel)modelType.GetConstructor(new Type[] { }).Invoke(new object[] { }); _AppendData(m, props, ref builder); _AppendComputed(m, props, ref builder); builder.AppendLine(string.Format(@" methods:{{ isNew:function(){{ return (this.{0}==undefined ? true : (this.id==undefined? true : this.id()==undefined||this.id()==null));}},", Constants.INITIAL_DATA_KEY)); _AppendInstanceMethods(modelType, urlRoot, ref builder); foreach (MethodInfo mi in modelType.GetMethods(Constants.STORE_DATA_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelSaveMethod), false).Length > 0) { _AppendSave(urlRoot, ref builder); } else if (mi.GetCustomAttributes(typeof(ModelUpdateMethod), false).Length > 0) { _AppendUpdate(urlRoot, ref builder); } else if (mi.GetCustomAttributes(typeof(ModelDeleteMethod), false).Length > 0) { _AppendDelete(urlRoot, ref builder); } } _AppendReloadMethod(modelType, urlRoot, ref builder); builder.AppendLine(" }"); builder.AppendLine("});"); }
private void _AppendComputed(List <PropertyInfo> props, ref WrappedStringBuilder builder) { builder.AppendLine(" computed = extend(computed,{"); foreach (PropertyInfo pi in props) { if (!pi.CanWrite) { builder.AppendLine(string.Format(@" {0}:{{ get:function(){{ return (getMap(this) == undefined ? undefined : getMap(this).{1}.{0}); }}, set:function(val){{}} }},", new object[] { pi.Name, Constants.INITIAL_DATA_KEY })); } } builder.AppendLine(string.Format(@" id:{{ get:function(){{ return (getMap(this)==undefined ? undefined : (getMap(this).{0}==undefined ? undefined : getMap(this).{0}.id)); }} }},", Constants.INITIAL_DATA_KEY)); _AppendValidations(props, ref builder); builder.AppendLine(" });"); }
private void _AppendComputed(IModel m, List <PropertyInfo> props, ref WrappedStringBuilder builder) { builder.AppendLine(" computed:{"); foreach (PropertyInfo pi in props) { if (!pi.CanWrite) { if (pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?)) { builder.AppendLine(string.Format(@" {0}:{{ get:function(){{ return (this.{1} == undefined ? undefined : (this.{1}().{0}==null ? null : new Date(this.{1}().{0}))); }} }},", new object[] { pi.Name, Constants.INITIAL_DATA_KEY })); } else { builder.AppendLine(string.Format(@" {0}:{{ get:function(){{ return (this.{1} == undefined ? undefined : this.{1}().{0}); }} }},", new object[] { pi.Name, Constants.INITIAL_DATA_KEY })); } } } _AppendValidations(props, ref builder); builder.AppendLine(" },"); }
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(); }
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();"); }
private void _AppendValidate(Type modelType, List <string> properties, WrappedStringBuilder sb, bool minimize) { bool add = false; foreach (string str in properties) { if (modelType.GetProperty(str).GetCustomAttributes(typeof(ModelRequiredField), false).Length > 0 || modelType.GetProperty(str).GetCustomAttributes(typeof(ModelFieldValidationRegex), false).Length > 0) { add = true; break; } } if (add) { sb.AppendLine((minimize ? "validate:function(attrs){var atts=this.attributes;_.extend(atts,attrs);var errors = new Array();" :@" validate : function(attrs) { var atts = this.attributes; _.extend(atts,attrs); var errors = new Array();")); foreach (string str in properties) { if (modelType.GetProperty(str).GetCustomAttributes(typeof(ModelRequiredField), false).Length > 0) { ModelRequiredField mrf = (ModelRequiredField)modelType.GetProperty(str).GetCustomAttributes(typeof(ModelRequiredField), false)[0]; sb.AppendFormat((minimize ? "if(atts.{0}==null||atts.{0}==undefined){{errors.push({{field:'{0}',error:Backbone.TranslateValidationError('{1}')}});}}" :@" if (atts.{0}==null || atts.{0}==undefined){{ errors.push({{field:'{0}',error:Backbone.TranslateValidationError('{1}')}}); }}"), str, mrf.ErrorMessageName); } else if (modelType.GetProperty(str).GetCustomAttributes(typeof(ModelFieldValidationRegex), false).Length > 0) { ModelFieldValidationRegex mfvr = (ModelFieldValidationRegex)modelType.GetProperty(str).GetCustomAttributes(typeof(ModelFieldValidationRegex), false)[0]; sb.AppendFormat((minimize ? "if(!new RegExp('{0}').test((atts.{1}==null||atts.{1}==undefined?'':atts.{1}))){{errors.push({{field:'{1}',error:Backbone.TranslateValidationError('{2}')}});}}" :@" if (!new RegExp('{0}').test((atts.{1}==null || atts.{1}==undefined ? '' : atts.{1}))){{ errors.push({{field:'{1}',error:Backbone.TranslateValidationError('{2}')}}); }}"), mfvr.Regex.Replace("'", "\'"), str, mfvr.ErrorMessageName); } } sb.AppendLine((minimize ? "this.errors=errors;if(errors.length>0){return errors;}}," :@" this.errors = errors; if (errors.length>0){return errors;} },")); } }
public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType) { string urlRoot = Utility.GetModelUrlRoot(modelType); foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS)) { if (mi.GetCustomAttributes(typeof(ModelLoadAllMethod), false).Length > 0) { builder.AppendLine(string.Format(@"App.Models.{0}=extend(App.Models.{0},{{LoadAll:function(){{ var ret = extend([],{{ {1} {2} {3} }}); ret.reload(); return ret; }} }});", new object[] { modelType.Name, Constants._LIST_EVENTS_CODE, Constants.ARRAY_TO_VUE_METHOD, Constants._LIST_RELOAD_CODE.Replace("$url$", string.Format("'{0}'", urlRoot)).Replace("$type$", modelType.Name) })); break; } } }
private void _AppendReloadMethod(Type modelType, string urlRoot, ref WrappedStringBuilder builder) { builder.AppendLine(string.Format(@"reload:function(){{ var model=this; return new Promise((resolve,reject)=>{{ if (model.isNew()){{ reject('Cannot reload unsaved model.'); }}else{{ ajax({{ url:'{0}/'+model.id, type:'GET' }}).then( response=>{{ if (response.ok){{ model.{1}(response.json()); if (model.$emit!=undefined){{ model.$emit('{2}',model); }} resolve(model); }}else{{ reject(response.text()); }} }}, response=>{{ reject(response.text()); }} ); }} }}); }}", new object[] { urlRoot, Constants.PARSE_FUNCTION_NAME, Constants.Events.MODEL_LOADED })); }
public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType) { builder.AppendLine(@" var methods = {}; var data = {}; var computed = {}; var map = new WeakMap(); const setMap=function(obj,val){ var t = obj; if (Vue!=undefined && Vue.isProxy!=undefined && Vue.toRaw!=undefined){ if (Vue.isProxy(obj)){ t = Vue.toRaw(obj); } } map.set(t,val); }; const getMap=function(obj){ var t = obj; if (Vue!=undefined && Vue.isProxy!=undefined && Vue.toRaw!=undefined){ if (Vue.isProxy(obj)){ t = Vue.toRaw(obj); } } return map.get(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) { 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 _RecurWrite(WrappedStringBuilder sb, Hashtable msgs, string indent, bool minimize) { string[] keys = new string[msgs.Keys.Count]; msgs.Keys.CopyTo(keys,0); for(int x=0;x<keys.Length;x++) { sb.Append(indent + "'" + keys[x] + (minimize ? "':" : "' : ")); if (msgs[keys[x]] is string) sb.Append("'" + msgs[keys[x]].ToString().Replace("'", "\'") + "'"); else { sb.AppendLine(indent+(minimize ? "" : "\t")+"{"); _RecurWrite(sb, (Hashtable)msgs[keys[x]], indent + (minimize ? "" : "\t"),minimize); sb.Append(indent+(minimize ? "" : "\t")+"}"); } sb.AppendLine((x == keys.Length - 1 ? "" : ",")); } }
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(" View\","); }
private void _AppendUpdate(string urlRoot, ref WrappedStringBuilder builder) { builder.AppendLine(string.Format(@" update:function(options){{ options = $.extend({{ async:true, success:function(){{}}, failure:function(error){{throw (error==undefined ? 'failed' : error);}} }},(options==undefined || options==null ?{{}}:options)); if (!this.isValid){{ options.failure('Invalid model.'); }} else if (this.isNew()){{ options.failure('Cannot updated unsaved model, please call save instead.'); }} else {{ var model=this; $.ajax({{ type:'{4}', url:'{0}/'+this.id(), content_type:'application/json; charset=utf-8', data:JSON.stringify({1}(this)), dataType:'text', async:options.async, cache:false }}).fail(function(jqXHR,testStatus,errorThrown){{ options.failure(errorThrown); }}).done(function(data,textStatus,jqXHR){{ if (jqXHR.status==200){{ data = JSON.parse(data); if (data){{ data=model.{3}(); for(var prop in data){{ if (prop!='id'){{ data[prop]=model[prop]; }} }} model.{3}=function(){{return data;}}; model.$emit('{2}',model); options.success(model); }}else{{ options.failure(); }} }}else{{ options.failure(data); }} }}); }} }},", new object[] { urlRoot, Constants.TO_JSON_VARIABLE, Constants.Events.MODEL_UPDATED, Constants.INITIAL_DATA_KEY, RequestHandler.RequestMethods.PATCH })); }
public void GeneratorJS(ref WrappedStringBuilder builder, bool minimize, Type modelType) { builder.AppendLine(string.Format(" var {0}={{}};", Constants.PARSERS_VARIABLE)); List <Type> types = new List <Type>(); types.AddRange(_RecurLocateLinkedTypes(modelType)); foreach (Type t in types) { _AppendParser(t, ref builder); } }
private void _RecurWrite(WrappedStringBuilder sb, Hashtable msgs, string indent, bool minimize) { string[] keys = new string[msgs.Keys.Count]; msgs.Keys.CopyTo(keys, 0); for (int x = 0; x < keys.Length; x++) { sb.Append(indent + "'" + keys[x] + (minimize ? "':" : "' : ")); if (msgs[keys[x]] is string) { sb.Append("'" + msgs[keys[x]].ToString().Replace("'", "\'") + "'"); } else { sb.AppendLine(indent + (minimize ? "" : "\t") + "{"); _RecurWrite(sb, (Hashtable)msgs[keys[x]], indent + (minimize ? "" : "\t"), minimize); sb.Append(indent + (minimize ? "" : "\t") + "}"); } sb.AppendLine((x == keys.Length - 1 ? "" : ",")); } }
public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType) { string urlRoot = Utility.GetModelUrlRoot(modelType); builder.AppendLine(string.Format(@"App.Models.{0}=extend(App.Models.{0},{{Load:function(id){{ var ret = App.Models.{0}.{1}(); ret.{2}({{id:id}}); ret.reload(); return ret; }} }});", new object[] { modelType.Name, Constants.CREATE_INSTANCE_FUNCTION_NAME, Constants.PARSE_FUNCTION_NAME })); }
public void GeneratorJS(ref WrappedStringBuilder builder, bool minimize, Type modelType) { builder.AppendLine(string.Format(@" var ext = function(clazz,data){{ var ret = $.extend((clazz._extend==undefined ? clazz.extend(data) : clazz._extend(data)),{1}); ret._extend=(clazz._extend==undefined ? clazz.extend : clazz._extend); ret.extend = function(data){{ return ext(this,data); }}; return ret; }}; App.Models.{0}=ext(App.Models.{0},{{}});", new object[] { modelType.Name, Constants.STATICS_VARAIBLE })); }
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") + "},"); } }
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\","); }
private void _AppendReadonly(List <string> readOnlyProperties, WrappedStringBuilder sb, bool minimize) { if (readOnlyProperties.Count > 0) { sb.AppendLine((minimize ? "_revertReadonlyFields:function(){" : "\t_revertReadonlyFields : function(){")); foreach (string str in readOnlyProperties) { sb.AppendFormat((minimize ? "if(this.changedAttributes.{0}!=this.previousAttributes.{0}){{this.set({{{0}:this.previousAttributes.{0}}});}}" :@" if (this.changedAttributes.{0} != this.previousAttributes.{0}){{ this.set({{{0}:this.previousAttributes.{0}}}); }}"), str); } sb.AppendLine((minimize ? "" : "\t") + "},"); sb.AppendLine((minimize ? "_save:function(key,val,options){if(key==null||typeof key==='object'){attrs=key;options=val;}else{(attrs={})[key]=val;}if(!this.isNew()){" :@"_save : function (key, val, options) { if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } if (!this.isNew()){")); foreach (string str in readOnlyProperties) { sb.AppendLine(string.Format((minimize ? "if(attrs.{0}!=undefined){{delete attrs.{0};}}" :"if (attrs.{0}!=undefined){{delete attrs.{0};}}"), str)); } sb.AppendLine((minimize ? "}options=_.extend({validate:true},options);this._baseSave(attrs, options);}," :@"} options = _.extend({ validate: true }, options); this._baseSave(attrs, options); },")); } }
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(); }
private void _AppendData(IModel m, List <PropertyInfo> props, ref WrappedStringBuilder builder) { builder.AppendLine(@" data:function(){ return {"); bool isFirst = true; foreach (PropertyInfo pi in props) { if (pi.CanRead && pi.CanWrite) { builder.Append(string.Format(@"{2} {0}:{1}", new object[] { pi.Name, (pi.GetValue(m, new object[0]) == null ? "null" : JSON.JsonEncode(pi.GetValue(m, new object[0]))), (isFirst ? "" : ",") })); isFirst = false; } } builder.AppendLine(@" }; },"); }
private void _AppendUpdate(string urlRoot, ref WrappedStringBuilder builder, bool useJSON) { builder.AppendLine(string.Format(@" update:function(){{ var model=this; return new Promise((resolve,reject)=>{{ if (!model.isValid){{ reject('Invalid model.'); }}else if (model.isNew()){{ reject('Cannot update unsaved model, please call save instead.'); }}else{{ var data = model.{1}(); ajax( {{ url:'{0}/'+model.id, type:'{4}', useJSON:{5}, data:data }}).then(response=>{{ if (response.ok){{ var data = response.json(); if (data){{ data=getMap(model).{3}; for(var prop in data){{ if (prop!='id'){{ data[prop]=model[prop]; }} }} setMap(model,{{{3}:data}}); if (model.$emit!=undefined){{model.$emit('{2}',model);}} resolve(model); }}else{{ reject(); }} }}else{{ reject(response.text()); }} }},response=>{{reject(response.text());}}); }} }}); }},", new object[] { urlRoot, Constants.TO_JSON_VARIABLE, Constants.Events.MODEL_UPDATED, Constants.INITIAL_DATA_KEY, RequestHandler.RequestMethods.PATCH, useJSON.ToString().ToLower() })); }
private void _AppendSave(string urlRoot, ref WrappedStringBuilder builder) { builder.AppendLine(string.Format(@" save:function(options){{ options = $.extend({{ async:true, success:function(){{}}, failure:function(error){{throw (error==undefined ? 'failed' : error);}} }},(options==undefined || options==null ?{{}}:options)); if (!this.isValid){{ options.failure('Invalid model.'); }} else if (!this.isNew()){{ options.failure('Cannot save a saved model,please call update instead.'); }} else {{ var data = {1}(this); var model=this; $.ajax({{ type:'{4}', url:'{0}', content_type:'application/json; charset=utf-8', data:JSON.stringify(data), dataType:'text', async:options.async, cache:false }}).fail(function(jqXHR,testStatus,errorThrown){{ options.failure(errorThrown); }}).done(function(ret,textStatus,jqXHR){{ if (jqXHR.status==200){{ data.id=JSON.parse(ret).id; model.{2}= function(){{return data;}}; model.id=function(){{return this.{2}().id;}}; model.$emit('{3}',model); options.success(model); }}else{{ options.failure(data); }} }}); }} }},", new object[] { urlRoot, Constants.TO_JSON_VARIABLE, Constants.INITIAL_DATA_KEY, Constants.Events.MODEL_SAVED, RequestHandler.RequestMethods.PUT })); }
public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType) { builder.AppendLine(string.Format(@" methods = extend(methods,{{{0}:function(data){{ if (data==null) {{ throw 'Unable to parse null result for a model'; }} if (isString(data)){{ data=JSON.parse(data); }}", Constants.PARSE_FUNCTION_NAME)); List <PropertyInfo> props = Utility.GetModelProperties(modelType); foreach (PropertyInfo pi in props) { Type t = pi.PropertyType; if (t.IsArray) { t = t.GetElementType(); } else if (t.IsGenericType) { t = t.GetGenericArguments()[0]; } if (new List <Type>(t.GetInterfaces()).Contains(typeof(IModel))) { if (Utility.IsArrayType(pi.PropertyType)) { builder.AppendLine(string.Format(@" if (data.{0}!=null){{ var tmp = []; for(var x=0;x<data.{0}.length;x++){{ tmp.push(_{1}(data.{0}[x])); }} data.{0}=tmp; }}", pi.Name, t.Name)); } else { builder.AppendLine(string.Format(@" if (data.{0}!=null){{ data.{0}=_{1}(data.{0}); }}", pi.Name, t.Name)); } } } builder.AppendLine(string.Format(" setMap(this,{{ {0}:data }});", new object[] { Constants.INITIAL_DATA_KEY })); foreach (PropertyInfo pi in props) { builder.AppendLine(string.Format(" this.{0}=(data.{0}==null ? null : (Array.isArray(data.{0}) ? data.{0}.slice() : data.{0}));", pi.Name)); } builder.AppendLine(@" if (this.$emit != undefined) { this.$emit('parsed',this); } return this; }});"); }
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 _AppendDelete(string urlRoot, ref WrappedStringBuilder builder) { builder.AppendLine(string.Format(@" destroy:function(options){{ options = $.extend({{ async:true, success:function(){{}}, failure:function(error){{throw (error==undefined ? 'failed' : error);}} }},(options==undefined || options==null ?{{}}:options)); if (this.isNew()){{ options.failure('Cannot delete unsaved model.'); }}else{{ var model=this; $.ajax({{ type:'{2}', url:'{0}/'+this.id(), content_type:'application/json; charset=utf-8', dataType:'text', async:options.async, cache:false }}).fail(function(jqXHR,testStatus,errorThrown){{ options.failure(errorThrown); }}).done(function(data,textStatus,jqXHR){{ if (jqXHR.status==200){{ data = JSON.parse(data); if (data){{ model.$emit('{1}',model); options.success(model); }}else{{ options.failure(); }} }}else{{ options.failure(data); }} }}); }} }},", new object[] { urlRoot, Constants.Events.MODEL_DESTROYED, RequestHandler.RequestMethods.DELETE })); }
public void GeneratorJS(ref WrappedStringBuilder builder, bool minimize, Type modelType) { string urlRoot = Utility.GetModelUrlRoot(modelType); builder.AppendLine(string.Format(@"{0}=$.extend({0},{{Load:function(id){{ var response = $.ajax({{ type:'GET', url:'{2}/'+id, dataType:'json', async:false, cache:false }}); if (response.status==200){{ var response=JSON.parse(response.responseText); return {3}['{1}'](response,new App.Models.{1}()); }}else{{ throw response.responseText; }} }} }});", new object[] { Constants.STATICS_VARAIBLE, modelType.Name, urlRoot, Constants.PARSERS_VARIABLE })); }
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) { 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(); }
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("},"); }
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(); }
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); }
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 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 _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 _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 _RenderInlineCode(Type modelType,string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, WrappedStringBuilder sb,bool minimize) { string tag = "div"; if (modelType.GetCustomAttributes(typeof(ModelViewTag), false).Length > 0) tag = ((ModelViewTag)modelType.GetCustomAttributes(typeof(ModelViewTag), false)[0]).TagName; string tstring = ""; switch (tag.ToLower()) { case "tr": tstring = "td"; break; case "ul": case "ol": tstring = "li"; break; default: tstring = tag; break; } sb.AppendFormat((minimize ? "var frm=view.$el;$(frm.find('{0}.buttons>span.button')).hide();" :@" var frm = view.$el; $(frm.find('{0}.buttons>span.button')).hide();"),tstring); foreach (string propName in properties) { if (propName != "id") { if (!readOnlyProperties.Contains(propName)) { Type propType = modelType.GetProperty(propName).PropertyType; sb.Append((minimize ? "var inp=$('" : "\t\tvar inp = $('")); _RenderFieldInput(propName,propType,host, sb); sb.AppendLine("');"); if (viewIgnoreProperties.Contains(propName)) { sb.AppendFormat((minimize ? "$(frm.find('{0}:last')[0]).before($('<{0} class=\"'+view.className+' {0}\"><span class=\"'+view.className+' FieldTitle\">{1}</span><br/></{0}>'));$(frm.find('{0}.{1}')[0]).append(inp);" :@" $(frm.find('{0}:last')[0]).before($('<{0} class=""'+view.className+' {0}""><span class=""'+view.className+' FieldTitle"">{1}</span><br/></{0}>')); $(frm.find('{0}.{1}')[0]).append(inp);"),tstring,propName); }else sb.AppendLine(string.Format((minimize ? "$(frm.find('{0}.{1}')[0]).html(inp);" : "\t\t$(frm.find('{0}.{1}')[0]).html(inp);"),tstring,propName)); }else sb.AppendFormat((minimize? "$(frm.find('{0}:last')[0]).before($('<{0} class=\"'+view.className+' {0}\"><span class=\"'+view.className+' FieldTitle\">{1}</span><br/></{0}>'));$(frm.find('{0}.{1}')[0]).append(this.model.get('{1}'));" :@" $(frm.find('{0}:last')[0]).before($('<{0} class=""'+view.className+' {0}""><span class=""'+view.className+' FieldTitle"">{1}</span><br/></{0}>')); $(frm.find('{0}.{1}')[0]).append(this.model.get('{1}'));"), tstring, propName); } } _AppendInputSetupCode(sb,host, properties, readOnlyProperties, modelType,minimize); _AppendArrayInputsCode(sb,minimize); sb.AppendFormat((minimize ? "$(frm.find('{0}.buttons')[0]).append($('<span class=\"button accept\">Okay</span><span class=\"button cancel\">Cancel</span>'));var butCancel=$(frm.find('{0}.buttons>span.cancel')[0]);butCancel.bind('click',{{view:view}},function(event){{event.data.view.render();}});" :@" $(frm.find('{0}.buttons')[0]).append($('<span class=""button accept"">Okay</span><span class=""button cancel"">Cancel</span>')); var butCancel = $(frm.find('{0}.buttons>span.cancel')[0]); butCancel.bind('click',{{view:view}},function(event){{ event.data.view.render(); }});"),tstring); _AppendAcceptCode(sb,minimize); }
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) { 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(); }