Ejemplo n.º 1
0
 private void _AppendClassName(Type modelType, string host, WrappedStringBuilder sb, bool minimize)
 {
     sb.Append((minimize ? "className:\"" : "\tclassName : \""));
     foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.'))
         sb.Append(str + " ");
     foreach (ModelViewClass mvc in modelType.GetCustomAttributes(typeof(ModelViewClass), false))
         sb.Append(mvc.ClassName + " ");
     sb.AppendLine(" View\",");
 }
Ejemplo n.º 2
0
 private void _AppendAttributes(Type modelType, WrappedStringBuilder sb,bool minimize)
 {
     if (modelType.GetCustomAttributes(typeof(ModelViewAttribute), false).Length > 0)
     {
         sb.Append((minimize ? "attributes:{":"\tattributes: {"));
         object[] atts = modelType.GetCustomAttributes(typeof(ModelViewAttribute),false);
         for (int x = 0; x < atts.Length; x++)
             sb.Append((minimize ? "" : "\t\t")+"\"" + ((ModelViewAttribute)atts[x]).Name + "\" : '" + ((ModelViewAttribute)atts[x]).Value + "'" + (x < atts.Length - 1 ? "," : ""));
         sb.Append((minimize ? "" : "\t")+"},");
     }
 }
 private void _AppendClassName(Type modelType, string host, WrappedStringBuilder sb, bool minimize)
 {
     sb.Append((minimize ? "className:\"" : "\tclassName : \""));
     foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.'))
     {
         sb.Append(str + " ");
     }
     foreach (ModelViewClass mvc in modelType.GetCustomAttributes(typeof(ModelViewClass), false))
     {
         sb.Append(mvc.ClassName + " ");
     }
     sb.AppendLine(" CollectionView\",");
 }
 private void _AppendAttributes(Type modelType, WrappedStringBuilder sb, bool minimize)
 {
     if (modelType.GetCustomAttributes(typeof(ModelCollectionViewAttribute), false).Length > 0)
     {
         sb.Append((minimize ? "attributes:{" : "\tattributes: {"));
         object[] atts = modelType.GetCustomAttributes(typeof(ModelCollectionViewAttribute), false);
         for (int x = 0; x < atts.Length; x++)
         {
             sb.Append((minimize ? "" : "\t\t\"") + ((ModelCollectionViewAttribute)atts[x]).Name + "\" : '" + ((ModelCollectionViewAttribute)atts[x]).Value + "'" + (x < atts.Length - 1 ? "," : ""));
         }
         sb.Append((minimize ? "" : "\t") + "},");
     }
 }
Ejemplo n.º 5
0
        private void _AppendData(Type modelType, List <PropertyInfo> props, ref WrappedStringBuilder builder)
        {
            IModel m = null;

            if (modelType.GetConstructor(Type.EmptyTypes) != null)
            {
                m = (IModel)modelType.GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
            }
            builder.AppendLine(@"    data = {");
            bool isFirst = true;

            foreach (PropertyInfo pi in props)
            {
                if (pi.CanRead && pi.CanWrite)
                {
                    builder.Append(string.Format(@"{2}
            {0}:{1}", new object[]
                    {
                        pi.Name,
                        (m == null ? "null" : (pi.GetValue(m, new object[0]) == null ? "null" : JSON.JsonEncode(pi.GetValue(m, new object[0])))),
                        (isFirst ? "" : ",")
                    }));
                    isFirst = false;
                }
            }
            builder.AppendLine(@"
    };");
        }
Ejemplo 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)
        {
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);
            if (!minimize)
                sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.RouterGenerator");
            Dictionary<string, List<BackboneHashRoute>> routes = new Dictionary<string, List<BackboneHashRoute>>();
            foreach (BackboneHashRoute bhr in modelType.GetCustomAttributes(typeof(BackboneHashRoute), false))
            {
                List<BackboneHashRoute> rts = new List<BackboneHashRoute>();
                if (routes.ContainsKey(bhr.RouterName))
                {
                    rts = routes[bhr.RouterName];
                    routes.Remove(bhr.RouterName);
                }
                rts.Add(bhr);
                routes.Add(bhr.RouterName, rts);
            }
            if (routes.Count > 0)
            {
                foreach (string routerName in routes.Keys)
                {
                    if (routerName.Contains("."))
                    {
                        string tmp = "";
                        foreach (string str in ModelNamespace.GetFullNameForModel(modelType, host).Split('.'))
                        {
                            sb.AppendLine(string.Format((minimize ? "{1}{0}={2}{0}||{{}};" : "{1}{0} = {2}{0} || {{}};"),
                                str,
                                (tmp.Length == 0 ? "var " : tmp+"."),
                                (tmp.Length == 0 ? "" : tmp + ".")));
                            tmp += (tmp.Length == 0 ? "" : ".") + str;
                        }
                    }
                    else
                        sb.AppendLine(string.Format((minimize ? "var {0}={0}||{{}};" : "var {0} = {0} || {{}};"), routerName));
                    sb.AppendLine(string.Format((minimize ?
                        "if(!Backbone.History.started){{Backbone.history.start({{pushState:false}});}}if({0}.navigate==undefined){{{0}=new Backbone.Router();}}"
                        : @"if (!Backbone.History.started){{
    Backbone.history.start({{ pushState: false }});
}}
if ({0}.navigate == undefined){{
    {0} = new Backbone.Router();
}}"), routerName));
                    foreach (BackboneHashRoute bhr in routes[routerName])
                    {
                        sb.AppendFormat(@"{0}.route('{1}','{2}',function(",routerName,bhr.Path,bhr.FunctionName);
                        if (bhr.Path.Contains(":"))
                        {
                            foreach (Match m in _REG_PARS.Matches(bhr.Path))
                                sb.Append(m.Groups[1].Value + ",");
                            sb.Length = sb.Length - 1;
                        }
                        sb.AppendLine(string.Format((minimize ? "){{{0}}});" : "){{ {0} }});"), bhr.Code));
                    }
                }
            }
            return sb.ToString();
        }
 private void _RecurWrite(WrappedStringBuilder sb, Hashtable msgs, string indent, bool minimize)
 {
     string[] keys = new string[msgs.Keys.Count];
     msgs.Keys.CopyTo(keys,0);
     for(int x=0;x<keys.Length;x++)
     {
         sb.Append(indent + "'" + keys[x] + (minimize ? "':" : "' : "));
         if (msgs[keys[x]] is string)
             sb.Append("'" + msgs[keys[x]].ToString().Replace("'", "\'") + "'");
         else
         {
             sb.AppendLine(indent+(minimize ? "" : "\t")+"{");
             _RecurWrite(sb, (Hashtable)msgs[keys[x]], indent + (minimize ? "" : "\t"),minimize);
             sb.Append(indent+(minimize ? "" : "\t")+"}");
         }
         sb.AppendLine((x == keys.Length - 1 ? "" : ","));
     }
 }
Ejemplo n.º 8
0
        private void _RenderFieldInput(string propName, Type propType, string host, WrappedStringBuilder sb)
        {
            bool array = false;

            if (propType.FullName.StartsWith("System.Nullable"))
            {
                if (propType.IsGenericType)
                {
                    propType = propType.GetGenericArguments()[0];
                }
                else
                {
                    propType = propType.GetElementType();
                }
            }
            if (propType.IsArray)
            {
                array    = true;
                propType = propType.GetElementType();
            }
            else if (propType.IsGenericType)
            {
                if (propType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    array    = true;
                    propType = propType.GetGenericArguments()[0];
                }
            }
            if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
            {
                sb.Append("<select class=\"'+view.className+' " + propName + "\" name=\"" + propName + "\" modeltype=\"" + ModelNamespace.GetFullNameForModel(propType, host) + "\" " + (array ? "multiple=\"multiple\"" : "") + "></select>");
            }
            else if (propType.IsEnum)
            {
                sb.Append("<select class=\"'+view.className+' " + propName + "\" name=\"" + propName + "\" " + (array ? "multiple=\"multiple\"" : "") + ">");
                foreach (string str in Enum.GetNames(propType))
                {
                    sb.Append("<option value=\"" + str + "\">" + str + "</option>");
                }
                sb.Append("</select>");
            }
            else
            {
                if (array)
                {
                    sb.Append("<input class=\"'+view.className+' " + propName + "\" type=\"text\" name=\"" + propName + "\" isarray=\"true\" proptype=\"" + propType.FullName + "\"/><span class=\"button add\">+</span>");
                }
                else if (propType == typeof(bool))
                {
                    sb.Append("<input class=\"'+view.className+' " + propName + " radTrue\" type=\"radio\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\" value=\"true\"/><label class=\"'+view.className+' " + propName + " lblTrue\">True</label><input class=\"'+view.className+' " + propName + " radFalse\" type=\"radio\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\" value=\"false\"/><label class=\"'+view.className+' " + propName + " lblFalse\">False</label>");
                }
                else
                {
                    sb.Append("<input class=\"'+view.className+' " + propName + "\" type=\"text\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\"/>");
                }
            }
        }
 private void _RecurWrite(WrappedStringBuilder sb, Hashtable msgs, string indent, bool minimize)
 {
     string[] keys = new string[msgs.Keys.Count];
     msgs.Keys.CopyTo(keys, 0);
     for (int x = 0; x < keys.Length; x++)
     {
         sb.Append(indent + "'" + keys[x] + (minimize ? "':" : "' : "));
         if (msgs[keys[x]] is string)
         {
             sb.Append("'" + msgs[keys[x]].ToString().Replace("'", "\'") + "'");
         }
         else
         {
             sb.AppendLine(indent + (minimize ? "" : "\t") + "{");
             _RecurWrite(sb, (Hashtable)msgs[keys[x]], indent + (minimize ? "" : "\t"), minimize);
             sb.Append(indent + (minimize ? "" : "\t") + "}");
         }
         sb.AppendLine((x == keys.Length - 1 ? "" : ","));
     }
 }
Ejemplo n.º 10
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(".", "_"));
 }
 private void _RenderFieldInput(string propName,Type propType,string host,WrappedStringBuilder sb)
 {
     bool array = false;
     if (propType.FullName.StartsWith("System.Nullable"))
     {
         if (propType.IsGenericType)
             propType = propType.GetGenericArguments()[0];
         else
             propType = propType.GetElementType();
     }
     if (propType.IsArray)
     {
         array = true;
         propType = propType.GetElementType();
     }
     else if (propType.IsGenericType)
     {
         if (propType.GetGenericTypeDefinition() == typeof(List<>))
         {
             array = true;
             propType = propType.GetGenericArguments()[0];
         }
     }
     if (new List<Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
         sb.Append("<select class=\"'+view.className+' " + propName + "\" name=\"" + propName + "\" modeltype=\"" + ModelNamespace.GetFullNameForModel(propType, host) + "\" " + (array ? "multiple=\"multiple\"" : "") + "></select>");
     else if (propType.IsEnum)
     {
         sb.Append("<select class=\"'+view.className+' " + propName + "\" name=\"" + propName + "\" " + (array ? "multiple=\"multiple\"" : "") + ">");
         foreach (string str in Enum.GetNames(propType))
             sb.Append("<option value=\"" + str + "\">" + str + "</option>");
         sb.Append("</select>");
     }
     else
     {
         if (array)
             sb.Append("<input class=\"'+view.className+' " + propName + "\" type=\"text\" name=\"" + propName + "\" isarray=\"true\" proptype=\"" + propType.FullName + "\"/><span class=\"button add\">+</span>");
         else if (propType == typeof(bool))
             sb.Append("<input class=\"'+view.className+' " + propName + " radTrue\" type=\"radio\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\" value=\"true\"/><label class=\"'+view.className+' " + propName + " lblTrue\">True</label><input class=\"'+view.className+' " + propName + " radFalse\" type=\"radio\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\" value=\"false\"/><label class=\"'+view.className+' " + propName + " lblFalse\">False</label>");
         else
             sb.Append("<input class=\"'+view.className+' " + propName + "\" type=\"text\" name=\"" + propName + "\" proptype=\"" + propType.FullName + "\"/>");
     }
 }
Ejemplo n.º 12
0
 private void _AppendDefaults(Type modelType, List <string> properties, WrappedStringBuilder sb, bool minimize)
 {
     if (modelType.GetConstructor(Type.EmptyTypes) != null)
     {
         sb.AppendLine((minimize ? "" : "\t") + "defaults:{");
         object obj = modelType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
         if (obj != null)
         {
             WrappedStringBuilder sbProps = new WrappedStringBuilder(minimize);
             foreach (string propName in properties)
             {
                 if (propName != "id")
                 {
                     object pobj = modelType.GetProperty(propName).GetValue(obj, new object[0]);
                     sbProps.AppendLine((minimize ? "" : "\t\t") + propName + ":" + (pobj == null ? "null" : JSON.JsonEncode(pobj)) + (properties.IndexOf(propName) == properties.Count - 1 ? "" : ","));
                 }
             }
             sb.Append(sbProps.ToString().TrimEnd(",\r\n".ToCharArray()));
         }
         sb.AppendLine((minimize ? "" : "\t") + "},");
     }
 }
        private void _AppendData(IModel m, List <PropertyInfo> props, ref WrappedStringBuilder builder)
        {
            builder.AppendLine(@"   data:function(){
        return {");
            bool isFirst = true;

            foreach (PropertyInfo pi in props)
            {
                if (pi.CanRead && pi.CanWrite)
                {
                    builder.Append(string.Format(@"{2}
            {0}:{1}", new object[]
                    {
                        pi.Name,
                        (pi.GetValue(m, new object[0]) == null ? "null" : JSON.JsonEncode(pi.GetValue(m, new object[0]))),
                        (isFirst ? "" : ",")
                    }));
                    isFirst = false;
                }
            }
            builder.AppendLine(@"
        };
    },");
        }
 private void _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(".", "_"));
 }
        private void _RenderInlineCode(Type modelType,string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, WrappedStringBuilder sb,bool minimize)
        {
            string tag = "div";
            if (modelType.GetCustomAttributes(typeof(ModelViewTag), false).Length > 0)
                tag = ((ModelViewTag)modelType.GetCustomAttributes(typeof(ModelViewTag), false)[0]).TagName;

            string tstring = "";
            switch (tag.ToLower())
            {
                case "tr":
                    tstring = "td";
                    break;
                case "ul":
                case "ol":
                    tstring = "li";
                    break;
                default:
                    tstring = tag;
                    break;
            }

            sb.AppendFormat((minimize ?
                "var frm=view.$el;$(frm.find('{0}.buttons>span.button')).hide();"
                :@"      var frm = view.$el;
        $(frm.find('{0}.buttons>span.button')).hide();"),tstring);
            
            foreach (string propName in properties)
            {
                if (propName != "id")
                {
                    if (!readOnlyProperties.Contains(propName))
                    {
                        Type propType = modelType.GetProperty(propName).PropertyType;
                        sb.Append((minimize ? "var inp=$('" : "\t\tvar inp = $('"));
                        _RenderFieldInput(propName,propType,host, sb);
                        sb.AppendLine("');");
                        if (viewIgnoreProperties.Contains(propName))
                        {
                            sb.AppendFormat((minimize ? 
                                "$(frm.find('{0}:last')[0]).before($('<{0} class=\"'+view.className+' {0}\"><span class=\"'+view.className+' FieldTitle\">{1}</span><br/></{0}>'));$(frm.find('{0}.{1}')[0]).append(inp);"
                                :@"      $(frm.find('{0}:last')[0]).before($('<{0} class=""'+view.className+' {0}""><span class=""'+view.className+' FieldTitle"">{1}</span><br/></{0}>'));
        $(frm.find('{0}.{1}')[0]).append(inp);"),tstring,propName);
                        }else
                            sb.AppendLine(string.Format((minimize ? "$(frm.find('{0}.{1}')[0]).html(inp);" : "\t\t$(frm.find('{0}.{1}')[0]).html(inp);"),tstring,propName));
                    }else
                        sb.AppendFormat((minimize?
                            "$(frm.find('{0}:last')[0]).before($('<{0} class=\"'+view.className+' {0}\"><span class=\"'+view.className+' FieldTitle\">{1}</span><br/></{0}>'));$(frm.find('{0}.{1}')[0]).append(this.model.get('{1}'));"
                            :@"      $(frm.find('{0}:last')[0]).before($('<{0} class=""'+view.className+' {0}""><span class=""'+view.className+' FieldTitle"">{1}</span><br/></{0}>'));
        $(frm.find('{0}.{1}')[0]).append(this.model.get('{1}'));"), tstring, propName);
                }
            }

            _AppendInputSetupCode(sb,host, properties, readOnlyProperties, modelType,minimize);
            _AppendArrayInputsCode(sb,minimize);

            sb.AppendFormat((minimize ? 
                "$(frm.find('{0}.buttons')[0]).append($('<span class=\"button accept\">Okay</span><span class=\"button cancel\">Cancel</span>'));var butCancel=$(frm.find('{0}.buttons>span.cancel')[0]);butCancel.bind('click',{{view:view}},function(event){{event.data.view.render();}});"
                :@"          $(frm.find('{0}.buttons')[0]).append($('<span class=""button accept"">Okay</span><span class=""button cancel"">Cancel</span>'));
            var butCancel = $(frm.find('{0}.buttons>span.cancel')[0]);
            butCancel.bind('click',{{view:view}},function(event){{
                event.data.view.render();
            }});"),tstring);

            _AppendAcceptCode(sb,minimize);
        }
 private void _AppendArrayInputsCode(WrappedStringBuilder sb,bool minimize)
 {
     sb.Append(Utility.ReadEmbeddedResource("Org.Reddragonit.BackBoneDotNet.resources.arrayInputFormCode.js",minimize));
 }
Ejemplo n.º 17
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();
 }"));
             }
         }
     }
        public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize)
        {
            string urlRoot = "";
            foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
            {
                if (mr.Host == host)
                {
                    urlRoot = mr.Path;
                    break;
                }
            }
            if (urlRoot == "")
            {
                foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
                {
                    if (mr.Host == "*")
                    {
                        urlRoot = mr.Path;
                        break;
                    }
                }
            }
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);
            if (!minimize)
                sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.SelectListCallGenerator");
            List<MethodInfo> methods = new List<MethodInfo>();
            foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS))
            {
                if (mi.GetCustomAttributes(typeof(ModelSelectListMethod), false).Length > 0)
                    methods.Add(mi);
            }
            int curLen = 0;
            for (int x = 0; x < methods.Count; x++)
                curLen = Math.Max(methods[x].GetParameters().Length, curLen);
            int index = 0;
            while (index < methods.Count)
            {
                for (int x = index; x < methods.Count; x++)
                {
                    if (curLen == methods[x].GetParameters().Length)
                    {
                        MethodInfo mi = methods[x];
                        methods.RemoveAt(x);
                        methods.Insert(index, mi);
                        index++;
                        x = index - 1;
                    }
                }
                curLen = 0;
                for (int x = index; x < methods.Count; x++)
                    curLen = Math.Max(methods[x].GetParameters().Length, curLen);
            }
            if (methods.Count > 0)
            {
                sb.AppendLine(string.Format((minimize ?
                    "{0}=_.extend(true,{0},{{SelectList:function(pars){{"
                    : "{0} = _.extend(true,{0},{{SelectList : function(pars){{"
                ),ModelNamespace.GetFullNameForModel(modelType, host)));
                for (int x = 0; x < methods.Count; x++)
                {
                    sb.Append((minimize ? "" : "\t") + (x == 0 ? "" : "else ") + "if(");
                    if (methods[x].GetParameters().Length == 0)
                    {
                        sb.AppendLine((minimize? 
                            "pars==undefined||pars==null){url='';"
                        : @"pars==undefined || pars==null){
        url='';"));
                    }
                    else
                    {
                        ParameterInfo[] pars = methods[x].GetParameters();
                        WrappedStringBuilder code = new WrappedStringBuilder(minimize);
                        code.AppendLine((minimize ? "url='?';" : "\t\turl='?';"));
                        sb.Append((minimize ? "pars!=undefined&&pars!=null&&(" : "pars!=undefined && pars!=null && ("));
                        for (int y = 0; y < pars.Length; y++)
                        {
                            sb.Append((y != 0 ? (minimize ? "&&" : " && ") : "") + "pars." + pars[y].Name + "!=undefined");
                            code.AppendLine(string.Format((minimize?
                                "pars.{0}=(pars.{0}==null?'NULL':pars.{0});"
                                :"\t\tpars.{0} = (pars.{0} == null ? 'NULL' : pars.{0});"),
                                pars[y].Name));
                            if (pars[y].ParameterType == typeof(bool))
                                code.AppendLine(string.Format((minimize?
                                "pars.{0}=(pars.{0}==null?'false':(pars.{0}?'true':'false'));"
                                :"\t\tpars.{0} = (pars.{0} == null ? 'false' : (pars.{0} ? 'true' : 'false'));"),
                                pars[y].Name));
                            else if (pars[y].ParameterType == typeof(DateTime)||pars[y].ParameterType == typeof(DateTime?))
                            {
                                code.AppendLine(string.Format((minimize ?
                                    "if(pars.{0}!='NULL'){{if(!(pars.{0} instanceof Date)){{pars.{0}=new Date(pars.{0});}}pars.{0}=Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds());}}"
                                    : @"if (pars.{0} != 'NULL'){{
    if (!(pars.{0} instanceof Date)){{
        pars.{0} = new Date(pars.{0});
    }}
    pars.{0} = Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds());
}}"),pars[y].Name));
                            }
                            code.AppendLine((minimize ? "" : "\t\t")+"url+='" + (y == 0 ? "" : "&") + pars[y].Name + "='+pars." + pars[y].Name + ".toString();");
                        }
                        sb.AppendLine(")){");
                        sb.Append(code.ToString());
                    }
                    sb.AppendLine("}");
                }
                sb.AppendLine(string.Format((minimize ? 
                    "else{{return null;}}var ret=$.ajax('{0}'+url,{{async:false,cache:false,type : 'SELECT'}}).responseText;var response=JSON.parse(ret);if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);response=response.response;}}return response;}}}});"
                    :@"  else{{
        return null;
    }}
    var ret=$.ajax(
        '{0}'+url,{{
            async:false,
            cache:false,
            type : 'SELECT'
}}).responseText;
    var response = JSON.parse(ret);
    if(response.Backbone!=undefined){{
        _.extend(Backbone,response.Backbone);
        response=response.response;
    }}
return response;
}}}});"),urlRoot));

            }
            return sb.ToString();
        }
 private void _AppendAcceptCode(WrappedStringBuilder sb,bool minimize)
 {
     sb.Append(Utility.ReadEmbeddedResource("Org.Reddragonit.BackBoneDotNet.resources.editFormAccept.js",minimize));
 }
        internal static void AppendMethodCall(string urlRoot,string host,MethodInfo mi,bool allowNull,ref WrappedStringBuilder sb,bool minimize){
            sb.Append(string.Format((minimize ? "" : "\t")+"{0}:function(", mi.Name));
            ParameterInfo[] pars = mi.GetParameters();
            for (int x = 0; x < pars.Length; x++)
                sb.Append(pars[x].Name + (x + 1 == pars.Length ? "" : ","));
            sb.Append((minimize ? "){var function_data={};":"){var function_data = {};"));
            foreach (ParameterInfo par in pars)
            {
                Type propType = par.ParameterType;
                bool array = false;
                if (propType.FullName.StartsWith("System.Nullable"))
                {
                    if (propType.IsGenericType)
                        propType = propType.GetGenericArguments()[0];
                    else
                        propType = propType.GetElementType();
                }
                if (propType.IsArray)
                {
                    array = true;
                    propType = propType.GetElementType();
                }
                else if (propType.IsGenericType)
                {
                    if (propType.GetGenericTypeDefinition() == typeof(List<>))
                    {
                        array = true;
                        propType = propType.GetGenericArguments()[0];
                    }
                }
                if (new List<Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
                {
                    if (array)
                    {
                        sb.AppendLine(string.Format((minimize ? 
                            "function_data.{0}=[];for(var x=0;x<{0}.length;x++){{function_data.{0}.push(({0}.at!=undefined?{0}.at(x).id:{0}[x].id));}}"
                            :@"function_data.{0}=[];
for(var x=0;x<{0}.length;x++){{
    function_data.{0}.push(({0}.at!=undefined ? {0}.at(x).id : {0}[x].id));
}}"), par.Name));
                    }
                    else
                        sb.AppendLine(string.Format((minimize ?"function_data.{0}={0}.id;" :"function_data.{0} = {0}.id;"), par.Name));
                }
                else
                    sb.AppendLine(string.Format((minimize ? "function_data.{0}={0};": "function_data.{0} = {0};"), par.Name));
            }
            sb.AppendLine(string.Format((minimize ?
"var response = $.ajax({{type:'{4}',url:'{0}/{3}{1}',processData:false,data:escape(JSON.stringify(function_data)),content_type:'application/json; charset=utf-8',dataType:'json',async:false,cache:false}});if(response.status==200){{{2}}}else{{throw new Exception(response.responseText);}}"
:@"var response = $.ajax({{
            type:'{4}',
            url:'{0}/{3}{1}',
            processData:false,
            data:escape(JSON.stringify(function_data)),
            content_type:'application/json; charset=utf-8',
            dataType:'json',
            async:false,
            cache:false
        }});
if (response.status==200){{
        {2}
}}else{{
    throw new Exception(response.responseText);
}}
"), new object[]{
            urlRoot,
            mi.Name,
            (mi.ReturnType==typeof(void) ? "" : (minimize ? "var ret=response.responseText; if(ret!=undefined){var response=JSON.parse(ret);if(response.Backbone!=undefined){_.extend(Backbone,response.Backbone);response=response.response;}" : @"var ret=response.responseText;
    if (ret!=undefined){
    var response = JSON.parse(ret);
    if(response.Backbone!=undefined){
        _.extend(Backbone,response.Backbone);
        response=response.response;
    }")),
      (mi.IsStatic ? "" : "'+this.id+'/"),
      (mi.IsStatic ? "SMETHOD" : "METHOD")
        }));
            if (mi.ReturnType != typeof(void))
            {
                Type propType = mi.ReturnType;
                bool array = false;
                if (propType.FullName.StartsWith("System.Nullable"))
                {
                    if (propType.IsGenericType)
                        propType = propType.GetGenericArguments()[0];
                    else
                        propType = propType.GetElementType();
                }
                if (propType.IsArray)
                {
                    array = true;
                    propType = propType.GetElementType();
                }
                else if (propType.IsGenericType)
                {
                    if (propType.GetGenericTypeDefinition() == typeof(List<>))
                    {
                        array = true;
                        propType = propType.GetGenericArguments()[0];
                    }
                }
                sb.AppendLine((minimize ? "if(response==null){":"if (response==null){"));
                if (!allowNull)
                    sb.AppendLine("throw \"A null response was returned by the server which is invalid.\";");
                else
                    sb.AppendLine("return response;");
                sb.AppendLine("}else{");
                if (new List<Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
                {
                    if (array)
                    {
                        sb.AppendLine(string.Format((minimize ? 
                            "if({0}.Collection!=undefined){{ret = new {0}.Collection();for(var x=0;x<response.length;x++){{ret.add(new {0}.Model({{'id':response[x].id}}));ret.at(x).attributes=ret.at(x).parse(response[x]);}}}}else{{ret=[];for(var x=0;x<response.length;x++){{ret.push(new {0}.Model({{'id':response[x].id}}));ret[x].attributes=ret[x].parse(response[x]);}}}}response=ret;" 
                            : @"          if({0}.Collection!=undefined){{
                ret = new {0}.Collection();
                for (var x=0;x<response.length;x++){{
                    ret.add(new {0}.Model({{'id':response[x].id}}));
                    ret.at(x).attributes=ret.at(x).parse(response[x]);
                }}
            }}else{{
                ret=[];
                for (var x=0;x<response.length;x++){{
                    ret.push(new {0}.Model({{'id':response[x].id}}));
                    ret[x].attributes=ret[x].parse(response[x]);
                }}
            }}
            response = ret;"),
                                ModelNamespace.GetFullNameForModel(propType, host)));
                    }
                    else
                    {
                        sb.AppendLine(string.Format((minimize ? 
                            "ret=new {0}.Model({{id:response.id}});ret.attributes=ret.parse(response);response=ret;" 
                            :@"ret = new {0}.Model({{id:response.id}});
ret.attributes = ret.parse(response);
response=ret;"), ModelNamespace.GetFullNameForModel(propType, host)));
                    }
                }
                sb.AppendLine((minimize ? 
                    "}return response;}else{return null;}"
                    :@"}
return response;}else{return null;}"));
            }
            sb.AppendLine("},");
        }
Ejemplo n.º 21
0
 private void _AppendArrayInputsCode(WrappedStringBuilder sb, bool minimize)
 {
     sb.Append(Utility.ReadEmbeddedResource("Org.Reddragonit.BackBoneDotNet.resources.arrayInputFormCode.js", minimize));
 }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
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)
        {
            string urlRoot = "";

            foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
            {
                if (mr.Host == host)
                {
                    urlRoot = mr.Path;
                    break;
                }
            }
            if (urlRoot == "")
            {
                foreach (ModelRoute mr in modelType.GetCustomAttributes(typeof(ModelRoute), false))
                {
                    if (mr.Host == "*")
                    {
                        urlRoot = mr.Path;
                        break;
                    }
                }
            }
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);

            if (!minimize)
            {
                sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.SelectListCallGenerator");
            }
            List <MethodInfo> methods = new List <MethodInfo>();

            foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS))
            {
                if (mi.GetCustomAttributes(typeof(ModelSelectListMethod), false).Length > 0)
                {
                    methods.Add(mi);
                }
            }
            int curLen = 0;

            for (int x = 0; x < methods.Count; x++)
            {
                curLen = Math.Max(methods[x].GetParameters().Length, curLen);
            }
            int index = 0;

            while (index < methods.Count)
            {
                for (int x = index; x < methods.Count; x++)
                {
                    if (curLen == methods[x].GetParameters().Length)
                    {
                        MethodInfo mi = methods[x];
                        methods.RemoveAt(x);
                        methods.Insert(index, mi);
                        index++;
                        x = index - 1;
                    }
                }
                curLen = 0;
                for (int x = index; x < methods.Count; x++)
                {
                    curLen = Math.Max(methods[x].GetParameters().Length, curLen);
                }
            }
            if (methods.Count > 0)
            {
                sb.AppendLine(string.Format((minimize ?
                                             "{0}=_.extend(true,{0},{{SelectList:function(pars){{"
                    : "{0} = _.extend(true,{0},{{SelectList : function(pars){{"
                                             ), ModelNamespace.GetFullNameForModel(modelType, host)));
                for (int x = 0; x < methods.Count; x++)
                {
                    sb.Append((minimize ? "" : "\t") + (x == 0 ? "" : "else ") + "if(");
                    if (methods[x].GetParameters().Length == 0)
                    {
                        sb.AppendLine((minimize?
                                       "pars==undefined||pars==null){url='';"
                        : @"pars==undefined || pars==null){
        url='';"));
                    }
                    else
                    {
                        ParameterInfo[]      pars = methods[x].GetParameters();
                        WrappedStringBuilder code = new WrappedStringBuilder(minimize);
                        code.AppendLine((minimize ? "url='?';" : "\t\turl='?';"));
                        sb.Append((minimize ? "pars!=undefined&&pars!=null&&(" : "pars!=undefined && pars!=null && ("));
                        for (int y = 0; y < pars.Length; y++)
                        {
                            sb.Append((y != 0 ? (minimize ? "&&" : " && ") : "") + "pars." + pars[y].Name + "!=undefined");
                            code.AppendLine(string.Format((minimize?
                                                           "pars.{0}=(pars.{0}==null?'NULL':pars.{0});"
                                :"\t\tpars.{0} = (pars.{0} == null ? 'NULL' : pars.{0});"),
                                                          pars[y].Name));
                            if (pars[y].ParameterType == typeof(bool))
                            {
                                code.AppendLine(string.Format((minimize?
                                                               "pars.{0}=(pars.{0}==null?'false':(pars.{0}?'true':'false'));"
                                :"\t\tpars.{0} = (pars.{0} == null ? 'false' : (pars.{0} ? 'true' : 'false'));"),
                                                              pars[y].Name));
                            }
                            else if (pars[y].ParameterType == typeof(DateTime) || pars[y].ParameterType == typeof(DateTime?))
                            {
                                code.AppendLine(string.Format((minimize ?
                                                               "if(pars.{0}!='NULL'){{if(!(pars.{0} instanceof Date)){{pars.{0}=new Date(pars.{0});}}pars.{0}=Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds());}}"
                                    : @"if (pars.{0} != 'NULL'){{
    if (!(pars.{0} instanceof Date)){{
        pars.{0} = new Date(pars.{0});
    }}
    pars.{0} = Date.UTC(pars.{0}.getUTCFullYear(), pars.{0}.getUTCMonth(), pars.{0}.getUTCDate(), pars.{0}.getUTCHours(), pars.{0}.getUTCMinutes(), pars.{0}.getUTCSeconds());
}}"), pars[y].Name));
                            }
                            code.AppendLine((minimize ? "" : "\t\t") + "url+='" + (y == 0 ? "" : "&") + pars[y].Name + "='+pars." + pars[y].Name + ".toString();");
                        }
                        sb.AppendLine(")){");
                        sb.Append(code.ToString());
                    }
                    sb.AppendLine("}");
                }
                sb.AppendLine(string.Format((minimize ?
                                             "else{{return null;}}var ret=$.ajax('{0}'+url,{{async:false,cache:false,type : 'SELECT'}}).responseText;var response=JSON.parse(ret);if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);response=response.response;}}return response;}}}});"
                    :@"  else{{
        return null;
    }}
    var ret=$.ajax(
        '{0}'+url,{{
            async:false,
            cache:false,
            type : 'SELECT'
}}).responseText;
    var response = JSON.parse(ret);
    if(response.Backbone!=undefined){{
        _.extend(Backbone,response.Backbone);
        response=response.response;
    }}
return response;
}}}});"), urlRoot));
            }
            return(sb.ToString());
        }
Ejemplo n.º 24
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);
                    });
    });
}});");
                }
            }
        }
        public string GenerateJS(Type modelType, string host, List<string> readOnlyProperties, List<string> properties, List<string> viewIgnoreProperties, bool hasUpdate, bool hasAdd, bool hasDelete,bool minimize)
        {
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);
            if (!minimize)
                sb.AppendLine("//Org.Reddragonit.BackBoneDotNet.JSGenerators.ModelListCallGenerators");
            foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS))
            {
                if (mi.GetCustomAttributes(typeof(ModelListMethod), false).Length > 0)
                {
                    foreach (ModelListMethod mlm in mi.GetCustomAttributes(typeof(ModelListMethod), false))
                    {
                        if (mlm.Host == host || mlm.Host == "*")
                        {
                            WrappedStringBuilder sbCurParameters = new WrappedStringBuilder(minimize);
                            sbCurParameters.Append((minimize ? "function(){return{":"function(){return {"));
                            sb.Append(string.Format((minimize ?
                                "{0}=_.extend({0},{{{1}:function(" 
                                : "{0} = _.extend({0}, {{{1}:function("),ModelNamespace.GetFullNameForModel(modelType, host),mi.Name));
                            for (int x = 0; x < (mlm.Paged ? mi.GetParameters().Length-3 : mi.GetParameters().Length); x++)
                            {
                                sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name);
                                sbCurParameters.AppendLine((x == 0 ? "" : ",") + string.Format("'{0}':{0}", mi.GetParameters()[x].Name));
                            }
                            sbCurParameters.Append("};}");
                            if (mlm.Paged)
                            {
                                if (mi.GetParameters().Length != 3)
                                    sb.Append(",");
                                sb.Append("pageStartIndex,pageSize");
                            }
                            sb.AppendLine("){");
                            string urlCode = URLUtility.CreateJavacriptUrlCode(mlm, mi, modelType);
                            sb.Append(urlCode);
                            if (mlm.Paged)
                            {
                                sb.AppendLine(string.Format((minimize ? 
                                    "pageStartIndex=(pageStartIndex==undefined?0:(pageStartIndex==null?0:pageStartIndex));pageSize=(pageSize==undefined?10:(pageSize==null?10:pageSize));var ret=Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize,CurrentParameters:{1},currentIndex:pageStartIndex*pageSize,currentPageSize:pageSize,CurrentPage:Math.floor(pageStartIndex/pageSize),parse:function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);}}response=response.response;this.TotalPages=response.Pager.TotalPages;return response.response;}},MoveToPage:function(pageNumber){{if(pageNumber>=0&&pageNumber<this.TotalPages){{this.currentIndex=pageNumber*this.currentPageSize;{2}this.fetch();this.CurrentPage=pageNumber;}}}},ChangePageSize:function(pageSize){{this.currentPageSize=pageSize;this.MoveToPage(Math.floor(this.currentIndex/pageSize));}},MoveToNextPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1);}}}},MoveToPreviousPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1);}}}},"
                                    :@"pageStartIndex = (pageStartIndex == undefined ? 0 : (pageStartIndex == null ? 0 : pageStartIndex));
pageSize = (pageSize == undefined ? 10 : (pageSize == null ? 10 : pageSize));
var ret = Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize,
    CurrentParameters:{1},
    currentIndex : pageStartIndex*pageSize,
    currentPageSize : pageSize,
    CurrentPage : Math.floor(pageStartIndex/pageSize),
    parse : function(response){{
        if(response.Backbone!=undefined){{
            _.extend(Backbone,response.Backbone);
        }}
        response = response.response;
        this.TotalPages = response.Pager.TotalPages;
        return response.response;
    }},
    MoveToPage : function(pageNumber){{
        if (pageNumber>=0 && pageNumber<this.TotalPages){{
            this.currentIndex = pageNumber*this.currentPageSize;
            {2}
            this.fetch();
            this.CurrentPage=pageNumber;
        }}
    }},
    ChangePageSize : function(pageSize){{
        this.currentPageSize = pageSize;
        this.MoveToPage(Math.floor(this.currentIndex/pageSize));
    }},
    MoveToNextPage : function(){{
        if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{
            this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1);
        }}
    }},
    MoveToPreviousPage : function(){{
        if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{
            this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1);
        }}
    }},"),new object[]{
           (mlm.Path.Contains("?") ? "&" : "?"),
           sbCurParameters.ToString(),
           (mlm.Path.Contains("?") ? 
                (minimize ? "" : "\t\t\t")+"this.url = this.url.substring(0,this.url.indexOf('&PageStartIndex='))+'&PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;" : 
                (minimize ? "" : "\t\t\t")+"this.url = this.url.substring(0,this.url.indexOf('?'))+'?PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;")
       }));
                                if (mi.GetParameters().Length > 0)
                                {
                                    sb.Append((minimize ? "" : "\t")+"ChangeParameters: function(");
                                    for (int x = 0; x < mi.GetParameters().Length - 3; x++)
                                    {
                                        sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name);
                                    }
                                    sb.AppendLine(string.Format((minimize ? 
                                        "){{{0}url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;this.CurrentParameters={2};this.currentIndex=0;this.url=url;this.fetch();}},"
                                        :@"){{{0}
        url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;
        this.CurrentParameters = {2};
        this.currentIndex=0;
        this.url=url;
        this.fetch();
}},"),new object[]{urlCode,(mlm.Path.Contains("?") ? "&" : "?"),sbCurParameters.ToString()}));
                                }
                                sb.AppendLine(string.Format((minimize ? 
                                    "model:{0}.Model}});"
                                    :@" model:{0}.Model
}});"),ModelNamespace.GetFullNameForModel(modelType, host)));
                            }
                            else
                            {
                                sb.AppendLine(string.Format((minimize ? 
                                    "var ret=Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);return response.response;}}else{{return response;}}}},"
                                    :@" var ret = Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{
    if(response.Backbone!=undefined){{
        _.extend(Backbone,response.Backbone);
        return response.response;
    }}else{{
        return response;
    }}
}},"),sbCurParameters.ToString()));
                                if (mi.GetParameters().Length > 0)
                                {
                                    sb.Append((minimize ? "" : "\t")+"ChangeParameters: function(");
                                    for (int x = 0; x < mi.GetParameters().Length; x++)
                                    {
                                        sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name);
                                    }
                                    sb.AppendLine(string.Format((minimize ? 
                                        "){{{0}this.CurrentParameters={1};this.currentIndex=0;this.url=url;this.fetch();}}," 
                                        :@"){{{0}
        this.CurrentParameters = {1};
        this.currentIndex=0;
        this.url=url;
        this.fetch();
}},"),urlCode,sbCurParameters.ToString()));
                                }
                                sb.AppendLine("model:" + ModelNamespace.GetFullNameForModel(modelType, host) + ".Model});");
                            }
                            sb.AppendLine((minimize ? 
                                "ret=new ret();return ret;}});"
                                :@"ret = new ret();
    return ret;
}});"));
                            break;
                        }
                    }
                }
            }
            return sb.ToString();
        }
Ejemplo n.º 26
0
        private string _RecurAddRenderModelPropertyCode(string prop, Type PropType, string host, string modelstring, out string arstring, bool addEls, bool minimize)
        {
            string className = ModelNamespace.GetFullNameForModel(PropType, host).Replace(".", " ") + (addEls ? " els " : "");

            foreach (ModelViewClass mvc in PropType.GetCustomAttributes(typeof(ModelViewClass), false))
            {
                className += mvc.ClassName + " ";
            }
            string code             = "";
            int    arIndex          = 0;
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);

            foreach (PropertyInfo pi in PropType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (pi.GetCustomAttributes(typeof(ModelIgnoreProperty), false).Length == 0)
                {
                    if (pi.GetCustomAttributes(typeof(ReadOnlyModelProperty), false).Length == 0 &&
                        pi.GetCustomAttributes(typeof(ViewIgnoreField), false).Length == 0)
                    {
                        Type ptype = pi.PropertyType;
                        bool array = false;
                        if (ptype.FullName.StartsWith("System.Nullable"))
                        {
                            if (ptype.IsGenericType)
                            {
                                ptype = ptype.GetGenericArguments()[0];
                            }
                            else
                            {
                                ptype = ptype.GetElementType();
                            }
                        }
                        if (ptype.IsArray)
                        {
                            array = true;
                            ptype = ptype.GetElementType();
                        }
                        else if (ptype.IsGenericType)
                        {
                            if (ptype.GetGenericTypeDefinition() == typeof(List <>))
                            {
                                array = true;
                                ptype = ptype.GetGenericArguments()[0];
                            }
                        }
                        if (new List <Type>(ptype.GetInterfaces()).Contains(typeof(IModel)))
                        {
                            if (array)
                            {
                                string tsets = "";
                                string tcode = _RecurAddRenderModelPropertyCode(pi.Name, ptype, host, string.Format(modelstring, pi.Name) + ".at(x).get('{0}')", out tsets, true, minimize);
                                if (tsets != "")
                                {
                                    sb.Append(tsets);
                                }
                                sb.AppendLine(string.Format((minimize ?
                                                             "var ars{0}{1}='';if({2}!=null{{for(var x=0;x<{2}).length;x++){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{5}+'</span>'}}}}"
                                    :@"     var ars{0}{1} = '';
        if({2}!=null{{
            for(var x=0;x<{2}.length;x++){{
                ars{0}{1} += '<span class=""{3} {4} els"">'+{5}+'</span>'
            }}
        }}"
                                                             ), new object[] {
                                    prop,
                                    arIndex,
                                    string.Format(modelstring, pi.Name),
                                    className,
                                    pi.Name,
                                    tcode
                                }));
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'";
                                arIndex++;
                            }
                            else
                            {
                                string tsets = "";
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "(" + string.Format(modelstring, prop) + "==null ? '' : '<span class=\"" + className + " " + pi.Name + "\">'+" + _RecurAddRenderModelPropertyCode(pi.Name, ptype, host, string.Format(modelstring, pi.Name) + ".get('{0}')", out tsets, false, minimize) + "+'</span>')";
                                if (tsets != "")
                                {
                                    sb.Append(tsets);
                                }
                            }
                        }
                        else
                        {
                            if (array)
                            {
                                sb.AppendLine(string.Format((minimize ?
                                                             "var ars{0}{1}='';if ({2}!=null){{for(x in {2}){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{2}[x]+'</span>';}}}}"
                                    : @"     var ars{0}{1} = '';
        if ({2}!=null){{
            for(x in {2}){{
                ars{0}{1} += '<span class=""{3} {4} els"">'+{2}[x]+'</span>';
            }}
        }}"), new object[] {
                                    prop,
                                    arIndex,
                                    string.Format(modelstring, pi.Name),
                                    className,
                                    pi.Name
                                }));
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'";
                                arIndex++;
                            }
                            else
                            {
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+(" + string.Format(modelstring, pi.Name) + "==null ? '' : " + string.Format(modelstring, pi.Name) + ")+'</span>'";
                            }
                        }
                    }
                }
            }
            arstring = sb.ToString();
            return(code);
        }
        private void _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("},");
                }
            }
        }
Ejemplo n.º 28
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;
    }
});");
                }
            }
        }
Ejemplo n.º 29
0
		private string _RecurAddRenderModelPropertyCode(string prop,Type PropType,string host,string modelstring,out string arstring,bool addEls,bool minimize)
		{
            string className = ModelNamespace.GetFullNameForModel(PropType, host).Replace(".", " ") + (addEls ? " els " : "");
            foreach (ModelViewClass mvc in PropType.GetCustomAttributes(typeof(ModelViewClass), false))
                className += mvc.ClassName + " ";
            string code = "";
            int arIndex = 0;
            WrappedStringBuilder sb = new WrappedStringBuilder(minimize);
			foreach (PropertyInfo pi in PropType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
		    {
			    if (pi.GetCustomAttributes(typeof(ModelIgnoreProperty), false).Length == 0)
			    {
				    if (pi.GetCustomAttributes(typeof(ReadOnlyModelProperty), false).Length == 0
                        && pi.GetCustomAttributes(typeof(ViewIgnoreField), false).Length == 0)
                    {
                        Type ptype = pi.PropertyType;
                        bool array = false;
                        if (ptype.FullName.StartsWith("System.Nullable"))
                        {
                            if (ptype.IsGenericType)
                                ptype = ptype.GetGenericArguments()[0];
                            else
                                ptype = ptype.GetElementType();
                        }
                        if (ptype.IsArray)
                        {
                            array = true;
                            ptype = ptype.GetElementType();
                        }
                        else if (ptype.IsGenericType)
                        {
                            if (ptype.GetGenericTypeDefinition() == typeof(List<>))
                            {
                                array = true;
                                ptype = ptype.GetGenericArguments()[0];
                            }
                        }
                        if (new List<Type>(ptype.GetInterfaces()).Contains(typeof(IModel))){
                            if (array)
                            {
                                string tsets = "";
                                string tcode = _RecurAddRenderModelPropertyCode(pi.Name, ptype,host, string.Format(modelstring, pi.Name) + ".at(x).get('{0}')", out tsets,true,minimize);
                                if (tsets != "")
                                    sb.Append(tsets);
                                sb.AppendLine(string.Format((minimize ? 
                                    "var ars{0}{1}='';if({2}!=null{{for(var x=0;x<{2}).length;x++){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{5}+'</span>'}}}}"
                                    :@"     var ars{0}{1} = '';
        if({2}!=null{{
            for(var x=0;x<{2}.length;x++){{
                ars{0}{1} += '<span class=""{3} {4} els"">'+{5}+'</span>'
            }}
        }}"
                                    ),new object[]{
                                        prop,
                                        arIndex,
                                        string.Format(modelstring, pi.Name),
                                        className,
                                        pi.Name,
                                        tcode
                                    }));
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'";
                                arIndex++;
                            }
                            else
                            {
                                string tsets = "";
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "("+string.Format(modelstring,prop)+"==null ? '' : '<span class=\"" + className + " " + pi.Name + "\">'+" + _RecurAddRenderModelPropertyCode(pi.Name, ptype,host, string.Format(modelstring, pi.Name) + ".get('{0}')",out tsets,false,minimize) + "+'</span>')";
                                if (tsets != "")
                                    sb.Append(tsets);
                            }
                        }else{
                            if (array)
                            {
                                sb.AppendLine(string.Format((minimize ?
                                    "var ars{0}{1}='';if ({2}!=null){{for(x in {2}){{ars{0}{1}+='<span class=\"{3} {4} els\">'+{2}[x]+'</span>';}}}}"
                                    : @"     var ars{0}{1} = '';
        if ({2}!=null){{
            for(x in {2}){{
                ars{0}{1} += '<span class=""{3} {4} els"">'+{2}[x]+'</span>';
            }}
        }}"), new object[]{
               prop,
               arIndex,
               string.Format(modelstring, pi.Name),
               className,
               pi.Name
           }));
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "") + "'<span class=\"" + className + " " + pi.Name + "\">'+ars" + prop + arIndex.ToString() + "+'</span>'";
                                arIndex++;
                            }else
                                code += (code.EndsWith(">'") || code.EndsWith(">')") ? "+" : "")+"'<span class=\"" + className + " " + pi.Name + "\">'+(" + string.Format(modelstring, pi.Name) + "==null ? '' : "+string.Format(modelstring,pi.Name)+")+'</span>'";
                        }
                    }
			    }
		    }
            arstring = sb.ToString();
            return code;
		}
Ejemplo n.º 30
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());
        }
Ejemplo n.º 31
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;
    }
});");
                }
            }
        }
Ejemplo n.º 32
0
 private void _AppendAcceptCode(WrappedStringBuilder sb, bool minimize)
 {
     sb.Append(Utility.ReadEmbeddedResource("Org.Reddragonit.BackBoneDotNet.resources.editFormAccept.js", minimize));
 }
Ejemplo n.º 33
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();
    }"));
                }
            }
        }
Ejemplo n.º 34
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.ModelListCallGenerators");
            }
            foreach (MethodInfo mi in modelType.GetMethods(Constants.LOAD_METHOD_FLAGS))
            {
                if (mi.GetCustomAttributes(typeof(ModelListMethod), false).Length > 0)
                {
                    foreach (ModelListMethod mlm in mi.GetCustomAttributes(typeof(ModelListMethod), false))
                    {
                        if (mlm.Host == host || mlm.Host == "*")
                        {
                            WrappedStringBuilder sbCurParameters = new WrappedStringBuilder(minimize);
                            sbCurParameters.Append((minimize ? "function(){return{":"function(){return {"));
                            sb.Append(string.Format((minimize ?
                                                     "{0}=_.extend({0},{{{1}:function("
                                : "{0} = _.extend({0}, {{{1}:function("), ModelNamespace.GetFullNameForModel(modelType, host), mi.Name));
                            for (int x = 0; x < (mlm.Paged ? mi.GetParameters().Length - 3 : mi.GetParameters().Length); x++)
                            {
                                sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name);
                                sbCurParameters.AppendLine((x == 0 ? "" : ",") + string.Format("'{0}':{0}", mi.GetParameters()[x].Name));
                            }
                            sbCurParameters.Append("};}");
                            if (mlm.Paged)
                            {
                                if (mi.GetParameters().Length != 3)
                                {
                                    sb.Append(",");
                                }
                                sb.Append("pageStartIndex,pageSize");
                            }
                            sb.AppendLine("){");
                            string urlCode = URLUtility.CreateJavacriptUrlCode(mlm, mi, modelType);
                            sb.Append(urlCode);
                            if (mlm.Paged)
                            {
                                sb.AppendLine(string.Format((minimize ?
                                                             "pageStartIndex=(pageStartIndex==undefined?0:(pageStartIndex==null?0:pageStartIndex));pageSize=(pageSize==undefined?10:(pageSize==null?10:pageSize));var ret=Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize,CurrentParameters:{1},currentIndex:pageStartIndex*pageSize,currentPageSize:pageSize,CurrentPage:Math.floor(pageStartIndex/pageSize),parse:function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);}}response=response.response;this.TotalPages=response.Pager.TotalPages;return response.response;}},MoveToPage:function(pageNumber){{if(pageNumber>=0&&pageNumber<this.TotalPages){{this.currentIndex=pageNumber*this.currentPageSize;{2}this.fetch();this.CurrentPage=pageNumber;}}}},ChangePageSize:function(pageSize){{this.currentPageSize=pageSize;this.MoveToPage(Math.floor(this.currentIndex/pageSize));}},MoveToNextPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1);}}}},MoveToPreviousPage:function(){{if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1);}}}},"
                                    :@"pageStartIndex = (pageStartIndex == undefined ? 0 : (pageStartIndex == null ? 0 : pageStartIndex));
pageSize = (pageSize == undefined ? 10 : (pageSize == null ? 10 : pageSize));
var ret = Backbone.Collection.extend({{url:url+'{0}PageStartIndex='+pageStartIndex+'&PageSize='+pageSize,
    CurrentParameters:{1},
    currentIndex : pageStartIndex*pageSize,
    currentPageSize : pageSize,
    CurrentPage : Math.floor(pageStartIndex/pageSize),
    parse : function(response){{
        if(response.Backbone!=undefined){{
            _.extend(Backbone,response.Backbone);
        }}
        response = response.response;
        this.TotalPages = response.Pager.TotalPages;
        return response.response;
    }},
    MoveToPage : function(pageNumber){{
        if (pageNumber>=0 && pageNumber<this.TotalPages){{
            this.currentIndex = pageNumber*this.currentPageSize;
            {2}
            this.fetch();
            this.CurrentPage=pageNumber;
        }}
    }},
    ChangePageSize : function(pageSize){{
        this.currentPageSize = pageSize;
        this.MoveToPage(Math.floor(this.currentIndex/pageSize));
    }},
    MoveToNextPage : function(){{
        if(Math.floor(this.currentIndex/this.currentPageSize)+1<this.TotalPages){{
            this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)+1);
        }}
    }},
    MoveToPreviousPage : function(){{
        if(Math.floor(this.currentIndex/this.currentPageSize)-1>=0){{
            this.MoveToPage(Math.floor(this.currentIndex/this.currentPageSize)-1);
        }}
    }},"), new object[] {
                                    (mlm.Path.Contains("?") ? "&" : "?"),
                                    sbCurParameters.ToString(),
                                    (mlm.Path.Contains("?") ?
                                     (minimize ? "" : "\t\t\t") + "this.url = this.url.substring(0,this.url.indexOf('&PageStartIndex='))+'&PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;" :
                                     (minimize ? "" : "\t\t\t") + "this.url = this.url.substring(0,this.url.indexOf('?'))+'?PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;")
                                }));
                                if (mi.GetParameters().Length > 0)
                                {
                                    sb.Append((minimize ? "" : "\t") + "ChangeParameters: function(");
                                    for (int x = 0; x < mi.GetParameters().Length - 3; x++)
                                    {
                                        sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name);
                                    }
                                    sb.AppendLine(string.Format((minimize ?
                                                                 "){{{0}url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;this.CurrentParameters={2};this.currentIndex=0;this.url=url;this.fetch();}},"
                                        :@"){{{0}
        url+='{1}PageStartIndex='+this.currentIndex+'&PageSize='+this.currentPageSize;
        this.CurrentParameters = {2};
        this.currentIndex=0;
        this.url=url;
        this.fetch();
}},"), new object[] { urlCode, (mlm.Path.Contains("?") ? "&" : "?"), sbCurParameters.ToString() }));
                                }
                                sb.AppendLine(string.Format((minimize ?
                                                             "model:{0}.Model}});"
                                    :@" model:{0}.Model
}});"), ModelNamespace.GetFullNameForModel(modelType, host)));
                            }
                            else
                            {
                                sb.AppendLine(string.Format((minimize ?
                                                             "var ret=Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{if(response.Backbone!=undefined){{_.extend(Backbone,response.Backbone);return response.response;}}else{{return response;}}}},"
                                    :@" var ret = Backbone.Collection.extend({{url:url,CurrentParameters:{0},parse : function(response){{
    if(response.Backbone!=undefined){{
        _.extend(Backbone,response.Backbone);
        return response.response;
    }}else{{
        return response;
    }}
}},"), sbCurParameters.ToString()));
                                if (mi.GetParameters().Length > 0)
                                {
                                    sb.Append((minimize ? "" : "\t") + "ChangeParameters: function(");
                                    for (int x = 0; x < mi.GetParameters().Length; x++)
                                    {
                                        sb.Append((x == 0 ? "" : ",") + mi.GetParameters()[x].Name);
                                    }
                                    sb.AppendLine(string.Format((minimize ?
                                                                 "){{{0}this.CurrentParameters={1};this.currentIndex=0;this.url=url;this.fetch();}},"
                                        :@"){{{0}
        this.CurrentParameters = {1};
        this.currentIndex=0;
        this.url=url;
        this.fetch();
}},"), urlCode, sbCurParameters.ToString()));
                                }
                                sb.AppendLine("model:" + ModelNamespace.GetFullNameForModel(modelType, host) + ".Model});");
                            }
                            sb.AppendLine((minimize ?
                                           "ret=new ret();return ret;}});"
                                :@"ret = new ret();
    return ret;
}});"));
                            break;
                        }
                    }
                }
            }
            return(sb.ToString());
        }
        internal static void AppendMethodCall(string urlRoot, string host, MethodInfo mi, bool allowNull, ref WrappedStringBuilder sb, bool minimize)
        {
            sb.Append(string.Format((minimize ? "" : "\t") + "{0}:function(", mi.Name));
            ParameterInfo[] pars = mi.GetParameters();
            for (int x = 0; x < pars.Length; x++)
            {
                sb.Append(pars[x].Name + (x + 1 == pars.Length ? "" : ","));
            }
            sb.Append((minimize ? "){var function_data={};":"){var function_data = {};"));
            foreach (ParameterInfo par in pars)
            {
                Type propType = par.ParameterType;
                bool array    = false;
                if (propType.FullName.StartsWith("System.Nullable"))
                {
                    if (propType.IsGenericType)
                    {
                        propType = propType.GetGenericArguments()[0];
                    }
                    else
                    {
                        propType = propType.GetElementType();
                    }
                }
                if (propType.IsArray)
                {
                    array    = true;
                    propType = propType.GetElementType();
                }
                else if (propType.IsGenericType)
                {
                    if (propType.GetGenericTypeDefinition() == typeof(List <>))
                    {
                        array    = true;
                        propType = propType.GetGenericArguments()[0];
                    }
                }
                if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
                {
                    if (array)
                    {
                        sb.AppendLine(string.Format((minimize ?
                                                     "function_data.{0}=[];for(var x=0;x<{0}.length;x++){{function_data.{0}.push(({0}.at!=undefined?{0}.at(x).id:{0}[x].id));}}"
                            :@"function_data.{0}=[];
for(var x=0;x<{0}.length;x++){{
    function_data.{0}.push(({0}.at!=undefined ? {0}.at(x).id : {0}[x].id));
}}"), par.Name));
                    }
                    else
                    {
                        sb.AppendLine(string.Format((minimize ?"function_data.{0}={0}.id;" :"function_data.{0} = {0}.id;"), par.Name));
                    }
                }
                else
                {
                    sb.AppendLine(string.Format((minimize ? "function_data.{0}={0};": "function_data.{0} = {0};"), par.Name));
                }
            }
            sb.AppendLine(string.Format((minimize ?
                                         "var response = $.ajax({{type:'{4}',url:'{0}/{3}{1}',processData:false,data:escape(JSON.stringify(function_data)),content_type:'application/json; charset=utf-8',dataType:'json',async:false,cache:false}});if(response.status==200){{{2}}}else{{throw new Exception(response.responseText);}}"
:@"var response = $.ajax({{
            type:'{4}',
            url:'{0}/{3}{1}',
            processData:false,
            data:escape(JSON.stringify(function_data)),
            content_type:'application/json; charset=utf-8',
            dataType:'json',
            async:false,
            cache:false
        }});
if (response.status==200){{
        {2}
}}else{{
    throw new Exception(response.responseText);
}}
"), new object[] {
                urlRoot,
                mi.Name,
                (mi.ReturnType == typeof(void) ? "" : (minimize ? "var ret=response.responseText; if(ret!=undefined){var response=JSON.parse(ret);if(response.Backbone!=undefined){_.extend(Backbone,response.Backbone);response=response.response;}" : @"var ret=response.responseText;
    if (ret!=undefined){
    var response = JSON.parse(ret);
    if(response.Backbone!=undefined){
        _.extend(Backbone,response.Backbone);
        response=response.response;
    }")),
                (mi.IsStatic ? "" : "'+this.id+'/"),
                (mi.IsStatic ? "SMETHOD" : "METHOD")
            }));
            if (mi.ReturnType != typeof(void))
            {
                Type propType = mi.ReturnType;
                bool array    = false;
                if (propType.FullName.StartsWith("System.Nullable"))
                {
                    if (propType.IsGenericType)
                    {
                        propType = propType.GetGenericArguments()[0];
                    }
                    else
                    {
                        propType = propType.GetElementType();
                    }
                }
                if (propType.IsArray)
                {
                    array    = true;
                    propType = propType.GetElementType();
                }
                else if (propType.IsGenericType)
                {
                    if (propType.GetGenericTypeDefinition() == typeof(List <>))
                    {
                        array    = true;
                        propType = propType.GetGenericArguments()[0];
                    }
                }
                sb.AppendLine((minimize ? "if(response==null){":"if (response==null){"));
                if (!allowNull)
                {
                    sb.AppendLine("throw \"A null response was returned by the server which is invalid.\";");
                }
                else
                {
                    sb.AppendLine("return response;");
                }
                sb.AppendLine("}else{");
                if (new List <Type>(propType.GetInterfaces()).Contains(typeof(IModel)))
                {
                    if (array)
                    {
                        sb.AppendLine(string.Format((minimize ?
                                                     "if({0}.Collection!=undefined){{ret = new {0}.Collection();for(var x=0;x<response.length;x++){{ret.add(new {0}.Model({{'id':response[x].id}}));ret.at(x).attributes=ret.at(x).parse(response[x]);}}}}else{{ret=[];for(var x=0;x<response.length;x++){{ret.push(new {0}.Model({{'id':response[x].id}}));ret[x].attributes=ret[x].parse(response[x]);}}}}response=ret;"
                            : @"          if({0}.Collection!=undefined){{
                ret = new {0}.Collection();
                for (var x=0;x<response.length;x++){{
                    ret.add(new {0}.Model({{'id':response[x].id}}));
                    ret.at(x).attributes=ret.at(x).parse(response[x]);
                }}
            }}else{{
                ret=[];
                for (var x=0;x<response.length;x++){{
                    ret.push(new {0}.Model({{'id':response[x].id}}));
                    ret[x].attributes=ret[x].parse(response[x]);
                }}
            }}
            response = ret;"),
                                                    ModelNamespace.GetFullNameForModel(propType, host)));
                    }
                    else
                    {
                        sb.AppendLine(string.Format((minimize ?
                                                     "ret=new {0}.Model({{id:response.id}});ret.attributes=ret.parse(response);response=ret;"
                            :@"ret = new {0}.Model({{id:response.id}});
ret.attributes = ret.parse(response);
response=ret;"), ModelNamespace.GetFullNameForModel(propType, host)));
                    }
                }
                sb.AppendLine((minimize ?
                               "}return response;}else{return null;}"
                    :@"}
return response;}else{return null;}"));
            }
            sb.AppendLine("},");
        }