Example #1
0
        private static async Task <(string errorMessage, JsonValue value)> _TryParseInterpretedStringAsync(StringBuilder builder, TextReader stream, char[] scratch)
        {
            // NOTE: `builder` contains the portion of the string found in `stream`, up to the first
            //       (possible) escape sequence.
            System.Diagnostics.Debug.Assert('\\' == (char)stream.Peek());
            System.Diagnostics.Debug.Assert(scratch.Length >= 4);

            bool complete = false;

            int?previousHex = null;

            while (stream.Peek() != -1)
            {
                await stream.TryRead(scratch, 0, 1);                 // eat this character

                var c = scratch[0];
                if (c == '\\')
                {
                    if (stream.Peek() == -1)
                    {
                        StringBuilderCache.Release(builder);
                        SmallBufferCache.Release(scratch);
                        return("Could not find end of string value.", null);
                    }

                    // escape sequence
                    var lookAhead = (char)stream.Peek();
                    if (!_MustInterpretComplex(lookAhead))
                    {
                        await stream.TryRead(scratch, 0, 1);                         // eat the simple escape

                        c = _InterpretSimpleEscapeSequence(lookAhead);
                    }
                    else
                    {
                        // NOTE: Currently we only handle 'u' here
                        if (lookAhead != 'u')
                        {
                            StringBuilderCache.Release(builder);
                            SmallBufferCache.Release(scratch);
                            return($"Invalid escape sequence: '\\{lookAhead}'.", null);
                        }

                        await stream.TryRead(scratch, 0, 1);                         // eat the 'u'

                        var charsRead = await stream.ReadAsync(scratch, 0, 4);

                        if (charsRead < 4)
                        {
                            StringBuilderCache.Release(builder);
                            SmallBufferCache.Release(scratch);
                            return("Could not find end of string value.", null);
                        }

                        var hexString  = new string(scratch, 0, 4);
                        var currentHex = int.Parse(hexString, NumberStyles.HexNumber);

                        if (previousHex != null)
                        {
                            // Our last character was \u, so combine and emit the UTF32 codepoint
                            currentHex = StringExtensions.CalculateUtf32(previousHex.Value, currentHex);
                            if (currentHex.IsValidUtf32CodePoint())
                            {
                                builder.Append(char.ConvertFromUtf32(currentHex));
                            }
                            else
                            {
                                return("Invalid UTF-32 code point.", null);
                            }
                            previousHex = null;
                        }
                        else
                        {
                            previousHex = currentHex;
                        }

                        continue;
                    }
                }
                else if (c == '"')
                {
                    complete = true;
                    break;
                }

                // Check if last character was \u, and if so emit it as-is, because
                // this character is not a continuation of a UTF-32 escape sequence
                if (previousHex != null)
                {
                    builder.Append(char.ConvertFromUtf32(previousHex.Value));
                    previousHex = null;
                }

                // non-escape sequence
                builder.Append(c);
            }

            SmallBufferCache.Release(scratch);

            // if we had a hanging UTF32 escape sequence, apply it now
            if (previousHex != null)
            {
                builder.Append(char.ConvertFromUtf32(previousHex.Value));
            }

            if (!complete)
            {
                StringBuilderCache.Release(builder);
                return("Could not find end of string value.", null);
            }

            JsonValue value = StringBuilderCache.GetStringAndRelease(builder);

            return(null, value);
        }
Example #2
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 = GetFieldValue(fieldDef, 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);
        }
Example #3
0
        public override string ToSelectStatement(ModelDefinition modelDef,
                                                 string selectExpression,
                                                 string bodyExpression,
                                                 string orderByExpression = null,
                                                 int?offset = null,
                                                 int?rows   = null)
        {
            var sb = StringBuilderCache.Allocate()
                     .Append(selectExpression)
                     .Append(bodyExpression);

            if (!offset.HasValue && !rows.HasValue)
            {
                return(StringBuilderCache.ReturnAndFree(sb) + orderByExpression);
            }

            if (offset.HasValue && offset.Value < 0)
            {
                throw new ArgumentException($"Skip value:'{offset.Value}' must be>=0");
            }

            if (rows.HasValue && rows.Value < 0)
            {
                throw new ArgumentException($"Rows value:'{rows.Value}' must be>=0");
            }

            var skip = offset ?? 0;
            var take = rows ?? int.MaxValue;

            var selectType = selectExpression.StartsWithIgnoreCase("SELECT DISTINCT") ? "SELECT DISTINCT" : "SELECT";

            //Temporary hack till we come up with a more robust paging sln for SqlServer
            if (skip == 0)
            {
                var sql = StringBuilderCache.ReturnAndFree(sb) + orderByExpression;

                if (take == int.MaxValue)
                {
                    return(sql);
                }

                if (sql.Length < "SELECT".Length)
                {
                    return(sql);
                }

                return($"{selectType} TOP {take + sql.Substring(selectType.Length)}");
            }

            // Required because ordering is done by Windowing function
            if (string.IsNullOrEmpty(orderByExpression))
            {
                if (modelDef.PrimaryKey == null)
                {
                    throw new ApplicationException("Malformed model, no PrimaryKey defined");
                }

                orderByExpression = $"ORDER BY {this.GetQuotedColumnName(modelDef, modelDef.PrimaryKey)}";
            }

            var row = take == int.MaxValue ? take : skip + take;

            var ret = $"SELECT * FROM (SELECT {selectExpression.Substring(selectType.Length)}, ROW_NUMBER() OVER ({orderByExpression}) As RowNum {bodyExpression}) AS RowConstrainedResult WHERE RowNum > {skip} AND RowNum <= {row}";

            return(ret);
        }
Example #4
0
        protected override void Render(HtmlTextWriter output)
        {
            var operationsPart = new TableTemplate
            {
                Title       = "Operations",
                Items       = this.OperationNames,
                ForEachItem = RenderRow
            }.ToString();

#if !NETSTANDARD2_0
            var xsdsPart = new ListTemplate
            {
                Title            = "XSDS:",
                ListItemsIntMap  = this.Xsds,
                ListItemTemplate = @"<li><a href=""?xsd={0}"">{1}</a></li>"
            }.ToString();
#else
            var xsdsPart = "";
#endif

            var wsdlTemplate = StringBuilderCache.Allocate();
            var soap11Config = MetadataConfig.GetMetadataConfig("soap11") as SoapMetadataConfig;
            var soap12Config = MetadataConfig.GetMetadataConfig("soap12") as SoapMetadataConfig;
            if (soap11Config != null || soap12Config != null)
            {
                wsdlTemplate.AppendLine("<h3>WSDLS:</h3>");
                wsdlTemplate.AppendLine("<ul>");
                if (soap11Config != null)
                {
                    wsdlTemplate.AppendFormat(
                        @"<li><a href=""{0}"">{0}</a></li>",
                        soap11Config.WsdlMetadataUri);
                }
                if (soap12Config != null)
                {
                    wsdlTemplate.AppendFormat(
                        @"<li><a href=""{0}"">{0}</a></li>",
                        soap12Config.WsdlMetadataUri);
                }
                wsdlTemplate.AppendLine("</ul>");
            }

            var metadata    = HostContext.GetPlugin <MetadataFeature>();
            var pluginLinks = metadata != null && metadata.PluginLinks.Count > 0
                ? new ListTemplate
            {
                Title            = metadata.PluginLinksTitle,
                ListItemsMap     = ToAbsoluteUrls(metadata.PluginLinks),
                ListItemTemplate = @"<li><a href=""{0}"">{1}</a></li>"
            }.ToString()
                : "";

            var debugOnlyInfo = HostContext.DebugMode && metadata != null && metadata.DebugLinks.Count > 0
                ? new ListTemplate
            {
                Title            = metadata.DebugLinksTitle,
                ListItemsMap     = ToAbsoluteUrls(metadata.DebugLinks),
                ListItemTemplate = @"<li><a href=""{0}"">{1}</a></li>"
            }.ToString()
                : "";

            var errorCount    = HostContext.AppHost.StartUpErrors.Count;
            var plural        = errorCount > 1 ? "s" : "";
            var startupErrors = HostContext.DebugMode && errorCount > 0
                ? $"<div class='error-popup'><a href='?debug=requestinfo'>Review {errorCount} Error{plural} on Startup</a></div>"
                : "";

            var renderedTemplate = HtmlTemplates.Format(
                HtmlTemplates.GetIndexOperationsTemplate(),
                this.Title,
                this.XsdServiceTypesIndex,
                operationsPart,
                xsdsPart,
                StringBuilderCache.ReturnAndFree(wsdlTemplate),
                pluginLinks,
                debugOnlyInfo,
                Env.VersionString,
                startupErrors);

            output.Write(renderedTemplate);
        }
Example #5
0
 public StringBuilder Get()
 {
     return(StringBuilderCache.Acquire());
 }
Example #6
0
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var typeNamespaces = new HashSet <string>();

            RemoveIgnoredTypes(metadata);
            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            var defaultImports = !Config.DefaultImports.IsEmpty()
                ? Config.DefaultImports
                : DefaultImports;

            Func <string, string> defaultValue = k =>
                                                 request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sbInner = StringBuilderCache.Allocate();
            var sb      = new StringBuilderWrapper(sbInner);
            var sbExt   = new StringBuilderWrapper(new StringBuilder());

            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("SwiftVersion: 3.0");
            sb.AppendLine("Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();

            sb.AppendLine("{0}BaseClass: {1}".Fmt(defaultValue("BaseClass"), Config.BaseClass));
            sb.AppendLine("{0}AddModelExtensions: {1}".Fmt(defaultValue("AddModelExtensions"), Config.AddModelExtensions));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeGenericBaseTypes: {1}".Fmt(defaultValue("ExcludeGenericBaseTypes"), Config.ExcludeGenericBaseTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(defaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}TreatTypesAsStrings: {1}".Fmt(defaultValue("TreatTypesAsStrings"), Config.TreatTypesAsStrings.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(",")));

            sb.AppendLine("*/");
            sb.AppendLine();

            foreach (var typeName in Config.TreatTypesAsStrings.Safe())
            {
                TypeAliases[typeName] = "String";
            }

            string lastNS = null;

            var existingTypes = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            allTypes = new List <MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);

            allTypes = FilterTypes(allTypes);

            //Swift doesn't support reusing same type name with different generic airity
            var conflictPartialNames = allTypes.Map(x => x.Name).Distinct()
                                       .GroupBy(g => g.LeftPart('`'))
                                       .Where(g => g.Count() > 1)
                                       .Select(g => g.Key)
                                       .ToList();

            this.conflictTypeNames = allTypes
                                     .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                                     .Map(x => x.Name);

            defaultImports.Each(x => sb.AppendLine("import {0};".Fmt(x)));

            //ServiceStack core interfaces
            foreach (var type in allTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType          response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                                            new CreateTypeOptions
                        {
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    !type.ReturnVoidMarker &&
                                    type.ReturnMarkerTypeName == null)
                                {
                                    return(null);
                                }

                                if (type.ReturnVoidMarker)
                                {
                                    return("IReturnVoid");
                                }
                                if (type.ReturnMarkerTypeName != null)
                                {
                                    return(ReturnType("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) }));
                                }
                                return(response != null
                                        ? ReturnType("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null);
                            },
                            IsRequest = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                                            new CreateTypeOptions
                        {
                            IsResponse = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                                        new CreateTypeOptions {
                        IsType = true
                    });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (Config.AddModelExtensions)
            {
                sb.AppendLine();
                sb.AppendLine(sbExt.ToString());
            }

            return(StringBuilderCache.ReturnAndFree(sbInner));
        }
Example #7
0
        private static string NormalizeDatePattern(string input)
        {
            StringBuilder destination = StringBuilderCache.Acquire(input.Length);

            int index = 0;

            while (index < input.Length)
            {
                switch (input[index])
                {
                case '\'':
                    // single quotes escape characters, like 'de' in es-SP
                    // so read verbatim until the next single quote
                    destination.Append(input[index++]);
                    while (index < input.Length)
                    {
                        char current = input[index++];
                        destination.Append(current);
                        if (current == '\'')
                        {
                            break;
                        }
                    }
                    break;

                case 'E':
                case 'e':
                case 'c':
                    // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
                    // 'e' in ICU is the local day of the week, which has no representation in .NET, but
                    // maps closest to 3 or 4 'd's in .NET
                    // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
                    // maps closest to 3 or 4 'd's in .NET
                    NormalizeDayOfWeek(input, destination, ref index);
                    break;

                case 'L':
                case 'M':
                    // 'L' in ICU is the stand-alone name of the month,
                    // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
                    // 'M' in both ICU and .NET is the month,
                    // but ICU supports 5 'M's, which is the super short month name
                    int occurrences = CountOccurrences(input, input[index], ref index);
                    if (occurrences > 4)
                    {
                        // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
                        occurrences = 3;
                    }
                    destination.Append('M', occurrences);
                    break;

                case 'G':
                    // 'G' in ICU is the era, which maps to 'g' in .NET
                    occurrences = CountOccurrences(input, 'G', ref index);

                    // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
                    // have the same meaning
                    destination.Append('g');
                    break;

                case 'y':
                    // a single 'y' in ICU is the year with no padding or trimming.
                    // a single 'y' in .NET is the year with 1 or 2 digits
                    // so convert any single 'y' to 'yyyy'
                    occurrences = CountOccurrences(input, 'y', ref index);
                    if (occurrences == 1)
                    {
                        occurrences = 4;
                    }
                    destination.Append('y', occurrences);
                    break;

                default:
                    const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
                    Debug.Assert(!unsupportedDateFieldSymbols.Contains(input[index]),
                                 $"Encountered an unexpected date field symbol '{input[index]}' from ICU which has no known corresponding .NET equivalent.");

                    destination.Append(input[index++]);
                    break;
                }
            }

            return(StringBuilderCache.GetStringAndRelease(destination));
        }
Example #8
0
 public static string UnCaptureSqlAndFree(StringBuilder sb)
 {
     OrmLiteConfig.BeforeExecFilter = null;
     return(StringBuilderCache.ReturnAndFree(sb));
 }
Example #9
0
        void ReadStringSegmentCore(out byte[] resultBytes, out int resultOffset, out int resultLength)
        {
            // SkipWhiteSpace is already called from IsNull

            byte[] builder       = null;
            var    builderOffset = 0;

            char[] codePointStringBuffer = null;
            var    codePointStringOffet  = 0;

            if (bytes[offset] != '\"')
            {
                throw CreateParsingException("String Begin Token");
            }
            offset++;

            var from = offset;

            // eliminate array-bound check
            for (int i = offset; i < bytes.Length; i++)
            {
                byte escapeCharacter = 0;
                switch (bytes[i])
                {
                case (byte)'\\':     // escape character
                    switch ((char)bytes[i + 1])
                    {
                    case '"':
                    case '\\':
                    case '/':
                        escapeCharacter = bytes[i + 1];
                        goto COPY;

                    case 'b':
                        escapeCharacter = (byte)'\b';
                        goto COPY;

                    case 'f':
                        escapeCharacter = (byte)'\f';
                        goto COPY;

                    case 'n':
                        escapeCharacter = (byte)'\n';
                        goto COPY;

                    case 'r':
                        escapeCharacter = (byte)'\r';
                        goto COPY;

                    case 't':
                        escapeCharacter = (byte)'\t';
                        goto COPY;

                    case 'u':
                        if (codePointStringBuffer == null)
                        {
                            codePointStringBuffer = StringBuilderCache.GetCodePointStringBuffer();
                        }

                        if (codePointStringOffet == 0)
                        {
                            if (builder == null)
                            {
                                builder = StringBuilderCache.GetBuffer();
                            }

                            var copyCount = i - from;
                            BinaryUtil.EnsureCapacity(ref builder, builderOffset, copyCount + 1);         // require + 1
                            Buffer.BlockCopy(bytes, from, builder, builderOffset, copyCount);
                            builderOffset += copyCount;
                        }

                        if (codePointStringBuffer.Length == codePointStringOffet)
                        {
                            Array.Resize(ref codePointStringBuffer, codePointStringBuffer.Length * 2);
                        }

                        var a         = (char)bytes[i + 2];
                        var b         = (char)bytes[i + 3];
                        var c         = (char)bytes[i + 4];
                        var d         = (char)bytes[i + 5];
                        var codepoint = GetCodePoint(a, b, c, d);
                        codePointStringBuffer[codePointStringOffet++] = (char)codepoint;
                        i      += 5;
                        offset += 6;
                        from    = offset;
                        continue;

                    default:
                        throw CreateParsingExceptionMessage("Bad JSON escape.");
                    }

                case (byte)'"':     // endtoken
                    offset++;
                    goto END;

                default:     // string
                    if (codePointStringOffet != 0)
                    {
                        if (builder == null)
                        {
                            builder = StringBuilderCache.GetBuffer();
                        }
                        BinaryUtil.EnsureCapacity(ref builder, builderOffset, StringEncoding.UTF8.GetMaxByteCount(codePointStringOffet));
                        builderOffset       += StringEncoding.UTF8.GetBytes(codePointStringBuffer, 0, codePointStringOffet, builder, builderOffset);
                        codePointStringOffet = 0;
                    }
                    offset++;
                    continue;
                }

COPY:
                {
                    if (builder == null)
                    {
                        builder = StringBuilderCache.GetBuffer();
                    }
                    if (codePointStringOffet != 0)
                    {
                        BinaryUtil.EnsureCapacity(ref builder, builderOffset, StringEncoding.UTF8.GetMaxByteCount(codePointStringOffet));
                        builderOffset       += StringEncoding.UTF8.GetBytes(codePointStringBuffer, 0, codePointStringOffet, builder, builderOffset);
                        codePointStringOffet = 0;
                    }

                    var copyCount = i - from;
                    BinaryUtil.EnsureCapacity(ref builder, builderOffset, copyCount + 1); // require + 1!
                    Buffer.BlockCopy(bytes, from, builder, builderOffset, copyCount);
                    builderOffset           += copyCount;
                    builder[builderOffset++] = escapeCharacter;
                    i      += 1;
                    offset += 2;
                    from    = offset;
                }
            }

            resultLength = 0;
            resultBytes  = null;
            resultOffset = 0;
            throw CreateParsingException("String End Token");

END:
            if (builderOffset == 0 && codePointStringOffet == 0) // no escape
            {
                resultBytes  = bytes;
                resultOffset = from;
                resultLength = offset - 1 - from; // skip last quote
            }
            else
            {
                if (builder == null)
                {
                    builder = StringBuilderCache.GetBuffer();
                }
                if (codePointStringOffet != 0)
                {
                    BinaryUtil.EnsureCapacity(ref builder, builderOffset, StringEncoding.UTF8.GetMaxByteCount(codePointStringOffet));
                    builderOffset       += StringEncoding.UTF8.GetBytes(codePointStringBuffer, 0, codePointStringOffet, builder, builderOffset);
                    codePointStringOffet = 0;
                }

                var copyCount = offset - from - 1;
                BinaryUtil.EnsureCapacity(ref builder, builderOffset, copyCount);
                Buffer.BlockCopy(bytes, from, builder, builderOffset, copyCount);
                builderOffset += copyCount;

                resultBytes  = builder;
                resultOffset = 0;
                resultLength = builderOffset;
            }
        }
Example #10
0
        private void ConstructEvaluator(IEnumerable <EvaluatorItem> items)
        {
            //var codeCompiler = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } });
            var codeCompiler = CodeDomProvider.CreateProvider("CSharp");

            var cp = new CompilerParameters              //(new[] { "mscorlib.dll", "system.core.dll" })
            {
                GenerateExecutable = false,
                GenerateInMemory   = true,
            };

            Assemblies.ForEach(x => AddAssembly(cp, x.Location));

            var code = StringBuilderCache.Allocate();

            AssemblyNames.ForEach(x =>
                                  code.AppendFormat("using {0};\n", x));

            code.Append(
                @"

namespace CSharpEval 
{
  public class _Expr
");

            if (this.BaseType != null)
            {
                code.Append("   : " + GetTypeName(this.BaseType));

                if (GenericArgs.Length > 0)
                {
                    code.Append("<");
                    var i = 0;
                    foreach (var genericArg in GenericArgs)
                    {
                        if (i++ > 0)
                        {
                            code.Append(", ");
                        }

                        code.Append(GetTypeName(genericArg));
                        ReferenceTypesIfNotExist(cp, Assemblies, genericArg);
                    }
                    code.AppendLine(">");
                }

                ReferenceTypesIfNotExist(cp, Assemblies, this.BaseType);
            }

            code.AppendLine("  {");

            AddPropertiesToTypeIfAny(code);

            foreach (var item in items)
            {
                var sbParams = StringBuilderCacheAlt.Allocate();
                foreach (var param in item.Params)
                {
                    if (sbParams.Length > 0)
                    {
                        sbParams.Append(", ");
                    }

                    var typeName = GetTypeName(param.Value);
                    sbParams.AppendFormat("{0} {1}", typeName, param.Key);

                    var paramType = param.Value;

                    ReferenceAssembliesIfNotExists(cp, paramType, Assemblies);
                }

                var isVoid = item.ReturnType == typeof(void);

                var returnType = isVoid ? "void" : GetTypeName(item.ReturnType);
                code.AppendFormat("    public {0} {1}({2})",
                                  returnType, item.Name, StringBuilderCacheAlt.ReturnAndFree(sbParams));

                code.AppendLine("    {");
                if (isVoid)
                {
                    code.AppendFormat("      {0}; \n", item.Expression);
                }
                else
                {
                    code.AppendFormat("      return ({0}); \n", item.Expression);
                }
                code.AppendLine("    }");
            }

            code.AppendLine("  }");
            code.AppendLine("}");

            if (IsVersion4AndUp)
            {
                if (!Env.IsMono)
                {
                    cp.ReferencedAssemblies.Add(Env.ReferenceAssembyPath + @"System.Core.dll");
                }
            }

            var src             = StringBuilderCache.ReturnAndFree(code);
            var compilerResults = codeCompiler.CompileAssemblyFromSource(cp, src);

            if (compilerResults.Errors.HasErrors)
            {
                var error = StringBuilderCache.Allocate();
                error.Append("Error Compiling Expression: ");
                foreach (CompilerError err in compilerResults.Errors)
                {
                    error.AppendFormat("{0}\n", err.ErrorText);
                }
                throw new Exception("Error Compiling Expression: " + StringBuilderCache.ReturnAndFree(error));
            }

            compiledAssembly   = compilerResults.CompiledAssembly;
            compiled           = compiledAssembly.CreateInstance("CSharpEval._Expr");
            compiledType       = compiled.GetType();
            compiledTypeCtorFn = ReflectionExtensions.GetConstructorMethodToCache(compiledType);
        }
Example #11
0
    static void ExportInjectionPublishInfo(SortedDictionary <string, List <InjectedMethodInfo> > data)
    {
        var temp = data.ToDictionary(
            typeInfo => typeInfo.Key,
            typeinfo =>
        {
            return(typeinfo.Value
                   .OrderBy(methodInfo => methodInfo.methodPublishedName)
                   .ToDictionary(
                       methodInfo => methodInfo.methodPublishedName,
                       methodInfo => methodInfo.methodIndex
                       ));
        }
            );

        StringBuilder sb = StringBuilderCache.Acquire();

        sb.Append("return ");
        ToLuaText.TransferDic(temp, sb);
        sb.Remove(sb.Length - 1, 1);
        File.WriteAllText(CustomSettings.baseLuaDir + "System/Injection/InjectionBridgeInfo.lua", StringBuilderCache.GetStringAndRelease(sb));
    }
Example #12
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 = d.Keys.ToList();
                            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;
            }
        }
Example #13
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)
                    {
                        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)
                            {
                                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;
            }
        }
            string GetName(SyntaxNode node)
            {
                if (tag is SyntaxTree)
                {
                    var type = node;
                    if (type != null)
                    {
                        var sb = StringBuilderCache.Allocate();
                        sb.Append(ext.GetEntityMarkup(type));
                        while (type.Parent is BaseTypeDeclarationSyntax)
                        {
                            sb.Insert(0, ext.GetEntityMarkup(type.Parent) + ".");
                            type = type.Parent;
                        }
                        return(StringBuilderCache.ReturnAndFree(sb));
                    }
                }
                var accessor = node as AccessorDeclarationSyntax;

                if (accessor != null)
                {
                    if (accessor.Kind() == SyntaxKind.GetAccessorDeclaration)
                    {
                        return("get");
                    }
                    if (accessor.Kind() == SyntaxKind.SetAccessorDeclaration)
                    {
                        return("set");
                    }
                    if (accessor.Kind() == SyntaxKind.AddAccessorDeclaration)
                    {
                        return("add");
                    }
                    if (accessor.Kind() == SyntaxKind.RemoveAccessorDeclaration)
                    {
                        return("remove");
                    }
                    return(node.ToString());
                }
                if (node is OperatorDeclarationSyntax)
                {
                    return("operator");
                }
                if (node is PropertyDeclarationSyntax)
                {
                    return(((PropertyDeclarationSyntax)node).Identifier.ToString());
                }
                if (node is MethodDeclarationSyntax)
                {
                    return(((MethodDeclarationSyntax)node).Identifier.ToString());
                }
                if (node is ConstructorDeclarationSyntax)
                {
                    return(((ConstructorDeclarationSyntax)node).Identifier.ToString());
                }
                if (node is DestructorDeclarationSyntax)
                {
                    return(((DestructorDeclarationSyntax)node).Identifier.ToString());
                }
                if (node is BaseTypeDeclarationSyntax)
                {
                    return(((BaseTypeDeclarationSyntax)node).Identifier.ToString());
                }

//				if (node is fixeds) {
//					return ((FixedVariableInitializer)node).Name;
//				}
                if (node is VariableDeclaratorSyntax)
                {
                    return(((VariableDeclaratorSyntax)node).Identifier.ToString());
                }
                return(node.ToString());
            }
Example #15
0
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var namespaces = Config.GetDefaultNamespaces(metadata);

            metadata.RemoveIgnoredTypesForNet(Config);

            if (!Config.ExcludeNamespace)
            {
                if (Config.GlobalNamespace == null)
                {
                    metadata.Types.Each(x => namespaces.Add(x.Namespace));
                    metadata.Operations.Each(x => {
                        namespaces.Add(x.Request.Namespace);
                        if (x.Response != null)
                        {
                            namespaces.Add(x.Response.Namespace);
                        }
                    });
                }
                else
                {
                    namespaces.Add(Config.GlobalNamespace);
                }
            }

            string defaultValue(string k) => request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sbInner = StringBuilderCache.Allocate();
            var sb      = new StringBuilderWrapper(sbInner);

            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(defaultValue("GlobalNamespace"), Config.GlobalNamespace));
            sb.AppendLine("{0}MakePartial: {1}".Fmt(defaultValue("MakePartial"), Config.MakePartial));
            sb.AppendLine("{0}MakeVirtual: {1}".Fmt(defaultValue("MakeVirtual"), Config.MakeVirtual));
            sb.AppendLine("{0}MakeInternal: {1}".Fmt(defaultValue("MakeInternal"), Config.MakeInternal));
            sb.AppendLine("{0}MakeDataContractsExtensible: {1}".Fmt(defaultValue("MakeDataContractsExtensible"), Config.MakeDataContractsExtensible));
            sb.AppendLine("{0}AddReturnMarker: {1}".Fmt(defaultValue("AddReturnMarker"), Config.AddReturnMarker));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}AddDataContractAttributes: {1}".Fmt(defaultValue("AddDataContractAttributes"), Config.AddDataContractAttributes));
            sb.AppendLine("{0}AddIndexesToDataMembers: {1}".Fmt(defaultValue("AddIndexesToDataMembers"), Config.AddIndexesToDataMembers));
            sb.AppendLine("{0}AddGeneratedCodeAttributes: {1}".Fmt(defaultValue("AddGeneratedCodeAttributes"), Config.AddGeneratedCodeAttributes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(defaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}ExportValueTypes: {1}".Fmt(defaultValue("ExportValueTypes"), Config.ExportValueTypes));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}AddNamespaces: {1}".Fmt(defaultValue("AddNamespaces"), Config.AddNamespaces.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}AddDefaultXmlNamespace: {1}".Fmt(defaultValue("AddDefaultXmlNamespace"), Config.AddDefaultXmlNamespace));

            sb.AppendLine("*/");
            sb.AppendLine();

            namespaces.Where(x => !string.IsNullOrEmpty(x))
            .Each(x => sb.AppendLine($"using {x};"));
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine("using System.CodeDom.Compiler;");
            }

            if (Config.AddDataContractAttributes &&
                Config.AddDefaultXmlNamespace != null)
            {
                sb.AppendLine();

                namespaces.Where(x => !Config.DefaultNamespaces.Contains(x)).ToList()
                .ForEach(x => sb.AppendLine(
                             $"[assembly: ContractNamespace(\"{Config.AddDefaultXmlNamespace}\", ClrNamespace=\"{x}\")]"));
            }

            sb.AppendLine();

            string lastNS = null;

            var existingTypes = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            allTypes = new List <MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);

            allTypes = FilterTypes(allTypes);

            var orderedTypes = allTypes
                               .OrderBy(x => x.Namespace)
                               .ThenBy(x => x.Name);

            foreach (var type in orderedTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        if (requestTypesMap.TryGetValue(type, out var operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                            new CreateTypeOptions
                        {
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    !type.ReturnVoidMarker &&
                                    type.ReturnMarkerTypeName == null)
                                {
                                    return(null);
                                }

                                if (type.ReturnVoidMarker)
                                {
                                    return("IReturnVoid");
                                }
                                if (type.ReturnMarkerTypeName != null)
                                {
                                    return(Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) }));
                                }
                                return(response != null
                                            ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                            : null);
                            },
                            IsRequest = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                            new CreateTypeOptions {
                            IsResponse = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                        new CreateTypeOptions {
                        IsType = true
                    });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (lastNS != null)
            {
                sb.AppendLine("}");
            }
            sb.AppendLine();

            return(StringBuilderCache.ReturnAndFree(sbInner));
        }
        public static Scope CreateScope <TTarget>(Tracer tracer, TTarget target)
        {
            if (!tracer.Settings.IsIntegrationEnabled(IntegrationId))
            {
                // integration disabled, don't create a scope, skip this trace
                return(null);
            }

            Scope scope = null;

            try
            {
                var tags        = new AerospikeTags();
                var serviceName = tracer.Settings.GetServiceName(tracer, ServiceName);
                scope = tracer.StartActiveInternal(OperationName, tags: tags, serviceName: serviceName);
                var span = scope.Span;
                span.LogicScope = OperationName;

                if (target.TryDuckCast <HasKey>(out var hasKey))
                {
                    var key = hasKey.Key;

                    tags.Key       = FormatKey(key);
                    tags.Namespace = key.Ns;
                    tags.SetName   = key.SetName;
                    tags.UserKey   = key.UserKey.ToString();
                }
                else if (target.TryDuckCast <HasKeys>(out var hasKeys))
                {
                    var sb = StringBuilderCache.Acquire(0);

                    foreach (var obj in hasKeys.Keys)
                    {
                        var key = obj.DuckCast <Key>();

                        if (sb.Length != 0)
                        {
                            sb.Append(';');
                        }

                        sb.Append(FormatKey(key));
                    }

                    tags.Key = StringBuilderCache.GetStringAndRelease(sb);
                }
                else if (target.TryDuckCast <HasStatement>(out var hasStatement))
                {
                    tags.Key       = hasStatement.Statement.Ns + ":" + hasStatement.Statement.SetName;
                    tags.Namespace = hasStatement.Statement.Ns;
                    tags.SetName   = hasStatement.Statement.SetName;
                }

                span.Type         = SpanTypes.Aerospike;
                span.ResourceName = ExtractResourceName(target.GetType());

                tags.SetAnalyticsSampleRate(IntegrationId, tracer.Settings, enabledWithGlobalSetting: false);
                tracer.TracerManager.Telemetry.IntegrationGeneratedSpan(IntegrationId);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error creating or populating scope.");
            }

            return(scope);
        }
Example #17
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}", 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($"SELECT EXISTS({StringBuilderCache.ReturnAndFree(sql)});");
        }
Example #18
0
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var namespaces = Config.GetDefaultNamespaces(metadata);

            metadata.RemoveIgnoredTypesForNet(Config);

            if (Config.GlobalNamespace == null)
            {
                metadata.Types.Each(x => namespaces.Add(x.Namespace));
                metadata.Operations.Each(x => {
                    namespaces.Add(x.Request.Namespace);
                    if (x.Response != null)
                    {
                        namespaces.Add(x.Response.Namespace);
                    }
                });
            }
            else
            {
                namespaces.Add(Config.GlobalNamespace);
            }

            string DefaultValue(string k) => request.QueryString[k].IsNullOrEmpty() ? "'''" : "'";

            var sbInner = new StringBuilder();
            var sb      = new StringBuilderWrapper(sbInner);

            sb.AppendLine("' Options:");
            sb.AppendLine("'Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("'Version: {0}".Fmt(Env.VersionString));
            sb.AppendLine("'Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("''")));
            sb.AppendLine("'BaseUrl: {0}".Fmt(Config.BaseUrl));
            if (Config.UsePath != null)
            {
                sb.AppendLine("'UsePath: {0}".Fmt(Config.UsePath));
            }

            sb.AppendLine("'");
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(DefaultValue("GlobalNamespace"), Config.GlobalNamespace));
            sb.AppendLine("{0}MakePartial: {1}".Fmt(DefaultValue("MakePartial"), Config.MakePartial));
            sb.AppendLine("{0}MakeVirtual: {1}".Fmt(DefaultValue("MakeVirtual"), Config.MakeVirtual));
            sb.AppendLine("{0}MakeDataContractsExtensible: {1}".Fmt(DefaultValue("MakeDataContractsExtensible"), Config.MakeDataContractsExtensible));
            sb.AppendLine("{0}AddReturnMarker: {1}".Fmt(DefaultValue("AddReturnMarker"), Config.AddReturnMarker));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(DefaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}AddDataContractAttributes: {1}".Fmt(DefaultValue("AddDataContractAttributes"), Config.AddDataContractAttributes));
            sb.AppendLine("{0}AddIndexesToDataMembers: {1}".Fmt(DefaultValue("AddIndexesToDataMembers"), Config.AddIndexesToDataMembers));
            sb.AppendLine("{0}AddGeneratedCodeAttributes: {1}".Fmt(DefaultValue("AddGeneratedCodeAttributes"), Config.AddGeneratedCodeAttributes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(DefaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(DefaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(DefaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}ExportValueTypes: {1}".Fmt(DefaultValue("ExportValueTypes"), Config.ExportValueTypes));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(DefaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(", ")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(DefaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(", ")));
            sb.AppendLine("{0}AddNamespaces: {1}".Fmt(DefaultValue("AddNamespaces"), Config.AddNamespaces.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}AddDefaultXmlNamespace: {1}".Fmt(DefaultValue("AddDefaultXmlNamespace"), Config.AddDefaultXmlNamespace));
            sb.AppendLine();

            namespaces.Where(x => !string.IsNullOrEmpty(x))
            .Each(x => sb.AppendLine("Imports {0}".Fmt(x)));
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine("Imports System.CodeDom.Compiler");
            }

            if (Config.AddDataContractAttributes &&
                Config.AddDefaultXmlNamespace != null)
            {
                sb.AppendLine();

                namespaces.Where(x => !Config.DefaultNamespaces.Contains(x)).ToList()
                .ForEach(x =>
                         sb.AppendLine("<Assembly: ContractNamespace(\"{0}\", ClrNamespace:=\"{1}\")>"
                                       .Fmt(Config.AddDefaultXmlNamespace, x)));
            }

            sb.AppendLine();

            sb.AppendLine("Namespace Global");
            sb = sb.Indent();

            string lastNS = null;

            var existingTypes = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            allTypes = new List <MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);

            var orderedTypes = allTypes
                               .OrderBy(x => x.Namespace)
                               .ThenBy(x => x.Name)
                               .ToList();

            orderedTypes = FilterTypes(orderedTypes);

            var insertCode = InsertCodeFilter?.Invoke(orderedTypes, Config);

            if (insertCode != null)
            {
                sb.AppendLine(insertCode);
            }

            foreach (var type in orderedTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        if (requestTypesMap.TryGetValue(type, out var operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                            new CreateTypeOptions
                        {
                            Routes       = metadata.Operations.GetRoutes(type),
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    operation?.ReturnsVoid != true &&
                                    operation?.ReturnType == null)
                                {
                                    return(null);
                                }

                                if (operation?.ReturnsVoid == true)
                                {
                                    return(nameof(IReturnVoid));
                                }
                                if (operation?.ReturnType != null)
                                {
                                    return(Type("IReturn`1", new[] { Type(operation.ReturnType) }));
                                }
                                return(response != null
                                        ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null);
                            },
                            IsRequest = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                            new CreateTypeOptions {
                            IsResponse = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                        new CreateTypeOptions {
                        IsType = true
                    });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (lastNS != null)
            {
                sb.AppendLine("End Namespace");
            }

            var addCode = AddCodeFilter?.Invoke(allTypes, Config);

            if (addCode != null)
            {
                sb.AppendLine(addCode);
            }

            sb = sb.UnIndent();
            sb.AppendLine("End Namespace");

            sb.AppendLine();

            return(StringBuilderCache.ReturnAndFree(sbInner));
        }
Example #19
0
            public override SpanParserResult GetSpans(string s, bool reverse = false)
            {
                StringBuilder sb = StringBuilderCache.GetInstance(s.Length - TokensLength);

                bool                        startPending = false;
                LinePositionInfo            start        = default;
                Stack <LinePositionInfo>    stack        = null;
                List <LinePositionSpanInfo> spans        = null;

                int lastPos = 0;

                int line   = 0;
                int column = 0;

                int length = s.Length;

                int i = 0;

                while (i < length)
                {
                    switch (s[i])
                    {
                    case '\r':
                    {
                        if (PeekNextChar() == '\n')
                        {
                            i++;
                        }

                        line++;
                        column = 0;
                        i++;
                        continue;
                    }

                    case '\n':
                    {
                        line++;
                        column = 0;
                        i++;
                        continue;
                    }

                    case '[':
                    {
                        char nextChar = PeekNextChar();
                        if (nextChar == '|')
                        {
                            sb.Append(s, lastPos, i - lastPos);

                            var start2 = new LinePositionInfo(sb.Length, line, column);

                            if (stack != null)
                            {
                                stack.Push(start2);
                            }
                            else if (!startPending)
                            {
                                start        = start2;
                                startPending = true;
                            }
                            else
                            {
                                stack = new Stack <LinePositionInfo>();
                                stack.Push(start);
                                stack.Push(start2);
                                startPending = false;
                            }

                            i      += 2;
                            lastPos = i;
                            continue;
                        }
                        else if (nextChar == '[' &&
                                 PeekChar(2) == '|' &&
                                 PeekChar(3) == ']')
                        {
                            i++;
                            column++;
                            CloseSpan();
                            i      += 3;
                            lastPos = i;
                            continue;
                        }

                        break;
                    }

                    case '|':
                    {
                        if (PeekNextChar() == ']')
                        {
                            CloseSpan();
                            i      += 2;
                            lastPos = i;
                            continue;
                        }

                        break;
                    }
                    }

                    column++;
                    i++;
                }

                if (startPending ||
                    stack?.Count > 0)
                {
                    throw new InvalidOperationException();
                }

                sb.Append(s, lastPos, s.Length - lastPos);

                if (spans != null &&
                    reverse)
                {
                    spans.Reverse();
                }

                return(new SpanParserResult(
                           StringBuilderCache.GetStringAndFree(sb),
                           spans?.ToImmutableArray() ?? ImmutableArray <LinePositionSpanInfo> .Empty));

                char PeekNextChar()
                {
                    return(PeekChar(1));
                }

                char PeekChar(int offset)
                {
                    return((i + offset >= s.Length) ? '\0' : s[i + offset]);
                }

                void CloseSpan()
                {
                    if (stack != null)
                    {
                        start = stack.Pop();
                    }
                    else if (startPending)
                    {
                        startPending = false;
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }

                    var end = new LinePositionInfo(sb.Length + i - lastPos, line, column);

                    var span = new LinePositionSpanInfo(start, end);

                    (spans ?? (spans = new List <LinePositionSpanInfo>())).Add(span);

                    sb.Append(s, lastPos, i - lastPos);
                }
            }
        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];
                            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;
            }
        }
Example #21
0
        private static string GetNextArgument(string arguments, ref int i)
        {
            var  currentArgument = StringBuilderCache.Acquire();
            bool inQuotes        = false;

            while (i < arguments.Length)
            {
                // From the current position, iterate through contiguous backslashes.
                int backslashCount = 0;
                while (i < arguments.Length && arguments[i] == '\\')
                {
                    i++;
                    backslashCount++;
                }

                if (backslashCount > 0)
                {
                    if (i >= arguments.Length || arguments[i] != '"')
                    {
                        // Backslashes not followed by a double quote:
                        // they should all be treated as literal backslashes.
                        currentArgument.Append('\\', backslashCount);
                    }
                    else
                    {
                        // Backslashes followed by a double quote:
                        // - Output a literal slash for each complete pair of slashes
                        // - If one remains, use it to make the subsequent quote a literal.
                        currentArgument.Append('\\', backslashCount / 2);
                        if (backslashCount % 2 != 0)
                        {
                            currentArgument.Append('"');
                            i++;
                        }
                    }

                    continue;
                }

                char c = arguments[i];

                // If this is a double quote, track whether we're inside of quotes or not.
                // Anything within quotes will be treated as a single argument, even if
                // it contains spaces.
                if (c == '"')
                {
                    if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"')
                    {
                        // Two consecutive double quotes inside an inQuotes region should result in a literal double quote
                        // (the parser is left in the inQuotes region).
                        // This behavior is not part of the spec of code:ParseArgumentsIntoList, but is compatible with CRT
                        // and .NET Framework.
                        currentArgument.Append('"');
                        i++;
                    }
                    else
                    {
                        inQuotes = !inQuotes;
                    }

                    i++;
                    continue;
                }

                // If this is a space/tab and we're not in quotes, we're done with the current
                // argument, it should be added to the results and then reset for the next one.
                if ((c == ' ' || c == '\t') && !inQuotes)
                {
                    break;
                }

                // Nothing special; add the character to the current argument.
                currentArgument.Append(c);
                i++;
            }

            return(StringBuilderCache.GetStringAndRelease(currentArgument));
        }
Example #22
0
            private string GetNextValue(string data, int currentIndex, bool expectQuotes, out int parsedIndex)
            {
                Debug.Assert(currentIndex < data.Length && !CharIsSpaceOrTab(data[currentIndex]));

                // If quoted value, skip first quote.
                bool quotedValue = false;

                if (data[currentIndex] == '"')
                {
                    quotedValue = true;
                    currentIndex++;
                }

                if (expectQuotes && !quotedValue)
                {
                    parsedIndex = currentIndex;
                    return(null);
                }

                StringBuilder sb = StringBuilderCache.Acquire();

                while (currentIndex < data.Length && ((quotedValue && data[currentIndex] != '"') || (!quotedValue && data[currentIndex] != ',')))
                {
                    sb.Append(data[currentIndex]);
                    currentIndex++;

                    if (currentIndex == data.Length)
                    {
                        break;
                    }

                    if (!quotedValue && CharIsSpaceOrTab(data[currentIndex]))
                    {
                        break;
                    }

                    if (quotedValue && data[currentIndex] == '"' && data[currentIndex - 1] == '\\')
                    {
                        // Include the escaped quote.
                        sb.Append(data[currentIndex]);
                        currentIndex++;
                    }
                }

                // Skip the quote.
                if (quotedValue)
                {
                    currentIndex++;
                }

                // Skip any whitespace.
                while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
                {
                    currentIndex++;
                }

                // Return if this is last value.
                if (currentIndex == data.Length)
                {
                    parsedIndex = currentIndex;
                    return(StringBuilderCache.GetStringAndRelease(sb));
                }

                // A key-value pair should end with ','
                if (data[currentIndex++] != ',')
                {
                    parsedIndex = currentIndex;
                    return(null);
                }

                // Skip space and tab
                while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex]))
                {
                    currentIndex++;
                }

                // Set parsedIndex to current valid char.
                parsedIndex = currentIndex;
                return(StringBuilderCache.GetStringAndRelease(sb));
            }
Example #23
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);
        }
Example #24
0
        public static async Task <string> GetDigestTokenForCredential(NetworkCredential credential, HttpRequestMessage request, DigestResponse digestResponse)
        {
            StringBuilder sb = StringBuilderCache.Acquire();

            // It is mandatory for servers to implement sha-256 per RFC 7616
            // Keep MD5 for backward compatibility.
            string algorithm;
            bool   isAlgorithmSpecified = digestResponse.Parameters.TryGetValue(Algorithm, out algorithm);

            if (isAlgorithmSpecified)
            {
                if (!algorithm.Equals(Sha256, StringComparison.OrdinalIgnoreCase) &&
                    !algorithm.Equals(Md5, StringComparison.OrdinalIgnoreCase) &&
                    !algorithm.Equals(Sha256Sess, StringComparison.OrdinalIgnoreCase) &&
                    !algorithm.Equals(MD5Sess, StringComparison.OrdinalIgnoreCase))
                {
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Error(digestResponse, "Algorithm not supported: {algorithm}");
                    }
                    return(null);
                }
            }
            else
            {
                algorithm = Md5;
            }

            // Check if nonce is there in challenge
            string nonce;

            if (!digestResponse.Parameters.TryGetValue(Nonce, out nonce))
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(digestResponse, "Nonce missing");
                }
                return(null);
            }

            // opaque token may or may not exist
            string opaque;

            digestResponse.Parameters.TryGetValue(Opaque, out opaque);

            string realm;

            if (!digestResponse.Parameters.TryGetValue(Realm, out realm))
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(digestResponse, "Realm missing");
                }
                return(null);
            }

            // Add username
            string userhash;

            if (digestResponse.Parameters.TryGetValue(UserHash, out userhash) && userhash == "true")
            {
                sb.AppendKeyValue(Username, ComputeHash(credential.UserName + ":" + realm, algorithm));
                sb.AppendKeyValue(UserHash, userhash, includeQuotes: false);
            }
            else
            {
                if (HeaderUtilities.ContainsNonAscii(credential.UserName))
                {
                    string usernameStar = HeaderUtilities.Encode5987(credential.UserName);
                    sb.AppendKeyValue(UsernameStar, usernameStar, includeQuotes: false);
                }
                else
                {
                    sb.AppendKeyValue(Username, credential.UserName);
                }
            }

            // Add realm
            if (realm != string.Empty)
            {
                sb.AppendKeyValue(Realm, realm);
            }

            // Add nonce
            sb.AppendKeyValue(Nonce, nonce);

            // Add uri
            sb.AppendKeyValue(Uri, request.RequestUri.PathAndQuery);

            // Set qop, default is auth
            string qop            = Auth;
            bool   isQopSpecified = digestResponse.Parameters.ContainsKey(Qop);

            if (isQopSpecified)
            {
                // Check if auth-int present in qop string
                int index1 = digestResponse.Parameters[Qop].IndexOf(AuthInt, StringComparison.Ordinal);
                if (index1 != -1)
                {
                    // Get index of auth if present in qop string
                    int index2 = digestResponse.Parameters[Qop].IndexOf(Auth, StringComparison.Ordinal);

                    // If index2 < index1, auth option is available
                    // If index2 == index1, check if auth option available later in string after auth-int.
                    if (index2 == index1)
                    {
                        index2 = digestResponse.Parameters[Qop].IndexOf(Auth, index1 + AuthInt.Length, StringComparison.Ordinal);
                        if (index2 == -1)
                        {
                            qop = AuthInt;
                        }
                    }
                }
            }

            // Set cnonce
            string cnonce = GetRandomAlphaNumericString();

            // Calculate response
            string a1 = credential.UserName + ":" + realm + ":" + credential.Password;

            if (algorithm.EndsWith("sess", StringComparison.OrdinalIgnoreCase))
            {
                a1 = ComputeHash(a1, algorithm) + ":" + nonce + ":" + cnonce;
            }

            string a2 = request.Method.Method + ":" + request.RequestUri.PathAndQuery;

            if (qop == AuthInt)
            {
                string content = request.Content == null ? string.Empty : await request.Content.ReadAsStringAsync().ConfigureAwait(false);

                a2 = a2 + ":" + ComputeHash(content, algorithm);
            }

            string response;

            if (isQopSpecified)
            {
                response = ComputeHash(ComputeHash(a1, algorithm) + ":" +
                                       nonce + ":" +
                                       DigestResponse.NonceCount + ":" +
                                       cnonce + ":" +
                                       qop + ":" +
                                       ComputeHash(a2, algorithm), algorithm);
            }
            else
            {
                response = ComputeHash(ComputeHash(a1, algorithm) + ":" +
                                       nonce + ":" +
                                       ComputeHash(a2, algorithm), algorithm);
            }

            // Add response
            sb.AppendKeyValue(Response, response, includeComma: opaque != null || isAlgorithmSpecified || isQopSpecified);

            // Add opaque
            if (opaque != null)
            {
                sb.AppendKeyValue(Opaque, opaque, includeComma: isAlgorithmSpecified || isQopSpecified);
            }

            if (isAlgorithmSpecified)
            {
                // Add algorithm
                sb.AppendKeyValue(Algorithm, algorithm, includeQuotes: false, includeComma: isQopSpecified);
            }

            if (isQopSpecified)
            {
                // Add qop
                sb.AppendKeyValue(Qop, qop, includeQuotes: false);

                // Add nc
                sb.AppendKeyValue(NC, DigestResponse.NonceCount, includeQuotes: false);

                // Add cnonce
                sb.AppendKeyValue(CNonce, cnonce, includeComma: false);
            }

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Example #25
0
 public StringBuilder Get(int capacity)
 {
     return(StringBuilderCache.Acquire(capacity));
 }
Example #26
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();
            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 : "");
        }
Example #27
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)
            {
                //insertFields contains Property "Name" of fields to insert
                var includeField = insertFields == null || insertFields.Contains(fieldDef.Name, StringComparer.OrdinalIgnoreCase);

                if (ShouldReturnOnInsert(modelDef, fieldDef) && (!fieldDef.AutoId || !includeField))
                {
                    if (sbReturningColumns.Length > 0)
                    {
                        sbReturningColumns.Append(",");
                    }
                    sbReturningColumns.Append("INSERTED." + GetQuotedColumnName(fieldDef.FieldName));
                }

                if (ShouldSkipInsert(fieldDef) && (!fieldDef.AutoId || !includeField))
                {
                    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)})";
        }
Example #28
0
        private static SyntaxTriviaList Generate(
            SeparatedSyntaxList <TypeParameterSyntax> typeParameters = default(SeparatedSyntaxList <TypeParameterSyntax>),
            SeparatedSyntaxList <ParameterSyntax> parameters         = default(SeparatedSyntaxList <ParameterSyntax>),
            bool canGenerateReturns = false,
            DocumentationCommentGeneratorSettings settings = null)
        {
            settings = settings ?? DocumentationCommentGeneratorSettings.Default;

            ImmutableArray <string> summary = settings.Summary;

            StringBuilder sb = StringBuilderCache.GetInstance();

            sb.Append(settings.Indentation);
            sb.Append("/// <summary>");

            if (settings.SingleLineSummary &&
                summary.Length <= 1)
            {
                if (summary.Length == 1)
                {
                    sb.Append(summary[0]);
                }

                sb.AppendLine("</summary>");
            }
            else
            {
                sb.AppendLine();

                if (summary.Any())
                {
                    foreach (string comment in summary)
                    {
                        sb.Append(settings.Indentation);
                        sb.Append("/// ");
                        sb.AppendLine(comment);
                    }
                }
                else
                {
                    sb.Append(settings.Indentation);
                    sb.AppendLine("/// ");
                }

                sb.Append(settings.Indentation);
                sb.AppendLine("/// </summary>");
            }

            foreach (TypeParameterSyntax typeParameter in typeParameters)
            {
                sb.Append(settings.Indentation);
                sb.Append("/// <typeparam name=\"");
                sb.Append(typeParameter.Identifier.ValueText);
                sb.AppendLine("\"></typeparam>");
            }

            foreach (ParameterSyntax parameter in parameters)
            {
                sb.Append(settings.Indentation);
                sb.Append("/// <param name=\"");
                sb.Append(parameter.Identifier.ValueText);
                sb.AppendLine("\"></param>");
            }

            if (canGenerateReturns &&
                settings.Returns)
            {
                sb.Append(settings.Indentation);
                sb.AppendLine("/// <returns></returns>");
            }

            return(ParseLeadingTrivia(StringBuilderCache.GetStringAndFree(sb)));
        }
        public string SelectInto <TModel>()
        {
            if ((CustomSelect && OnlyFields == null) || (typeof(TModel) == typeof(T) && !PrefixFieldWithTableName))
            {
                return(ToSelectStatement());
            }

            useFieldName = true;

            var sbSelect    = StringBuilderCache.Allocate();
            var selectDef   = modelDef;
            var orderedDefs = tableDefs;

            if (typeof(TModel) != typeof(List <object>) &&
                typeof(TModel) != typeof(Dictionary <string, object>) &&
                typeof(TModel) != typeof(object)) //dynamic
            {
                selectDef = typeof(TModel).GetModelDefinition();
                if (selectDef != modelDef && tableDefs.Contains(selectDef))
                {
                    orderedDefs = tableDefs.ToList(); //clone
                    orderedDefs.Remove(selectDef);
                    orderedDefs.Insert(0, selectDef);
                }
            }

            foreach (var fieldDef in selectDef.FieldDefinitions)
            {
                var found = false;

                if (fieldDef.BelongToModelName != null)
                {
                    var tableDef = orderedDefs.FirstOrDefault(x => x.Name == fieldDef.BelongToModelName);
                    if (tableDef != null)
                    {
                        var matchingField = FindWeakMatch(tableDef, fieldDef);
                        if (matchingField != null)
                        {
                            if (OnlyFields == null || OnlyFields.Contains(fieldDef.Name))
                            {
                                if (sbSelect.Length > 0)
                                {
                                    sbSelect.Append(", ");
                                }

                                if (fieldDef.CustomSelect == null)
                                {
                                    if (!fieldDef.IsRowVersion)
                                    {
                                        sbSelect.Append($"{GetQuotedColumnName(tableDef, matchingField.Name)} AS {SqlColumn(fieldDef.Name)}");
                                    }
                                    else
                                    {
                                        sbSelect.Append(DialectProvider.GetRowVersionColumnName(fieldDef, DialectProvider.GetTableName(tableDef.ModelName)));
                                    }
                                }
                                else
                                {
                                    sbSelect.Append(fieldDef.CustomSelect + " AS " + fieldDef.FieldName);
                                }

                                continue;
                            }
                        }
                    }
                }

                foreach (var tableDef in orderedDefs)
                {
                    foreach (var tableFieldDef in tableDef.FieldDefinitions)
                    {
                        if (tableFieldDef.Name == fieldDef.Name)
                        {
                            if (OnlyFields != null && !OnlyFields.Contains(fieldDef.Name))
                            {
                                continue;
                            }

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

                            if (fieldDef.CustomSelect == null)
                            {
                                if (!fieldDef.IsRowVersion)
                                {
                                    sbSelect.Append(GetQuotedColumnName(tableDef, tableFieldDef.Name));

                                    if (tableFieldDef.Alias != null)
                                    {
                                        sbSelect.Append(" AS ").Append(SqlColumn(fieldDef.Name));
                                    }
                                }
                                else
                                {
                                    sbSelect.Append(DialectProvider.GetRowVersionColumnName(fieldDef, DialectProvider.GetTableName(tableDef.ModelName)));
                                }
                            }
                            else
                            {
                                sbSelect.Append(tableFieldDef.CustomSelect).Append(" AS ").Append(tableFieldDef.FieldName);
                            }

                            found = true;
                            break;
                        }
                    }

                    if (found)
                    {
                        break;
                    }
                }

                if (!found)
                {
                    // Add support for auto mapping `{Table}{Field}` convention
                    foreach (var tableDef in orderedDefs)
                    {
                        var matchingField = FindWeakMatch(tableDef, fieldDef);
                        if (matchingField != null)
                        {
                            if (OnlyFields != null && !OnlyFields.Contains(fieldDef.Name))
                            {
                                continue;
                            }

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

                            sbSelect.Append($"{DialectProvider.GetQuotedColumnName(tableDef, matchingField)} as {SqlColumn(fieldDef.Name)}");

                            break;
                        }
                    }
                }
            }

            var select = StringBuilderCache.ReturnAndFree(sbSelect);

            var columns = select.Length > 0 ? select : "*";

            SelectExpression = "SELECT " + (selectDistinct ? "DISTINCT " : "") + columns;

            return(ToSelectStatement());
        }
Example #30
0
        private static string _TryParseInterpretedString(StringBuilder builder, TextReader stream, out JsonValue value)
        {
            // NOTE: `builder` contains the portion of the string found in `stream`, up to the first
            //       (possible) escape sequence.
            System.Diagnostics.Debug.Assert('\\' == (char)stream.Peek());

            value = null;

            string errorMessage = null;
            bool   complete     = false;

            int?previousHex = null;

            while (stream.Peek() != -1)
            {
                var c = (char)stream.Read();

                if (c == '\\')
                {
                    if (stream.Peek() == -1)
                    {
                        StringBuilderCache.Release(builder);
                        return("Could not find end of string value.");
                    }

                    // escape sequence
                    var lookAhead = (char)stream.Peek();
                    if (!_MustInterpretComplex(lookAhead))
                    {
                        stream.Read();                         // eat the simple escape
                        c = _InterpretSimpleEscapeSequence(lookAhead);
                    }
                    else
                    {
                        // NOTE: Currently we only handle 'u' here
                        if (lookAhead != 'u')
                        {
                            StringBuilderCache.Release(builder);
                            return($"Invalid escape sequence: '\\{lookAhead}'.");
                        }

                        var buffer = SmallBufferCache.Acquire(4);
                        stream.Read();                         // eat the 'u'
                        if (4 != stream.Read(buffer, 0, 4))
                        {
                            StringBuilderCache.Release(builder);
                            return("Could not find end of string value.");
                        }

                        var hexString = new string(buffer, 0, 4);
                        if (!_IsValidHex(hexString, 0, 4) ||
                            !int.TryParse(hexString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var currentHex))
                        {
                            StringBuilderCache.Release(builder);
                            return($"Invalid escape sequence: '\\{lookAhead}{hexString}'.");
                        }

                        if (previousHex != null)
                        {
                            // Our last character was \u, so combine and emit the UTF32 codepoint
                            currentHex = StringExtensions.CalculateUtf32(previousHex.Value, currentHex);
                            if (currentHex.IsValidUtf32CodePoint())
                            {
                                builder.Append(char.ConvertFromUtf32(currentHex));
                            }
                            else
                            {
                                value = null;
                                return("Invalid UTF-32 code point.");
                            }
                            previousHex = null;
                        }
                        else
                        {
                            previousHex = currentHex;
                        }

                        SmallBufferCache.Release(buffer);
                        continue;
                    }
                }
                else if (c == '"')
                {
                    complete = true;
                    break;
                }

                // Check if last character was \u, and if so emit it as-is, because
                // this character is not a continuation of a UTF-32 escape sequence
                if (previousHex != null)
                {
                    builder.Append(char.ConvertFromUtf32(previousHex.Value));
                    previousHex = null;
                }

                // non-escape sequence
                builder.Append(c);
            }

            // if we had a hanging UTF32 escape sequence, apply it now
            if (previousHex != null)
            {
                builder.Append(char.ConvertFromUtf32(previousHex.Value));
            }

            if (!complete)
            {
                value = null;
                StringBuilderCache.Release(builder);
                return("Could not find end of string value.");
            }

            value = StringBuilderCache.GetStringAndRelease(builder);
            return(errorMessage);
        }