Example #1
0
        public static bool TryFormat(this DateTimeOffset value, Span <byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), EncodingData encoding = default(EncodingData))
        {
            if (format.IsDefault)
            {
                format.Symbol = 'G';
            }
            Precondition.Require(format.Symbol == 'R' || format.Symbol == 'O' || format.Symbol == 'G');
            switch (format.Symbol)
            {
            case 'R':

                if (encoding.IsInvariantUtf16)     // TODO: there are many checks like this one in the code. They need to also verify that the UTF8 branch is invariant.
                {
                    return(TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, out bytesWritten, EncodingData.InvariantUtf16));
                }
                else
                {
                    return(TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, out bytesWritten, EncodingData.InvariantUtf8));
                }

            case 'O':
                if (encoding.IsInvariantUtf16)
                {
                    return(TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, out bytesWritten, EncodingData.InvariantUtf16));
                }
                else
                {
                    return(TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, out bytesWritten, EncodingData.InvariantUtf8));
                }

            case 'G':
                return(TryFormatDateTimeFormatG(value.DateTime, buffer, out bytesWritten, encoding));

            default:
                throw new NotImplementedException();
            }
        }
        /// <summary>
        /// Parses an unsigned 64-bit integer from a location within a UTF-8 byte array buffer.
        /// </summary>
        /// <param name="utf8Text">The UTF-8 buffer, passed as a byte array.</param>
        /// <param name="index">The index location of the value to be parsed within the buffer.</param>
        /// <param name="value">The parsed value.</param>
        /// <param name="bytesConsumed">The length (in bytes) of the unparsed value within the UTF-8 buffer.</param>
        /// <returns>True if parsing is successful; false otherwise.</returns>
        public static bool TryParse(byte[] utf8Text, int index, out byte value, out int bytesConsumed)
        {
            Precondition.Require(utf8Text.Length > 0);

            value         = 0;
            bytesConsumed = 0;

            for (int byteIndex = index; byteIndex < utf8Text.Length; byteIndex++) // loop through the byte array
            {
                byte nextByte = utf8Text[byteIndex];
                if (nextByte < '0' || nextByte > '9') // if the next character is not a digit
                {
                    if (bytesConsumed == 0)           // check to see if we've processed any digits at all
                    {
                        value = default(byte);        // if we haven't, set value to 0 and return false
                        return(false);
                    }
                    else
                    {
                        return(true); // otherwise return true
                    }
                }
                byte candidate = (byte)(value * 10); // left shift the value
                candidate += (byte)(nextByte - '0'); // parse the current digit to a byte and add it to the temporary value
                if (candidate >= value)              // if it was a digit 0-9, this should be true
                {
                    value = candidate;
                }
                else // this should never happen, but just in case
                {
                    return(true);
                }
                bytesConsumed++; // increment the number of bytes consumed, then loop
            }

            return(true);
        }
Example #3
0
        public static bool TryFormatNumber(double value, bool isSingle, Span<byte> buffer, out int bytesWritten, TextFormat format, EncodingData encoding)
        {
            Precondition.Require(format.Symbol == 'G' || format.Symbol == 'E' || format.Symbol == 'F');

            bytesWritten = 0;
            int written;

            if (Double.IsNaN(value))
            {
                return encoding.TryEncode(EncodingData.Symbol.NaN, buffer, out bytesWritten);
            }

            if (Double.IsInfinity(value))
            {
                if (Double.IsNegativeInfinity(value))
                {
                    if (!encoding.TryEncode(EncodingData.Symbol.MinusSign, buffer, out written))
                    {
                        bytesWritten = 0;
                        return false;
                    }
                    bytesWritten += written;
                }
                if (!encoding.TryEncode(EncodingData.Symbol.InfinitySign, buffer.Slice(bytesWritten), out written))
                {
                    bytesWritten = 0;
                    return false;
                }
                bytesWritten += written;
                return true;
            }

            // TODO: the lines below need to be replaced with properly implemented algorithm
            // the problem is the algorithm is complex, so I am commiting a stub for now
            var hack = value.ToString(format.Symbol.ToString());
            return encoding.TextEncoder.TryEncodeString(hack, buffer, out bytesWritten);
        }
Example #4
0
        public static bool TryParse(Utf8String text, out uint value, out int bytesConsumed)
        {
            Precondition.Require(text.Length > 0);

            value         = 0;
            bytesConsumed = 0;

            for (int byteIndex = 0; byteIndex < text.Length; byteIndex++)
            {
                byte nextByte = (byte)text[byteIndex];
                if (nextByte < '0' || nextByte > '9')
                {
                    if (bytesConsumed == 0)
                    {
                        value = default(uint);
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }
                uint candidate = value * 10;
                candidate += (uint)nextByte - '0';
                if (candidate >= value)
                {
                    value = candidate;
                }
                else
                {
                    return(true);
                }
                bytesConsumed++;
            }

            return(true);
        }
Example #5
0
        public static bool TryFormat(this DateTimeOffset value, Span <byte> buffer, Format.Parsed format, EncodingData formattingData, out int bytesWritten)
        {
            if (format.IsDefault)
            {
                format.Symbol = 'G';
            }
            Precondition.Require(format.Symbol == 'R' || format.Symbol == 'O' || format.Symbol == 'G');
            switch (format.Symbol)
            {
            case 'R':

                if (formattingData.IsUtf16)
                {
                    return(TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, EncodingData.InvariantUtf16, out bytesWritten));
                }
                else
                {
                    return(TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, EncodingData.InvariantUtf8, out bytesWritten));
                }

            case 'O':
                if (formattingData.IsUtf16)
                {
                    return(TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, EncodingData.InvariantUtf16, out bytesWritten));
                }
                else
                {
                    return(TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, EncodingData.InvariantUtf8, out bytesWritten));
                }

            case 'G':
                return(TryFormatDateTimeFormagG(value.DateTime, buffer, formattingData, out bytesWritten));

            default:
                throw new NotImplementedException();
            }
        }
Example #6
0
        public override void Execute(ControllerContext context)
        {
            Precondition.Require(context, () => Error.ArgumentNull("context"));
            if (context.IsChild)
            {
                throw Error.CannotExecuteResultInChildAction();
            }

            HttpResponseBase response = context.Context.Response;

            response.ContentType = (String.IsNullOrEmpty(_contentType))
                                ? _defaultContentType : _contentType;

            if (_contentEncoding != null)
            {
                response.ContentEncoding = _contentEncoding;
            }

            if (_data != null)
            {
                using (MemoryStream ms = new MemoryStream(500))
                {
                    using (XmlWriter writer = XmlTextWriter.Create(ms,
                                                                   new XmlWriterSettings()
                    {
                        OmitXmlDeclaration = true, Indent = true,
                        Encoding = response.ContentEncoding
                    }))
                    {
                        XmlSerializer xs = new XmlSerializer(_data.GetType(), _includedTypes);
                        xs.Serialize(writer, _data);
                    }
                    ms.WriteTo(response.OutputStream);
                }
            }
        }
        /// <summary>
        /// Executes the specified <paramref name="action"/> against the connection.
        /// </summary>
        /// <param name="connection">The connection instance.</param>
        /// <param name="action">An action to execute.</param>
        public static void Execute(this IDbConnection connection, Action <IDbConnection> action)
        {
            Precondition.Require(connection, () => Error.ArgumentNull("connection"));
            Precondition.Require(action, () => Error.ArgumentNull("action"));

            ConnectionState state = connection.State;

            try
            {
                if (state == ConnectionState.Closed)
                {
                    connection.Open();
                }

                action(connection);
            }
            finally
            {
                if (state == ConnectionState.Closed)
                {
                    connection.Close();
                }
            }
        }
        public void OnAuthorization(AuthorizationContext context)
        {
            Precondition.Require(context, () => Error.ArgumentNull("context"));
            if (Validate(context.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = context.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidationHandler, null);
            }
            else
            {
                context.Cancel = true;
                string url = CreateRedirectionUrl(context);

                if (RedirectAllowed(context, url))
                {
                    context.Result = new RedirectResult(url);
                }
                else
                {
                    context.Result = DefaultResult;
                }
            }
        }
Example #9
0
 // TODO: implement a real pool
 // Maybe the pool should support renting Span<byte> instead of byte[]. This would make it cheaper to have many small buffers.
 public static byte[] RentBuffer(int minSize)
 {
     Precondition.Require(minSize > 0);
     return(new byte[minSize]);
 }
Example #10
0
 public void SetControllerFactory(IControllerFactory factory)
 {
     Precondition.Require(factory, () => Error.ArgumentNull("factory"));
     _factoryThunk = () => factory;
 }
Example #11
0
 public bool TryWriteDigit(ulong digit, Span <byte> buffer, out int bytesWritten)
 {
     Precondition.Require(digit < 10);
     return(TryWriteDigitOrSymbol(digit, buffer, out bytesWritten));
 }
 /// <summary>
 /// When overridden in a derived class, disposes the specified
 /// <see cref="Radischevo.Wahha.Data.IDbDataProvider"/>.
 /// </summary>
 /// <param name="provider">The provider instance to dispose.</param>
 public virtual void DisposeProvider(IDbDataProvider provider)
 {
     Precondition.Require(provider, () => Error.ArgumentNull("provider"));
     provider.Dispose();
 }
Example #13
0
 public ValidationHelper(ViewContext context)
 {
     Precondition.Require(context, () => Error.ArgumentNull("context"));
     _context = context;
 }
Example #14
0
 public HttpServerUtilityWrapper(HttpServerUtility server)
 {
     Precondition.Require(server, () => Error.ArgumentNull("server"));
     _server = server;
 }
 public ModelBinderAttribute(Type type)
 {
     Precondition.Require(type, () => Error.ArgumentNull("type"));
     _type = type;
 }
 public void Add(ModelBinderProvider provider)
 {
     Precondition.Require(provider, () => Error.ArgumentNull("provider"));
     _providers.Add(provider);
 }
Example #17
0
 /// <summary>
 /// Creates a <see cref="Radischevo.Wahha.Data.DbCommandResult"/> wrapper for
 /// the specified <paramref name="command"/>.
 /// </summary>
 /// <param name="provider">An instance of data provider being extended.</param>
 /// <param name="command">The object, describing the command to execute.</param>
 public static DbCommandResult Execute(this IDbDataProvider provider, DbCommandDescriptor command)
 {
     Precondition.Require(provider, () => Error.ArgumentNull("provider"));
     return(new DbCommandResult(provider, command));
 }
Example #18
0
        public static bool TryFormat(this Guid value, Span <byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), TextEncoder encoder = null)
        {
            if (format.IsDefault)
            {
                format.Symbol = 'G';
            }
            Precondition.Require(format.Symbol == 'G' || format.Symbol == 'D' || format.Symbol == 'N' || format.Symbol == 'B' || format.Symbol == 'P');

            encoder = encoder == null ? TextEncoder.Utf8 : encoder;

            bool dash = true;
            char tail = '\0';

            bytesWritten = 0;

            switch (format.Symbol)
            {
            case 'D':
            case 'G':
                break;

            case 'N':
                dash = false;
                break;

            case 'B':
                if (!TryWriteChar('{', buffer, ref bytesWritten, encoder))
                {
                    return(false);
                }
                tail = '}';
                break;

            case 'P':
                if (!TryWriteChar('(', buffer, ref bytesWritten, encoder))
                {
                    return(false);
                }
                tail = ')';
                break;

            default:
                Precondition.Require(false);     // how did we get here?
                break;
            }


            var byteFormat = new TextFormat('x', 2);

            unsafe
            {
                byte *bytes = (byte *)&value;

                if (!TryWriteByte(bytes[3], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[2], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[1], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[0], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoder))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[5], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[4], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoder))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[7], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[6], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoder))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[8], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[9], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }

                if (dash)
                {
                    if (!TryWriteChar('-', buffer, ref bytesWritten, encoder))
                    {
                        return(false);
                    }
                }

                if (!TryWriteByte(bytes[10], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[11], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[12], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[13], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[14], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
                if (!TryWriteByte(bytes[15], buffer, ref bytesWritten, byteFormat, encoder))
                {
                    return(false);
                }
            }

            if (tail != '\0')
            {
                if (!TryWriteChar(tail, buffer, ref bytesWritten, encoder))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #19
0
        public MultiSelectList(IEnumerable <ListItem> items)
        {
            Precondition.Require(items, () => Error.ArgumentNull("items"));

            _listItems = items;
        }
Example #20
0
        private static bool TryFormatHexadecimalInvariantCultureUtf8(ulong value, Span <byte> buffer, out int bytesWritten, ParsedFormat format)
        {
            Precondition.Require(format.Symbol == 'X' || format.Symbol == 'x');

            byte firstDigitOffset   = (byte)'0';
            byte firstHexCharOffset = format.Symbol == 'X' ? (byte)'A' : (byte)'a';

            firstHexCharOffset -= 10;

            // Count amount of hex digits
            var   hexDigitsCount = 1;
            ulong valueToCount   = value;

            if (valueToCount > 0xFFFFFFFF)
            {
                hexDigitsCount += 8;
                valueToCount  >>= 0x20;
            }
            if (valueToCount > 0xFFFF)
            {
                hexDigitsCount += 4;
                valueToCount  >>= 0x10;
            }
            if (valueToCount > 0xFF)
            {
                hexDigitsCount += 2;
                valueToCount  >>= 0x8;
            }
            if (valueToCount > 0xF)
            {
                hexDigitsCount++;
            }

            var bytesCount = hexDigitsCount;

            // Count leading zeros
            var leadingZerosCount = format.HasPrecision ? format.Precision - hexDigitsCount : 0;

            bytesCount += leadingZerosCount > 0 ? leadingZerosCount : 0;

            if (bytesCount > buffer.Length)
            {
                bytesWritten = 0;
                return(false);
            }

            var index = bytesCount;

            while (hexDigitsCount-- > 0)
            {
                byte digit = (byte)(value & 0xF);
                value         >>= 0x4;
                digit          += digit < 10 ? firstDigitOffset : firstHexCharOffset;
                buffer[--index] = digit;
            }

            // Write leading zeros if any
            while (leadingZerosCount-- > 0)
            {
                buffer[--index] = firstDigitOffset;
            }

            bytesWritten = bytesCount;
            return(true);
        }
Example #21
0
 public ContentSegment(IEnumerable <PathSubsegment> segments)
 {
     Precondition.Require(segments, () => Error.ArgumentNull("segments"));
     _segments = new List <PathSubsegment>(segments);
 }
 public VariableSubsegment(string variableName)
     : base("variable")
 {
     Precondition.Require(variableName, () => Error.ArgumentNull("variableName"));
     _variableName = variableName;
 }
Example #23
0
 internal static ResultContext GetResultContext(ResultContext context)
 {
     Precondition.Require(context, () => Error.ArgumentNull("context"));
     return(context);
 }
Example #24
0
 public HttpRequestWrapper(HttpRequest request)
 {
     Precondition.Require(request, () => Error.ArgumentNull("request"));
     _request = request;
 }
Example #25
0
        // TODO: this whole routine is too slow. It does div and mod twice, which are both costly (especially that some JITs cannot optimize it).
        // It does it twice to avoid reversing the formatted buffer, which can be tricky given it should handle arbitrary cultures.
        // One optimization I thought we could do is to do div/mod once and store digits in a temp buffer (but that would allocate). Modification to the idea would be to store the digits in a local struct
        // Another idea possibly worth tying would be to special case cultures that have constant digit size, and go back to the format + reverse buffer approach.
        private static bool TryFormatDecimal(ulong value, Span <byte> buffer, out int bytesWritten, ParsedFormat format, SymbolTable symbolTable)
        {
            char symbol = char.ToUpperInvariant(format.Symbol);

            Precondition.Require(symbol == 'D' || format.Symbol == 'G' || format.Symbol == 'N');

            // Reverse value on decimal basis, count digits and trailing zeros before the decimal separator
            ulong reversedValueExceptFirst = 0;
            var   digitsCount        = 1;
            var   trailingZerosCount = 0;

            // We reverse the digits in numeric form because reversing encoded digits is hard and/or costly.
            // If value contains 20 digits, its reversed value will not fit into ulong size.
            // So reverse it till last digit (reversedValueExceptFirst will have all the digits except the first one).
            while (value >= 10)
            {
                var digit = value % 10UL;
                value = value / 10UL;

                if (reversedValueExceptFirst == 0 && digit == 0)
                {
                    trailingZerosCount++;
                }
                else
                {
                    reversedValueExceptFirst = reversedValueExceptFirst * 10UL + digit;
                    digitsCount++;
                }
            }

            bytesWritten = 0;
            int digitBytes;

            // If format is D and precision is greater than digitsCount + trailingZerosCount, append leading zeros
            if (symbol == 'D' && format.HasPrecision)
            {
                var leadingZerosCount = format.Precision - digitsCount - trailingZerosCount;
                while (leadingZerosCount-- > 0)
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                }
            }

            // Append first digit
            if (!symbolTable.TryEncode((SymbolTable.Symbol)value, buffer.Slice(bytesWritten), out digitBytes))
            {
                bytesWritten = 0;
                return(false);
            }
            bytesWritten += digitBytes;
            digitsCount--;

            if (symbol == 'N')
            {
                const int GroupSize = 3;

                // Count amount of digits before first group separator. It will be reset to groupSize every time digitsLeftInGroup == zero
                var digitsLeftInGroup = (digitsCount + trailingZerosCount) % GroupSize;
                if (digitsLeftInGroup == 0)
                {
                    if (digitsCount + trailingZerosCount > 0)
                    {
                        // There is a new group immediately after the first digit
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten += digitBytes;
                    }
                    digitsLeftInGroup = GroupSize;
                }

                // Append digits
                while (reversedValueExceptFirst > 0)
                {
                    if (digitsLeftInGroup == 0)
                    {
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten     += digitBytes;
                        digitsLeftInGroup = GroupSize;
                    }

                    var nextDigit = reversedValueExceptFirst % 10UL;
                    reversedValueExceptFirst = reversedValueExceptFirst / 10UL;

                    if (!symbolTable.TryEncode((SymbolTable.Symbol)nextDigit, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                    digitsLeftInGroup--;
                }

                // Append trailing zeros if any
                while (trailingZerosCount-- > 0)
                {
                    if (digitsLeftInGroup == 0)
                    {
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.GroupSeparator, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten     += digitBytes;
                        digitsLeftInGroup = GroupSize;
                    }

                    if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                    digitsLeftInGroup--;
                }
            }
            else
            {
                while (reversedValueExceptFirst > 0)
                {
                    var bufferSlice = buffer.Slice(bytesWritten);
                    var nextDigit   = reversedValueExceptFirst % 10UL;
                    reversedValueExceptFirst = reversedValueExceptFirst / 10UL;
                    if (!symbolTable.TryEncode((SymbolTable.Symbol)nextDigit, bufferSlice, out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                }

                // Append trailing zeros if any
                while (trailingZerosCount-- > 0)
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;
                }
            }

            // If format is N and precision is not defined or is greater than zero, append trailing zeros after decimal point
            if (symbol == 'N')
            {
                int trailingZerosAfterDecimalCount = format.HasPrecision ? format.Precision : 2;

                if (trailingZerosAfterDecimalCount > 0)
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.DecimalSeparator, buffer.Slice(bytesWritten), out digitBytes))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += digitBytes;

                    while (trailingZerosAfterDecimalCount-- > 0)
                    {
                        if (!symbolTable.TryEncode(SymbolTable.Symbol.D0, buffer.Slice(bytesWritten), out digitBytes))
                        {
                            bytesWritten = 0;
                            return(false);
                        }
                        bytesWritten += digitBytes;
                    }
                }
            }

            return(true);
        }
Example #26
0
 public static void ReturnBuffer(ref byte[] buffer)
 {
     Precondition.Require(buffer != null);
     buffer = null;
 }
 protected DataAnnotationsModelValidator(ValidationAttribute attribute)
     : base()
 {
     Precondition.Require(attribute, () => Error.ArgumentNull("attribute"));
     _attribute = attribute;
 }
Example #28
0
        public IAsyncResult BeginInvokeAction(ControllerContext context,
                                              string actionName, AsyncCallback callback, object state,
                                              IDictionary <string, object> values)
        {
            Precondition.Require(context, () => Error.ArgumentNull("context"));
            Precondition.Defined(actionName, () => Error.ArgumentNull("actionName"));

            ControllerDescriptor controller = GetControllerDescriptor(context);
            ActionDescriptor     action     = controller.FindAction(context, actionName);

            if (action == null)
            {
                return(ActionNotFound(callback, state));
            }

            context.Parameters.Merge(GetParameterValues(context, action))
            .Merge(values);

            ActionFilterInfo filters      = GetFilters(context, action);
            Action           continuation = null;

            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                try
                {
                    AuthorizationContext authContext = InvokeAuthorizationFilters(context, action, filters.AuthorizationFilters);
                    if (authContext.Cancel)
                    {
                        continuation = () => InvokeActionResult(context, authContext.Result ?? EmptyResult.Instance);
                    }
                    else
                    {
                        if (context.Controller.ValidateRequest)
                        {
                            ValidateRequest(context.Context.Request);
                        }

                        IAsyncResult asyncResult = BeginInvokeActionFilters(context, action,
                                                                            filters.ActionFilters, context.Parameters, asyncCallback, asyncState);

                        continuation = () => {
                            ActionExecutedContext postContext = EndInvokeActionFilters(asyncResult);
                            InvokeActionResultFilters(context, filters.ResultFilters, postContext.Result);
                        };
                        return(asyncResult);
                    }
                }
                catch (ThreadAbortException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    ExceptionContext ctx = InvokeExceptionFilters(context, ex, filters.ExceptionFilters);
                    if (!ctx.Handled)
                    {
                        throw;
                    }

                    continuation = () => InvokeActionResult(context, ctx.Result);
                }
                return(MakeSynchronousAsyncResult(asyncCallback, asyncState));
            };

            EndInvokeDelegate <bool> endDelegate = delegate(IAsyncResult asyncResult) {
                try
                {
                    continuation();
                }
                catch (ThreadAbortException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    ExceptionContext ctx = InvokeExceptionFilters(context, ex, filters.ExceptionFilters);
                    if (!ctx.Handled)
                    {
                        throw;
                    }

                    InvokeActionResult(context, ctx.Result);
                }
                return(true);
            };

            return(AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeTag));
        }
Example #29
0
        private static bool TryFormatNumber(double value, bool isSingle, Span <byte> buffer, out int bytesWritten, StandardFormat format = default, SymbolTable symbolTable = null)
        {
            Precondition.Require(format.Symbol == 'G' || format.Symbol == 'E' || format.Symbol == 'F');

            symbolTable = symbolTable ?? SymbolTable.InvariantUtf8;

            bytesWritten = 0;
            int written;

            if (Double.IsNaN(value))
            {
                return(symbolTable.TryEncode(SymbolTable.Symbol.NaN, buffer, out bytesWritten));
            }

            if (Double.IsInfinity(value))
            {
                if (Double.IsNegativeInfinity(value))
                {
                    if (!symbolTable.TryEncode(SymbolTable.Symbol.MinusSign, buffer, out written))
                    {
                        bytesWritten = 0;
                        return(false);
                    }
                    bytesWritten += written;
                }
                if (!symbolTable.TryEncode(SymbolTable.Symbol.InfinitySign, buffer.Slice(bytesWritten), out written))
                {
                    bytesWritten = 0;
                    return(false);
                }
                bytesWritten += written;
                return(true);
            }

            // TODO: the lines below need to be replaced with properly implemented algorithm
            // the problem is the algorithm is complex, so I am commiting a stub for now
            var hack       = value.ToString(format.Symbol.ToString());
            var utf16Bytes = hack.AsSpan().AsBytes();

            if (symbolTable == SymbolTable.InvariantUtf8)
            {
                var status = Encodings.Utf16.ToUtf8(utf16Bytes, buffer, out int consumed, out bytesWritten);
                return(status == OperationStatus.Done);
            }
            else if (symbolTable == SymbolTable.InvariantUtf16)
            {
                bytesWritten = utf16Bytes.Length;
                if (utf16Bytes.TryCopyTo(buffer))
                {
                    return(true);
                }

                bytesWritten = 0;
                return(false);
            }
            else
            {
                // TODO: This is currently pretty expensive. Can this be done more efficiently?
                //       Note: removing the hack might solve this problem a very different way.
                var status = Encodings.Utf16.ToUtf8Length(utf16Bytes, out int needed);
                if (status != OperationStatus.Done)
                {
                    bytesWritten = 0;
                    return(false);
                }

                Span <byte> temp = stackalloc byte[needed];

                status = Encodings.Utf16.ToUtf8(utf16Bytes, temp, out int consumed, out written);
                if (status != OperationStatus.Done)
                {
                    bytesWritten = 0;
                    return(false);
                }

                return(symbolTable.TryEncode(temp, buffer, out consumed, out bytesWritten));
            }
        }
Example #30
0
 public BlockRenderer(HttpContextBase context)
 {
     Precondition.Require(context, () => Error.ArgumentNull("context"));
     _context = context;
 }