Indented() public method

public Indented ( string s ) : void
s string
return void
Beispiel #1
0
        private void GenerateEnum(Type enumType)
        {
            cw.IndentedLine("[NamedValues, PreserveMemberCase]");
            cw.Indented("public enum ");
            sb.AppendLine(enumType.Name);
            cw.InBrace(delegate
            {
                var names  = Enum.GetNames(enumType);
                var values = Enum.GetValues(enumType);

                int i = 0;
                foreach (var name in names)
                {
                    if (i > 0)
                    {
                        sb.AppendLine(",");
                    }

                    cw.Indented(name);
                    sb.Append(" = ");
                    sb.Append(Convert.ToInt32(((IList)values)[i]));
                    i++;
                }

                sb.AppendLine();
            });
        }
Beispiel #2
0
        public string GenerateCode(string anamespace, params Type[] fromTypes)
        {
            this.sb            = new StringBuilder(4096);
            this.cw            = new CodeWriter(sb, 4);
            this.generateQueue = new Queue <Type>();
            this.visited       = new HashSet <Type>();

            sb.Append("namespace ");
            sb.AppendLine(anamespace);
            cw.InBrace(delegate
            {
                foreach (var ns in
                         new string[] {
                    "Newtonsoft.Json",
                    "Newtonsoft.Json.Converters",
                    "System",
                    "System.Collections.Generic"
                })
                {
                    cw.Indented("using ");
                    sb.Append(ns);
                    sb.AppendLine(";");
                }

                sb.AppendLine();

                foreach (var fromType in fromTypes)
                {
                    EnqueueType(fromType);
                }

                int i = 0;
                while (generateQueue.Count > 0)
                {
                    if (i++ > 0)
                    {
                        sb.AppendLine();
                    }

                    GenerateCodeFor(generateQueue.Dequeue());
                }
            });

            return(sb.ToString());
        }
Beispiel #3
0
        public string GenerateCode(string anamespace, params Type[] fromTypes)
        {
            this.sb = new StringBuilder(4096);
            this.cw = new CodeWriter(sb, 4);
            this.generateQueue = new Queue<Type>();
            this.visited = new HashSet<Type>();

            sb.Append("namespace ");
            sb.AppendLine(anamespace);
            cw.InBrace(delegate
            {
                foreach (var ns in
                    new string[] {
                        "Newtonsoft.Json",
                        "Newtonsoft.Json.Converters",
                        "System",
                        "System.Collections.Generic"
                    })
                {
                    cw.Indented("using ");
                    sb.Append(ns);
                    sb.AppendLine(";");
                }

                sb.AppendLine();

                foreach (var fromType in fromTypes)
                    EnqueueType(fromType);

                int i = 0;
                while (generateQueue.Count > 0)
                {
                    if (i++ > 0)
                        sb.AppendLine();

                    GenerateCodeFor(generateQueue.Dequeue());
                }
            });

            return sb.ToString();
        }
Beispiel #4
0
        private void GenerateEnum(Type enumType)
        {
            cw.IndentedLine("[JsonConverter(typeof(StringEnumConverter))]");
            cw.Indented("public enum ");
            sb.AppendLine(enumType.Name);
            cw.InBrace(delegate
            {
                var names  = Enum.GetNames(enumType);
                var values = Enum.GetValues(enumType);

                int i = 0;
                foreach (var name in names)
                {
                    cw.Indented(name);
                    sb.Append(" = ");
                    sb.Append(Convert.ToInt32(((IList)values)[i]));
                    sb.AppendLine(",");
                    i++;
                }
            });
        }
        public SortedDictionary <string, string> GenerateCode()
        {
            var codeByType = new Dictionary <Type, string>();
            var sb         = new StringBuilder();
            var cw         = new Serenity.Reflection.CodeWriter(sb, 4);

            foreach (var assembly in Assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    var formScriptAttribute = (FormScriptAttribute)type.GetCustomAttribute(typeof(FormScriptAttribute));
                    if (formScriptAttribute == null)
                    {
                        continue;
                    }

                    var ns = DoGetNamespace(type);

                    sb.Clear();
                    cw.Indented("public partial class ");
                    sb.Append(DoGetTypeName(type));
                    sb.AppendLine(" : PrefixedContext");
                    cw.InBrace(delegate
                    {
                        cw.Indented("[InlineConstant] public const string FormKey = \"");
                        sb.Append(formScriptAttribute.Key);
                        sb.AppendLine("\";");
                        sb.AppendLine();

                        cw.Indented("public ");
                        sb.Append(DoGetTypeName(type));
                        sb.AppendLine("(string idPrefix) : base(idPrefix) {}");
                        sb.AppendLine();

                        foreach (var item in Serenity.PropertyGrid.PropertyItemHelper.GetPropertyItemsFor(type))
                        {
                            var editorType        = item.EditorType ?? "String";
                            string widgetTypeName = null;
                            foreach (var rootNamespace in RootNamespaces)
                            {
                                string wn = rootNamespace + "." + editorType;
                                if (WidgetTypes.Contains(wn))
                                {
                                    widgetTypeName = wn;
                                    break;
                                }

                                wn += "Editor";
                                if (WidgetTypes.Contains(wn))
                                {
                                    widgetTypeName = wn;
                                    break;
                                }
                            }

                            if (widgetTypeName == null)
                            {
                                var wn = editorType;
                                if (!WidgetTypes.Contains(editorType))
                                {
                                    wn = editorType + "Editor";
                                }

                                if (WidgetTypes.Contains(wn))
                                {
                                    widgetTypeName = wn;
                                }
                            }

                            if (widgetTypeName == null)
                            {
                                continue;
                            }

                            var fullName = widgetTypeName;

                            if (widgetTypeName.StartsWith(ns + "."))
                            {
                                widgetTypeName = widgetTypeName.Substring(ns.Length + 1);
                            }
                            else
                            {
                                foreach (var rn in RootNamespaces)
                                {
                                    if (widgetTypeName.StartsWith(rn + "."))
                                    {
                                        widgetTypeName = widgetTypeName.Substring(rn.Length + 1);
                                    }
                                }
                            }

                            cw.Indented("public ");
                            sb.Append(widgetTypeName);
                            sb.Append(" ");
                            sb.Append(item.Name);
                            sb.Append(" { ");
                            sb.Append("[InlineCode(\"{this}.w('");
                            sb.Append(item.Name);
                            sb.Append("', ");
                            sb.Append(fullName);
                            sb.AppendLine(")\")] get; private set; }");
                        }
                    });

                    codeByType[type] = sb.ToString();
                    sb.Clear();
                }
            }

            var ordered     = codeByType.Keys.OrderBy(x => DoGetNamespace(x)).ThenBy(x => x.Name);
            var byNameSpace = ordered.ToLookup(x => DoGetNamespace(x));

            var result = new SortedDictionary <string, string>();

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                foreach (var type in ns)
                {
                    sb.Clear();
                    sb.AppendLine();
                    cw.Indented("namespace ");
                    sb.AppendLine(ns.Key);
                    cw.InBrace(delegate
                    {
                        foreach (var usingNamespace in UsingNamespaces.ToArray().OrderBy(x => x))
                        {
                            cw.Indented("using ");
                            sb.Append(usingNamespace);
                            sb.AppendLine(";");
                        }

                        sb.AppendLine();

                        int i = 0;

                        {
                            if (i++ > 0)
                            {
                                sb.AppendLine();
                            }

                            cw.IndentedMultiLine(codeByType[type].TrimEnd());
                        }
                    });

                    var filename = ns.Key + "." + DoGetTypeName(type) + ".cs";

                    foreach (var rn in RootNamespaces)
                    {
                        if (filename.StartsWith(rn + "."))
                        {
                            filename = filename.Substring(rn.Length + 1);
                        }
                    }

                    result.Add(filename, sb.ToString());
                }
            }

            return(result);
        }
        public SortedDictionary<string, string> GenerateCode()
        {
            this.sb = new StringBuilder(4096);
            this.cw = new CodeWriter(sb, 4);
            this.generateQueue = new Queue<Type>();
            this.visited = new HashSet<Type>();
            this.lookupScripts = new List<Type>();

            foreach (var assembly in this.Assemblies)
            foreach (var fromType in assembly.GetTypes())
            {
                if (fromType.IsAbstract)
                    continue;

                if (fromType.IsSubclassOf(typeof(ServiceRequest)) ||
                    fromType.IsSubclassOf(typeof(ServiceResponse)) ||
                    fromType.IsSubclassOf(typeof(Row)) ||
                    fromType.GetCustomAttribute<ScriptIncludeAttribute>() != null)
                {
                    EnqueueType(fromType);
                    continue;
                }

                if (fromType.GetCustomAttribute<FormScriptAttribute>() != null ||
                    fromType.GetCustomAttribute<ColumnsScriptAttribute>() != null)
                {
                    EnqueueTypeMembers(fromType);
                    continue;
                }

                if (fromType.GetCustomAttribute<LookupScriptAttribute>() != null)
                {
                    lookupScripts.Add(fromType);
                    continue;
                }
            }

            Dictionary<Type, string> generatedCode = new Dictionary<Type, string>();
            while (generateQueue.Count > 0)
            {
                var type = generateQueue.Dequeue();

                if (!this.Assemblies.Contains(type.Assembly))
                    continue;

                GenerateCodeFor(type);
                generatedCode[type] = sb.ToString();
                sb.Clear();
            }

            sb.Clear();

            sb.AppendLine();

            var ordered = generatedCode.Keys.OrderBy(x => GetNamespace(x)).ThenBy(x => x.Name);
            var byNameSpace = ordered.ToLookup(x => GetNamespace(x));
            var byOwnerType = ordered.ToLookup(x => (x.IsNested ? x.DeclaringType : null));
            var outputted = new HashSet<Type>();

            var result = new SortedDictionary<string, string>();

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                Action<Type> outputType = delegate(Type type)
                {
                    var filename = ns.Key + "." + type.Name + ".cs";

                    foreach (var rn in RootNamespaces)
                    {
                        if (filename.StartsWith(rn + "."))
                            filename = filename.Substring(rn.Length + 1);
                    }

                    result.Add(filename, sb.ToString());
                };

                foreach (var owner in byOwnerType)
                {
                    bool skip = false;

                    sb.Clear();
                    sb.AppendLine();
                    cw.Indented("namespace ");
                    sb.AppendLine(ns.Key);

                    cw.InBrace(delegate
                    {
                        foreach (var usingNamespace in UsingNamespaces.OrderBy(x => x))
                        {
                            cw.Indented("using ");
                            sb.Append(usingNamespace);
                            sb.AppendLine(";");
                        }

                        sb.AppendLine();

                        if (owner.Key == null)
                        {
                            skip = true;
                            return;
                        }

                        if (GetNamespace(owner.Key) != ns.Key)
                        {
                            skip = true;
                            return;
                        }

                        if (outputted.Contains(owner.Key))
                        {
                            skip = true;
                            return;
                        }

                        outputted.Add(owner.Key);

                        if (!generatedCode.ContainsKey(owner.Key))
                            return;

                        string code = generatedCode[owner.Key].TrimEnd();
                        code = code.Substring(0, code.Length - 1).TrimEnd();
                        cw.IndentedMultiLine(code);

                        cw.Block(delegate
                        {
                            sb.AppendLine();

                            foreach (var subType in owner)
                            {
                                cw.IndentedMultiLine(generatedCode[subType]);
                                outputted.Add(subType);
                            }
                        });

                        cw.IndentedLine("}");
                        sb.AppendLine();
                    });

                    if (skip)
                        continue;

                    outputType(owner.Key);
                }

                foreach (var type in ns)
                {
                    if (outputted.Contains(type))
                        continue;

                    sb.Clear();
                    sb.AppendLine();
                    cw.Indented("namespace ");
                    sb.AppendLine(ns.Key);

                    cw.InBrace(() =>
                    {
                        foreach (var usingNamespace in UsingNamespaces.OrderBy(x => x))
                        {
                            cw.Indented("using ");
                            sb.Append(usingNamespace);
                            sb.AppendLine(";");
                        }

                        sb.AppendLine();

                        cw.IndentedMultiLine(generatedCode[type]);
                    });

                    outputType(type);
                    outputted.Add(type);
                }
            }

            return result;
        }
Beispiel #7
0
        public string GenerateCode()
        {
            this.sb            = new StringBuilder(4096);
            this.cw            = new CodeWriter(sb, 4);
            this.generateQueue = new Queue <Type>();
            this.visited       = new HashSet <Type>();

            foreach (var fromType in this.Assembly.GetTypes())
            {
                if (fromType.IsAbstract)
                {
                    continue;
                }

                if (fromType.IsSubclassOf(typeof(ServiceRequest)) ||
                    fromType.IsSubclassOf(typeof(ServiceResponse)) ||
                    fromType.IsSubclassOf(typeof(Row)) ||
                    fromType.GetCustomAttribute <ScriptIncludeAttribute>() != null)
                {
                    EnqueueType(fromType);
                }
            }

            Dictionary <Type, string> generatedCode = new Dictionary <Type, string>();

            while (generateQueue.Count > 0)
            {
                var type = generateQueue.Dequeue();

                if (type.Assembly != this.Assembly)
                {
                    continue;
                }

                GenerateCodeFor(type);
                generatedCode[type] = sb.ToString();
                sb.Clear();
            }

            sb.Clear();

            foreach (var ns in UsingNamespaces.OrderBy(x => x))
            {
                cw.Indented("using ");
                sb.Append(ns);
                sb.AppendLine(";");
            }

            sb.AppendLine();

            var ordered     = generatedCode.Keys.OrderBy(x => GetNamespace(x)).ThenBy(x => x.Name);
            var byNameSpace = ordered.ToLookup(x => GetNamespace(x));
            var byOwnerType = ordered.ToLookup(x => (x.IsNested ? x.DeclaringType : null));
            var outputted   = new HashSet <Type>();

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                sb.AppendLine();
                cw.Indented("namespace ");
                sb.AppendLine(ns.Key);
                cw.InBrace(delegate
                {
                    foreach (var owner in byOwnerType)
                    {
                        if (owner.Key == null)
                        {
                            continue;
                        }

                        if (GetNamespace(owner.Key) != ns.Key)
                        {
                            continue;
                        }

                        if (outputted.Contains(owner.Key))
                        {
                            continue;
                        }

                        if (!generatedCode.ContainsKey(owner.Key))
                        {
                            continue;
                        }

                        outputted.Add(owner.Key);

                        string code = generatedCode[owner.Key].TrimEnd();
                        code        = code.Substring(0, code.Length - 1).TrimEnd();
                        cw.IndentedMultiLine(code);

                        cw.Block(delegate
                        {
                            sb.AppendLine();

                            foreach (var subType in owner)
                            {
                                cw.IndentedMultiLine(generatedCode[subType]);
                                outputted.Add(subType);
                            }
                        });

                        cw.IndentedLine("}");
                        sb.AppendLine();
                    }

                    foreach (var type in ns)
                    {
                        if (outputted.Contains(type))
                        {
                            continue;
                        }

                        cw.IndentedMultiLine(generatedCode[type]);
                        outputted.Add(type);
                    }
                });
            }

            return(sb.ToString());
        }
Beispiel #8
0
        public override void ExecuteResult(ControllerContext context)
        {
            var types = new HashSet<Type>();

            var sb = new StringBuilder();
            var cw = new CodeWriter(sb, 4);
            cw.Indented("namespace ");
            sb.AppendLine(this.Namespace);
            cw.InBrace(delegate
            {
                foreach (var ns in
                    new string[] {
                        "System",
                        "System.Collections.Generic"
                    })
                {
                    cw.Indented("using ");
                    sb.Append(ns);
                    sb.AppendLine(";");
                }

                sb.AppendLine();

                cw.Indented("public interface I");
                var className = context.Controller.GetType().Name;
                if (className.EndsWith("Controller"))
                    className = className.Substring(0, className.Length - 10);
                sb.Append(className);
                sb.AppendLine("Service");

                cw.InBrace(delegate
                {
                    foreach (var method in context.Controller.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
                    {
                        if (method.GetCustomAttribute<NonActionAttribute>() != null)
                            continue;

                        if (typeof(Controller).IsSubclassOf(method.DeclaringType))
                            continue;

                        if (method.IsSpecialName && (method.Name.StartsWith("set_") || method.Name.StartsWith("get_")))
                            continue;

                        // belki burada daha sonra metod listesini de verebiliriz (ayrı bir namespace de?)
                        var parameters = method.GetParameters();
                        if (parameters.Length != 1)
                        {
                            // tek parametreli olmalı
                            continue;
                        }

                        var returnType = method.ReturnType;
                        if (returnType.IsAssignableFrom(typeof(DtoActionResult)))
                            continue;

                        var paramType = parameters[0].ParameterType;
                        if (paramType.IsPrimitive || !DtoGenerator.CanHandleType(paramType))
                            continue;

                        types.Add(parameters[0].ParameterType);

                        Type responseType = returnType;
                        if (returnType != null &&
                            returnType.IsGenericType &&
                            returnType.GetGenericTypeDefinition() == typeof(Result<>))
                        {
                            responseType = returnType.GenericTypeArguments[0];
                            types.Add(responseType);
                        }

                        cw.Indent();
                        DtoGenerator.HandleMemberType(sb, responseType, enqueueType: null);
                        sb.Append(' ');
                        sb.Append(method.Name);

                        sb.Append("(");
                        DtoGenerator.HandleMemberType(sb, paramType, enqueueType: null);
                        sb.Append(' ');
                        sb.Append(parameters[0].Name);
                        sb.AppendLine(");");
                    }
                });
            });

            if (ExtraTypes != null &&
                ExtraTypes.Length > 0)
                types.AddRange(ExtraTypes);

            Type[] fromTypes = new Type[types.Count];
            types.CopyTo(fromTypes, 0);

            sb.AppendLine();
            sb.AppendLine();
            var code = sb.ToString() + new DtoGenerator().GenerateCode(Namespace, fromTypes);

            new ContentResult
            {
                ContentEncoding = Encoding.UTF8,
                ContentType = "text/plain",
                Content = code
            }.ExecuteResult(context);
        }
Beispiel #9
0
        public string GenerateCode()
        {
            var codeByType = new Dictionary <string, string>();
            var sb         = new StringBuilder();
            var cw         = new Serenity.Reflection.CodeWriter(sb, 4);

            foreach (var key in EditorTypes.Keys)
            {
                var ns = DoGetNamespace(key);

                var editorInfo = EditorTypes[key];

                sb.Clear();
                cw.Indented("public partial class ");
                var type = DoGetTypeName(key);
                sb.Append(type);
                sb.AppendLine(" : CustomEditorAttribute");
                cw.InBrace(delegate
                {
                    cw.Indented("public const string Key = \"");
                    sb.Append(key);
                    sb.AppendLine("\";");
                    sb.AppendLine();

                    cw.Indented("public ");
                    sb.Append(type);
                    sb.AppendLine("()");
                    cw.IndentedLine("    : base(Key)");
                    cw.IndentedLine("{");
                    cw.IndentedLine("}");
                    var opt = editorInfo.Options.Keys.ToList();
                    opt.Sort();

                    foreach (var item in opt)
                    {
                        var option         = editorInfo.Options[item];
                        var typeName       = option.Type;
                        var nullablePrefix = "System.Nullable`1";
                        bool nullable      = option.Type.StartsWith(nullablePrefix);
                        if (nullable)
                        {
                            typeName = typeName.Substring(nullablePrefix.Length + 1, typeName.Length - nullablePrefix.Length - 2);
                        }

                        var systemType = Type.GetType(typeName);
                        if (systemType == null)
                        {
                            typeName = "object";
                        }
                        else if (typeName.StartsWith("System."))
                        {
                            typeName = typeName.Substring(7);
                        }

                        sb.AppendLine();
                        cw.Indented("public ");
                        sb.Append(typeName);
                        //if (nullable) //Attribute name argument nullable problem
                        //    sb.Append("?");
                        sb.Append(" ");
                        sb.AppendLine(item);
                        cw.InBrace(() =>
                        {
                            string propName = item.Substring(0, 1).ToLowerInvariant() + item.Substring(1);
                            if (item == "ID")
                            {
                                propName = "id";
                            }
                            cw.Indented("get { return GetOption<");
                            sb.Append(typeName);
                            //if (nullable) //Attribute name argument nullable problem
                            //    sb.Append("?");
                            sb.Append(">(\"");
                            sb.Append(propName);
                            sb.AppendLine("\"); }");
                            cw.Indented("set { SetOption(\"");
                            sb.Append(propName);
                            sb.AppendLine("\", value); }");
                        });
                    }
                });

                codeByType[key] = sb.ToString();
                sb.Clear();
            }

            sb.Clear();
            sb.AppendLine();

            foreach (var ns in UsingNamespaces)
            {
                cw.Indented("using ");
                sb.Append(ns);
                sb.AppendLine(";");
            }

            var ordered     = codeByType.Keys.OrderBy(x => DoGetNamespace(x)).ThenBy(x => x);
            var byNameSpace = ordered.ToLookup(x => DoGetNamespace(x));

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                sb.AppendLine();
                cw.Indented("namespace ");
                sb.AppendLine(ns.Key);
                cw.InBrace(delegate
                {
                    int i = 0;
                    foreach (var type in ns)
                    {
                        if (i++ > 0)
                        {
                            sb.AppendLine();
                        }

                        cw.IndentedMultiLine(codeByType[type].TrimEnd());
                    }
                });
            }

            return(sb.ToString());
        }
        public SortedDictionary<string, string> GenerateCode()
        {
            var codeByType = new Dictionary<Type, string>();
            var sb = new StringBuilder();
            var cw = new Serenity.Reflection.CodeWriter(sb, 4);

            foreach (var assembly in Assemblies)
            foreach (var type in assembly.GetTypes())
            {
                var formScriptAttribute = (FormScriptAttribute)type.GetCustomAttribute(typeof(FormScriptAttribute));
                if (formScriptAttribute == null)
                    continue;

                var ns = DoGetNamespace(type);

                sb.Clear();
                cw.Indented("public partial class ");
                sb.Append(DoGetTypeName(type));
                sb.AppendLine(" : PrefixedContext");
                cw.InBrace(delegate
                {
                    cw.Indented("[InlineConstant] public const string FormKey = \"");
                    sb.Append(formScriptAttribute.Key);
                    sb.AppendLine("\";");
                    sb.AppendLine();

                    cw.Indented("public ");
                    sb.Append(DoGetTypeName(type));
                    sb.AppendLine("(string idPrefix) : base(idPrefix) {}");
                    sb.AppendLine();

                    foreach (var item in Serenity.PropertyGrid.PropertyItemHelper.GetPropertyItemsFor(type))
                    {
                        var editorType = item.EditorType;
                        string widgetTypeName = null;
                        foreach (var rootNamespace in RootNamespaces)
                        {
                            string wn = rootNamespace + "." + editorType;
                            if (WidgetTypes.Contains(wn))
                            {
                                widgetTypeName = wn;
                                break;
                            }

                            wn += "Editor";
                            if (WidgetTypes.Contains(wn))
                            {
                                widgetTypeName = wn;
                                break;
                            }
                        }

                        if (widgetTypeName == null)
                        {
                            var wn = editorType;
                            if (!WidgetTypes.Contains(editorType))
                                wn = editorType + "Editor";

                            if (WidgetTypes.Contains(wn))
                                widgetTypeName = wn;
                        }

                        if (widgetTypeName == null)
                            continue;

                        if (widgetTypeName.StartsWith(ns + "."))
                            widgetTypeName = widgetTypeName.Substring(ns.Length + 1);
                        else
                        {
                            foreach (var rn in RootNamespaces)
                            {
                                if (widgetTypeName.StartsWith(rn + "."))
                                    widgetTypeName = widgetTypeName.Substring(rn.Length + 1);
                            }
                        }

                        cw.Indented("public ");
                        sb.Append(widgetTypeName);
                        sb.Append(" ");
                        sb.Append(item.Name);
                        sb.Append(" { get { return ById<");
                        sb.Append(widgetTypeName);
                        sb.Append(">(\"");
                        sb.Append(item.Name);
                        sb.AppendLine("\"); } }");
                    }
                });

                codeByType[type] = sb.ToString();
                sb.Clear();
            }

            var ordered = codeByType.Keys.OrderBy(x => DoGetNamespace(x)).ThenBy(x => x.Name);
            var byNameSpace = ordered.ToLookup(x => DoGetNamespace(x));

            var result = new SortedDictionary<string, string>();

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                foreach (var type in ns)
                {
                    sb.Clear();
                    sb.AppendLine();
                    cw.Indented("namespace ");
                    sb.AppendLine(ns.Key);
                    cw.InBrace(delegate
                    {
                        foreach (var usingNamespace in UsingNamespaces.ToArray().OrderBy(x => x))
                        {
                            cw.Indented("using ");
                            sb.Append(usingNamespace);
                            sb.AppendLine(";");
                        }

                        sb.AppendLine();

                        int i = 0;

                        {
                            if (i++ > 0)
                                sb.AppendLine();

                            cw.IndentedMultiLine(codeByType[type].TrimEnd());
                        }
                    });

                    var filename = ns.Key + "." + DoGetTypeName(type) + ".cs";

                    foreach (var rn in RootNamespaces)
                    {
                        if (filename.StartsWith(rn + "."))
                            filename = filename.Substring(rn.Length + 1);
                    }

                    result.Add(filename, sb.ToString());
                }
            }

            return result;
        }
        public string GenerateCode()
        {
            var codeByType = new Dictionary<string, string>();
            var sb = new StringBuilder();
            var cw = new Serenity.Reflection.CodeWriter(sb, 4);

            foreach (var key in EditorTypes.Keys)
            {
                var ns = DoGetNamespace(key);

                var editorInfo = EditorTypes[key];

                sb.Clear();
                cw.Indented("public partial class ");
                var type = DoGetTypeName(key);
                sb.Append(type);

                // yes it's ugly, but backward compatible
                if (editorInfo.Options.Count >= lookupEditorBaseOptions.Length &&
                    lookupEditorBaseOptions.All(x => editorInfo.Options.ContainsKey(x)))
                {
                    sb.AppendLine(" : LookupEditorBaseAttribute");
                    foreach (var x in lookupEditorBaseOptions)
                        editorInfo.Options.Remove(x);
                }
                else
                    sb.AppendLine(" : CustomEditorAttribute");

                cw.InBrace(delegate
                {
                    cw.Indented("public const string Key = \"");
                    sb.Append(key);
                    sb.AppendLine("\";");
                    sb.AppendLine();

                    cw.Indented("public ");
                    sb.Append(type);
                    sb.AppendLine("()");
                    cw.IndentedLine("    : base(Key)");
                    cw.IndentedLine("{");
                    cw.IndentedLine("}");
                    var opt = editorInfo.Options.Keys.ToList();
                    opt.Sort();

                    foreach (var item in opt)
                    {
                        var option = editorInfo.Options[item];
                        var typeName = option.Type;
                        var nullablePrefix = "System.Nullable`1";
                        bool nullable = option.Type.StartsWith(nullablePrefix);
                        if (nullable)
                            typeName = typeName.Substring(nullablePrefix.Length + 1, typeName.Length - nullablePrefix.Length - 2);

                        var systemType = Type.GetType(typeName);
                        if (systemType == null)
                            typeName = "object";
                        else if (typeName.StartsWith("System."))
                            typeName = typeName.Substring(7);

                        sb.AppendLine();
                        cw.Indented("public ");
                        sb.Append(typeName);
                        //if (nullable) //Attribute name argument nullable problem
                        //    sb.Append("?");
                        sb.Append(" ");
                        sb.AppendLine(item);
                        cw.InBrace(() =>
                        {
                            string propName = item.Substring(0, 1).ToLowerInvariant() + item.Substring(1);
                            if (item == "ID")
                                propName = "id";
                            cw.Indented("get { return GetOption<");
                            sb.Append(typeName);
                            //if (nullable) //Attribute name argument nullable problem
                            //    sb.Append("?");
                            sb.Append(">(\"");
                            sb.Append(propName);
                            sb.AppendLine("\"); }");
                            cw.Indented("set { SetOption(\"");
                            sb.Append(propName);
                            sb.AppendLine("\", value); }");
                        });
                    }
                });

                codeByType[key] = sb.ToString();
                sb.Clear();
            }

            sb.Clear();
            sb.AppendLine();

            foreach (var ns in UsingNamespaces)
            {
                cw.Indented("using ");
                sb.Append(ns);
                sb.AppendLine(";");
            }

            var ordered = codeByType.Keys.OrderBy(x => DoGetNamespace(x)).ThenBy(x => x);
            var byNameSpace = ordered.ToLookup(x => DoGetNamespace(x));

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                sb.AppendLine();
                cw.Indented("namespace ");
                sb.AppendLine(ns.Key);
                cw.InBrace(delegate
                {
                    int i = 0;
                    foreach (var type in ns)
                    {
                        if (i++ > 0)
                            sb.AppendLine();

                        cw.IndentedMultiLine(codeByType[type].TrimEnd());
                    }
                });
            }

            return sb.ToString();
        }
        public SortedDictionary<string, string> GenerateCode()
        {
            var endpointCodes = new Dictionary<Type, string>();
            var sb = new StringBuilder();
            var cw = new CodeWriter(sb, 4);
            var result = new SortedDictionary<string, string>();

            Func<Type, string> getClassName = (t) =>
            {
                string className = t.Name;
                if (className.EndsWith("Controller"))
                    className = className.Substring(0, className.Length - 10);
                return className;
            };

            foreach (var assembly in this.Assemblies)
                foreach (var type in assembly.GetTypes())
                {
                    if (!type.IsSubclassOf(typeof(Controller)))
                        continue;

                    if (type.IsAbstract)
                        continue;

                    if (this.IsEndpoint != null && !this.IsEndpoint(type))
                        continue;

                    var className = getClassName(type);

                    cw.IndentedLine("[Imported, PreserveMemberCase]");
                    cw.Indented("public partial class ");
                    sb.Append(className);
                    sb.AppendLine("Service");

                    var methods = new List<string>();

                    string serviceUrl;
                    if (GetServiceUrl != null)
                    {
                        serviceUrl = GetServiceUrl(type);
                        serviceUrl = UriHelper.Combine(serviceUrl, className);
                    }
                    else
                    {
                        serviceUrl = GetServiceUrlFromRoute(type);
                        if (serviceUrl == null)
                            serviceUrl = DoGetNamespace(type).Replace(".", "/");
                    }

                    cw.InBrace(delegate
                    {
                        cw.Indented("[InlineConstant] public const string BaseUrl = \"");
                        sb.Append(serviceUrl);
                        sb.AppendLine("\";");
                        sb.AppendLine();

                        foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public))
                        {
                            if (method.GetCustomAttribute<NonActionAttribute>() != null)
                                continue;

                            if (typeof(Controller).IsSubclassOf(method.DeclaringType))
                                continue;

                            if (method.IsSpecialName && (method.Name.StartsWith("set_") || method.Name.StartsWith("get_")))
                                continue;

                            // belki burada daha sonra metod listesini de verebiliriz (ayrı bir namespace de?)
                            var parameters = method.GetParameters().Where(x => !x.ParameterType.IsInterface).ToArray();
                            if (parameters.Length > 1)
                            {
                                // tek parametreli olmalı
                                continue;
                            }

                            Type paramType;
                            if (parameters.Length == 1)
                            {
                                paramType = parameters[0].ParameterType;
                                if (paramType.IsPrimitive || !ScriptDtoGenerator.CanHandleType(paramType))
                                    continue;
                            }
                            else
                                paramType = typeof(ServiceRequest);

                            var returnType = method.ReturnType;

                            Type responseType = returnType;
                            if (returnType != null &&
                                returnType.IsGenericType &&
                                returnType.GetGenericTypeDefinition() == typeof(Result<>))
                            {
                                responseType = returnType.GenericTypeArguments[0];
                            }
                            else if (typeof(ActionResult).IsAssignableFrom(returnType))
                                continue;
                            else if (returnType == typeof(void))
                                continue;

                            if (methods.Count > 0)
                                sb.AppendLine();

                            methods.Add(method.Name);

                            var parameterName = parameters.Length == 0 ? "request" : parameters[0].Name;
                            cw.Indented("[InlineCode(\"Q.serviceRequest(\'");
                            sb.Append(UriHelper.Combine(serviceUrl, method.Name));
                            sb.Append("\', {");
                            sb.Append(parameterName);
                            sb.AppendLine("}, {onSuccess}, {options})\")]");
                            cw.Indented("public static jQueryXmlHttpRequest ");
                            sb.Append(method.Name);

                            sb.Append("(");

                            ScriptDtoGenerator.HandleMemberType(sb, paramType,
                                codeNamespace: DoGetNamespace(type),
                                usingNamespaces: UsingNamespaces,
                                enqueueType: null);

                            sb.Append(' ');
                            sb.Append(parameterName);
                            sb.Append(", Action<");

                            ScriptDtoGenerator.HandleMemberType(sb, responseType,
                                codeNamespace: DoGetNamespace(type),
                                usingNamespaces: UsingNamespaces,
                                enqueueType: null);

                            sb.Append("> onSuccess, ServiceCallOptions options = null");
                            sb.AppendLine(")");

                            cw.InBrace(delegate
                            {
                                cw.IndentedLine("return null;");
                            });
                        }

                        sb.AppendLine();
                        cw.IndentedLine("[Imported, PreserveMemberCase]");
                        cw.IndentedLine("public static class Methods");
                        cw.InBrace(delegate
                        {
                            foreach (var method in methods)
                            {
                                cw.Indented("[InlineConstant] public const string ");
                                sb.Append(method);
                                sb.Append(" = \"");
                                sb.Append(UriHelper.Combine(serviceUrl, method));
                                sb.AppendLine("\";");
                            }
                        });

                    });

                    if (methods.Count > 0)
                        endpointCodes.Add(type, sb.ToString());

                    sb.Clear();
                }

            var ordered = endpointCodes.Keys.OrderBy(DoGetNamespace).ThenBy(x => x.Name);
            var byNameSpace = ordered.ToLookup(DoGetNamespace);

            sb.Clear();

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                Action<Type> outputType = delegate(Type type)
                {
                    var filename = ns.Key + "." + getClassName(type) + "Service.cs";

                    foreach (var rn in RootNamespaces)
                    {
                        if (filename.StartsWith(rn + "."))
                            filename = filename.Substring(rn.Length + 1);
                    }

                    result.Add(filename, sb.ToString());
                };

                foreach (var type in ns)
                {
                    cw.Indented("namespace ");
                    sb.AppendLine(ns.Key);

                    cw.InBrace(delegate
                    {
                        foreach (var nsStr in UsingNamespaces.ToArray().OrderBy(x => x))
                        {
                            cw.Indented("using ");
                            sb.Append(nsStr);
                            sb.AppendLine(";");
                        }

                        sb.AppendLine();

                        cw.IndentedMultiLine(endpointCodes[type]);
                    });

                    outputType(type);

                    sb.Clear();
                }
            }

            return result;
        }
Beispiel #13
0
        public string Generate()
        {
            var endpointCodes  = new Dictionary <Type, string>();
            var usedNamespaces = new HashSet <string>();
            var sb             = new StringBuilder();
            var cw             = new CodeWriter(sb, 4);

            foreach (var type in this.Assembly.GetTypes())
            {
                if (!type.IsSubclassOf(typeof(Controller)))
                {
                    continue;
                }

                if (type.IsAbstract)
                {
                    continue;
                }

                if (this.IsEndpoint != null && !this.IsEndpoint(type))
                {
                    continue;
                }

                string className = type.Name;
                if (className.EndsWith("Controller"))
                {
                    className = className.Substring(0, className.Length - 10);
                }

                string ns = GetNamespace != null?GetNamespace(type) : type.Namespace;

                cw.Indented("public partial class ");
                sb.Append(className);
                sb.AppendLine("Service");

                bool hasAnyMethod = false;
                cw.InBrace(delegate
                {
                    foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public))
                    {
                        if (method.GetCustomAttribute <NonActionAttribute>() != null)
                        {
                            continue;
                        }

                        if (typeof(Controller).IsSubclassOf(method.DeclaringType))
                        {
                            continue;
                        }

                        if (method.IsSpecialName && (method.Name.StartsWith("set_") || method.Name.StartsWith("get_")))
                        {
                            continue;
                        }

                        // belki burada daha sonra metod listesini de verebiliriz (ayrı bir namespace de?)
                        var parameters = method.GetParameters();
                        if (parameters.Length != 1)
                        {
                            // tek parametreli olmalı
                            continue;
                        }

                        var paramType = parameters[0].ParameterType;
                        if (paramType.IsPrimitive || !ScriptDtoGenerator.CanHandleType(paramType))
                        {
                            continue;
                        }

                        var returnType = method.ReturnType;

                        Type responseType = returnType;
                        if (returnType != null &&
                            returnType.IsGenericType &&
                            returnType.GetGenericTypeDefinition() == typeof(Result <>))
                        {
                            responseType = returnType.GenericTypeArguments[0];
                        }
                        else if (returnType.IsAssignableFrom(typeof(ActionResult)))
                        {
                            continue;
                        }

                        if (hasAnyMethod)
                        {
                            sb.AppendLine();
                        }

                        hasAnyMethod = true;

                        cw.Indented("public static void ");
                        sb.Append(method.Name);

                        sb.Append("(");
                        ScriptDtoGenerator.HandleMemberType(sb, paramType, enqueueType: null);
                        sb.Append(' ');
                        sb.Append(parameters[0].Name);
                        sb.Append(", Action<");
                        ScriptDtoGenerator.HandleMemberType(sb, responseType, enqueueType: null);
                        sb.Append("> onSuccess, ServiceCallOptions options = null");
                        sb.AppendLine(")");

                        cw.InBrace(delegate
                        {
                            cw.Indented("Q.ServiceRequest(\"");

                            string url = GetServiceUrl != null ? GetServiceUrl(type) : ns.Replace(".", "/");
                            url        = UriHelper.Combine(url, UriHelper.Combine(className, method.Name));

                            sb.Append(url);

                            sb.AppendLine("\", request, onSuccess, options);");
                        });
                    }
                });

                if (hasAnyMethod)
                {
                    endpointCodes.Add(type, sb.ToString());
                    usedNamespaces.Add(ns);
                }

                sb.Clear();
            }

            usedNamespaces.Add("Serenity");
            usedNamespaces.Add("System");
            usedNamespaces.Add("System.Collections");
            usedNamespaces.Add("System.Collections.Generic");

            foreach (var ns in usedNamespaces)
            {
                cw.Indented("using ");
                sb.Append(ns);
                sb.AppendLine(";");
            }

            sb.AppendLine();
            var ordered     = endpointCodes.Keys.OrderBy(x => GetNamespace != null ? GetNamespace(x) : x.Namespace).ThenBy(x => x.Name);
            var byNameSpace = ordered.ToLookup(x => GetNamespace != null ? GetNamespace(x) : x.Namespace);

            foreach (var ns in byNameSpace.ToArray().OrderBy(x => x.Key))
            {
                sb.AppendLine();
                cw.Indented("namespace ");
                sb.AppendLine(ns.Key);
                cw.InBrace(delegate
                {
                    foreach (var type in ns)
                    {
                        cw.IndentedMultiLine(endpointCodes[type]);
                    }
                });
            }

            return(sb.ToString());
        }