Exemple #1
0
        public bool AppendAttributes(StringBuilderWrapper sb, List <MetadataAttribute> attributes)
        {
            if (attributes == null || attributes.Count == 0)
            {
                return(false);
            }

            foreach (var attr in attributes)
            {
                if ((attr.Args == null || attr.Args.Count == 0) &&
                    (attr.ConstructorArgs == null || attr.ConstructorArgs.Count == 0))
                {
                    sb.AppendLine("// @{0}()".Fmt(attr.Name));
                }
                else
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    if (attr.ConstructorArgs != null)
                    {
                        foreach (var ctorArg in attr.ConstructorArgs)
                        {
                            if (args.Length > 0)
                            {
                                args.Append(", ");
                            }
                            args.Append("{0}".Fmt(TypeValue(ctorArg.Type, ctorArg.Value)));
                        }
                    }
                    else if (attr.Args != null)
                    {
                        foreach (var attrArg in attr.Args)
                        {
                            if (args.Length > 0)
                            {
                                args.Append(", ");
                            }
                            args.Append("{0}={1}".Fmt(attrArg.Name, TypeValue(attrArg.Type, attrArg.Value)));
                        }
                    }
                    sb.AppendLine("// @{0}({1})".Fmt(attr.Name, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }

            return(true);
        }
        public string Type(string type, string[] genericArgs)
        {
            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return("{0}?".Fmt(GenericArg(genericArgs[0])));
                }
                if (ArrayTypes.Contains(type))
                {
                    return("{0}[]".Fmt(GenericArg(genericArgs[0])).StripNullable());
                }
                if (DictionaryTypes.Contains(type))
                {
                    return("{{ [index:{0}]: {1}; }}".Fmt(
                               GenericArg(genericArgs[0]),
                               GenericArg(genericArgs[1])));
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return("{0}<{1}>".Fmt(typeName, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }
            else
            {
                type = type.StripNullable();
            }

            return(TypeAlias(type));
        }
Exemple #3
0
        public string GetTypeName(Type type)
        {
            try
            {
                //Inner classes?
                var typeName = type == null
                               //|| type.FullName == null
                                        ? null
                                        : StringBuilderCacheAlt.Allocate()
                               .Append(type.FullName.Replace('+', '.').LeftPart('`'));

                if (typeName == null)
                {
                    return(null);
                }

                if (type.HasGenericType()
                    //TODO: support GenericTypeDefinition properly
                    && !type.IsGenericTypeDefinition
                    )
                {
                    var genericArgs = type.GetGenericArguments();

                    typeName.Append("<");
                    var i = 0;
                    foreach (var genericArg in genericArgs)
                    {
                        if (i++ > 0)
                        {
                            typeName.Append(", ");
                        }
                        typeName.Append(GetTypeName(genericArg));
                    }
                    typeName.Append(">");
                }

                return(StringBuilderCacheAlt.ReturnAndFree(typeName));
            }
            catch (Exception)
            {
                //Console.WriteLine(ex);
                throw;
            }
        }
Exemple #4
0
        public string Type(string type, string[] genericArgs)
        {
            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return /*@Nullable*/ (GenericArg(genericArgs[0]));
                }
                if (ArrayTypes.Contains(type))
                {
                    return($"ArrayList<{GenericArg(genericArgs[0])}>".StripNullable());
                }
                if (DictionaryTypes.Contains(type))
                {
                    return($"HashMap<{GenericArg(genericArgs[0])},{GenericArg(genericArgs[1])}>");
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return($"{typeName}<{StringBuilderCacheAlt.ReturnAndFree(args)}>");
                }
            }
            else
            {
                type = type.StripNullable();
            }

            return(TypeAlias(type));
        }
        public string Type(string type, string[] genericArgs)
        {
            if (!genericArgs.IsEmpty())
            {
                if (type == "Nullable`1")
                {
                    return("{0}?".Fmt(TypeAlias(GenericArg(genericArgs[0]))));
                }
                if (ArrayTypes.Contains(type))
                {
                    return("[{0}]".Fmt(TypeAlias(GenericArg(genericArgs[0]))));
                }
                if (DictionaryTypes.Contains(type))
                {
                    return("[{0}:{1}]".Fmt(
                               TypeAlias(GenericArg(genericArgs[0])),
                               TypeAlias(GenericArg(genericArgs[1]))));
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(GenericArg(arg));
                    }

                    var typeName = TypeAlias(type);
                    return("{0}<{1}>".Fmt(typeName, StringBuilderCacheAlt.ReturnAndFree(args)));
                }
            }

            return(TypeAlias(type));
        }
Exemple #6
0
        // Join previously split sections back into one document
        public static string JoinSections(List <string> sections)
        {
            var sb = StringBuilderCacheAlt.Allocate();

            for (int i = 0; i < sections.Count; i++)
            {
                if (i > 0)
                {
                    // For subsequent sections, need to make sure we
                    // have a line break after the previous section.
                    string strPrev = sections[sections.Count - 1];
                    if (strPrev.Length > 0 && !strPrev.EndsWith("\n") && !strPrev.EndsWith("\r"))
                    {
                        sb.Append("\n");
                    }
                }

                sb.Append(sections[i]);
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
        public string Type(string type, string[] genericArgs, bool includeNested = false)
        {
            var useType = TypeFilter?.Invoke(type, genericArgs);

            if (useType != null)
            {
                return(useType);
            }

            if (genericArgs != null)
            {
                if (type == "Nullable`1")
                {
                    return($"{TypeAlias(genericArgs[0], includeNested: includeNested)}?");
                }

                var parts = type.Split('`');
                if (parts.Length > 1)
                {
                    var args = StringBuilderCacheAlt.Allocate();
                    foreach (var arg in genericArgs)
                    {
                        if (args.Length > 0)
                        {
                            args.Append(", ");
                        }

                        args.Append(TypeAlias(arg.SanitizeType(), includeNested: includeNested));
                    }

                    var typeName = NameOnly(type, includeNested: includeNested).SanitizeType();
                    return($"{typeName}<{StringBuilderCacheAlt.ReturnAndFree(args)}>");
                }
            }

            return(TypeAlias(type, includeNested: includeNested));
        }
Exemple #8
0
        // Remove the markdown escapes from a string
        public static string UnescapeString(string str, bool ExtraMode)
        {
            if (str == null || str.IndexOf('\\') == -1)
            {
                return(str);
            }

            var sb = StringBuilderCacheAlt.Allocate();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '\\' && i + 1 < str.Length && IsEscapableChar(str[i + 1], ExtraMode))
                {
                    sb.Append(str[i + 1]);
                    i++;
                }
                else
                {
                    sb.Append(str[i]);
                }
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
Exemple #9
0
        public override string ToInsertRowStatement(IDbCommand cmd, object objWithProperties, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();

            var tableType = objWithProperties.GetType();
            var modelDef  = GetModel(tableType);

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (fieldDef.ReturnOnInsert || (fieldDef.IsPrimaryKey && fieldDef.AutoIncrement && HasInsertReturnValues(modelDef)))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append(GetQuotedColumnName(fieldDef.FieldName));
                }

                if (fieldDef.IsComputed)
                {
                    continue;
                }

                if ((fieldDef.AutoIncrement || !string.IsNullOrEmpty(fieldDef.Sequence) ||
                     fieldDef.Name == OrmLiteConfig.IdField) &&
                    cmd != null)
                {
                    EnsureAutoIncrementSequence(modelDef, fieldDef);

                    var result = GetNextValue(cmd, fieldDef.Sequence, fieldDef.GetValue(objWithProperties));

                    var fieldValue = this.ConvertNumber(fieldDef.FieldType, result);
                    fieldDef.SetValueFn(objWithProperties, fieldValue);
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
                    sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));

                    var p = AddParameter(cmd, fieldDef);
                    p.Value = GetFieldValue(fieldDef, fieldDef.GetValue(objWithProperties)) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in ToInsertRowStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);
            var sql          = string.Format("INSERT INTO {0} ({1}) VALUES ({2}) {3};",
                                             GetQuotedTableName(modelDef),
                                             StringBuilderCache.ReturnAndFree(sbColumnNames),
                                             StringBuilderCacheAlt.ReturnAndFree(sbColumnValues),
                                             strReturning.Length > 0 ? "RETURNING " + strReturning : "");

            return(sql);
        }
Exemple #10
0
        public override string ToInsertRowStatement(IDbCommand cmd, object objWithProperties, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var tableType          = objWithProperties.GetType();
            var modelDef           = GetModel(tableType);

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef) && !fieldDef.AutoId)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
                    sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));

                    var p = AddParameter(cmd, fieldDef);
                    p.Value = GetFieldValue(fieldDef, fieldDef.GetValue(objWithProperties)) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in ToInsertRowStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            foreach (var fieldDef in modelDef.AutoIdFields) // need to include any AutoId fields that weren't included
            {
                if (fieldDefs.Contains(fieldDef))
                {
                    continue;
                }

                if (sbReturningColumns.Length > 0)
                {
                    sbReturningColumns.Append(",");
                }
                sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            var sql = sbColumnNames.Length > 0
                ? $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
                      strReturning +
                      $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})"
                : $"INSERT INTO {GetQuotedTableName(modelDef)} {strReturning} DEFAULT VALUES";

            return(sql);
        }
Exemple #11
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null,
                                                                     Func <FieldDefinition, bool> shouldInclude        = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if ((ShouldSkipInsert(fieldDef) && !fieldDef.AutoId) &&
                    shouldInclude?.Invoke(fieldDef) != true)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (SupportsSequences(fieldDef))
                    {
                        sbColumnValues.Append("NEXT VALUE FOR " + Sequence(NamingStrategy.GetSchemaName(modelDef), fieldDef.Sequence));
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName), fieldDef.CustomInsert));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            foreach (var fieldDef in modelDef.AutoIdFields) // need to include any AutoId fields that weren't included
            {
                if (fieldDefs.Contains(fieldDef))
                {
                    continue;
                }

                if (sbReturningColumns.Length > 0)
                {
                    sbReturningColumns.Append(",");
                }
                sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning    = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            cmd.CommandText = sbColumnNames.Length > 0
                ? $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) {strReturning}" +
                              $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})"
                : $"INSERT INTO {GetQuotedTableName(modelDef)}{strReturning} DEFAULT VALUES";
        }
Exemple #12
0
        public static string HtmlDump(object target, HtmlDumpOptions options)
        {
            if (options == null)
            {
                options = new HtmlDumpOptions();
            }

            var depth      = options.Depth;
            var childDepth = options.ChildDepth;

            options.Depth += 1;

            try
            {
                target = DefaultScripts.ConvertDumpType(target);

                if (!isComplexType(target))
                {
                    return(GetScalarHtml(target, options.Defaults));
                }

                var parentClass = options.ClassName;
                var childClass  = options.ChildClass;
                var className   = ((depth < childDepth ? parentClass : childClass ?? parentClass)
                                   ?? options.Defaults.GetDefaultTableClassName());

                var headerStyle = options.HeaderStyle;
                var headerTag   = options.HeaderTag ?? "th";

                if (target is IEnumerable e)
                {
                    var objs = e.Map(x => x);

                    var isEmpty = objs.Count == 0;
                    if (isEmpty && options.CaptionIfEmpty == null)
                    {
                        return(string.Empty);
                    }

                    var first = !isEmpty ? objs[0] : null;
                    if (first is IDictionary && objs.Count > 1 && options.Display != "table")
                    {
                        return(HtmlList(objs, options));
                    }

                    var sb = StringBuilderCacheAlt.Allocate();

                    sb.Append("<table");

                    if (options.Id != null)
                    {
                        sb.Append(" id=\"").Append(options.Id).Append("\"");
                    }
                    if (!string.IsNullOrEmpty(className))
                    {
                        sb.Append(" class=\"").Append(className).Append("\"");
                    }

                    sb.Append(">");

                    var caption = options.Caption;
                    if (isEmpty)
                    {
                        caption = options.CaptionIfEmpty;
                    }

                    var holdCaption = options.HasCaption;
                    if (caption != null && !options.HasCaption)
                    {
                        sb.Append("<caption>").Append(caption.HtmlEncode()).Append("</caption>");
                        options.HasCaption = true;
                    }

                    if (!isEmpty)
                    {
                        sb.Append("<tbody>");

                        if (first is KeyValuePair <string, object> )
                        {
                            foreach (var o in objs)
                            {
                                if (o is KeyValuePair <string, object> kvp)
                                {
                                    if (kvp.Value == target)
                                    {
                                        break;                      // Prevent cyclical deps like 'it' binding
                                    }
                                    sb.Append("<tr>");
                                    sb.Append('<').Append(headerTag).Append('>');
                                    sb.Append(ViewUtils.StyleText(kvp.Key, headerStyle)?.HtmlEncode());
                                    sb.Append("</").Append(headerTag).Append('>');
                                    sb.Append("<td>");
                                    if (!isComplexType(kvp.Value))
                                    {
                                        sb.Append(GetScalarHtml(kvp.Value, options.Defaults));
                                    }
                                    else
                                    {
                                        var body = HtmlDump(kvp.Value, options);
                                        sb.Append(body.AsString());
                                    }
                                    sb.Append("</td>");
                                    sb.Append("</tr>");
                                }
                            }
                        }
                        else if (!isComplexType(first))
                        {
                            foreach (var o in objs)
                            {
                                sb.Append("<tr>");
                                sb.Append("<td>");
                                sb.Append(GetScalarHtml(o, options.Defaults));
                                sb.Append("</td>");
                                sb.Append("</tr>");
                            }
                        }
                        else
                        {
                            if (objs.Count > 1 || options.Display == "table")
                            {
                                var rows = objs.Map(x => x.ToObjectDictionary());
                                StringBuilderCache.Free(sb);
                                options.HasCaption = holdCaption;
                                return(HtmlList(rows, options));
                            }
                            else
                            {
                                foreach (var o in objs)
                                {
                                    sb.Append("<tr>");

                                    if (!isComplexType(o))
                                    {
                                        sb.Append("<td>");
                                        sb.Append(GetScalarHtml(o, options.Defaults));
                                        sb.Append("</td>");
                                    }
                                    else
                                    {
                                        sb.Append("<td>");
                                        var body = HtmlDump(o, options);
                                        sb.Append(body.AsString());
                                        sb.Append("</td>");
                                    }

                                    sb.Append("</tr>");
                                }
                            }
                        }

                        sb.Append("</tbody>");
                    }

                    sb.Append("</table>");

                    var html = StringBuilderCacheAlt.ReturnAndFree(sb);
                    return(html);
                }

                return(HtmlDump(target.ToObjectDictionary(), options));
            }
            finally
            {
                options.Depth = depth;
            }
        }
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null,
                                                                     Func <FieldDefinition, bool> shouldInclude        = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();
            cmd.CommandTimeout = OrmLiteConfig.CommandTimeout;

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append(GetQuotedColumnName(fieldDef.FieldName));
                }

                if ((ShouldSkipInsert(fieldDef) || (fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))) &&
                    shouldInclude?.Invoke(fieldDef) != true)
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    // in FB4 only use 'next value for' if the fielddef has a sequence explicitly.
                    if (fieldDef.AutoIncrement && !string.IsNullOrEmpty(fieldDef.Sequence))
                    {
                        EnsureAutoIncrementSequence(modelDef, fieldDef);
                        sbColumnValues.Append("NEXT VALUE FOR " + fieldDef.Sequence);
                    }
                    if (fieldDef.AutoId && usesCompactGuid)
                    {
                        sbColumnValues.Append("GEN_UUID()");
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName), fieldDef.CustomInsert));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            cmd.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2}) {3}",
                                            GetQuotedTableName(modelDef),
                                            StringBuilderCache.ReturnAndFree(sbColumnNames),
                                            StringBuilderCacheAlt.ReturnAndFree(sbColumnValues),
                                            strReturning.Length > 0 ? "RETURNING " + strReturning : "");
        }
Exemple #14
0
        public void AddProperties(StringBuilderWrapper sb, MetadataType type,
                                  bool includeResponseStatus,
                                  bool addPropertyAccessors,
                                  string settersReturnType)
        {
            var wasAdded = false;

            var sbInner     = StringBuilderCacheAlt.Allocate();
            var sbAccessors = new StringBuilderWrapper(sbInner);

            if (addPropertyAccessors)
            {
                sbAccessors.AppendLine();
                sbAccessors = sbAccessors.Indent().Indent();
            }

            var dataMemberIndex = 1;

            if (type.Properties != null)
            {
                foreach (var prop in type.Properties)
                {
                    if (wasAdded)
                    {
                        sb.AppendLine();
                    }

                    var propType = Type(prop.GetTypeName(Config, allTypes), prop.GenericArgs);

                    var fieldName    = prop.Name.SafeToken().PropertyStyle();
                    var accessorName = fieldName.ToPascalCase();

                    wasAdded = AppendComments(sb, prop.Description);
                    wasAdded = AppendDataMember(sb, prop.DataMember, dataMemberIndex++) || wasAdded;
                    wasAdded = AppendAttributes(sb, prop.Attributes) || wasAdded;

                    if (!fieldName.IsKeyWord())
                    {
                        sb.AppendLine("public {0} {1} = null;".Fmt(propType, fieldName));
                    }
                    else
                    {
                        var originalName = fieldName;
                        fieldName = Char.ToUpper(fieldName[0]) + fieldName.SafeSubstring(1);
                        sb.AppendLine("@SerializedName(\"{0}\") public {1} {2} = null;".Fmt(originalName, propType, fieldName));
                    }

                    if (addPropertyAccessors)
                    {
                        sbAccessors.AppendPropertyAccessor(propType, fieldName, accessorName, settersReturnType);
                    }
                }
            }

            if (includeResponseStatus)
            {
                if (wasAdded)
                {
                    sb.AppendLine();
                }

                AppendDataMember(sb, null, dataMemberIndex++);
                sb.AppendLine("public ResponseStatus {0} = null;".Fmt(typeof(ResponseStatus).Name.PropertyStyle()));

                if (addPropertyAccessors)
                {
                    sbAccessors.AppendPropertyAccessor("ResponseStatus", "ResponseStatus", settersReturnType);
                }
            }

            if (sbAccessors.Length > 0)
            {
                sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbInner).TrimEnd()); //remove last \n
            }
        }
        public string SelectInto <T>()
        {
            var modelDef = typeof(T).GetModelMetadata();

            CheckAggregateUsage(false);

            var sbSelect = StringBuilderCache.Allocate();

            sbSelect.Append("SELECT ");

            var dbColumns = StringBuilderCache.Allocate();

            if (columnList.Count > 0)
            {
                if (isDistinct)
                {
                    sbSelect.Append(" DISTINCT ");
                }

                foreach (var col in columnList)
                {
                    dbColumns.AppendFormat("{0}{1}", dbColumns.Length > 0 ? "," : "", col);
                }
            }
            else
            {
                // improve performance avoiding multiple calls to GetModelDefinition()
                if (isDistinct && modelDef.FieldDefinitions.Count > 0)
                {
                    sbSelect.Append(" DISTINCT ");
                }

                foreach (var fi in modelDef.FieldDefinitions)
                {
                    dbColumns.AppendFormat("{0}{1}", dbColumns.Length > 0 ? "," : "", (String.IsNullOrEmpty(fi.BelongToModelName) ? (dialectProvider.GetQuotedTableName(modelDef.ModelName)) : (dialectProvider.GetQuotedTableName(fi.BelongToModelName))) + "." + dialectProvider.GetQuotedColumnName(fi.FieldName));
                }
                if (dbColumns.Length == 0)
                {
                    dbColumns.AppendFormat("\"{0}{1}\".*", baseSchema, dialectProvider.GetQuotedTableName(baseTableName));
                }
            }

            sbSelect.Append(StringBuilderCache.ReturnAndFree(dbColumns) + " \n");

            var sbBody = StringBuilderCacheAlt.Allocate();

            sbBody.AppendFormat("FROM {0}{1} \n", baseSchema, dialectProvider.GetQuotedTableName(baseTableName));
            int i = 0;

            foreach (var join in joinList)
            {
                i++;
                if ((join.JoinType == JoinType.INNER) || (join.JoinType == JoinType.SELF))
                {
                    sbBody.Append(" INNER JOIN ");
                }
                else if (join.JoinType == JoinType.LEFTOUTER)
                {
                    sbBody.Append(" LEFT OUTER JOIN ");
                }
                else if (join.JoinType == JoinType.RIGHTOUTER)
                {
                    sbBody.Append(" RIGHT OUTER JOIN ");
                }
                else if (join.JoinType == JoinType.FULLOUTER)
                {
                    sbBody.Append(" FULL OUTER JOIN ");
                }
                else if (join.JoinType == JoinType.CROSS)
                {
                    sbBody.Append(" CROSS JOIN ");
                }

                if (join.JoinType == JoinType.CROSS)
                {
                    sbBody.AppendFormat(" {0}{1} ON {2} = {3}  \n", join.RefTypeSchema, dialectProvider.GetQuotedTableName(join.RefTypeTableName));
                }
                else
                {
                    if (join.JoinType != JoinType.SELF)
                    {
                        sbBody.AppendFormat(" {0}{1} ON {2} = {3}  \n", join.RefTypeSchema, dialectProvider.GetQuotedTableName(join.RefTypeTableName), join.Class1ColumnName, join.Class2ColumnName);
                    }
                    else
                    {
                        sbBody.AppendFormat(" {0}{1} AS {2} ON {2}.{3} = \"{1}\".{4}  \n", join.RefTypeSchema, dialectProvider.GetQuotedTableName(join.RefTypeTableName), dialectProvider.GetQuotedTableName(join.RefTypeTableName) + "_" + i.ToString(), join.Class1ColumnName, join.Class2ColumnName);
                    }
                }
            }

            if (whereList.Count > 0)
            {
                var sbWhere = new StringBuilder();
                foreach (var where in whereList)
                {
                    sbWhere.AppendFormat("{0}{1}", sbWhere.Length > 0
                        ? (where.Value == WhereType.OR ? " OR " : " AND ") : "", where.Key);
                }
                sbBody.Append("WHERE " + sbWhere + " \n");
            }

            var sbOrderBy = new StringBuilder();

            if (orderByList.Count > 0)
            {
                foreach (var ob in orderByList)
                {
                    sbOrderBy.AppendFormat("{0}{1} {2} ", sbOrderBy.Length > 0 ? "," : "", ob.Key, ob.Value ? "ASC" : "DESC");
                }
                sbOrderBy.Insert(0, "ORDER BY ");
                sbOrderBy.Append(" \n");
            }

            var sql = dialectProvider.ToSelectStatement(
                modelDef, StringBuilderCache.ReturnAndFree(sbSelect), StringBuilderCacheAlt.ReturnAndFree(sbBody), sbOrderBy.ToString(), Offset, Rows);

            return(sql);
        }
Exemple #16
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();

            foreach (var fieldDef in modelDef.FieldDefinitionsArray)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef))
                {
                    continue;
                }

                //insertFields contains Property "Name" of fields to insert ( that's how expressions work )
                if (insertFields != null && !insertFields.Contains(fieldDef.Name, StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (SupportsSequences(fieldDef))
                    {
                        sbColumnValues.Append("NEXT VALUE FOR " + Sequence(NamingStrategy.GetSchemaName(modelDef), fieldDef.Sequence));
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning    = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            cmd.CommandText = $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
                              strReturning +
                              $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})";
        }
        public override string ToExistStatement(Type fromTableType, object objWithProperties, string sqlFilter, params object[] filterParams)
        {
            var fromModelDef = GetModel(fromTableType);

            var sql = StringBuilderCache.Allocate();

            sql.AppendFormat("SELECT 1 \nFROM {0}", this.GetQuotedTableName(fromModelDef));

            var filter    = StringBuilderCacheAlt.Allocate();
            var hasFilter = false;

            if (objWithProperties != null)
            {
                var tableType = objWithProperties.GetType();

                if (fromTableType != tableType)
                {
                    int i        = 0;
                    var fpk      = new List <FieldDefinition>();
                    var modelDef = GetModel(tableType);

                    foreach (var def in modelDef.FieldDefinitions)
                    {
                        if (def.IsPrimaryKey)
                        {
                            fpk.Add(def);
                        }
                    }

                    foreach (var fieldDef in fromModelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed || fieldDef.ForeignKey == null)
                        {
                            continue;
                        }

                        var model = GetModel(fieldDef.ForeignKey.ReferenceType);
                        if (model.ModelName != modelDef.ModelName)
                        {
                            continue;
                        }

                        if (filter.Length > 0)
                        {
                            filter.Append(" AND ");
                        }

                        filter.AppendFormat("{0} = {1}", GetQuotedColumnName(fieldDef.FieldName), fpk[i++].GetQuotedValue(objWithProperties));
                    }
                }
                else
                {
                    var modelDef = GetModel(tableType);
                    foreach (var fieldDef in modelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed || !fieldDef.IsPrimaryKey)
                        {
                            continue;
                        }

                        if (filter.Length > 0)
                        {
                            filter.Append(" AND ");
                        }

                        filter.AppendFormat("{0} = {1}",
                                            GetQuotedColumnName(fieldDef.FieldName), fieldDef.GetQuotedValue(objWithProperties));
                    }
                }

                hasFilter = filter.Length > 0;
                if (hasFilter)
                {
                    sql.AppendFormat("\nWHERE {0} ", StringBuilderCacheAlt.ReturnAndFree(filter));
                }
            }

            if (!string.IsNullOrEmpty(sqlFilter))
            {
                sqlFilter = sqlFilter.SqlFmt(filterParams);
                sql.Append(hasFilter ? " AND  " : "\nWHERE ");
                sql.Append(sqlFilter);
            }

            return(string.Format("SELECT EXISTS({0});", StringBuilderCache.ReturnAndFree(sql)));
        }
        public IRawString htmlList(TemplateScopeContext scope, object target, object scopeOptions)
        {
            if (target is IDictionary <string, object> single)
            {
                target = new[] { single }
            }
            ;

            var items        = target.AssertEnumerable(nameof(htmlList));
            var scopedParams = scope.AssertOptions(nameof(htmlList), scopeOptions);
            var depth        = scopedParams.TryGetValue("depth", out object oDepth) ? (int)oDepth : 0;
            var childDepth   = scopedParams.TryGetValue("childDepth", out object oChildDepth) ? oChildDepth.ConvertTo <int>() : 1;

            scopedParams["depth"] = depth + 1;

            try
            {
                scopedParams.TryGetValue("className", out object parentClass);
                scopedParams.TryGetValue("childClass", out object childClass);
                var className = ((depth < childDepth ? parentClass : childClass ?? parentClass)
                                 ?? Context.Args[TemplateConstants.DefaultTableClassName]).ToString();

                scopedParams.TryGetValue("headerStyle", out object oHeaderStyle);
                scopedParams.TryGetValue("headerTag", out object oHeaderTag);
                scopedParams.TryGetValue("captionIfEmpty", out object captionIfEmpty);
                var headerTag   = oHeaderTag as string ?? "th";
                var headerStyle = oHeaderStyle as string ?? "splitCase";

                var           sbHeader = StringBuilderCache.Allocate();
                var           sbRows   = StringBuilderCacheAlt.Allocate();
                List <string> keys     = null;

                foreach (var item in items)
                {
                    if (item is IDictionary <string, object> d)
                    {
                        if (keys == null)
                        {
                            keys = d.Keys.ToList();
                            sbHeader.Append("<tr>");
                            foreach (var key in keys)
                            {
                                sbHeader.Append('<').Append(headerTag).Append('>');
                                sbHeader.Append(Context.DefaultFilters?.textStyle(key, headerStyle)?.HtmlEncode());
                                sbHeader.Append("</").Append(headerTag).Append('>');
                            }
                            sbHeader.Append("</tr>");
                        }

                        sbRows.Append("<tr>");
                        foreach (var key in keys)
                        {
                            var value = d[key];
                            if (value == target)
                            {
                                break;                  // Prevent cyclical deps like 'it' binding
                            }
                            sbRows.Append("<td>");

                            if (!isComplexType(value))
                            {
                                sbRows.Append(GetScalarHtml(value));
                            }
                            else
                            {
                                var htmlValue = htmlDump(scope, value, scopeOptions);
                                sbRows.Append(htmlValue.ToRawString());
                            }

                            sbRows.Append("</td>");
                        }
                        sbRows.Append("</tr>");
                    }
                }

                var isEmpty = sbRows.Length == 0;
                if (isEmpty && captionIfEmpty == null)
                {
                    return(RawString.Empty);
                }

                var htmlHeaders = StringBuilderCache.ReturnAndFree(sbHeader);
                var htmlRows    = StringBuilderCacheAlt.ReturnAndFree(sbRows);

                var sb = StringBuilderCache.Allocate();
                sb.Append("<table");

                if (scopedParams.TryGetValue("id", out object id))
                {
                    sb.Append(" id=\"").Append(id).Append("\"");
                }
                if (!string.IsNullOrEmpty(className))
                {
                    sb.Append(" class=\"").Append(className).Append("\"");
                }

                sb.Append(">");

                scopedParams.TryGetValue("caption", out object caption);
                if (isEmpty)
                {
                    caption = captionIfEmpty;
                }

                if (caption != null && !scopedParams.TryGetValue("hasCaption", out _))
                {
                    sb.Append("<caption>").Append(caption.ToString().HtmlEncode()).Append("</caption>");
                    scopedParams["hasCaption"] = true;
                }

                if (htmlHeaders.Length > 0)
                {
                    sb.Append("<thead>").Append(htmlHeaders).Append("</thead>");
                }
                if (htmlRows.Length > 0)
                {
                    sb.Append("<tbody>").Append(htmlRows).Append("</tbody>");
                }

                sb.Append("</table>");

                var html = StringBuilderCache.ReturnAndFree(sb);
                return(html.ToRawString());
            }
            finally
            {
                scopedParams["depth"] = depth;
            }
        }
        public IRawString htmlDump(TemplateScopeContext scope, object target, object scopeOptions)
        {
            var scopedParams = scope.AssertOptions(nameof(htmlDump), scopeOptions);
            var depth        = scopedParams.TryGetValue("depth", out object oDepth) ? (int)oDepth : 0;
            var childDepth   = scopedParams.TryGetValue("childDepth", out object oChildDepth) ? oChildDepth.ConvertTo <int>() : 1;

            scopedParams["depth"] = depth + 1;

            try
            {
                if (!isComplexType(target))
                {
                    return(GetScalarHtml(target).ToRawString());
                }

                scopedParams.TryGetValue("captionIfEmpty", out object captionIfEmpty);
                scopedParams.TryGetValue("headerStyle", out object oHeaderStyle);
                scopedParams.TryGetValue("className", out object parentClass);
                scopedParams.TryGetValue("childClass", out object childClass);
                var headerStyle = oHeaderStyle as string ?? "splitCase";
                var className   = ((depth < childDepth ? parentClass : childClass ?? parentClass)
                                   ?? Context.Args[TemplateConstants.DefaultTableClassName]).ToString();

                if (target is IEnumerable e)
                {
                    var objs = e.Map(x => x);

                    var isEmpty = objs.Count == 0;
                    if (isEmpty && captionIfEmpty == null)
                    {
                        return(RawString.Empty);
                    }

                    var first = !isEmpty ? objs[0] : null;
                    if (first is IDictionary)
                    {
                        return(htmlList(scope, target, scopeOptions));
                    }

                    var sb = StringBuilderCacheAlt.Allocate();

                    sb.Append("<table");

                    if (scopedParams.TryGetValue("id", out object id))
                    {
                        sb.Append(" id=\"").Append(id).Append("\"");
                    }

                    sb.Append(" class=\"").Append(className).Append("\"");

                    sb.Append(">");

                    scopedParams.TryGetValue("caption", out object caption);
                    if (isEmpty)
                    {
                        caption = captionIfEmpty;
                    }

                    if (caption != null && !scopedParams.TryGetValue("hasCaption", out _))
                    {
                        sb.Append("<caption>").Append(caption.ToString().HtmlEncode()).Append("</caption>");
                        scopedParams["hasCaption"] = true;
                    }

                    if (!isEmpty)
                    {
                        sb.Append("<tbody>");

                        if (first is KeyValuePair <string, object> )
                        {
                            foreach (var o in objs)
                            {
                                if (o is KeyValuePair <string, object> kvp)
                                {
                                    if (kvp.Value == target)
                                    {
                                        break;                      // Prevent cyclical deps like 'it' binding
                                    }
                                    sb.Append("<tr>");
                                    sb.Append("<th>");
                                    sb.Append(Context.DefaultFilters?.textStyle(kvp.Key, headerStyle)?.HtmlEncode());
                                    sb.Append("</th>");
                                    sb.Append("<td>");
                                    if (!isComplexType(kvp.Value))
                                    {
                                        sb.Append(GetScalarHtml(kvp.Value));
                                    }
                                    else
                                    {
                                        var body = htmlDump(scope, kvp.Value, scopeOptions);
                                        sb.Append(body.ToRawString());
                                    }
                                    sb.Append("</td>");
                                    sb.Append("</tr>");
                                }
                            }
                        }
                        else if (!isComplexType(first))
                        {
                            foreach (var o in objs)
                            {
                                sb.Append("<tr>");
                                sb.Append("<td>");
                                sb.Append(GetScalarHtml(o));
                                sb.Append("</td>");
                                sb.Append("</tr>");
                            }
                        }
                        else
                        {
                            if (objs.Count > 1)
                            {
                                var rows = objs.Map(x => x.ToObjectDictionary());
                                sb.Append("<tr>");
                                sb.Append("<td>");
                                var list = htmlList(scope, rows, scopeOptions);
                                sb.Append(list.ToRawString());
                                sb.Append("</td>");
                                sb.Append("</tr>");
                            }
                            else
                            {
                                foreach (var o in objs)
                                {
                                    sb.Append("<tr>");

                                    if (!isComplexType(o))
                                    {
                                        sb.Append("<td>");
                                        sb.Append(GetScalarHtml(o));
                                        sb.Append("</td>");
                                    }
                                    else
                                    {
                                        sb.Append("<td>");
                                        var body = htmlDump(scope, o, scopeOptions);
                                        sb.Append(body.ToRawString());
                                        sb.Append("</td>");
                                    }

                                    sb.Append("</tr>");
                                }
                            }
                        }

                        sb.Append("</tbody>");
                    }

                    sb.Append("</table>");

                    var html = StringBuilderCacheAlt.ReturnAndFree(sb);
                    return(html.ToRawString());
                }

                return(htmlDump(scope, target.ToObjectDictionary(), scopeOptions));
            }
            finally
            {
                scopedParams["depth"] = depth;
            }
        }
        private string AppendType(ref StringBuilderWrapper sb, MetadataType type, string lastNS,
                                  CreateTypeOptions options)
        {
            sb.AppendLine();
            AppendComments(sb, type.Description);
            if (type.Routes != null)
            {
                AppendAttributes(sb, type.Routes.ConvertAll(x => x.ToMetadataAttribute()));
            }
            AppendAttributes(sb, type.Attributes);
            AppendDataContract(sb, type.DataContract);

            PreTypeFilter?.Invoke(sb, type);

            if (type.IsEnum.GetValueOrDefault())
            {
                var enumType = Type(type.Name, type.GenericArgs);
                RegisterType(type, enumType);

                var isIntEnum = type.IsEnumInt.GetValueOrDefault() || type.EnumNames.IsEmpty();
                if (!isIntEnum)
                {
                    sb.AppendLine($"enum {enumType}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    foreach (var name in type.EnumNames.Safe())
                    {
                        sb.AppendLine($"{name},");
                    }
                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
                else
                {
                    sb.AppendLine($"class {enumType}");
                    sb.AppendLine("{");
                    sb = sb.Indent();

                    if (type.EnumNames != null)
                    {
                        for (var i = 0; i < type.EnumNames.Count; i++)
                        {
                            var name  = type.EnumNames[i];
                            var value = type.EnumValues?[i];

                            sb.AppendLine($"static const {enumType} {name} = const {enumType}._({value});");
                        }
                    }


                    sb.AppendLine();
                    sb.AppendLine("final int _value;");
                    sb.AppendLine($"const {enumType}._(this._value);");
                    sb.AppendLine($"int get value => _value;");

                    var enumNames = (type.EnumNames ?? TypeConstants.EmptyStringList).Join(",");
                    sb.AppendLine($"static List<{enumType}> get values => const [{enumNames}];");

                    sb = sb.UnIndent();
                    sb.AppendLine("}");
                }
            }
            else
            {
                var extends = new List <string>();

                //: BaseClass, Interfaces
                if (type.Inherits != null)
                {
                    extends.Add(Type(type.Inherits).InDeclarationType());
                }

                string responseTypeExpression = null;

                var interfaces = new List <string>();
                var implStr    = options.ImplementsFn?.Invoke();
                if (!string.IsNullOrEmpty(implStr))
                {
                    interfaces.Add(implStr);

                    if (implStr.StartsWith("IReturn<"))
                    {
                        var types      = implStr.RightPart('<');
                        var returnType = types.Substring(0, types.Length - 1);

                        if (returnType == "any")
                        {
                            returnType = "dynamic";
                        }

                        // This is to avoid invalid syntax such as "return new string()"
                        responseTypeExpression = defaultValues.TryGetValue(returnType, out var newReturnInstance)
                            ? $"createResponse() {{ return {newReturnInstance}; }}"
                            : $"createResponse() {{ return new {returnType}(); }}";
                    }
                    else if (implStr == "IReturnVoid")
                    {
                        responseTypeExpression = "createResponse() {}";
                    }
                }

                type.Implements.Each(x => interfaces.Add(Type(x)));

                var isClass         = type.IsInterface != true;
                var isAbstractClass = type.IsInterface == true || type.IsAbstract == true;
                var baseClass       = extends.Count > 0 ? extends[0] : null;
                var hasDtoBaseClass = baseClass != null;
                var hasListBase     = baseClass != null && baseClass.StartsWith("List<");
                if (hasListBase)
                {
                    baseClass       = "ListBase" + baseClass.Substring(4);
                    hasDtoBaseClass = false;
                }
                if (!isAbstractClass)
                {
                    interfaces.Add("IConvertible");
                }
                var extend = baseClass != null
                    ? " extends " + baseClass
                    : "";

                if (interfaces.Count > 0)
                {
                    if (isClass)
                    {
                        extend += " implements " + string.Join(", ", interfaces.ToArray());
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(extend))
                        {
                            extend = " extends ";
                        }
                        else
                        {
                            extend += ", ";
                        }

                        extend += string.Join(", ", interfaces.ToArray());
                    }
                }

                var typeDeclaration = !isAbstractClass ? "class" : "abstract class";

                var typeName = Type(type.Name, type.GenericArgs);

                RegisterType(type, typeName);

                sb.AppendLine($"{typeDeclaration} {typeName}{extend}");
                sb.AppendLine("{");

                sb = sb.Indent();

                var addVersionInfo = Config.AddImplicitVersion != null && options.IsRequest && !isAbstractClass;
                if (addVersionInfo)
                {
                    sb.AppendLine($"int {"Version".PropertyStyle()};");
                }

                if (type.Name == "IReturn`1")
                {
                    sb.AppendLine("T createResponse();");
                    sb.AppendLine("String getTypeName();");
                }
                else if (type.Name == "IReturnVoid")
                {
                    sb.AppendLine("void createResponse();");
                    sb.AppendLine("String getTypeName();");
                }

                AddProperties(sb, type,
                              includeResponseStatus: Config.AddResponseStatus && options.IsResponse &&
                              type.Properties.Safe().All(x => x.Name != typeof(ResponseStatus).Name));

                if (isClass)
                {
                    var typeNameWithoutGenericArgs = typeName.LeftPart('<');
                    var props = (type.Properties ?? TypeConstants <MetadataPropertyType> .EmptyList).ToList();

                    if (addVersionInfo)
                    {
                        props.Insert(0, new MetadataPropertyType {
                            Name          = "Version".PropertyStyle(),
                            Type          = "Int32",
                            TypeNamespace = "System",
                            IsValueType   = true,
                            Value         = Config.AddImplicitVersion.ToString()
                        });
                    }

                    if (props.Count > 0)
                    {
                        sb.AppendLine();
                    }

                    if (hasListBase)
                    {
                        var genericArg = baseClass.Substring(9, baseClass.Length - 10);
                        sb.AppendLine($"final List<{genericArg}> l = [];");
                        sb.AppendLine("void set length(int newLength) { l.length = newLength; }");
                        sb.AppendLine("int get length => l.length;");
                        sb.AppendLine($"{genericArg} operator [](int index) => l[index];");
                        sb.AppendLine($"void operator []=(int index, {genericArg} value) {{ l[index] = value; }}");
                    }

                    var sbBody = StringBuilderCacheAlt.Allocate();
                    if (props.Count > 0)
                    {
                        foreach (var prop in props)
                        {
                            if (sbBody.Length == 0)
                            {
                                sbBody.Append(typeNameWithoutGenericArgs + "({");
                            }
                            else
                            {
                                sbBody.Append(",");
                            }
                            sbBody.Append($"this.{prop.Name.PropertyStyle().PropertyName()}");
                            if (!string.IsNullOrEmpty(prop.Value))
                            {
                                sbBody.Append("=" + prop.Value);
                            }
                        }
                        if (sbBody.Length > 0)
                        {
                            sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody) + "});");
                        }
                    }
                    else
                    {
                        sb.AppendLine(typeNameWithoutGenericArgs + "();");
                    }

                    if (props.Count > 0)
                    {
                        sbBody = StringBuilderCacheAlt.Allocate();
                        sbBody.Append(typeNameWithoutGenericArgs + ".fromJson(Map<String, dynamic> json)");
                        sbBody.Append(" { fromMap(json); }");
                        sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));
                        sb.AppendLine();
                    }
                    else
                    {
                        sb.AppendLine(typeNameWithoutGenericArgs + ".fromJson(Map<String, dynamic> json) : " +
                                      (hasDtoBaseClass ? "super.fromJson(json);" : "super();"));
                    }

                    sbBody = StringBuilderCacheAlt.Allocate();
                    sbBody.AppendLine("fromMap(Map<String, dynamic> json) {");
                    if (hasDtoBaseClass)
                    {
                        sbBody.AppendLine("        super.fromMap(json);");
                    }
                    foreach (var prop in props)
                    {
                        var propType = DartPropertyType(prop);
                        var jsonName = prop.Name.PropertyStyle();
                        var propName = jsonName.PropertyName();
                        if (UseTypeConversion(prop))
                        {
                            bool registerType = true;
                            if (type.GenericArgs?.Length > 0 && prop.GenericArgs?.Length > 0)
                            {
                                var argIndexes = new List <int>();
                                foreach (var arg in prop.GenericArgs)
                                {
                                    var argIndex = Array.IndexOf(type.GenericArgs, arg);
                                    argIndexes.Add(argIndex);
                                }
                                if (argIndexes.All(x => x != -1))
                                {
                                    propType     = prop.Type.LeftPart('`') + "<${runtimeGenericTypeDefs(this,[" + argIndexes.Join(",") + "]).join(\",\")}>";
                                    registerType = false;
                                }
                            }

                            if (registerType)
                            {
                                RegisterPropertyType(prop, propType);
                            }

                            sbBody.AppendLine($"        {propName} = JsonConverters.fromJson(json['{jsonName}'],'{propType}',context);");
                        }
                        else
                        {
                            if (DartToJsonConverters.TryGetValue(propType, out var conversionFn))
                            {
                                sbBody.AppendLine($"        {propName} = JsonConverters.{conversionFn}(json['{jsonName}']);");
                            }
                            else
                            {
                                sbBody.AppendLine($"        {propName} = json['{jsonName}'];");
                            }
                        }
                    }
                    sbBody.AppendLine("        return this;");
                    sbBody.AppendLine("    }");
                    sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));

                    sbBody = StringBuilderCacheAlt.Allocate();
                    if (props.Count > 0)
                    {
                        foreach (var prop in props)
                        {
                            if (sbBody.Length == 0)
                            {
                                sbBody.Append("Map<String, dynamic> toJson() => ");
                                if (hasDtoBaseClass)
                                {
                                    sbBody.Append("super.toJson()..addAll(");
                                }

                                sbBody.AppendLine("{");
                            }
                            else
                            {
                                sbBody.AppendLine(",");
                            }

                            var propType = DartPropertyType(prop);
                            var jsonName = prop.Name.PropertyStyle();
                            var propName = jsonName.PropertyName();
                            if (UseTypeConversion(prop))
                            {
                                sbBody.Append($"        '{jsonName}': JsonConverters.toJson({propName},'{propType}',context)");
                            }
                            else
                            {
                                sbBody.Append($"        '{jsonName}': {propName}");
                            }
                        }
                        if (sbBody.Length > 0)
                        {
                            sb.AppendLine(StringBuilderCacheAlt.ReturnAndFree(sbBody));
                            sb.AppendLine(hasDtoBaseClass ? "});" : "};");
                            sb.AppendLine();
                        }
                    }
                    else
                    {
                        sb.AppendLine("Map<String, dynamic> toJson() => " +
                                      (hasDtoBaseClass ? "super.toJson();" : "{};"));
                    }

                    if (responseTypeExpression != null)
                    {
                        sb.AppendLine(responseTypeExpression);
                        sb.AppendLine($"String getTypeName() {{ return \"{type.Name}\"; }}");
                    }

                    if (isClass)
                    {
                        sb.AppendLine("TypeContext context = _ctx;");
                    }
                }

                sb = sb.UnIndent();
                sb.AppendLine("}");
            }

            PostTypeFilter?.Invoke(sb, type);

            return(lastNS);
        }
Exemple #21
0
        private static string CreateIcons(Operation op)
        {
            var sbIcons = StringBuilderCache.Allocate();

            if (op.RequiresAuthentication)
            {
                sbIcons.Append("<i class=\"auth\" title=\"");

                var hasRoles = op.RequiredRoles.Count + op.RequiresAnyRole.Count > 0;
                if (hasRoles)
                {
                    sbIcons.Append("Requires Roles:");
                    var sbRoles = StringBuilderCacheAlt.Allocate();
                    foreach (var role in op.RequiredRoles)
                    {
                        if (sbRoles.Length > 0)
                        {
                            sbRoles.Append(",");
                        }

                        sbRoles.Append(" " + role);
                    }

                    foreach (var role in op.RequiresAnyRole)
                    {
                        if (sbRoles.Length > 0)
                        {
                            sbRoles.Append(", ");
                        }

                        sbRoles.Append(" " + role + "?");
                    }
                    sbIcons.Append(StringBuilderCacheAlt.ReturnAndFree(sbRoles));
                }

                var hasPermissions = op.RequiredPermissions.Count + op.RequiresAnyPermission.Count > 0;
                if (hasPermissions)
                {
                    if (hasRoles)
                    {
                        sbIcons.Append(". ");
                    }

                    sbIcons.Append("Requires Permissions:");
                    var sbPermission = StringBuilderCacheAlt.Allocate();
                    foreach (var permission in op.RequiredPermissions)
                    {
                        if (sbPermission.Length > 0)
                        {
                            sbPermission.Append(",");
                        }

                        sbPermission.Append(" " + permission);
                    }

                    foreach (var permission in op.RequiresAnyPermission)
                    {
                        if (sbPermission.Length > 0)
                        {
                            sbPermission.Append(",");
                        }

                        sbPermission.Append(" " + permission + "?");
                    }
                    sbIcons.Append(StringBuilderCacheAlt.ReturnAndFree(sbPermission));
                }

                if (!hasRoles && !hasPermissions)
                {
                    sbIcons.Append("Requires Authentication");
                }

                sbIcons.Append("\"></i>");
            }

            var icons = sbIcons.Length > 0
                ? "<span class=\"icons\">" + StringBuilderCache.ReturnAndFree(sbIcons) + "</span>"
                : "";

            return(icons);
        }
Exemple #22
0
        public static string HtmlList(IEnumerable items, HtmlDumpOptions options)
        {
            if (options == null)
            {
                options = new HtmlDumpOptions();
            }

            if (items is IDictionary <string, object> single)
            {
                items = new[] { single }
            }
            ;

            var depth      = options.Depth;
            var childDepth = options.ChildDepth;

            options.Depth += 1;

            try
            {
                var parentClass = options.ClassName;
                var childClass  = options.ChildClass;
                var className   = ((depth < childDepth ? parentClass : childClass ?? parentClass)
                                   ?? options.Defaults.GetDefaultTableClassName());

                var headerStyle = options.HeaderStyle;
                var headerTag   = options.HeaderTag ?? "th";

                var           sbHeader = StringBuilderCache.Allocate();
                var           sbRows   = StringBuilderCacheAlt.Allocate();
                List <string> keys     = null;

                foreach (var item in items)
                {
                    if (item is IDictionary <string, object> d)
                    {
                        if (keys == null)
                        {
                            keys = options.Headers?.ToList() ?? EnumerableExtensions.AllKeysWithDefaultValues(items);
                            sbHeader.Append("<tr>");
                            foreach (var key in keys)
                            {
                                sbHeader.Append('<').Append(headerTag).Append('>');
                                sbHeader.Append(ViewUtils.StyleText(key, headerStyle)?.HtmlEncode());
                                sbHeader.Append("</").Append(headerTag).Append('>');
                            }
                            sbHeader.Append("</tr>");
                        }

                        sbRows.Append("<tr>");
                        foreach (var key in keys)
                        {
                            var value = d[key];
                            if (ReferenceEquals(value, items))
                            {
                                break; // Prevent cyclical deps like 'it' binding
                            }
                            sbRows.Append("<td>");

                            if (!isComplexType(value))
                            {
                                sbRows.Append(GetScalarHtml(value, options.Defaults));
                            }
                            else
                            {
                                var htmlValue = HtmlDump(value, options);
                                sbRows.Append(htmlValue.AsString());
                            }

                            sbRows.Append("</td>");
                        }
                        sbRows.Append("</tr>");
                    }
                }

                var isEmpty = sbRows.Length == 0;
                if (isEmpty && options.CaptionIfEmpty == null)
                {
                    return(string.Empty);
                }

                var htmlHeaders = StringBuilderCache.ReturnAndFree(sbHeader);
                var htmlRows    = StringBuilderCacheAlt.ReturnAndFree(sbRows);

                var sb = StringBuilderCache.Allocate();
                sb.Append("<table");

                if (options.Id != null)
                {
                    sb.Append(" id=\"").Append(options.Id).Append("\"");
                }
                if (!string.IsNullOrEmpty(className))
                {
                    sb.Append(" class=\"").Append(className).Append("\"");
                }

                sb.Append(">");

                var caption = options.Caption;
                if (isEmpty)
                {
                    caption = options.CaptionIfEmpty;
                }

                if (caption != null && !options.HasCaption)
                {
                    sb.Append("<caption>").Append(caption.HtmlEncode()).Append("</caption>");
                    options.HasCaption = true;
                }

                if (htmlHeaders.Length > 0)
                {
                    sb.Append("<thead>").Append(htmlHeaders).Append("</thead>");
                }
                if (htmlRows.Length > 0)
                {
                    sb.Append("<tbody>").Append(htmlRows).Append("</tbody>");
                }

                sb.Append("</table>");

                var html = StringBuilderCache.ReturnAndFree(sb);
                return(html);
            }
            finally
            {
                options.Depth = depth;
            }
        }
Exemple #23
0
        public override void PrepareParameterizedInsertStatement <T>(IDbCommand cmd, ICollection <string> insertFields = null)
        {
            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var modelDef           = OrmLiteUtils.GetModelDefinition(typeof(T));

            cmd.Parameters.Clear();
            cmd.CommandTimeout = OrmLiteConfig.CommandTimeout;

            var fieldDefs = GetInsertFieldDefinitions(modelDef, insertFields);

            foreach (var fieldDef in fieldDefs)
            {
                if (fieldDef.ReturnOnInsert || (fieldDef.IsPrimaryKey && fieldDef.AutoIncrement && HasInsertReturnValues(modelDef)))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append(GetQuotedColumnName(fieldDef.FieldName));
                }

                if (fieldDef.ShouldSkipInsert() && !fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));

                    if (fieldDef.AutoIncrement || !string.IsNullOrEmpty(fieldDef.Sequence))
                    {
                        EnsureAutoIncrementSequence(modelDef, fieldDef);
                        sbColumnValues.Append("NEXT VALUE FOR " + fieldDef.Sequence);
                    }
                    else
                    {
                        sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));
                        AddParameter(cmd, fieldDef);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in PrepareParameterizedInsertStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            cmd.CommandText = string.Format("INSERT INTO {0} ({1}) VALUES ({2}) {3}",
                                            GetQuotedTableName(modelDef),
                                            StringBuilderCache.ReturnAndFree(sbColumnNames),
                                            StringBuilderCacheAlt.ReturnAndFree(sbColumnValues),
                                            strReturning.Length > 0 ? "RETURNING " + strReturning : "");
        }
Exemple #24
0
        public static string TextDump(object target, TextDumpOptions options)
        {
            if (options == null)
            {
                options = new TextDumpOptions();
            }

            var depth = options.Depth;

            options.Depth += 1;

            try
            {
                if (!isComplexType(target))
                {
                    return(GetScalarText(target, options.Defaults));
                }

                var headerStyle = options.HeaderStyle;

                if (target is IEnumerable e)
                {
                    var objs = e.Map(x => x);

                    var isEmpty = objs.Count == 0;
                    if (isEmpty)
                    {
                        return(options.CaptionIfEmpty ?? string.Empty);
                    }

                    var first = objs[0];
                    if (first is IDictionary && objs.Count > 1)
                    {
                        return(TextList(objs, options));
                    }

                    var sb = StringBuilderCacheAlt.Allocate();

                    string writeCaption = null;
                    var    caption      = options.Caption;
                    if (caption != null && !options.HasCaption)
                    {
                        writeCaption       = caption;
                        options.HasCaption = true;
                    }

                    if (!isEmpty)
                    {
                        var keys   = new List <string>();
                        var values = new List <string>();

                        string TextKvps(StringBuilder s, IEnumerable <KeyValuePair <string, object> > kvps)
                        {
                            foreach (var kvp in kvps)
                            {
                                if (kvp.Value == target)
                                {
                                    break; // Prevent cyclical deps like 'it' binding
                                }
                                keys.Add(ViewUtils.StyleText(kvp.Key, headerStyle) ?? "");

                                var field = !isComplexType(kvp.Value)
                                    ? GetScalarText(kvp.Value, options.Defaults)
                                    : TextDump(kvp.Value, options);

                                values.Add(field);
                            }

                            var keySize    = keys.Max(x => x.Length);
                            var valuesSize = values.Max(x => x.Length);

                            s.AppendLine(writeCaption != null
                                ? $"| {writeCaption.PadRight(keySize + valuesSize + 2, ' ')} ||"
                                : $"|||");
                            s.AppendLine(writeCaption != null
                                ? $"|-{"".PadRight(keySize, '-')}-|-{"".PadRight(valuesSize, '-')}-|"
                                : "|-|-|");

                            for (var i = 0; i < keys.Count; i++)
                            {
                                s.Append("| ")
                                .Append(keys[i].PadRight(keySize, ' '))
                                .Append(" | ")
                                .Append(values[i].PadRight(valuesSize, ' '))
                                .Append(" |")
                                .AppendLine();
                            }

                            return(StringBuilderCache.ReturnAndFree(s));
                        }

                        if (first is KeyValuePair <string, object> )
                        {
                            return(TextKvps(sb, objs.Cast <KeyValuePair <string, object> >()));
                        }
                        else
                        {
                            if (!isComplexType(first))
                            {
                                foreach (var o in objs)
                                {
                                    values.Add(GetScalarText(o, options.Defaults));
                                }

                                var valuesSize = values.Max(MaxLineLength);
                                if (writeCaption?.Length > valuesSize)
                                {
                                    valuesSize = writeCaption.Length;
                                }

                                sb.AppendLine(writeCaption != null
                                    ? $"| {writeCaption.PadRight(valuesSize)} |"
                                    : $"||");
                                sb.AppendLine(writeCaption != null
                                    ? $"|-{"".PadRight(valuesSize,'-')}-|"
                                    : "|-|");

                                foreach (var value in values)
                                {
                                    sb.Append("| ")
                                    .Append(value.PadRight(valuesSize, ' '))
                                    .Append(" |")
                                    .AppendLine();
                                }
                            }
                            else
                            {
                                if (objs.Count > 1)
                                {
                                    if (writeCaption != null)
                                    {
                                        sb.AppendLine(writeCaption)
                                        .AppendLine();
                                    }

                                    var rows = objs.Map(x => x.ToObjectDictionary());
                                    var list = TextList(rows, options);
                                    sb.AppendLine(list);
                                    return(StringBuilderCache.ReturnAndFree(sb));
                                }
                                else
                                {
                                    foreach (var o in objs)
                                    {
                                        if (!isComplexType(o))
                                        {
                                            values.Add(GetScalarText(o, options.Defaults));
                                        }
                                        else
                                        {
                                            var body = TextDump(o, options);
                                            values.Add(body);
                                        }
                                    }

                                    var valuesSize = values.Max(MaxLineLength);
                                    if (writeCaption?.Length > valuesSize)
                                    {
                                        valuesSize = writeCaption.Length;
                                    }

                                    sb.AppendLine(writeCaption != null
                                        ? $"| {writeCaption.PadRight(valuesSize, ' ')} |"
                                        : $"||");
                                    sb.AppendLine(writeCaption != null ? $"|-{"".PadRight(valuesSize,'-')}-|" : "|-|");

                                    foreach (var value in values)
                                    {
                                        sb.Append("| ")
                                        .Append(value.PadRight(valuesSize, ' '))
                                        .Append(" |")
                                        .AppendLine();
                                    }
                                }
                            }
                        }
                    }

                    return(StringBuilderCache.ReturnAndFree(sb));
                }

                return(TextDump(target.ToObjectDictionary(), options));
            }
            finally
            {
                options.Depth = depth;
            }
        }
Exemple #25
0
        public override string ToExistStatement(Type fromTableType,
                                                object objWithProperties,
                                                string sqlFilter,
                                                params object[] filterParams)
        {
            var fromModelDef = GetModel(fromTableType);
            var sql          = StringBuilderCache.Allocate();

            sql.AppendFormat("SELECT 1 \nFROM {0}", GetQuotedTableName(fromModelDef));

            var filter    = StringBuilderCacheAlt.Allocate();
            var hasFilter = false;

            if (objWithProperties != null)
            {
                var tableType = objWithProperties.GetType();

                if (fromTableType != tableType)
                {
                    int i        = 0;
                    var fpk      = new List <FieldDefinition>();
                    var modelDef = GetModel(tableType);

                    foreach (var def in modelDef.FieldDefinitions)
                    {
                        if (def.IsPrimaryKey)
                        {
                            fpk.Add(def);
                        }
                    }

                    foreach (var fieldDef in fromModelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed)
                        {
                            continue;
                        }

                        if (fieldDef.ForeignKey != null &&
                            GetModel(fieldDef.ForeignKey.ReferenceType).ModelName == modelDef.ModelName)
                        {
                            if (filter.Length > 0)
                            {
                                filter.Append(" AND ");
                            }

                            filter.AppendFormat("{0} = {1}", GetQuotedColumnName(fieldDef.FieldName),
                                                fpk[i].GetQuotedValue(objWithProperties));
                            i++;
                        }
                    }
                }
                else
                {
                    var modelDef = GetModel(tableType);
                    foreach (var fieldDef in modelDef.FieldDefinitions)
                    {
                        if (fieldDef.IsComputed)
                        {
                            continue;
                        }

                        if (fieldDef.IsPrimaryKey)
                        {
                            if (filter.Length > 0)
                            {
                                filter.Append(" AND ");
                            }
                            filter.AppendFormat("{0} = {1}",
                                                GetQuotedColumnName(fieldDef.FieldName),
                                                fieldDef.GetQuotedValue(objWithProperties));
                        }
                    }
                }

                hasFilter = filter.Length > 0;
                if (hasFilter)
                {
                    sql.AppendFormat("\nWHERE {0} ", StringBuilderCacheAlt.ReturnAndFree(filter));
                }
            }

            if (!string.IsNullOrEmpty(sqlFilter))
            {
                sqlFilter = sqlFilter.SqlFmt(filterParams);
                if (!sqlFilter.StartsWith("\nORDER ", StringComparison.OrdinalIgnoreCase) &&
                    !sqlFilter.StartsWith("\nROWS ", StringComparison.OrdinalIgnoreCase))    // ROWS <m> [TO <n>])
                {
                    sql.Append(hasFilter ? " AND  " : "\nWHERE ");
                }
                sql.Append(sqlFilter);
            }

            var sb = StringBuilderCacheAlt.Allocate()
                     .Append("select 1 from RDB$DATABASE where")
                     .AppendFormat(" exists ({0})", StringBuilderCache.ReturnAndFree(sql));

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
Exemple #26
0
        internal string MakeID(string str, int start, int len)
        {
            // Parse the string into a list of tokens
            Tokenize(str, start, len);

            var sb = StringBuilderCacheAlt.Allocate();

            foreach (var t in m_Tokens)
            {
                switch (t.type)
                {
                case TokenType.Text:
                    sb.Append(str, t.startOffset, t.length);
                    break;

                case TokenType.link:
                    LinkInfo li = (LinkInfo)t.data;
                    sb.Append(li.link_text);
                    break;
                }

                FreeToken(t);
            }

            // Now clean it using the same rules as pandoc
            base.Reset(sb.ToString());

            // Skip everything up to the first letter
            while (!eof)
            {
                if (Char.IsLetter(current))
                {
                    break;
                }
                SkipForward(1);
            }

            // Process all characters
            sb.Length = 0;
            while (!eof)
            {
                char ch = current;
                if (char.IsLetterOrDigit(ch) || ch == '_' || ch == '-' || ch == '.')
                {
                    sb.Append(Char.ToLower(ch));
                }
                else if (ch == ' ')
                {
                    sb.Append("-");
                }
                else if (IsLineEnd(ch))
                {
                    sb.Append("-");
                    SkipEol();
                    continue;
                }

                SkipForward(1);
            }

            return(StringBuilderCacheAlt.ReturnAndFree(sb));
        }
Exemple #27
0
    /// <summary>
    /// Run a Process asynchronously, returning  entire captured process output, whilst streaming stdOut, stdErr callbacks
    /// </summary>
    /// <param name="startInfo">The start information.</param>
    /// <param name="timeoutMs">The timeout ms.</param>
    /// <param name="onOut">The on out.</param>
    /// <param name="onError">The on error.</param>
    /// <returns>A Task&lt;ProcessResult&gt; representing the asynchronous operation.</returns>
    public static async Task <ProcessResult> RunAsync(ProcessStartInfo startInfo, int?timeoutMs = null,
                                                      Action <string> onOut = null, Action <string> onError = null)
    {
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError  = true;

        using var process = new Process
              {
                  StartInfo           = startInfo,
                  EnableRaisingEvents = true,
              };

        // List of tasks to wait for a whole process exit
        var processTasks = new List <Task>();

        // === EXITED Event handling ===
        var processExitEvent = new TaskCompletionSource <object>();

        process.Exited += (sender, args) =>
        {
            processExitEvent.TrySetResult(true);
        };
        processTasks.Add(processExitEvent.Task);

        long callbackTicks = 0;

        // === STDOUT handling ===
        var stdOutBuilder    = StringBuilderCache.Allocate();
        var stdOutCloseEvent = new TaskCompletionSource <bool>();

        process.OutputDataReceived += (s, e) =>
        {
            if (e.Data == null)
            {
                stdOutCloseEvent.TrySetResult(true);
            }
            else
            {
                stdOutBuilder.AppendLine(e.Data);
                if (onOut != null)
                {
                    var swCallback = Stopwatch.StartNew();
                    onOut(e.Data);
                    callbackTicks += swCallback.ElapsedTicks;
                }
            }
        };

        processTasks.Add(stdOutCloseEvent.Task);

        // === STDERR handling ===
        var stdErrBuilder    = StringBuilderCacheAlt.Allocate();
        var stdErrCloseEvent = new TaskCompletionSource <bool>();

        process.ErrorDataReceived += (s, e) =>
        {
            if (e.Data == null)
            {
                stdErrCloseEvent.TrySetResult(true);
            }
            else
            {
                stdErrBuilder.AppendLine(e.Data);
                if (onError != null)
                {
                    var swCallback = Stopwatch.StartNew();
                    onError(e.Data);
                    callbackTicks += swCallback.ElapsedTicks;
                }
            }
        };

        processTasks.Add(stdErrCloseEvent.Task);

        // === START OF PROCESS ===
        var sw     = Stopwatch.StartNew();
        var result = new ProcessResult
        {
            StartAt = DateTime.UtcNow,
        };

        if (!process.Start())
        {
            result.ExitCode = process.ExitCode;
            return(result);
        }

        // Reads the output stream first as needed and then waits because deadlocks are possible
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();
        // === ASYNC WAIT OF PROCESS ===

        // Process completion = exit AND stdout (if defined) AND stderr (if defined)
        var processCompletionTask = Task.WhenAll(processTasks);

        // Task to wait for exit OR timeout (if defined)
        var awaitingTask = timeoutMs.HasValue
                               ? Task.WhenAny(Task.Delay(timeoutMs.Value), processCompletionTask)
                               : Task.WhenAny(processCompletionTask);

        // Let's now wait for something to end...
        if (await awaitingTask.ConfigureAwait(false) == processCompletionTask)
        {
            // -> Process exited cleanly
            result.ExitCode = process.ExitCode;
        }
        else
        {
            // -> Timeout, let's kill the process
            try
            {
                process.Kill();
            }
            catch
            {
                // ignored
            }
        }

        // Read stdout/stderr
        result.EndAt = DateTime.UtcNow;
        if (callbackTicks > 0)
        {
            var callbackMs = callbackTicks / Stopwatch.Frequency * 1000;
            result.CallbackDurationMs = callbackMs;
            result.DurationMs         = sw.ElapsedMilliseconds - callbackMs;
        }
        else
        {
            result.DurationMs = sw.ElapsedMilliseconds;
        }
        result.StdOut = StringBuilderCache.ReturnAndFree(stdOutBuilder);
        result.StdErr = StringBuilderCacheAlt.ReturnAndFree(stdErrBuilder);

        return(result);
    }
Exemple #28
0
        public override string ToInsertRowStatement(IDbCommand cmd, object objWithProperties, ICollection <string> insertFields = null)
        {
            if (insertFields == null)
            {
                insertFields = new List <string>();
            }

            var sbColumnNames      = StringBuilderCache.Allocate();
            var sbColumnValues     = StringBuilderCacheAlt.Allocate();
            var sbReturningColumns = StringBuilderCacheAlt.Allocate();
            var tableType          = objWithProperties.GetType();
            var modelDef           = GetModel(tableType);

            foreach (var fieldDef in modelDef.FieldDefinitionsArray)
            {
                if (ShouldReturnOnInsert(modelDef, fieldDef))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef))
                {
                    continue;
                }

                if (insertFields.Count > 0 && !insertFields.Contains(fieldDef.Name, StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (sbColumnNames.Length > 0)
                {
                    sbColumnNames.Append(",");
                }
                if (sbColumnValues.Length > 0)
                {
                    sbColumnValues.Append(",");
                }

                try
                {
                    sbColumnNames.Append(GetQuotedColumnName(fieldDef.FieldName));
                    sbColumnValues.Append(this.GetParam(SanitizeFieldNameForParamName(fieldDef.FieldName)));

                    var p = AddParameter(cmd, fieldDef);
                    p.Value = fieldDef.GetValue(objWithProperties) ?? DBNull.Value;
                }
                catch (Exception ex)
                {
                    Log.Error("ERROR in ToInsertRowStatement(): " + ex.Message, ex);
                    throw;
                }
            }

            var strReturning = StringBuilderCacheAlt.ReturnAndFree(sbReturningColumns);

            strReturning = strReturning.Length > 0 ? "OUTPUT " + strReturning + " " : "";
            var sql = $"INSERT INTO {GetQuotedTableName(modelDef)} ({StringBuilderCache.ReturnAndFree(sbColumnNames)}) " +
                      strReturning +
                      $"VALUES ({StringBuilderCacheAlt.ReturnAndFree(sbColumnValues)})";

            return(sql);
        }
Exemple #29
0
        public override string ToCreateTableStatement(Type tableType)
        {
            var sbColumns      = StringBuilderCache.Allocate();
            var sbConstraints  = StringBuilderCacheAlt.Allocate();
            var sbTableOptions = StringBuilderCacheAlt.Allocate();

            var fileTableAttrib = tableType.FirstAttribute <SqlServerFileTableAttribute>();

            var modelDef = GetModel(tableType);

            if (fileTableAttrib == null)
            {
                foreach (var fieldDef in modelDef.FieldDefinitions)
                {
                    if (fieldDef.CustomSelect != null)
                    {
                        continue;
                    }

                    var columnDefinition = GetColumnDefinition(fieldDef);

                    if (columnDefinition == null)
                    {
                        continue;
                    }

                    if (sbColumns.Length != 0)
                    {
                        sbColumns.Append(", \n  ");
                    }

                    sbColumns.Append(columnDefinition);

                    if (fieldDef.ForeignKey == null || OrmLiteConfig.SkipForeignKeys)
                    {
                        continue;
                    }

                    var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);
                    sbConstraints.Append(
                        $", \n\n  CONSTRAINT {GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef))} " +
                        $"FOREIGN KEY ({GetQuotedColumnName(fieldDef.FieldName)}) " +
                        $"REFERENCES {GetQuotedTableName(refModelDef)} ({GetQuotedColumnName(refModelDef.PrimaryKey.FieldName)})");

                    sbConstraints.Append(GetForeignKeyOnDeleteClause(fieldDef.ForeignKey));
                    sbConstraints.Append(GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
                }
            }
            else
            {
                if (fileTableAttrib.FileTableDirectory != null || fileTableAttrib.FileTableCollateFileName != null)
                {
                    sbTableOptions.Append(" WITH (");

                    if (fileTableAttrib.FileTableDirectory != null)
                    {
                        sbTableOptions.Append($" FILETABLE_DIRECTORY = N'{fileTableAttrib.FileTableDirectory}'\n");
                    }

                    if (fileTableAttrib.FileTableCollateFileName != null)
                    {
                        if (fileTableAttrib.FileTableDirectory != null)
                        {
                            sbTableOptions.Append(" ,");
                        }

                        sbTableOptions.Append($" FILETABLE_COLLATE_FILENAME = {fileTableAttrib.FileTableCollateFileName ?? "database_default" }\n");
                    }
                    sbTableOptions.Append(")");
                }
            }

            var sql = $"CREATE TABLE {GetQuotedTableName(modelDef)} ";

            sql += (fileTableAttrib != null)
                ? $"\n AS FILETABLE{StringBuilderCache.ReturnAndFree(sbTableOptions)};"
                : $"\n(\n  {StringBuilderCache.ReturnAndFree(sbColumns)}{StringBuilderCacheAlt.ReturnAndFree(sbConstraints)} \n){StringBuilderCache.ReturnAndFree(sbTableOptions)}; \n";

            return(sql);
        }
        public override string ToCreateTableStatement(Type tableType)
        {
            var sbColumns     = StringBuilderCache.Allocate();
            var sbConstraints = StringBuilderCacheAlt.Allocate();

            var sbPk = new StringBuilder();

            var modelDef = GetModel(tableType);

            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
                if (fieldDef.IsPrimaryKey)
                {
                    sbPk.AppendFormat(sbPk.Length != 0 ? ",{0}" : "{0}", GetQuotedColumnName(fieldDef.FieldName));
                }

                if (sbColumns.Length != 0)
                {
                    sbColumns.Append(", \n  ");
                }

                var columnDefinition = GetColumnDefinition(
                    fieldDef.FieldName,
                    fieldDef.ColumnType,
                    fieldDef.IsPrimaryKey,
                    fieldDef.AutoIncrement,
                    fieldDef.IsNullable,
                    fieldDef.IsRowVersion,
                    fieldDef.FieldLength,
                    fieldDef.Scale,
                    GetDefaultValue(fieldDef),
                    fieldDef.CustomFieldDefinition);

                sbColumns.Append(columnDefinition);

                if (fieldDef.ForeignKey == null)
                {
                    continue;
                }

                var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);

                var fkName = NamingStrategy.ApplyNameRestrictions(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef)).ToLower();
                sbConstraints.AppendFormat(", \n\n  CONSTRAINT {0} FOREIGN KEY ({1}) REFERENCES {2} ({3})",
                                           GetQuotedName(fkName),
                                           GetQuotedColumnName(fieldDef.FieldName),
                                           GetQuotedTableName(refModelDef),
                                           GetQuotedColumnName(refModelDef.PrimaryKey.FieldName));

                sbConstraints.Append(GetForeignKeyOnDeleteClause(fieldDef.ForeignKey));
                sbConstraints.Append(GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
            }

            if (sbPk.Length != 0)
            {
                sbColumns.AppendFormat(", \n  PRIMARY KEY({0})", sbPk);
            }

            var sql = string.Format(
                "CREATE TABLE {0} \n(\n  {1}{2} \n); \n",
                GetQuotedTableName(modelDef),
                StringBuilderCache.ReturnAndFree(sbColumns),
                StringBuilderCacheAlt.ReturnAndFree(sbConstraints));

            return(sql);
        }