private static void WriteValues <T>(LinkedList <T> llist, Stream stream, Type elementType, ValueSerializer elementSerializer, SerializerSession session, bool preserveObjectReferences) { if (preserveObjectReferences) { session.TrackSerializedObject(llist); } Int32Serializer.WriteValueImpl(stream, llist.Count, session); foreach (var value in llist) { stream.WriteObject(value, elementType, elementSerializer, preserveObjectReferences, session); } }
/// <summary> /// Gets the value asynchronous. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public async Task <TValue> GetAsync(TKey key) { var redisValue = await RedisDb.HashGetAsync(RedisKey, KeySerializer.Serialize(key)); return(redisValue.IsNull ? default(TValue) : ValueSerializer.Deserialize <TValue>(redisValue)); }
/// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An enumerator that can be used to iterate through the collection. /// </returns> public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator() { foreach (var hashKey in RedisDb.HashKeys(RedisKey)) { var redisValue = RedisDb.HashGet(RedisKey, hashKey); yield return(new KeyValuePair <TKey, TValue>(KeySerializer.Deserialize <TKey>(hashKey), ValueSerializer.Deserialize <TValue>(redisValue))); } }
public static bool ValueIsEqual(this HtmlTag tag, object value, string format = null) { return(tag.Val().Equals(ValueSerializer.Serialize(value, format))); }
/// <summary> /// Adds the multiple. /// </summary> /// <param name="items">The items.</param> public void AddMultiple(IEnumerable <KeyValuePair <TKey, TValue> > items) { RedisDb.HashSet(RedisKey, items.Select(i => new HashEntry(KeySerializer.Serialize(i.Key), ValueSerializer.Serialize(i.Value))).ToArray()); }
/// <summary> /// Asserts that the document in snapshot is the serialized form of the expected value. /// Note that the actual snapshot is the first parameter, somewhat unconventionally, as the expected value /// is usually wordier in code, and works better as the final argument. /// </summary> internal static void AssertSerialized(DocumentSnapshot snapshot, object expectedValue) { var serialized = ValueSerializer.SerializeMap(expectedValue); Assert.Equal(serialized, snapshot.Document.Fields); }
private void AddValueSerializer <T>(ValueSerializer instance) { _serializers.TryAdd(typeof(T), instance); }
public void SerializeMap_Invalid() { // It's unlikely that we'll ever support serializing System.Type... Assert.Throws <ArgumentException>(() => ValueSerializer.SerializeMap(SerializationContext.Default, typeof(ValueSerializer))); }
public void BadDateTimeKind(DateTimeKind kind) { var date = new DateTime(2017, 10, 6, 1, 2, 3, kind); Assert.Throws <ArgumentException>(() => ValueSerializer.Serialize(SerializationContext.Default, date)); }
public void Serialize(object input, Value expectedOutput) { var actual = ValueSerializer.Serialize(SerializationContext.Default, input); Assert.Equal(expectedOutput, actual); }
public void SerializeMap(object input, Dictionary <string, Value> expectedOutput) { var actual = ValueSerializer.SerializeMap(SerializationContext.Default, input); Assert.Equal(expectedOutput, actual); }
// Return the type named by the given name Type GetTypeFromName(string name, object context) { // use the parser context, if available. This allows early resolution. // bchapman 5/8/2009 - I believe with System.Xaml there is never an old parserContext here. // But cannot be sure. ParserContext parserContext = context as ParserContext; if (parserContext != null) { // Find the namespace prefix string nsPrefix; int nsIndex = name.IndexOf(':'); if (nsIndex == -1) { nsPrefix = string.Empty; } else { // Found a namespace prefix separator, so create replacement _pathString. // String processing - split "foons" from "BarClass.BazProp" nsPrefix = name.Substring(0, nsIndex).TrimEnd(); name = name.Substring(nsIndex + 1).TrimStart(); } // Find the namespace URI, even if its the default one string namespaceURI = parserContext.XmlnsDictionary[nsPrefix]; if (namespaceURI == null) { throw new ArgumentException(SR.Get(SRID.ParserPrefixNSProperty, nsPrefix, name)); } TypeAndSerializer typeAndSerializer = parserContext.XamlTypeMapper.GetTypeOnly(namespaceURI, name); return((typeAndSerializer != null) ? typeAndSerializer.ObjectType : null); } else { if (context is IServiceProvider) { IXamlTypeResolver xtr = (context as IServiceProvider).GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver; if (xtr != null) { return(xtr.Resolve(name)); } } IValueSerializerContext serializerContext = context as IValueSerializerContext; if (serializerContext != null) { ValueSerializer typeSerializer = ValueSerializer.GetSerializerFor(typeof(Type), serializerContext); if (typeSerializer != null) { return(typeSerializer.ConvertFromString(name, serializerContext) as Type); } } } // if there's no parser or serializer context, use the tree context DependencyObject hostElement = context as DependencyObject; if (hostElement == null) { if (FrameworkCompatibilityPreferences.TargetsDesktop_V4_0) { // WPF "OneTime" Data binding can work inconsistently when running // a .NET 4 application on .NET 4.5 compared to running it on .NET 4 // app targets 4.0, so return null, for compat return(null); } else { hostElement = new DependencyObject(); // at least pick up the default namespaces } } var wpfSharedSchemaContext = XamlReader.BamlSharedSchemaContext; Type type = wpfSharedSchemaContext.ResolvePrefixedNameWithAdditionalWpfSemantics(name, hostElement); return(type); }
public static void WriteObject(this Stream stream, object value, Type valueType, ValueSerializer valueSerializer, bool preserveObjectReferences, SerializerSession session) { if (value == null) //value is null { NullSerializer.Instance.WriteManifest(stream, session); } else { int existingId; if (preserveObjectReferences && session.TryGetObjectId(value, out existingId)) { //write the serializer manifest ObjectReferenceSerializer.Instance.WriteManifest(stream, session); //write the object reference id ObjectReferenceSerializer.Instance.WriteValue(stream, existingId, session); } else { var vType = value.GetType(); var s2 = valueSerializer; if (vType != valueType) { //value is of subtype, lookup the serializer for that type s2 = session.Serializer.GetSerializerByType(vType); } //lookup serializer for subtype s2.WriteManifest(stream, session); s2.WriteValue(stream, value, session); } } }
// Token: 0x0600247B RID: 9339 RVA: 0x000B0C84 File Offset: 0x000AEE84 private string ConvertMarkupItemToString(MarkupObject item) { ValueSerializer valueSerializerFor = this._context.GetValueSerializerFor(typeof(Type)); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('{'); string text = valueSerializerFor.ConvertToString(item.ObjectType, this._context); if (text.EndsWith("Extension", StringComparison.Ordinal)) { stringBuilder.Append(text, 0, text.Length - 9); } else { stringBuilder.Append(text); } bool flag = true; foreach (MarkupProperty markupProperty in item.Properties) { stringBuilder.Append(flag ? " " : ", "); flag = false; if (!markupProperty.IsConstructorArgument) { stringBuilder.Append(markupProperty.Name); stringBuilder.Append('='); } string text2 = markupProperty.StringValue; if (text2 != null && text2.Length > 0) { if (text2[0] == '{') { if (text2.Length <= 1 || text2[1] != '}') { stringBuilder.Append(text2); continue; } text2 = text2.Substring(2); } foreach (char c in text2) { if (c != ',') { if (c != '{') { if (c != '}') { stringBuilder.Append(c); } else { stringBuilder.Append("\\}"); } } else { stringBuilder.Append("\\{"); } } else { stringBuilder.Append("\\,"); } } } } stringBuilder.Append('}'); return(stringBuilder.ToString()); }
private string ConvertMarkupItemToString(MarkupObject item) { ValueSerializer typeSerializer = _context.GetValueSerializerFor(typeof(Type)); Debug.Assert(typeSerializer != null, "Could not retrieve typeSerializer for Type"); // Serialize the markup extension into a string StringBuilder resultBuilder = new StringBuilder(); resultBuilder.Append('{'); string typeName = typeSerializer.ConvertToString(item.ObjectType, _context); if (typeName.EndsWith("Extension", StringComparison.Ordinal)) { // The "Extension" suffix is optional, much like the Attribute suffix of an Attribute. // The normalized version is without the suffix. resultBuilder.Append(typeName, 0, typeName.Length - EXTENSIONLENGTH); } else { resultBuilder.Append(typeName); } bool first = true; bool propertyWritten = false; foreach (MarkupProperty property in item.Properties) { resultBuilder.Append(first ? " " : ", "); first = false; if (!property.IsConstructorArgument) { resultBuilder.Append(property.Name); resultBuilder.Append('='); propertyWritten = true; } else { Debug.Assert(!propertyWritten, "An argument was returned after a property was set. All arguments must be returned first and in order"); } string value = property.StringValue; if (value != null && value.Length > 0) { if (value[0] == '{') { if (value.Length > 1 && value[1] == '}') { // It is a literal quote, remove the literals and write the text with escapes. value = value.Substring(2); } else { // It is a nested markup-extension, just insert the text literally. resultBuilder.Append(value); continue; } } // Escape the string for (int i = 0; i < value.Length; i++) { char ch = value[i]; switch (ch) { case '{': resultBuilder.Append(@"\{"); break; case '}': resultBuilder.Append(@"\}"); break; case ',': resultBuilder.Append(@"\,"); break; default: resultBuilder.Append(ch); break; } } } } resultBuilder.Append('}'); return(resultBuilder.ToString()); }
private static void WriteValues <T>(T[] array, Stream stream, Type elementType, ValueSerializer elementSerializer, SerializerSession session) { Int32Serializer.WriteValueImpl(stream, array.Length, session); var preserveObjectReferences = session.Serializer.Options.PreserveObjectReferences; foreach (var value in array) { stream.WriteObject(value, elementType, elementSerializer, preserveObjectReferences, session); } }
public void StringValueSerializer() { var vs = ValueSerializer.GetSerializerFor(typeof(string)); Assert.AreEqual(String.Empty, vs.ConvertToString(String.Empty, null), "#1"); // it does not convert String.Empty to "\"\"" }
private static void WriteValues <T>(T[] array, Stream stream, Type elementType, ValueSerializer elementSerializer, SerializerSession session, bool preserveObjectReferences) { if (preserveObjectReferences) { session.TrackSerializedObject(array); } Int32Serializer.WriteValueImpl(stream, array.Length, session); foreach (var value in array) { stream.WriteObject(value, elementType, elementSerializer, preserveObjectReferences, session); } }
private void AddValueSerializer(ValueSerializer instance, Type type) { _serializers.TryAdd(type, instance); }
public void Query(SerializableTest wrapper) { QueryTest test = wrapper.Test.Query; if (test.IsError) { var exception = Assert.ThrowsAny <Exception>(() => BuildQuery()); Assert.True(exception is ArgumentException || exception is InvalidOperationException, $"Exception type: {exception.GetType()}"); } else { var query = BuildQuery(); Assert.Equal(test.Query, query.ToStructuredQuery()); } Query BuildQuery() { Query query = GetCollectionReference(test.CollPath); foreach (var clause in test.Clauses) { switch (clause.ClauseCase) { case Clause.ClauseOneofCase.EndAt: query = query.EndAt(ConvertCursor(clause.EndAt)); break; case Clause.ClauseOneofCase.EndBefore: query = query.EndBefore(ConvertCursor(clause.EndBefore)); break; case Clause.ClauseOneofCase.Limit: query = query.Limit(clause.Limit); break; case Clause.ClauseOneofCase.Offset: query = query.Offset(clause.Offset); break; case Clause.ClauseOneofCase.OrderBy: var ordering = clause.OrderBy; var path = ConvertFieldPath(ordering.Path); query = ordering.Direction == "asc" ? query.OrderBy(path) : query.OrderByDescending(path); break; case Clause.ClauseOneofCase.Select: query = query.Select(clause.Select.Fields.Select(ConvertFieldPath).ToArray()); break; case Clause.ClauseOneofCase.StartAfter: query = query.StartAfter(ConvertCursor(clause.StartAfter)); break; case Clause.ClauseOneofCase.StartAt: query = query.StartAt(ConvertCursor(clause.StartAt)); break; case Clause.ClauseOneofCase.Where: var filterPath = ConvertFieldPath(clause.Where.Path); if (!QueryOperators.TryGetValue(clause.Where.Op, out var filterProvider)) { throw new ArgumentException($"Invalid where operator: {clause.Where.Op}"); } var value = DeserializeJson(clause.Where.JsonValue); query = filterProvider(query, filterPath, value); break; default: throw new InvalidOperationException($"Unexpected clause case: {clause.ClauseCase}"); } } return(query); } // Note: dynamic to allow a DocumentSnapshot to be returned and used in overload resolution. dynamic ConvertCursor(Cursor cursor) { var docSnapshot = cursor.DocSnapshot; if (docSnapshot == null) { return(cursor.JsonValues.Select(DeserializeJson).ToArray()); } var docRef = GetDocumentReference(docSnapshot.Path); return(DocumentSnapshot.ForDocument( docRef.Database, new Document { Name = docRef.Path, Fields = { ValueSerializer.SerializeMap(DeserializeJson(cursor.DocSnapshot.JsonData)) }, CreateTime = wkt::Timestamp.FromDateTimeOffset(DateTimeOffset.MinValue), UpdateTime = wkt::Timestamp.FromDateTimeOffset(DateTimeOffset.MinValue), }, Timestamp.FromDateTimeOffset(DateTimeOffset.MinValue))); } }
public static THtmlTag Val <THtmlTag>(this THtmlTag tag, object value, string format = null) where THtmlTag : HtmlTag { return(tag.Attrib("value", ValueSerializer.Serialize(value, format))); }
abstract public string ConvertToString(IValueSerializerContext context, ValueSerializer serializer, object instance);
/// <summary> /// ConvertTo - Attempt to convert a PropertyPath to the given type /// </summary> /// <returns> /// The object which was constructed. /// </returns> /// <exception cref="ArgumentNullException"> /// An ArgumentNullException is thrown if the example object is null. /// </exception> /// <exception cref="ArgumentException"> /// An ArgumentException is thrown if the example object is not null and is not a Brush, /// or if the destinationType isn't one of the valid destination types. /// </exception> /// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call. /// If this is null, then no namespace prefixes will be included.</param> /// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param> /// <param name="value"> The PropertyPath to convert. </param> /// <param name="destinationType">The type to which to convert the PropertyPath instance. </param> public override object ConvertTo(ITypeDescriptorContext typeDescriptorContext, CultureInfo cultureInfo, object value, Type destinationType) { if (null == value) { throw new ArgumentNullException("value"); } if (null == destinationType) { throw new ArgumentNullException("destinationType"); } if (destinationType != typeof(String)) { throw new ArgumentException(SR.Get(SRID.CannotConvertType, typeof(PropertyPath), destinationType.FullName)); } PropertyPath path = value as PropertyPath; if (path == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(PropertyPath)), "value"); } if (path.PathParameters.Count == 0) { // if the path didn't use paramaters, just write it out as it is return(path.Path); } else { // if the path used parameters, convert them to (NamespacePrefix:OwnerType.DependencyPropertyName) syntax string originalPath = path.Path; Collection <object> parameters = path.PathParameters; XamlDesignerSerializationManager manager = typeDescriptorContext == null ? null : typeDescriptorContext.GetService(typeof(XamlDesignerSerializationManager)) as XamlDesignerSerializationManager; ValueSerializer typeSerializer = null; IValueSerializerContext serializerContext = null; if (manager == null) { serializerContext = typeDescriptorContext as IValueSerializerContext; if (serializerContext != null) { typeSerializer = ValueSerializer.GetSerializerFor(typeof(Type), serializerContext); } } StringBuilder builder = new StringBuilder(); int start = 0; for (int i = 0; i < originalPath.Length; ++i) { // look for (n) if (originalPath[i] == '(') { int j; for (j = i + 1; j < originalPath.Length; ++j) { if (originalPath[j] == ')') { break; } } int index; if (Int32.TryParse(originalPath.AsSpan(i + 1, j - i - 1), NumberStyles.Integer, TypeConverterHelper.InvariantEnglishUS.NumberFormat, out index)) { // found (n). Write out the path so far, including the opening ( builder.Append(originalPath.AsSpan(start, i - start + 1)); object pathPart = parameters[index]; // get the owner type and name of the accessor DependencyProperty dp; PropertyInfo pi; PropertyDescriptor pd; DynamicObjectAccessor doa; PropertyPath.DowncastAccessor(pathPart, out dp, out pi, out pd, out doa); Type type; // the accessor's ownerType, or type of indexer parameter string name; // the accessor's propertyName, or string value of indexer parameter if (dp != null) { type = dp.OwnerType; name = dp.Name; } else if (pi != null) { type = pi.DeclaringType; name = pi.Name; } else if (pd != null) { type = pd.ComponentType; name = pd.Name; } else if (doa != null) { type = doa.OwnerType; name = doa.PropertyName; } else { // pathPart is an Indexer Parameter type = pathPart.GetType(); name = null; } // write out the type of the accessor or index parameter if (typeSerializer != null) { builder.Append(typeSerializer.ConvertToString(type, serializerContext)); } else { // Need the prefix here string prefix = null; if (prefix != null && prefix != string.Empty) { builder.Append(prefix); builder.Append(':'); } builder.Append(type.Name); } if (name != null) { // write out the accessor name builder.Append('.'); builder.Append(name); // write out the closing ) builder.Append(')'); } else { // write out the ) that closes the parameter's type builder.Append(')'); name = pathPart as string; if (name == null) { // convert the parameter into string TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { try { name = converter.ConvertToString(pathPart); } catch (NotSupportedException) { } } } // write out the parameter's value string builder.Append(name); } // resume after the (n) i = j; start = j + 1; } } } if (start < originalPath.Length) { builder.Append(originalPath.AsSpan(start)); } return(builder.ToString()); } }
public override string ConvertToString(IValueSerializerContext context, ValueSerializer serializer, object instance) { return(_transparentRuntime.ConvertToString(context, serializer, instance)); }
/// <summary> /// Adds the multiple asynchronous. /// </summary> /// <param name="tran">The tran.</param> /// <param name="items">The items.</param> /// <returns></returns> public async Task AddMultipleAsync(ITransaction tran, IEnumerable <KeyValuePair <TKey, TValue> > items) { await tran.HashSetAsync(RedisKey, items.Select(i => new HashEntry(KeySerializer.Serialize(i.Key), ValueSerializer.Serialize(i.Value))).ToArray()); }
public override bool CanConvertFromString(string value, IValueSerializerContext context) { return(ValueSerializer.GetSerializerFor(typeof(Type), context) != null); }
/// <summary> /// Gets the values asynchronous. /// </summary> /// <returns></returns> public async Task <ICollection <TValue> > GetValuesAsync() { return(new Collection <TValue>((await RedisDb.HashValuesAsync(RedisKey)).Select(h => ValueSerializer.Deserialize <TValue>(h)).ToList())); }
public void CanConvertToStringNullContext() { ValueSerializer serializer = (ValueSerializer)ValueSerializer.GetSerializerFor(typeof(DateTime)); Assert.IsTrue(serializer.CanConvertToString(DateTime.Now, null)); }
/// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="when">The when.</param> /// <returns></returns> public bool Add(TKey key, TValue value, When when) { return(RedisDb.HashSet(RedisKey, KeySerializer.Serialize(key), ValueSerializer.Serialize(value), when: when)); }
private static void WriteValues <T>(T[] array, Stream stream, Type elementType, ValueSerializer elementSerializer, SerializerSession session) { stream.WriteInt32(array.Length); var preserveObjectReferences = session.Serializer.Options.PreserveObjectReferences; for (int i = 0; i < array.Length; i++) { var value = array[i]; stream.WriteObject(value, elementType, elementSerializer, preserveObjectReferences, session); } }