Esempio n. 1
0
        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;}
},"));
            }
        }
Esempio n. 2
0
        public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize)
        {
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);

            sb.AppendFormat((minimize ?
                             "{0}=_.extend(true,{0},{{Model:Backbone.Model.extend({{initialize:function(){{if(this._revertReadonlyFields!=undefined){{this.on(\"change\",this._revertReadonlyFields);}}}},"
                :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.ModelDefinitionGenerator
{0} = _.extend(true,{0}, {{Model : Backbone.Model.extend({{
    initialize : function() {{
        if (this._revertReadonlyFields != undefined){{
            this.on(""change"",this._revertReadonlyFields);
        }}
    }},"),
                            ModelNamespace.GetFullNameForModel(modelType, host));
            _AppendDefaults(modelType, properties, sb, minimize);
            if (!hasDelete)
            {
                _AppendBlockDestroy(sb, minimize);
            }
            if (!hasAdd && !hasUpdate)
            {
                _AppendBlockSave(sb, minimize);
            }
            else if (!hasAdd)
            {
                _AppendBlockAdd(sb, minimize);
            }
            else if (!hasUpdate)
            {
                _AppendBlockUpdate(sb, minimize);
            }
            _AppendReadonly(readOnlyProperties, sb, minimize);
            _AppendValidate(modelType, properties, sb, minimize);
            _AppendParse(modelType, host, properties, readOnlyProperties, sb, minimize);
            string urlRoot = "";

            foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
            {
                if (mr.Host == host)
                {
                    urlRoot = mr.Path;
                    break;
                }
            }
            if (urlRoot == "")
            {
                foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
                {
                    if (mr.Host == "*")
                    {
                        urlRoot = mr.Path;
                        break;
                    }
                }
            }
            _AppendExposedMethods(modelType, urlRoot, host, sb, minimize);
            sb.AppendLine(string.Format((minimize ? "urlRoot:\"{0}\"}})}});" : "\turlRoot : \"{0}\"}})}});"), urlRoot));
            return(sb.ToString());
        }
        public 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();
        }
Esempio n. 4
0
 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);
            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());
        }
Esempio n. 6
0
        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());
        }
Esempio n. 7
0
        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());
        }
Esempio n. 8
0
        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);
    },"));
            }
        }
Esempio n. 9
0
        public string GenerateJS(Type modelType, string host, List <string> readOnlyProperties, List <string> properties, List <string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete, bool minimize)
        {
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);

            if (!minimize)
            {
                sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.RouterGenerator");
            }
            Dictionary <string, List <BackboneHashRoute> > routes = new Dictionary <string, List <BackboneHashRoute> >();

            foreach (BackboneHashRoute bhr in modelType.GetCustomAttributes(typeof(BackboneHashRoute), false))
            {
                List <BackboneHashRoute> rts = new List <BackboneHashRoute>();
                if (routes.ContainsKey(bhr.RouterName))
                {
                    rts = routes[bhr.RouterName];
                    routes.Remove(bhr.RouterName);
                }
                rts.Add(bhr);
                routes.Add(bhr.RouterName, rts);
            }
            if (routes.Count > 0)
            {
                foreach (string routerName in routes.Keys)
                {
                    if (routerName.Contains("."))
                    {
                        string tmp = "";
                        foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.'))
                        {
                            sb.AppendLine(string.Format((minimize ? "{1}{0}={2}{0}||{{}};" : "{1}{0} = {2}{0} || {{}};"),
                                                        str,
                                                        (tmp.Length == 0 ? "var " : tmp + "."),
                                                        (tmp.Length == 0 ? "" : tmp + ".")));
                            tmp += (tmp.Length == 0 ? "" : ".") + str;
                        }
                    }
                    else
                    {
                        sb.AppendLine(string.Format((minimize ? "var {0}={0}||{{}};" : "var {0} = {0} || {{}};"), routerName));
                    }
                    sb.AppendLine(string.Format((minimize ?
                                                 "if(!Backbone.History.started){{Backbone.history.start({{pushState:false}});}}if({0}.navigate==undefined){{{0}=new Backbone.Router();}}"
                        : @"if (!Backbone.History.started){{
    Backbone.history.start({{ pushState: false }});
}}
if ({0}.navigate == undefined){{
    {0} = new Backbone.Router();
}}"), routerName));
                    foreach (BackboneHashRoute bhr in routes[routerName])
                    {
                        sb.AppendFormat(@"{0}.route('{1}','{2}',function(", routerName, bhr.Path, bhr.FunctionName);
                        if (bhr.Path.Contains(":"))
                        {
                            foreach (Match m in _REG_PARS.Matches(bhr.Path))
                            {
                                sb.Append(m.Groups[1].Value + ",");
                            }
                            sb.Length = sb.Length - 1;
                        }
                        sb.AppendLine(string.Format((minimize ? "){{{0}}});" : "){{ {0} }});"), bhr.Code));
                    }
                }
            }
            return(sb.ToString());
        }
        public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize)
        {
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);
            string urlRoot = "";
            foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
            {
                if (mr.Host == host)
                {
                    urlRoot = mr.Path;
                    break;
                }
            }
            if (urlRoot == "")
            {
                foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
                {
                    if (mr.Host == "*")
                    {
                        urlRoot = mr.Path;
                        break;
                    }
                }
            }
            sb.AppendFormat((minimize ?
                "{0}=_.extend(true,{0},{{"
                :@"//Org.Reddragonit.BackBoneDotNet.JSGenerators.StaticExposedMethodGenerator
{0} = _.extend(true,{0}, {{"),
                ModelNamespace.GetFullNameForModel(modelType, host));
            foreach (MethodInfo mi in modelType.GetMethods(BindingFlags.Public | BindingFlags.Static))
            {
                if (mi.GetCustomAttributes(typeof(ExposedMethod), false).Length > 0)
                    AppendMethodCall(urlRoot,host, mi,((ExposedMethod)mi.GetCustomAttributes(typeof(ExposedMethod), false)[0]).AllowNullResponse, ref sb,minimize);
            }
            while (sb.ToString().TrimEnd().EndsWith(","))
                sb.Length = sb.Length - 1;
            sb.AppendLine("});");
            return sb.ToString();
        }
        private void _AppendInstanceMethods(Type modelType, string urlRoot, ref WrappedStringBuilder builder)
        {
            foreach (MethodInfo mi in modelType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
            {
                if (mi.GetCustomAttributes(typeof(ExposedMethod), false).Length > 0)
                {
                    bool allowNull = ((ExposedMethod)mi.GetCustomAttributes(typeof(ExposedMethod), false)[0]).AllowNullResponse;
                    builder.AppendFormat("          {0}:function(", mi.Name);
                    ParameterInfo[] pars = mi.GetParameters();
                    for (int x = 0; x < pars.Length; x++)
                    {
                        builder.Append(pars[x].Name + (x + 1 == pars.Length ? "" : ","));
                    }
                    builder.AppendLine(@"){
                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)
                            {
                                builder.AppendLine(string.Format(@"function_data.{0}=[];
for(var x=0;x<{0}.length;x++){{
    function_data.{0}.push({{id:{0}[x].id()}});
}}", par.Name));
                            }
                            else
                            {
                                builder.AppendLine(string.Format("function_data.{0} = {{ id: {0}.id() }};", par.Name));
                            }
                        }
                        else
                        {
                            builder.AppendLine(string.Format("function_data.{0} = {0};", par.Name));
                        }
                    }
                    builder.AppendLine(string.Format(@"             var response = $.ajax({{
                    type:'METHOD',
                    url:'{0}/'+this.id()+'/{1}?_='+parseInt((new Date().getTime() / 1000).toFixed(0)).toString(),
                    data:JSON.stringify(function_data),
                    content_type:'application/json; charset=utf-8',
                    dataType:'json',
                    async:false,
                    cache:false
                }});
                if (response.status==200){{
                    {2}
                }}else{{
                    throw response.responseText;
                }}", new object[] {
                        urlRoot,
                        mi.Name,
                        (mi.ReturnType == typeof(void) ? "" : @"var ret=response.responseText;
                    if (ret!=undefined)
                        var response = JSON.parse(ret);")
                    }));
                    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];
                            }
                        }
                        builder.AppendLine("if (response==null){");
                        if (!allowNull)
                        {
                            builder.AppendLine("throw \"A null response was returned by the server which is invalid.\";");
                        }
                        else
                        {
                            builder.AppendLine("return response;");
                        }
                        builder.AppendLine("}else{");
                        if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
                        {
                            if (array)
                            {
                                builder.AppendLine(string.Format(@"         ret=[];
            for (var x=0;x<response.length;x++){{
                ret.push({1}(response[x],new App.Models.{0}()));
            }}
            response = ret;", new object[] {
                                    propType.Name,
                                    Constants.PARSERS_VARIABLE
                                }));
                            }
                            else
                            {
                                builder.AppendLine(string.Format(@"             ret = {1}(response,new App.Models.{0}());
response=ret;", new object[] {
                                    propType.Name,
                                    Constants.PARSERS_VARIABLE
                                }));
                            }
                        }
                        builder.AppendLine(@"           return response;
        }");
                    }
                    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)
        {
            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());
        }
Esempio n. 13
0
        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 _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);
        }
        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(".", "_"));
 }
Esempio n. 17
0
        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);
        }
Esempio n. 18
0
        public void GeneratorJS(ref WrappedStringBuilder builder, bool minimize, Type modelType)
        {
            foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS))
            {
                if (mi.GetCustomAttributes(typeof(ModelListMethod), false).Length > 0)
                {
                    ModelListMethod mlm = (ModelListMethod)mi.GetCustomAttributes(typeof(ModelListMethod), false)[0];
                    builder.AppendFormat(@"{0}=$.extend({0},{{
    {1}:function(", new object[] { Constants.STATICS_VARAIBLE, mi.Name });
                    ParameterInfo[] pars = mi.GetParameters();
                    string          url  = _CreateJavacriptUrlCode(mlm, mi, modelType);
                    if (mlm.Paged)
                    {
                        url += string.Format("+'{0}PageStartIndex='+this.currentIndex()+'&PageSize='+this.currentPageSize()", (mlm.Path.Contains("?") ? "&" : "?"));
                    }
                    for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                    {
                        builder.Append((x > 0 ? "," : "") + pars[x].Name);
                    }
                    if (mlm.Paged)
                    {
                        builder.Append((pars.Length > 3 ? "," : "") + "pageStartIndex,pageSize");
                        builder.AppendLine(@"){
        pageStartIndex = (pageStartIndex == undefined ? 0 : (pageStartIndex == null ? 0 : pageStartIndex));
        pageSize = (pageSize == undefined ? 10 : (pageSize == null ? 10 : pageSize));
        var ret = $.extend([],{
            currentIndex:function(){return pageStartIndex;},
            currentPageSize:function(){return pageSize;},
            currentPage:function(){return Math.floor(this.currentIndex()/this.currentPageSize());},
            totalPages:function(){return 0;},
            moveToPage:function(pageNumber){
                if (pageNumber>=this.totalPages()){
                    throw 'Unable to move to Page that exceeds current total pages.';
                }else{
                    this.currentIndex=function(){return pageNumber*this.currentPageSize();};
                    this.reload();
                }
            },
            moveToNextPage:function(){
                if(Math.floor(this.currentIndex()/this.currentPageSize())+1<this.totalPages()){
                    this.moveToPage(Math.floor(this.currentIndex()/this.currentPageSize())+1);
                }else{
                    throw 'Unable to move to next Page as that will excess current total pages.';
                }
            },
            moveToPreviousPage:function(){
                if(Math.floor(this.currentIndex()/this.currentPageSize())-1>=0){
                    this.moveToPage(Math.floor(this.currentIndex()/this.currentPageSize())-1);
                }else{
                    throw 'Unable to move to previous Page as that will be before the first page.';
                }
            },
            changePageSize:function(size){
                this.currentPageSize = function(){ return size;};
                this.reload();
            },");
                    }
                    else
                    {
                        builder.AppendLine(@"){
        var ret = $.extend([],{");
                    }
                    builder.Append(string.Format("url:function(){{ return {0};}},", url));
                    builder.Append(Constants._LIST_EVENTS_CODE);
                    builder.Append(Constants._LIST_RELOAD_CODE.Replace("$url$", "this.url()").Replace("$type$", modelType.Name));

                    /*builder.AppendLine(@"reload:function(){
                     * var tmp = this;
                     * var response = $.ajax({
                     * type:'GET',
                     * url:this.url(),
                     * dataType:'text',
                     * async:false,
                     * cache:false
                     * }).fail(function(jqXHR,testStatus,errorThrown){
                     * throw errorThrown;
                     * }).done(function(data,textStatus,jqXHR){
                     * if (jqXHR.status==200){
                     *  data = JSON.parse(data);
                     *  while(tmp.length>0){ret.pop();}");
                     * if (mlm.Paged)
                     *  builder.AppendLine("tmp.totalPages=function(){return data.TotalPages;};");
                     * builder.AppendLine(string.Format(@"                 if (data{2}!=null){{
                     *      for(var x=0;x<data{2}.length;x++){{
                     *          tmp.push({1}['{0}'](data{2}[x],new App.Models.{0}()));
                     *      }}
                     *  }}
                     *  for(var x=0;x<tmp.length;x++){{
                     *      tmp[x].$on('{4}',function(model){{
                     *          tmp.reload();
                     *      }});
                     *      tmp[x].$on('{5}',function(model){{
                     *          for(var x=0;x<tmp.length;x++){{
                     *              if (tmp[x].id()==model.id()){{
                     *                  Vue.set(tmp,x,model);
                     *                  break;
                     *              }}
                     *          }}
                     *      }});
                     *      tmp[x].$on('{6}',function(model){{
                     *          for(var x=0;x<tmp.length;x++){{
                     *              if (tmp[x].id()==model.id()){{
                     *                  Vue.set(tmp,x,model);
                     *                  break;
                     *              }}
                     *          }}
                     *      }});
                     *  }}
                     * }}else{{
                     *  throw data;
                     * }}
                     * }});
                     * }},
                     * url:function(){{ return {3};}}", new object[] {
                     *  modelType.Name,
                     *  Constants.PARSERS_VARIABLE,
                     *  (mlm.Paged ? ".response" : ""),
                     *  url,
                     *  Constants.Events.MODEL_DESTROYED,
                     *  Constants.Events.MODEL_UPDATED,
                     *  Constants.Events.MODEL_LOADED
                     * }));*/
                    if ((mlm.Paged && pars.Length > 3) || (!mlm.Paged && pars.Length > 0))
                    {
                        builder.AppendLine(@",
            currentParameters:function(){
                return {");
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.AppendLine(string.Format("              {0}:{0}{1}", new object[] { pars[x].Name, (x + 1 == (mlm.Paged ? pars.Length - 3 : pars.Length) ? "" : ",") }));
                        }
                        builder.AppendLine(@"                };
            },");
                        builder.Append("            changeParameters:function(");
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.Append((x > 0 ? "," : "") + pars[x].Name);
                        }
                        builder.AppendLine(string.Format(@"){{
                this.url=function(){{ return {0};}};
                this.currentParameters=function(){{
                    return {{", url));
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.AppendLine(string.Format("              {0}:{0}{1}", new object[] { pars[x].Name, (x + 1 == (mlm.Paged ? pars.Length - 3 : pars.Length) ? "" : ",") }));
                        }
                        builder.AppendLine(@"                   };
                };
                this.reload();
            }");
                    }
                    builder.AppendLine(@"        });
        ret.reload(false);
        return ret;
    }
});");
                }
            }
        }
        public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize)
        {
            if (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();
        }
Esempio n. 20
0
 public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType)
 {
     builder.AppendLine(string.Format(@"     App.Models.{0} = App.Models.{0}||{{}};
 App.Models.{0}.{1} = function(){{ ", modelType.Name, Constants.CREATE_INSTANCE_FUNCTION_NAME));
     builder.AppendLine(@"         if (Vue.version.indexOf('2')==0){
         return new Vue({data:function(){return data;},methods:methods,computed:computed});
     }else if (Vue.version.indexOf('3')==0){
         var ret = {
             $on:function(event,callback){
                 if (this._$events==undefined){this._$events={};}
                 if (Array.isArray(event)){
                     for(var x=0;x<event.length;x++){
                         if (this._$events[event[x]]==undefined){this._$events[event[x]]=[];}
                         this._$events[event[x]].push(callback);
                     }
                 }else{
                     if (this._$events[event]==undefined){this._$events[event]=[];}
                     this._$events[event].push(callback);
                 }
             },
             $off:function(callback){
                 if (this._$events!=undefined){
                     for(var evt in this._$events){
                         for(var x=0;x<this._$events[evt].length;x++){
                             if (this._$events[evt][x]==callback){
                                 this._$events[evt].splice(x,1);
                                 break;
                             }
                         }
                     }
                 }
             },
             $emit:function(event,data){
                 if (this._$events!=undefined){
                     if (this._$events[event]!=undefined){
                         for(var x=0;x<this._$events[event].length;x++){
                             this._$events[event][x]((data==undefined ? this : data));
                         }
                     }
                 }
             },
             toVue:function(options){
                 if (options.mixins==undefined){options.mixins=[];}
                 options.mixins.push(this.toMixin());
                 return Vue.createApp(options);
             },
             toMixin:function(){
                 var tmp = {};
                 for(var prop in data){
                     tmp[prop] = this[prop];
                 }
                 if (tmp.id!=undefined)
                     delete tmp.id;
                 var og = this;
                 Object.defineProperty(tmp,'id',{get:function(){return (getMap(this)==undefined ? undefined : getMap(this).id);}});
                 return {
                     data:function(){return tmp;},
                     methods:extend({$on:ret.$on,$off:ret.$off},methods),
                     computed:computed,
                     created:function(){
                         var view=this;
                         this.$on([");
     builder.AppendFormat("'{0}','{1}','{2}','parsed'", new object[] {
         Constants.Events.MODEL_LOADED,
         Constants.Events.MODEL_SAVED,
         Constants.Events.MODEL_UPDATED
     });
     builder.AppendLine(@"],function(){view.$forceUpdate();});
                     }
                 };
             }
         };
         var tmp = extend({_hashCode:null},data);
         Object.defineProperty(ret,'_hashCode',{ get:function(){return tmp._hashCode;},set:function(hash){tmp._hashCode=null;H(JSON.stringify(ret)).then(hash=>{tmp._hashCode=hash;});}});");
     foreach (PropertyInfo pi in Utility.GetModelProperties(modelType))
     {
         if (pi.CanRead && pi.CanWrite)
         {
             builder.AppendLine(string.Format(@"                Object.defineProperty(ret,'{0}',{{
             get:function(){{return tmp.{0};}},
             set:function(value){{
                 tmp.{0}=value;
                 ret._hashCode='';
             }},
             enumerable: true,
             configurable: false
         }});", pi.Name));
         }
     }
     builder.AppendLine(@"                ret = extend(ret,methods);
         for(var prop in computed){
             Object.defineProperty(ret,prop,computed[prop]);
         }
         setMap(ret,getMap(this));
         return ret;
     }else{
         throw 'unsupported version of VueJS found.';
     }
 };");
 }
 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);
 }
Esempio n. 22
0
        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;
    },"));
            }
        }
Esempio n. 23
0
 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);
 }
Esempio n. 24
0
     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();
 }"));
             }
         }
     }
Esempio n. 25
0
        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();
        }
Esempio n. 26
0
        public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType)
        {
            string urlRoot = "";

            foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
            {
                urlRoot = mr.Path;
                break;
            }
            if (urlRoot == "")
            {
                foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
                {
                    urlRoot = mr.Path;
                    break;
                }
            }
            foreach (MethodInfo mi in modelType.GetMethods(BindingFlags.Public | BindingFlags.Static))
            {
                if (mi.GetCustomAttributes(typeof(ExposedMethod), false).Length > 0)
                {
                    bool allowNull = ((ExposedMethod)mi.GetCustomAttributes(typeof(ExposedMethod), false)[0]).AllowNullResponse;
                    builder.AppendFormat("App.Models.{0}=extend(App.Models.{0},{{{1}:function(", new object[] { modelType.Name, mi.Name });
                    ParameterInfo[] pars = Utility.ExtractStrippedParameters(mi);
                    for (int x = 0; x < pars.Length; x++)
                    {
                        builder.Append(pars[x].Name + (x + 1 == pars.Length ? "" : ","));
                    }
                    builder.AppendLine(@"){
                        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)
                            {
                                builder.AppendLine(string.Format(@"function_data.{0}=[];
for(var x=0;x<{0}.length;x++){{
    function_data.{0}.push({{id:{0}[x].id}});
}}", par.Name));
                            }
                            else
                            {
                                builder.AppendLine(string.Format("function_data.{0} = {{ id: {0}.id }};", par.Name));
                            }
                        }
                        else
                        {
                            builder.AppendLine(string.Format("function_data.{0} = {0};", par.Name));
                        }
                    }
                    builder.AppendLine(string.Format(@"             return new Promise((resolve,reject)=>{{
                    ajax(
                    {{
                        url:'{0}/{1}',
                        type:'SMETHOD',
                        useJSON:{2},
                        data:function_data
                    }}).then(response=>{{
                        {3}", new object[] {
                        urlRoot,
                        mi.Name,
                        (mi.GetCustomAttributes(typeof(UseFormData), false).Length == 0).ToString().ToLower(),
                        (mi.ReturnType == typeof(void) ? "" : @"var ret=response.json();
                    if (ret!=undefined||ret==null)
                        response = ret;")
                    }));
                    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];
                            }
                        }
                        builder.AppendLine("if (response==null){");
                        if (!allowNull)
                        {
                            builder.AppendLine("reject(\"A null response was returned by the server which is invalid.\");");
                        }
                        else
                        {
                            builder.AppendLine("resolve(response);");
                        }
                        builder.AppendLine("}else{");
                        if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
                        {
                            if (array)
                            {
                                builder.AppendLine(string.Format(@"         ret=[];
            for (var x=0;x<response.length;x++){{
                ret.push(_{0}(response[x]));
            }}
            response = ret;", new object[] {
                                    propType.Name
                                }));
                            }
                            else
                            {
                                builder.AppendLine(string.Format(@"             ret = _{0}(response);
            response=ret;", new object[] {
                                    propType.Name
                                }));
                            }
                        }
                        builder.AppendLine(@"           resolve(response);
        }");
                    }
                    else
                    {
                        builder.AppendLine("           resolve();");
                    }
                    builder.AppendLine(@"},
                    response=>{
                        reject(response);
                    });
    });
}});");
                }
            }
        }
Esempio n. 27
0
        public void GeneratorJS(ref WrappedStringBuilder builder, Type modelType)
        {
            foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS))
            {
                if (mi.GetCustomAttributes(typeof(ModelListMethod), false).Length > 0)
                {
                    ModelListMethod mlm = (ModelListMethod)mi.GetCustomAttributes(typeof(ModelListMethod), false)[0];
                    builder.AppendFormat(@"App.Models.{0}=extend(App.Models.{0},{{
    {1}:function(", new object[] { modelType.Name, mi.Name });
                    ParameterInfo[] pars = Utility.ExtractStrippedParameters(mi);
                    string          url  = _CreateJavacriptUrlCode(mlm, pars, modelType);
                    if (mlm.Paged)
                    {
                        url += string.Format("+'{0}PageStartIndex='+this.currentIndex()+'&PageSize='+this.currentPageSize()", (mlm.Path.Contains("?") ? "&" : "?"));
                    }
                    for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                    {
                        builder.Append((x > 0 ? "," : "") + pars[x].Name);
                    }
                    if (mlm.Paged)
                    {
                        builder.Append((pars.Length > 3 ? "," : "") + "pageStartIndex,pageSize");
                        builder.AppendLine(@"){
        pageStartIndex = (pageStartIndex == undefined ? 0 : (pageStartIndex == null ? 0 : pageStartIndex));
        pageSize = (pageSize == undefined ? 10 : (pageSize == null ? 10 : pageSize));
        var ret = extend([],{
            currentIndex:function(){return pageStartIndex;},
            currentPageSize:function(){return pageSize;},
            currentPage:function(){return Math.floor(this.currentIndex()/this.currentPageSize());},
            totalPages:function(){return 0;},
            moveToPage:function(pageNumber){
                if (pageNumber>=this.totalPages()){
                    throw 'Unable to move to Page that exceeds current total pages.';
                }else{
                    this.currentIndex=function(){return pageNumber*this.currentPageSize();};
                    return this.reload();
                }
            },
            moveToNextPage:function(){
                if(Math.floor(this.currentIndex()/this.currentPageSize())+1<this.totalPages()){
                    return this.moveToPage(Math.floor(this.currentIndex()/this.currentPageSize())+1);
                }else{
                    throw 'Unable to move to next Page as that will excess current total pages.';
                }
            },
            moveToPreviousPage:function(){
                if(Math.floor(this.currentIndex()/this.currentPageSize())-1>=0){
                    return this.moveToPage(Math.floor(this.currentIndex()/this.currentPageSize())-1);
                }else{
                    throw 'Unable to move to previous Page as that will be before the first page.';
                }
            },
            changePageSize:function(size){
                this.currentPageSize = function(){ return size;};
                return this.reload();
            },");
                    }
                    else
                    {
                        builder.AppendLine(@"){
        var ret = extend([],{");
                    }
                    builder.Append(string.Format("url:function(){{ return {0};}},", url));
                    builder.Append(Constants._LIST_EVENTS_CODE);
                    builder.Append(Constants.ARRAY_TO_VUE_METHOD);
                    builder.Append(Constants._LIST_RELOAD_CODE.Replace("$url$", "this.url()").Replace("$type$", modelType.Name));
                    if ((mlm.Paged && pars.Length > 3) || (!mlm.Paged && pars.Length > 0))
                    {
                        builder.AppendLine(@",
            currentParameters:function(){
                return {");
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.AppendLine(string.Format("              {0}:{0}{1}", new object[] { pars[x].Name, (x + 1 == (mlm.Paged ? pars.Length - 3 : pars.Length) ? "" : ",") }));
                        }
                        builder.AppendLine(@"                };
            },");
                        builder.Append("            changeParameters:function(");
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.Append((x > 0 ? "," : "") + pars[x].Name);
                        }
                        builder.AppendLine(@"){
                if (arguments.length!=0){
                    if (Array.isArray(arguments[0]) && arguments.length==1){
                        var args = arguments[0];");
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.AppendLine(string.Format("                      {0} = (args.length>{1} ? args[{1}] : undefined);", pars[x].Name, x));
                        }
                        builder.AppendLine(string.Format(@"                    }}
                }}
                this.url=function(){{ return {0};}};
                this.currentParameters=function(){{
                    return {{", url));
                        for (int x = 0; x < (mlm.Paged ? pars.Length - 3 : pars.Length); x++)
                        {
                            builder.AppendLine(string.Format("              {0}:{0}{1}", new object[] { pars[x].Name, (x + 1 == (mlm.Paged ? pars.Length - 3 : pars.Length) ? "" : ",") }));
                        }
                        builder.AppendLine(@"                   };
                };
                this.reload();
            }");
                    }
                    builder.AppendLine(@"        });
        ret.reload();
        return ret;
    }
});");
                }
            }
        }