ServiceStack.Text
Utils to load types
Find the type from the name supplied
[typeName] or [typeName, assemblyName]
The top-most interface of the given type, if any.
Find type if it exists
The type if it exists
If AlwaysUseUtc is set to true then convert all DateTime to UTC. If PreserveUtc is set to true then UTC dates will not convert to local
Repairs an out-of-spec XML date/time string which incorrectly uses a space instead of a 'T' to separate the date from the time.
These string are occasionally generated by SQLite and can cause errors in OrmLite when reading these columns from the DB.
The XML date/time string to repair
The repaired string. If no repairs were made, the original string is returned.
WCF Json format: /Date(unixts+0000)/
WCF Json format: /Date(unixts+0000)/
Get the type(string) constructor if exists
The type.
micro optimizations: using flags instead of value.IndexOfAny(EscapeChars)
Class to hold
A fast, standards-based, serialization-issue free DateTime serailizer.
Determines whether this serializer can create the specified type from a string.
The type.
true if this instance [can create from string] the specified type; otherwise, false.
Parses the specified value.
The value.
Deserializes from reader.
The reader.
Serializes to string.
The value.
Serializes to writer.
The value.
The writer.
Sets which format to use when serializing TimeSpans
if the is configured
to take advantage of specification,
to support user-friendly serialized formats, ie emitting camelCasing for JSON
and parsing member names and enum values in a case-insensitive manner.
if the is configured
to support web-friendly serialized formats, ie emitting lowercase_underscore_casing for JSON
Define how property names are mapped during deserialization
Gets or sets a value indicating if the framework should throw serialization exceptions
or continue regardless of deserialization errors. If the framework
will throw; otherwise, it will parse as many fields as possible. The default is .
Gets or sets a value indicating if the framework should always convert to UTC format instead of local time.
Gets or sets a value indicating if the framework should skip automatic conversions.
Dates will be handled literally, any included timezone encoding will be lost and the date will be treaded as DateTimeKind.Local
Utc formatted input will result in DateTimeKind.Utc output. Any input without TZ data will be set DateTimeKind.Unspecified
This will take precedence over other flags like AlwaysUseUtc
JsConfig.DateHandler = DateHandler.ISO8601 should be used when set true for consistent de/serialization.
Gets or sets a value indicating if the framework should always assume is in UTC format if Kind is Unspecified.
Gets or sets whether we should append the Utc offset when we serialize Utc dates. Defaults to no.
Only supported for when the JsConfig.DateHandler == JsonDateHandler.TimestampOffset
Gets or sets a value indicating if unicode symbols should be serialized as "\uXXXX".
Gets or sets a value indicating if the framework should call an error handler when
an exception happens during the deserialization.
Parameters have following meaning in order: deserialized entity, property name, parsed value, property type, caught exception.
If set to true, Interface types will be prefered over concrete types when serializing.
If set to true, Interface types will be prefered over concrete types when serializing.
Sets the maximum depth to avoid circular dependencies
Set this to enable your own type construction provider.
This is helpful for integration with IoC containers where you need to call the container constructor.
Return null if you don't know how to construct the type and the parameterless constructor will be used.
Always emit type info for this type. Takes precedence over ExcludeTypeInfo
Never emit type info for this type
if the is configured
to take advantage of specification,
to support user-friendly serialized formats, ie emitting camelCasing for JSON
and parsing member names and enum values in a case-insensitive manner.
Define custom serialization fn for BCL Structs
Opt-in flag to set some Value Types to be treated as a Ref Type
Whether there is a fn (raw or otherwise)
Define custom raw serialization fn
Define custom serialization hook
Define custom after serialization hook
Define custom deserialization fn for BCL Structs
Define custom raw deserialization fn for objects
Exclude specific properties of this type from being serialized
The property names on target types must match property names in the JSON source
The property names on target types may not match the property names in the JSON source
Uses the xsd format like PT15H10M20S
Uses the standard .net ToString method of the TimeSpan class
Get JSON string value converted to T
Get JSON string value
Get JSON string value
Get unescaped string value
Get unescaped string value
Write JSON Array, Object, bool or number values as raw string
Creates an instance of a Type from a string value
Parses the specified value.
The value.
Shortcut escape when we're sure value doesn't contain any escaped chars
Given a character as utf32, returns the equivalent string provided that the character
is legal json.
Micro-optimization keep pre-built char arrays saving a .ToCharArray() + function call (see .net implementation of .Write(string))
Searches the string for one or more non-printable characters.
The string to search.
True if there are any characters that require escaping. False if the value can be written verbatim.
Micro optimizations: since quote and backslash are the only printable characters requiring escaping, removed previous optimization
(using flags instead of value.IndexOfAny(EscapeChars)) in favor of two equality operations saving both memory and CPU time.
Also slightly reduced code size by re-arranging conditions.
TODO: Possible Linq-only solution requires profiling: return value.Any(c => !c.IsPrintable() || c == QuoteChar || c == EscapeChar);
Implement the serializer using a more static approach
Implement the serializer using a more static approach
Pretty Thread-Safe cache class from:
http://code.google.com/p/dapper-dot-net/source/browse/Dapper/SqlMapper.cs
This is a micro-cache; suitable when the number of terms is controllable (a few hundred, for example),
and strictly append-only; you cannot change existing values. All key matches are on **REFERENCE**
equality. The type is fully thread-safe.
Represents an individual object, allowing access to members by-name
Get or Set the value of a named member for the underlying object
The object represented by this instance
Use the target types definition of equality
Obtain the hash of the target object
Use the target's definition of a string representation
Wraps an individual object, allowing by-name access to that instance
Provides by-name member-access to objects of a given type
Does this type support new instances via a parameterless constructor?
Create a new instance of this type
Provides a type-specific accessor, allowing by-name access for all objects of that type
The accessor is cached internally; a pre-existing accessor may be returned
Get or set the value of a named member on the target instance
Generic implementation of object pooling pattern with predefined pool size limit. The main
purpose is that limited number of frequently used objects can be kept in the pool for
further recycling.
Notes:
1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there
is no space in the pool, extra returned objects will be dropped.
2) it is implied that if object was obtained from a pool, the caller will return it back in
a relatively short time. Keeping checked out objects for long durations is ok, but
reduces usefulness of pooling. Just new up your own.
Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice.
Rationale:
If there is no intent for reusing the object, do not use pool - just use "new".
Not using System.Func{T} because this file is linked into the (debugger) Formatter,
which does not have that type (since it compiles against .NET 2.0).
Produces an instance.
Search strategy is a simple linear probing which is chosen for it cache-friendliness.
Note that Free will try to store recycled objects close to the start thus statistically
reducing how far we will typically search.
Returns objects to the pool.
Search strategy is a simple linear probing which is chosen for it cache-friendliness.
Note that Free will try to store recycled objects close to the start thus statistically
reducing how far we will typically search in Allocate.
Removes an object from leak tracking.
This is called when an object is returned to the pool. It may also be explicitly
called if an object allocated from the pool is intentionally not being returned
to the pool. This can be of use with pooled arrays if the consumer wants to
return a larger array to the pool than was originally allocated.
this is RAII object to automatically release pooled object when its owning pool
Shared object pool for roslyn
Use this shared pool if only concern is reducing object allocations.
if perf of an object pool itself is also a concern, use ObjectPool directly.
For example, if you want to create a million of small objects within a second,
use the ObjectPool directly. it should have much less overhead than using this.
pool that uses default constructor with 100 elements pooled
pool that uses default constructor with 20 elements pooled
pool that uses string as key with StringComparer.OrdinalIgnoreCase as key comparer
pool that uses string as element with StringComparer.OrdinalIgnoreCase as element comparer
pool that uses string as element with StringComparer.Ordinal as element comparer
Used to reduce the # of temporary byte[]s created to satisfy serialization and
other I/O requests
pooled memory : 4K * 512 = 4MB
Reusable StringBuilder ThreadStatic Cache
Alternative Reusable StringBuilder ThreadStatic Cache
Reusable StringWriter ThreadStatic Cache
Alternative Reusable StringWriter ThreadStatic Cache
Manages pools of RecyclableMemoryStream objects.
There are two pools managed in here. The small pool contains same-sized buffers that are handed to streams
as they write more data.
For scenarios that need to call GetBuffer(), the large pool contains buffers of various sizes, all
multiples of LargeBufferMultiple (1 MB by default). They are split by size to avoid overly-wasteful buffer
usage. There should be far fewer 8 MB buffers than 1 MB buffers, for example.
Generic delegate for handling events without any arguments.
Delegate for handling large buffer discard reports.
Reason the buffer was discarded.
Delegate for handling reports of stream size when streams are allocated
Bytes allocated.
Delegate for handling periodic reporting of memory use statistics.
Bytes currently in use in the small pool.
Bytes currently free in the small pool.
Bytes currently in use in the large pool.
Bytes currently free in the large pool.
pools[0] = 1x largeBufferMultiple buffers
pools[1] = 2x largeBufferMultiple buffers
etc., up to maximumBufferSize
Initializes the memory manager with the default block/buffer specifications.
Initializes the memory manager with the given block requiredSize.
Size of each block that is pooled. Must be > 0.
Each large buffer will be a multiple of this value.
Buffers larger than this are not pooled
blockSize is not a positive number, or largeBufferMultiple is not a positive number, or maximumBufferSize is less than blockSize.
maximumBufferSize is not a multiple of largeBufferMultiple
The size of each block. It must be set at creation and cannot be changed.
All buffers are multiples of this number. It must be set at creation and cannot be changed.
Gets or sets the maximum buffer size.
Any buffer that is returned to the pool that is larger than this will be
discarded and garbage collected.
Number of bytes in small pool not currently in use
Number of bytes currently in use by stream from the small pool
Number of bytes in large pool not currently in use
Number of bytes currently in use by streams from the large pool
How many blocks are in the small pool
How many buffers are in the large pool
How many bytes of small free blocks to allow before we start dropping
those returned to us.
How many bytes of large free buffers to allow before we start dropping
those returned to us.
Maximum stream capacity in bytes. Attempts to set a larger capacity will
result in an exception.
A value of 0 indicates no limit.
Whether to save callstacks for stream allocations. This can help in debugging.
It should NEVER be turned on generally in production.
Whether dirty buffers can be immediately returned to the buffer pool. E.g. when GetBuffer() is called on
a stream and creates a single large buffer, if this setting is enabled, the other blocks will be returned
to the buffer pool immediately.
Note when enabling this setting that the user is responsible for ensuring that any buffer previously
retrieved from a stream which is subsequently modified is not used after modification (as it may no longer
be valid).
Removes and returns a single block from the pool.
A byte[] array
Returns a buffer of arbitrary size from the large buffer pool. This buffer
will be at least the requiredSize and always be a multiple of largeBufferMultiple.
The minimum length of the buffer
The tag of the stream returning this buffer, for logging if necessary.
A buffer of at least the required size.
Returns the buffer to the large pool
The buffer to return.
The tag of the stream returning this buffer, for logging if necessary.
buffer is null
buffer.Length is not a multiple of LargeBufferMultiple (it did not originate from this pool)
Returns the blocks to the pool
Collection of blocks to return to the pool
The tag of the stream returning these blocks, for logging if necessary.
blocks is null
blocks contains buffers that are the wrong size (or null) for this memory manager
Retrieve a new MemoryStream object with no tag and a default initial capacity.
A MemoryStream.
Retrieve a new MemoryStream object with the given tag and a default initial capacity.
A tag which can be used to track the source of the stream.
A MemoryStream.
Retrieve a new MemoryStream object with the given tag and at least the given capacity.
A tag which can be used to track the source of the stream.
The minimum desired capacity for the stream.
A MemoryStream.
Retrieve a new MemoryStream object with the given tag and at least the given capacity, possibly using
a single continugous underlying buffer.
Retrieving a MemoryStream which provides a single contiguous buffer can be useful in situations
where the initial size is known and it is desirable to avoid copying data between the smaller underlying
buffers to a single large one. This is most helpful when you know that you will always call GetBuffer
on the underlying stream.
A tag which can be used to track the source of the stream.
The minimum desired capacity for the stream.
Whether to attempt to use a single contiguous buffer.
A MemoryStream.
Retrieve a new MemoryStream object with the given tag and with contents copied from the provided
buffer. The provided buffer is not wrapped or used after construction.
The new stream's position is set to the beginning of the stream when returned.
A tag which can be used to track the source of the stream.
The byte buffer to copy data from.
The offset from the start of the buffer to copy from.
The number of bytes to copy from the buffer.
A MemoryStream.
Triggered when a new block is created.
Triggered when a new block is created.
Triggered when a new large buffer is created.
Triggered when a new stream is created.
Triggered when a stream is disposed.
Triggered when a stream is finalized.
Triggered when a stream is finalized.
Triggered when a user converts a stream to array.
Triggered when a large buffer is discarded, along with the reason for the discard.
Periodically triggered to report usage statistics.
MemoryStream implementation that deals with pooling and managing memory streams which use potentially large
buffers.
This class works in tandem with the RecylableMemoryStreamManager to supply MemoryStream
objects to callers, while avoiding these specific problems:
1. LOH allocations - since all large buffers are pooled, they will never incur a Gen2 GC
2. Memory waste - A standard memory stream doubles its size when it runs out of room. This
leads to continual memory growth as each stream approaches the maximum allowed size.
3. Memory copying - Each time a MemoryStream grows, all the bytes are copied into new buffers.
This implementation only copies the bytes when GetBuffer is called.
4. Memory fragmentation - By using homogeneous buffer sizes, it ensures that blocks of memory
can be easily reused.
The stream is implemented on top of a series of uniformly-sized blocks. As the stream's length grows,
additional blocks are retrieved from the memory manager. It is these blocks that are pooled, not the stream
object itself.
The biggest wrinkle in this implementation is when GetBuffer() is called. This requires a single
contiguous buffer. If only a single block is in use, then that block is returned. If multiple blocks
are in use, we retrieve a larger buffer from the memory manager. These large buffers are also pooled,
split by size--they are multiples of a chunk size (1 MB by default).
Once a large buffer is assigned to the stream the blocks are NEVER again used for this stream. All operations take place on the
large buffer. The large buffer can be replaced by a larger buffer from the pool as needed. All blocks and large buffers
are maintained in the stream until the stream is disposed (unless AggressiveBufferReturn is enabled in the stream manager).
All of these blocks must be the same size
This is only set by GetBuffer() if the necessary buffer is larger than a single block size, or on
construction if the caller immediately requests a single large buffer.
If this field is non-null, it contains the concatenation of the bytes found in the individual
blocks. Once it is created, this (or a larger) largeBuffer will be used for the life of the stream.
This list is used to store buffers once they're replaced by something larger.
This is for the cases where you have users of this class that may hold onto the buffers longer
than they should and you want to prevent race conditions which could corrupt the data.
Unique identifier for this stream across it's entire lifetime
Object has been disposed
A temporary identifier for the current usage of this stream.
Object has been disposed
Gets the memory manager being used by this stream.
Object has been disposed
Callstack of the constructor. It is only set if MemoryManager.GenerateCallStacks is true,
which should only be in debugging situations.
Callstack of the Dispose call. It is only set if MemoryManager.GenerateCallStacks is true,
which should only be in debugging situations.
This buffer exists so that WriteByte can forward all of its calls to Write
without creating a new byte[] buffer on every call.
Allocate a new RecyclableMemoryStream object.
The memory manager
Allocate a new RecyclableMemoryStream object
The memory manager
A string identifying this stream for logging and debugging purposes
Allocate a new RecyclableMemoryStream object
The memory manager
A string identifying this stream for logging and debugging purposes
The initial requested size to prevent future allocations
Allocate a new RecyclableMemoryStream object
The memory manager
A string identifying this stream for logging and debugging purposes
The initial requested size to prevent future allocations
An initial buffer to use. This buffer will be owned by the stream and returned to the memory manager upon Dispose.
Returns the memory used by this stream back to the pool.
Whether we're disposing (true), or being called by the finalizer (false)
This method is not thread safe and it may not be called more than once.
Equivalent to Dispose
Gets or sets the capacity
Capacity is always in multiples of the memory manager's block size, unless
the large buffer is in use. Capacity never decreases during a stream's lifetime.
Explicitly setting the capacity to a lower value than the current value will have no effect.
This is because the buffers are all pooled by chunks and there's little reason to
allow stream truncation.
Object has been disposed
Gets the number of bytes written to this stream.
Object has been disposed
Gets the current position in the stream
Object has been disposed
Whether the stream can currently read
Whether the stream can currently seek
Always false
Whether the stream can currently write
Returns a single buffer containing the contents of the stream.
The buffer may be longer than the stream length.
A byte[] buffer
IMPORTANT: Doing a Write() after calling GetBuffer() invalidates the buffer. The old buffer is held onto
until Dispose is called, but the next time GetBuffer() is called, a new buffer from the pool will be required.
Object has been disposed
Returns a new array with a copy of the buffer's contents. You should almost certainly be using GetBuffer combined with the Length to
access the bytes in this stream. Calling ToArray will destroy the benefits of pooled buffers, but it is included
for the sake of completeness.
Object has been disposed
Reads from the current position into the provided buffer
Destination buffer
Offset into buffer at which to start placing the read bytes.
Number of bytes to read.
The number of bytes read
buffer is null
offset or count is less than 0
offset subtracted from the buffer length is less than count
Object has been disposed
Writes the buffer to the stream
Source buffer
Start position
Number of bytes to write
buffer is null
offset or count is negative
buffer.Length - offset is not less than count
Object has been disposed
Returns a useful string for debugging. This should not normally be called in actual production code.
Writes a single byte to the current position in the stream.
byte value to write
Object has been disposed
Reads a single byte from the current position in the stream.
The byte at the current position, or -1 if the position is at the end of the stream.
Object has been disposed
Sets the length of the stream
value is negative or larger than MaxStreamLength
Object has been disposed
Sets the position to the offset from the seek location
How many bytes to move
From where
The new position
Object has been disposed
offset is larger than MaxStreamLength
Invalid seek origin
Attempt to set negative position
Synchronously writes this stream's bytes to the parameter stream.
Destination stream
Important: This does a synchronous write, which may not be desired in some situations
Release the large buffer (either stores it for eventual release or returns it immediately).
A class to allow the conversion of doubles to string representations of
their exact decimal values. The implementation aims for readability over
efficiency.
Courtesy of @JonSkeet
http://www.yoda.arachsys.com/csharp/DoubleConverter.cs
How many digits are *after* the decimal point
Constructs an arbitrary decimal expansion from the given long.
The long must not be negative.
Multiplies the current expansion by the given amount, which should
only be 2 or 5.
Shifts the decimal point; a negative value makes
the decimal expansion bigger (as fewer digits come after the
decimal place) and a positive value makes the decimal
expansion smaller.
Removes leading/trailing zeroes from the expansion.
Converts the value to a proper decimal string representation.
Creates an instance of a Type from a string value
Determines whether the specified type is convertible from string.
The type.
true if the specified type is convertible from string; otherwise, false.
Parses the specified value.
The value.
Parses the specified type.
The type.
The value.
Useful extension method to get the Dictionary[string,string] representation of any POCO type.
Recursively prints the contents of any POCO object in a human-friendly, readable format
Print Dump to Console.WriteLine
Print string.Format to Console.WriteLine
Parses the specified value.
The value.
Populate an object with Example data.
Populates the object with example data.
Tracks how deeply nested we are
Public Code API to register commercial license for ServiceStack.
Internal Utilities to verify licensing
Maps the path of a file in the context of a VS project
the relative path
the absolute path
Assumes static content is two directories above the /bin/ directory,
eg. in a unit test scenario the assembly would be in /bin/Debug/.
Maps the path of a file in a self-hosted scenario
the relative path
the absolute path
Assumes static content is copied to /bin/ folder with the assemblies
Maps the path of a file in an Asp.Net hosted scenario
the relative path
the absolute path
Assumes static content is in the parent folder of the /bin/ directory
Implement the serializer using a more static approach
Creates a new instance of type.
First looks at JsConfig.ModelFactory before falling back to CreateInstance
Creates a new instance of type.
First looks at JsConfig.ModelFactory before falling back to CreateInstance
Creates a new instance from the default constructor of type
Add a Property attribute at runtime.
Not threadsafe, should only add attributes on Startup.
Add a Property attribute at runtime.
Not threadsafe, should only add attributes on Startup.
@jonskeet: Collection of utility methods which operate on streams.
r285, February 26th 2009: http://www.yoda.arachsys.com/csharp/miscutil/
Reads the given stream up to the end, returning the data as a byte
array.
Reads the given stream up to the end, returning the data as a byte
array, using the given buffer size.
Reads the given stream up to the end, returning the data as a byte
array, using the given buffer for transferring data. Note that the
current contents of the buffer is ignored, so the buffer needn't
be cleared beforehand.
Copies all the data from one stream into another.
Copies all the data from one stream into another, using a buffer
of the given size.
Copies all the data from one stream into another, using the given
buffer for transferring data. Note that the current contents of
the buffer is ignored, so the buffer needn't be cleared beforehand.
Reads exactly the given number of bytes from the specified stream.
If the end of the stream is reached before the specified amount
of data is read, an exception is thrown.
Reads into a buffer, filling it completely.
Reads exactly the given number of bytes from the specified stream,
into the given buffer, starting at position 0 of the array.
Reads exactly the given number of bytes from the specified stream,
into the given buffer, starting at position 0 of the array.
Same as ReadExactly, but without the argument checks.
Converts from base: 0 - 62
The source.
From.
To.
Skip the encoding process for 'safe strings'