public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { IDictionary<string, object> obj = value as IDictionary<string, object>; if (obj == null) { bsonWriter.WriteNull(); return; } bsonWriter.WriteStartDocument(); foreach (var member in obj) { bsonWriter.WriteName(member.Key); object memberValue = member.Value; if (memberValue == null) { bsonWriter.WriteNull(); } else { nominalType = memberValue.GetType(); var serializer = BsonSerializer.LookupSerializer(nominalType); serializer.Serialize(bsonWriter, nominalType, memberValue, options); } } bsonWriter.WriteEndDocument(); }
private void WriteBson(BsonWriter writer, Regex regex) { // Regular expression - The first cstring is the regex pattern, the second // is the regex options string. Options are identified by characters, which // must be stored in alphabetical order. Valid options are 'i' for case // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. string options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) options += "i"; if (HasFlag(regex.Options, RegexOptions.Multiline)) options += "m"; if (HasFlag(regex.Options, RegexOptions.Singleline)) options += "s"; options += "u"; if (HasFlag(regex.Options, RegexOptions.ExplicitCapture)) options += "x"; writer.WriteRegex(regex.ToString(), options); }
private static bool IsRelationalAssociation(BsonWriter bsonWriter, object value) { if (value == null || bsonWriter.State != BsonWriterState.Value) return false; return IsRelationalType(value.GetType()); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (IsRelationalAssociation(bsonWriter, value)) RelationSerializer.Instance.Serialize(bsonWriter, nominalType, value, options); else CustomBsonClassMapSerializer.Instance.Serialize(bsonWriter, nominalType, value, options); }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { if (value == null) { bsonWriter.WriteNull(); return; } var nvc = (NameValueCollection)value; bsonWriter.WriteStartArray(); foreach (var key in nvc.AllKeys) { foreach (var val in nvc.GetValues(key)) { bsonWriter.WriteStartArray(); StringSerializer.Instance.Serialize(bsonWriter, typeof(string), key, options); StringSerializer.Instance.Serialize(bsonWriter, typeof(string), val, options); bsonWriter.WriteEndArray(); } } bsonWriter.WriteEndArray(); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var idPropertyInfo = value.GetType().GetProperty("ID"); var id = (ObjectId) idPropertyInfo.GetValue(value, null); if (id == ObjectId.Empty) throw new Exception("Relational associations must be saved before saving the parent relation"); ObjectIdSerializer.Instance.Serialize(bsonWriter, id.GetType(), id, options); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var c = (C)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteString("nominalType", nominalType.Name); bsonWriter.WriteInt32("X", c.X); bsonWriter.WriteEndDocument(); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { int intValue; if (value is string && int.TryParse((string)value, out intValue)) bsonWriter.WriteInt32(intValue); else throw new InvalidOperationException(); }
public void TestCalculateSizeOfEmptyDoc() { Document doc = new Document(); MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); Assert.AreEqual(5,writer.CalculateSize(doc)); }
protected override void WriteBody(BsonWriter writer) { writer.WriteValue(BsonDataType.Integer,0); writer.WriteString(this.FullCollectionName); writer.WriteValue(BsonDataType.Integer,this.Flags); writer.Write(selector); writer.Write(Document); }
protected override void Serialize( BsonWriter bsonWriter, Type nominalType, bool serializeIdFirst ) { document.Serialize(bsonWriter, nominalType, serializeIdFirst); }
void IBsonSerializable.Serialize( BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options ) { Serialize(bsonWriter, nominalType, options); }
public void Serialize( BsonWriter bsonWriter, Type nominalType, // ignored bool serializeIdFirst ) { BsonSerializer.Serialize(bsonWriter, this.nominalType, obj, serializeIdFirst); // use wrapped nominalType }
void IBsonSerializable.Serialize( BsonWriter bsonWriter, Type nominalType, bool serializeIdFirst ) { Serialize(bsonWriter, nominalType, serializeIdFirst); }
public void Serialize( BsonWriter bsonWriter, Type nominalType, // ignored IBsonSerializationOptions options ) { BsonSerializer.Serialize(bsonWriter, this.nominalType, obj, options); // use wrapped nominalType }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { var dateTime = (DateTime) value; bsonWriter.WriteString(dateTime.ToString("yyyy-MM-dd")); }
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var timeOfDay = (TimeOfDay)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteInt32("Hour", timeOfDay.Hour); bsonWriter.WriteInt32("Minute", timeOfDay.Minute); bsonWriter.WriteInt32("Second", timeOfDay.Second); bsonWriter.WriteEndDocument(); }
protected override int CalculateBodySize(BsonWriter writer) { int size = 4; //first int32 size += writer.CalculateSize(this.FullCollectionName,false); size += 4; //flags size += writer.CalculateSize(this.Selector); size += writer.CalculateSize(this.Document); return size; }
protected override void WriteBody(Stream stream) { BsonWriter writer = new BsonWriter(stream); writer.Write((int)0); writer.Write(this.FullCollectionName); writer.Write(this.Upsert); selector.Write(writer); document.Write(writer); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { ObjectIdSerializer.Instance.Serialize(bsonWriter, nominalType, IdentifierFinder.GetId(value), options); } }
public void TestNullsDontThrowExceptionsExceptions() { MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); Document doc = new Document().Append("n", null); try{ writer.Write(doc); }catch(NullReferenceException){ Assert.Fail("Null Reference Exception was thrown on trying to serialize a null value"); } }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var attachment = (Attachment)value; ObjectIdSerializer.Instance.Serialize(bsonWriter, nominalType, attachment.ID, options); } }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value != null) { bsonWriter.WriteString(value.ToString()); } else { bsonWriter.WriteNull(); } }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value != null) { var idPropertyInfo = value.GetType().GetProperty("ID"); var id = (ObjectId) idPropertyInfo.GetValue(value, null); if (id == ObjectId.Empty) idPropertyInfo.SetValue(value, ObjectId.GenerateNewId(), null); } base.Serialize(bsonWriter, nominalType, value, options); }
public void TestCalculateSizeOfSimpleDoc() { Document doc = new Document(); doc.Append("a","a"); doc.Append("b",1); MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); //BsonDocument bdoc = BsonConvert.From(doc); Assert.AreEqual(21,writer.CalculateSize(doc)); }
public void TestCalculateSizeOfComplexDoc() { Document doc = new Document(); doc.Append("a","a"); doc.Append("b",1); Document sub = new Document().Append("c_1",1).Append("c_2",DateTime.Now); doc.Append("c",sub); MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); Assert.AreEqual(51,writer.CalculateSize(doc)); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) throw new PBException("serialize OXmlSimpleFieldElement value is null"); if (_trace) pb.Trace.WriteLine("OXmlSimpleFieldElementSerializer.Serialize()"); OXmlSimpleFieldElement element = (OXmlSimpleFieldElement)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteString("Type", "SimpleField"); bsonWriter.WriteString("Instruction", element.Instruction); bsonWriter.WriteEndDocument(); }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, bool serializeIdFirst ) { if (value == null) { bsonWriter.WriteNull(); } else { ((BsonArray) value).WriteTo(bsonWriter); } }
public void TestWriteArrayDoc() { String expected = "2000000002300002000000610002310002000000620002320002000000630000"; MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); String[] str = new String[]{"a","b","c"}; writer.WriteValue(BsonDataType.Array,str); string hexdump = BitConverter.ToString(ms.ToArray()); hexdump = hexdump.Replace("-",""); Assert.AreEqual(expected, hexdump); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { if (value == null) { bsonWriter.WriteNull(); } else { var array = (BsonArray) value; array.WriteTo(bsonWriter); } }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { bsonWriter.WriteString(((ReflectionType)value).ToString()); }
// protected methods /// <summary> /// Serializes the result of the builder to a BsonWriter. /// </summary> /// <param name="bsonWriter">The writer.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="options">The serialization options.</param> protected abstract void Serialize( BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options);
// protected /// <summary> /// Serializes the result of the builder to a BsonWriter. /// </summary> /// <param name="bsonWriter">The writer.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="options">The serialization options.</param> protected override void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { ((IBsonSerializable)_document).Serialize(bsonWriter, nominalType, options); }
protected override void BeginProcessing() { FileFormat = ResolveFileFormat(FileFormat, Path); Path = GetUnresolvedProviderPathFromPSPath(Path); var time = Stopwatch.StartNew(); for (; ;) { try { if (FileFormat == FileFormat.Bson) { FileStream fileStream = null; try { fileStream = File.Open(Path, (Append ? FileMode.Append : FileMode.Create)); _bsonWriter = new BsonBinaryWriter(fileStream); } finally { _dispose = () => { fileStream?.Dispose(); }; } } else { StreamWriter streamWriter = null; try { var settings = JsonWriterSettings.Defaults; switch (FileFormat) { case FileFormat.JsonShell: settings = settings.Clone(); settings.OutputMode = JsonOutputMode.Shell; break; case FileFormat.JsonStrict: settings = settings.Clone(); #pragma warning disable 618 // obsolete JsonOutputMode.Strict settings.OutputMode = JsonOutputMode.Strict; #pragma warning restore 618 break; case FileFormat.JsonCanonicalExtended: settings = settings.Clone(); settings.OutputMode = JsonOutputMode.CanonicalExtendedJson; break; case FileFormat.JsonRelaxedExtended: settings = settings.Clone(); settings.OutputMode = JsonOutputMode.RelaxedExtendedJson; break; } streamWriter = new StreamWriter(Path, Append); _bsonWriter = new JsonWriter(streamWriter, settings); _endDocument = () => { streamWriter.WriteLine(); }; } finally { _dispose = () => { streamWriter?.Dispose(); }; } } _context = BsonSerializationContext.CreateRoot(_bsonWriter); break; } catch (IOException) { if (Retry == null || time.Elapsed > Retry[0]) { throw; } if (Retry.Length < 2) { Thread.Sleep(50); } else { Thread.Sleep(Retry[1]); } WriteVerbose("Retrying to write..."); } } }
/// <summary> /// Serializes the fields. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="obj">The GeoJson object.</param> protected override void SerializeFields(BsonWriter bsonWriter, GeoJsonObject <TCoordinates> obj) { var multiPolygon = (GeoJsonMultiPolygon <TCoordinates>)obj; SerializeCoordinates(bsonWriter, multiPolygon.Coordinates); }
public void SerializeGoogleGeoCode() { string json = @"{ ""name"": ""1600 Amphitheatre Parkway, Mountain View, CA, USA"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""address"": ""1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"", ""AddressDetails"": { ""Country"": { ""CountryNameCode"": ""US"", ""AdministrativeArea"": { ""AdministrativeAreaName"": ""CA"", ""SubAdministrativeArea"": { ""SubAdministrativeAreaName"": ""Santa Clara"", ""Locality"": { ""LocalityName"": ""Mountain View"", ""Thoroughfare"": { ""ThoroughfareName"": ""1600 Amphitheatre Pkwy"" }, ""PostalCode"": { ""PostalCodeNumber"": ""94043"" } } } } }, ""Accuracy"": 8 }, ""Point"": { ""coordinates"": [-122.083739, 37.423021, 0] } } ] }"; GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject <GoogleMapGeocoderStructure>(json); MemoryStream ms = new MemoryStream(); BsonWriter writer = new BsonWriter(ms); JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, jsonGoogleMapGeocoder); ms.Seek(0, SeekOrigin.Begin); BsonReader reader = new BsonReader(ms); GoogleMapGeocoderStructure bsonGoogleMapGeocoder = (GoogleMapGeocoderStructure)serializer.Deserialize(reader, typeof(GoogleMapGeocoderStructure)); Assert.IsNotNull(bsonGoogleMapGeocoder); Assert.AreEqual("1600 Amphitheatre Parkway, Mountain View, CA, USA", bsonGoogleMapGeocoder.Name); Assert.AreEqual("200", bsonGoogleMapGeocoder.Status.Code); Assert.AreEqual("geocode", bsonGoogleMapGeocoder.Status.Request); IList <Placemark> placemarks = bsonGoogleMapGeocoder.Placemark; Assert.IsNotNull(placemarks); Assert.AreEqual(1, placemarks.Count); Placemark placemark = placemarks[0]; Assert.AreEqual("1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", placemark.Address); Assert.AreEqual(8, placemark.AddressDetails.Accuracy); Assert.AreEqual("US", placemark.AddressDetails.Country.CountryNameCode); Assert.AreEqual("CA", placemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName); Assert.AreEqual("Santa Clara", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName); Assert.AreEqual("Mountain View", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName); Assert.AreEqual("1600 Amphitheatre Pkwy", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName); Assert.AreEqual("94043", placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber); Assert.AreEqual(-122.083739m, placemark.Point.Coordinates[0]); Assert.AreEqual(37.423021m, placemark.Point.Coordinates[1]); Assert.AreEqual(0m, placemark.Point.Coordinates[2]); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { // Nullable types are weird because they get boxed as their underlying value type // we can best handle that by switching the nominalType to the underlying value type // (so VerifyNominalType doesn't fail and we don't get an unnecessary discriminator) if (nominalType.IsGenericType && nominalType.GetGenericTypeDefinition() == typeof(Nullable <>)) { nominalType = nominalType.GetGenericArguments()[0]; } VerifyNominalType(nominalType); var actualType = (value == null) ? nominalType : value.GetType(); if (actualType != _classMap.ClassType) { var message = string.Format("BsonClassMapSerializer.Serialize for type {0} was called with actualType {1}.", BsonUtils.GetFriendlyTypeName(_classMap.ClassType), BsonUtils.GetFriendlyTypeName(actualType)); throw new BsonSerializationException(message); } var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions; if (documentSerializationOptions == null) { var message = string.Format( "Serializer BsonClassMapSerializer expected serialization options of type {0}, not {1}.", BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)), BsonUtils.GetFriendlyTypeName(options.GetType())); throw new BsonSerializationException(message); } bsonWriter.WriteStartDocument(); BsonMemberMap idMemberMap = null; if (documentSerializationOptions.SerializeIdFirst) { idMemberMap = _classMap.IdMemberMap; if (idMemberMap != null) { SerializeMember(bsonWriter, value, idMemberMap); } } if (actualType != nominalType || _classMap.DiscriminatorIsRequired || _classMap.HasRootClass) { // never write out a discriminator for an anonymous class if (!_classMap.IsAnonymous) { var discriminatorConvention = _classMap.GetDiscriminatorConvention(); var discriminator = discriminatorConvention.GetDiscriminator(nominalType, actualType); if (discriminator != null) { bsonWriter.WriteName(discriminatorConvention.ElementName); BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), discriminator, null); } } } var allMemberMaps = _classMap.AllMemberMaps; var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex; for (var memberMapIndex = 0; memberMapIndex < allMemberMaps.Count; ++memberMapIndex) { var memberMap = allMemberMaps[memberMapIndex]; // note: if serializeIdFirst is false then idMemberMap will be null (so no property will be skipped) if (memberMap != idMemberMap) { if (memberMapIndex != extraElementsMemberMapIndex) { SerializeMember(bsonWriter, value, memberMap); } else { SerializeExtraElements(bsonWriter, value, memberMap); } } } bsonWriter.WriteEndDocument(); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <typeparam name="TNominalType">The nominal type of the object.</typeparam> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="value">The object.</param> public static void Serialize <TNominalType>(BsonWriter bsonWriter, TNominalType value) { Serialize(bsonWriter, value, null); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="value">The object.</param> public static void Serialize(BsonWriter bsonWriter, Type nominalType, object value) { Serialize(bsonWriter, nominalType, value, null); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { bsonWriter.WriteObjectId(ObjectId.Parse((string)value)); }
void IBsonSerializable.Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { Serialize(bsonWriter, nominalType, options); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType bsonWriter.WriteEndDocument(); return; } var dictionary = (IDictionary)value; var dictionarySerializationOptions = EnsureSerializationOptions(options); var dictionaryRepresentation = dictionarySerializationOptions.Representation; var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions; if (dictionaryRepresentation == DictionaryRepresentation.Dynamic) { dictionaryRepresentation = DictionaryRepresentation.Document; foreach (object key in dictionary.Keys) { var name = key as string; // key might not be a string if (string.IsNullOrEmpty(name) || name[0] == '$' || name.IndexOf('.') != -1 || name.IndexOf('\0') != -1) { dictionaryRepresentation = DictionaryRepresentation.ArrayOfArrays; break; } } } switch (dictionaryRepresentation) { case DictionaryRepresentation.Document: bsonWriter.WriteStartDocument(); foreach (DictionaryEntry dictionaryEntry in dictionary) { bsonWriter.WriteName((string)dictionaryEntry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), dictionaryEntry.Value, keyValuePairSerializationOptions.ValueSerializationOptions); } bsonWriter.WriteEndDocument(); break; case DictionaryRepresentation.ArrayOfArrays: case DictionaryRepresentation.ArrayOfDocuments: // override KeyValuePair representation if necessary var keyValuePairRepresentation = (dictionaryRepresentation == DictionaryRepresentation.ArrayOfArrays) ? BsonType.Array : BsonType.Document; if (keyValuePairSerializationOptions.Representation != keyValuePairRepresentation) { keyValuePairSerializationOptions = new KeyValuePairSerializationOptions( keyValuePairRepresentation, keyValuePairSerializationOptions.KeySerializationOptions, keyValuePairSerializationOptions.ValueSerializationOptions); } bsonWriter.WriteStartArray(); foreach (DictionaryEntry dictionaryEntry in dictionary) { var keyValuePair = new KeyValuePair <object, object>(dictionaryEntry.Key, dictionaryEntry.Value); _keyValuePairSerializer.Serialize( bsonWriter, typeof(KeyValuePair <object, object>), keyValuePair, keyValuePairSerializationOptions); } bsonWriter.WriteEndArray(); break; default: var message = string.Format("'{0}' is not a valid IDictionary representation.", dictionaryRepresentation); throw new BsonSerializationException(message); } } }
/// <summary> /// Calculates the size of the body. /// </summary> /// <param name="writer">The writer.</param> /// <returns></returns> protected abstract int CalculateBodySize(BsonWriter writer);
/// <summary> /// Writes the body. /// </summary> /// <param name="writer">The writer.</param> protected abstract void WriteBody(BsonWriter writer);
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { serializer.Serialize(bsonWriter, nominalType, value, options); }
// protected methods /// <summary> /// Serializes the result of the builder to a BsonWriter. /// </summary> /// <param name="bsonWriter">The writer.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="options">The serialization options.</param> protected override void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { BsonDocumentSerializer.Instance.Serialize(bsonWriter, nominalType, _document, options); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var dateTime = (DateTime)value; var dateTimeOptions = (options == null) ? DateTimeSerializationOptions.Defaults : (DateTimeSerializationOptions)options; DateTime utcDateTime; if (dateTimeOptions.DateOnly) { if (dateTime.TimeOfDay != TimeSpan.Zero) { throw new BsonSerializationException("TimeOfDay component is not zero."); } utcDateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); // not ToLocalTime } else { utcDateTime = BsonUtils.ToUniversalTime(dateTime); } var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); switch (dateTimeOptions.Representation) { case BsonType.DateTime: bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch); bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks); bsonWriter.WriteEndDocument(); break; case BsonType.Int64: bsonWriter.WriteInt64(utcDateTime.Ticks); break; case BsonType.String: if (dateTimeOptions.DateOnly) { bsonWriter.WriteString(dateTime.ToString("yyyy-MM-dd")); } else { // we're not using XmlConvert.ToString because of bugs in Mono if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) { // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); } else if (dateTime.Kind == DateTimeKind.Unspecified) { // serialize Unspecified as Local se we get the time zone offset dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local); } bsonWriter.WriteString(dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK")); } break; default: var message = string.Format("'{0}' is not a valid representation for type DateTime.", dateTimeOptions.Representation); throw new BsonSerializationException(message); } }
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var timeZoneInfo = (TimeZoneInfo)value; bsonWriter.WriteString(timeZoneInfo.Id); }
/// <summary> /// Gets the serializer specific serialization context info. /// </summary> /// <param name="model">The model, can be <c>null</c> for value types.</param> /// <param name="modelType">Type of the model.</param> /// <param name="stream">The stream.</param> /// <param name="contextMode">The context mode.</param> /// <param name="configuration">The configuration.</param> /// <returns> /// The serialization context. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="model" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="modelType" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="configuration" /> is <c>null</c>.</exception> protected override ISerializationContext <JsonSerializationContextInfo> GetSerializationContextInfo(object model, Type modelType, Stream stream, SerializationContextMode contextMode, ISerializationConfiguration configuration) { JsonReader jsonReader = null; JsonWriter jsonWriter = null; var useBson = false; var dateTimeKind = DateTimeKind.Unspecified; var dateParseHandling = DateParseHandling.None; var dateTimeZoneHandling = DateTimeZoneHandling.Unspecified; var formatting = Formatting.None; var jsonConfiguration = configuration as JsonSerializationConfiguration; if (jsonConfiguration != null) { useBson = jsonConfiguration.UseBson; dateTimeKind = jsonConfiguration.DateTimeKind; dateParseHandling = jsonConfiguration.DateParseHandling; dateTimeZoneHandling = jsonConfiguration.DateTimeZoneHandling; formatting = jsonConfiguration.Formatting; } switch (contextMode) { case SerializationContextMode.Serialization: if (useBson) { #if SUPPORT_BSON #pragma warning disable 618 jsonWriter = new BsonWriter(stream); #pragma warning restore 618 #endif } if (jsonWriter is null) { var streamWriter = new StreamWriter(stream, Encoding.UTF8); jsonWriter = new JsonTextWriter(streamWriter); } break; case SerializationContextMode.Deserialization: if (useBson) { #if SUPPORT_BSON var shouldSerializeAsCollection = false; var shouldSerializeAsDictionary = ShouldSerializeAsDictionary(modelType); if (!shouldSerializeAsDictionary) { // Only check if we should deserialize as collection if we are not a dictionary shouldSerializeAsCollection = ShouldSerializeAsCollection(modelType); } #pragma warning disable 618 jsonReader = new BsonReader(stream, shouldSerializeAsCollection, dateTimeKind); #pragma warning restore 618 #endif } if (jsonReader is null) { var streamReader = new StreamReader(stream, Encoding.UTF8); jsonReader = new JsonTextReader(streamReader); } break; default: throw new ArgumentOutOfRangeException("contextMode"); } if (jsonReader != null) { jsonReader.Culture = configuration.Culture; jsonReader.DateParseHandling = dateParseHandling; jsonReader.DateTimeZoneHandling = dateTimeZoneHandling; } if (jsonWriter != null) { jsonWriter.Culture = configuration.Culture; jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling; jsonWriter.Formatting = formatting; } return(GetSerializationContextInfo(model, modelType, jsonReader, jsonWriter, contextMode, null, null, configuration)); }
/// <summary> /// Serializes the fields. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="obj">The GeoJson object.</param> protected override void SerializeFields(BsonWriter bsonWriter, GeoJsonObject <TCoordinates> obj) { var multiLineString = (GeoJsonMultiLineString <TCoordinates>)obj; SerializeCoordinates(bsonWriter, multiLineString.Coordinates); }
private void SerializeGeometry(BsonWriter bsonWriter, GeoJsonGeometry <TCoordinates> geometry) { bsonWriter.WriteName("geometry"); _geometrySerializer.Serialize(bsonWriter, typeof(GeoJsonGeometry <TCoordinates>), geometry, null); }
private void SerializeSize(object value) { // this is extremely slow with 5000 interations int interations = 100; byte[] jsonBytes = TimeOperation(() => { string json = null; for (int i = 0; i < interations; i++) { json = JsonConvert.SerializeObject(value, Formatting.None); } return(Encoding.UTF8.GetBytes(json)); }, "Json.NET"); byte[] bsonBytes = TimeOperation(() => { MemoryStream ms = null; for (int i = 0; i < interations; i++) { ms = new MemoryStream(); JsonSerializer serializer = new JsonSerializer(); BsonWriter writer = new BsonWriter(ms); serializer.Serialize(writer, value); writer.Flush(); } return(ms.ToArray()); }, "Json.NET BSON"); byte[] xmlBytes = TimeOperation(() => { MemoryStream ms = null; for (int i = 0; i < interations; i++) { ms = new MemoryStream(); DataContractSerializer dataContractSerializer = new DataContractSerializer(value.GetType()); dataContractSerializer.WriteObject(ms, value); } return(ms.ToArray()); }, "DataContractSerializer"); byte[] wcfJsonBytes = TimeOperation(() => { MemoryStream ms = null; for (int i = 0; i < interations; i++) { ms = new MemoryStream(); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(value.GetType()); dataContractJsonSerializer.WriteObject(ms, value); } return(ms.ToArray()); }, "DataContractJsonSerializer"); byte[] binaryFormatterBytes = TimeOperation(() => { MemoryStream ms = null; for (int i = 0; i < interations; i++) { ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, value); } return(ms.ToArray()); }, "BinaryFormatter"); Console.WriteLine("Json.NET size: {0} bytes", jsonBytes.Length); Console.WriteLine("BSON size: {0} bytes", bsonBytes.Length); Console.WriteLine("WCF JSON size: {0} bytes", wcfJsonBytes.Length); Console.WriteLine("WCF XML size: {0} bytes", xmlBytes.Length); Console.WriteLine("BinaryFormatter size: {0} bytes", binaryFormatterBytes.Length); }
private async void FirstConnection(object sender, Sockets.Plugin.Abstractions.TcpSocketListenerConnectEventArgs e) { Debug.WriteLine("TCP/ Host connected!"); var messageBuffer = new byte[8]; await e.SocketClient.ReadStream.ReadAsync(messageBuffer, 0, 8); //var client = e.SocketClient; //var bytesRead = -1; //var buf = new byte[1]; //string message = ""; //List<byte> bytes = new List<byte>(); //while (bytesRead != 0) //{ // bytesRead = await e.SocketClient.ReadStream.ReadAsync(buf, 0, 1); // if (bytesRead > 0) // { // Debug.WriteLine(buf[0]); // message += System.Text.Encoding.UTF8.GetString(buf, 0, 1); // bytes.Add(buf[0]); // } //} //Checking if te first 4 bytes are the host address var connectedAddress = e.SocketClient.RemoteAddress.Split('.'); for (int i = 0; i < 4; i++) { if ((int)messageBuffer[i] != int.Parse(connectedAddress[i])) { Debug.WriteLine("TCP/ Connected Someone else then server. Disconnecting!"); await e.SocketClient.DisconnectAsync(); await _tcpListener.StopListeningAsync(); return; } } int deviceUserID = BitConverter.ToInt32(messageBuffer, 4); User.InitializeDeviceUser(deviceUserID); Debug.WriteLine("TCP/ RECEIVED Connection from: {0}:{1}", e.SocketClient.RemoteAddress, e.SocketClient.RemotePort); using (var ms = new MemoryStream()) using (var writer = new BsonWriter(ms)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, User.DeviceUser, typeof(User)); int dvcusSize = ms.ToArray().Length; await e.SocketClient.WriteStream.WriteAsync(BitConverter.GetBytes(dvcusSize), 0, 4); Debug.WriteLine("TCP/ Sending to server Device User Size: {0}", dvcusSize); await e.SocketClient.WriteStream.FlushAsync(); await e.SocketClient.WriteStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length); Debug.WriteLine("TCP/ Sending to server Device User: {0}", Convert.ToBase64String(ms.ToArray())); } await e.SocketClient.WriteStream.FlushAsync(); int intOk = (byte)e.SocketClient.ReadStream.ReadByte(); //bool okCheck = BitConverter.ToBoolean(okByte, 0); //if ok check.... OnMessegeTCP(messageBuffer); await _tcpListener.StopListeningAsync(); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { SerializeGeoJsonObject(bsonWriter, (GeoJsonObject <TCoordinates>)value); }
public static async Task Main(string[] args) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(consoleTarget); var fileTarget = new FileTarget("target2") { FileName = "${basedir}/file.txt", Layout = "${longdate} ${level} ${message} ${exception}" }; config.AddTarget(fileTarget); config.AddRuleForOneLevel(LogLevel.Error, fileTarget); // only errors to file config.AddRuleForAllLevels(consoleTarget); // all to console LogManager.Configuration = config; Logger = LogManager.GetLogger("Main"); // Backup data before we begin. if (File.Exists("parsedata.bin")) { if (File.Exists("parsedata.bak")) { File.Delete("parsedata.bak"); } Logger.Log(LogLevel.Info, "Backing Up Parse Data."); File.Copy("parsedata.bin", "parsedata.bak"); } Logger.Log(LogLevel.Info, "Loading Parse Data."); percentileData = PercentileData.Load("parsedata.bin"); Logger.Log(LogLevel.Info, "Parse Data Loaded, Last Update: " + percentileData.LastUpdated); Logger.Log(LogLevel.Info, "Obtaining Job/Class Data."); await BuildClasses(APIKey); Logger.Log(LogLevel.Info, "Job/Class Data Obtained."); Logger.Log(LogLevel.Info, "Obtaining Zone/Instance Data."); await BuildInstances(APIKey); Logger.Log(LogLevel.Info, "Zone/Instance Data Obtained."); Logger.Log(LogLevel.Info, "Obtaining latest Parse Data."); await BuildPercentiles(); Logger.Log(LogLevel.Info, "Latest Parse Data Obtained."); Logger.Log(LogLevel.Info, "Cleaning Up New Data."); // Remove Duplicated Entries. var distinctDictionary = new Dictionary <string, Dictionary <string, List <double> > >(percentileData.Rankings); Logger.Log(LogLevel.Info, "Removing Unused Fights."); // Remove unused fights foreach (var encounter in distinctDictionary.Keys) { var used = false; foreach (var instance in instances) { if (instance.Encounters.FirstOrDefault(e => e.Value.Name.ToLower() == encounter.ToLower()).Value != null) { Logger.Log(LogLevel.Debug, encounter + " is used."); used = true; } } if (!used) { Logger.Log(LogLevel.Warn, "Encounter: " + encounter + " Is no longer needed."); } } Logger.Log(LogLevel.Info, "Unused Fights Removed."); percentileData.Rankings = distinctDictionary; Logger.Log(LogLevel.Info, "Saving Parse Data."); // Save var file = new FileStream("parsedata.bin", FileMode.OpenOrCreate); using (var writer = new BsonWriter(file)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, percentileData); } file.Close(); File.WriteAllText("parsejson.json", JsonConvert.SerializeObject(percentileData, Formatting.Indented)); Logger.Log(LogLevel.Info, "Parse Data Saved."); Console.ReadKey(); }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext) { return(Task.Factory.StartNew(() => { string callback; //This fixes a bug in javascript to do with returning json arrays //Instead of returning an array we simply return odata format which we'll need eventually anyhow. This lends itself to getting the count in the future for paging. // See here: http://haacked.com/archive/2009/06/25/json-hijacking.aspx var response = new BaseResponse <object>(); if (value == null) { response.results = new object[] { }; } else if (value.GetType() == typeof(HttpError)) { response.results = null; var errors = value as HttpError; response.errors = new ResponseError[] { new ResponseError { ErrorType = (errors.FirstOrDefault(e => e.Key == "ExceptionType").Value ?? "Message").ToStringEx(), Description = (errors.FirstOrDefault(e => e.Key == "ExceptionMessage").Value ?? errors.First().Value).ToStringEx() } }; } else if (type == typeof(IQueryable) || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IQueryable <>) || type.GetGenericTypeDefinition() == typeof(DbQuery <>)))) { response.results = ((IQueryable <object>)value).ToArray(); if (_request != null) { response.InlineCount = _request.GetInlineCount(); } } else if (type == typeof(IEnumerable <Guid>)) { response.results = ((IEnumerable <Guid>)value).Select(g => (object)g).ToArray(); if (_request != null) { response.InlineCount = _request.GetInlineCount(); } } else if (type == typeof(IEnumerable) || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List <>) || type.GetGenericTypeDefinition() == typeof(IEnumerable <>)))) { response.results = ((IEnumerable <object>)value).ToArray(); if (_request != null) { response.InlineCount = _request.GetInlineCount(); } } else { var al = new List <object>(); al.Add(value); response.results = al.ToArray(); response.InlineCount = 1; } var serializer = JsonSerializer.Create(SerializerSettings); if (_request != null && _request.Headers.Accept.Contains(MediaTypeWithQualityHeaderValue.Parse("application/bson"))) { using (BinaryWriter streamWriter = new BinaryWriter(writeStream, encoding)) { callback = null; var jsonp = IsJsonpRequest(_request, out callback); if (jsonp) { streamWriter.Write(callback + "("); } using (BsonWriter bsonWriter = new BsonWriter(streamWriter) { CloseOutput = false }) { serializer.Serialize(bsonWriter, response); bsonWriter.Flush(); if (jsonp) { streamWriter.Write(")"); } } } } else { using (StreamWriter streamWriter = new StreamWriter(writeStream, encoding)) { callback = null; var jsonp = IsJsonpRequest(_request, out callback); if (jsonp) { streamWriter.Write(callback + "("); } using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter)) { serializer.Serialize(jsonTextWriter, response); if (jsonp) { streamWriter.Write(")"); } jsonTextWriter.Flush(); } } } })); }
/// <summary> /// Serializes a wrapped object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The writer.</param> /// <param name="nominalType">The nominal type (ignored).</param> /// <param name="options">The serialization options.</param> public void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { BsonSerializer.Serialize(bsonWriter, this.nominalType, obj, options); // use wrapped nominalType }
public static void GenerateDotnetApiBloomFilter(string clientName, string accessKey) { double falsePositiveRate = 0.00001; string baseUri = "https://op-dhs-prod-read-nus.azurewebsites.net/";// "https://op-dhs-sandbox-read.azurewebsites.net/"; // IDocumentHostingService dhsClient = new DocumentHostingServiceClient(new Uri(baseUri), clientName, accessKey); IList <DepotBloomFilter> result = new List <DepotBloomFilter>(); Dictionary <string, List <string> > conflicts = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase); IList <GetDepotResponse> depots = dhsClient.GetAllDepotsBySiteBasePath("docs", "docs.microsoft.com/dotnet/", null, CancellationToken.None).Result; foreach (GetDepotResponse depot in depots.Skip(20).Take(1)) { if (depot.SystemMetadata.GetValueOrDefault <bool>(MetadataConstants.ActiveKey)) { string depotName = depot.DepotName; string continueAt = null; Console.WriteLine($"{depotName} Start."); IEnumerable <GetDocumentResponse> allDocuments = new List <GetDocumentResponse>(); int i = 0; do { for (int retry = 0; retry < 3; i++) { try { GetDocumentsResponse documents = dhsClient.GetDocumentsPaginated(depot.DepotName, "en-us", "live", true, continueAt, null, null, CancellationToken.None).Result; continueAt = documents.ContinueAt; allDocuments = allDocuments.Concat(documents.Documents); break; } catch (Exception e) { Console.WriteLine(e); Console.WriteLine($"Retry for {retry + 1} times"); } } i++; Console.WriteLine($"{i:000} .................."); }while (!string.IsNullOrEmpty(continueAt)); Console.WriteLine($"{depotName} Size: {allDocuments.Count()}."); var bloomFilter = new BloomFilter(allDocuments.Count(), falsePositiveRate); foreach (var document in allDocuments) { bloomFilter.Add(document.AssetId); } Console.WriteLine($"{depotName} Bloom Filter Size: {bloomFilter.BitLength / 1024 / 8} KB."); result.Add(new DepotBloomFilter { DepotName = depotName, BloomFilter = bloomFilter.BitArray, Count = allDocuments.Count(), FalsePositiveRate = falsePositiveRate }); Console.WriteLine($"{depotName} Done."); } } /* * using (StreamWriter file = new StreamWriter(@"output.json", true)) * { * file.WriteLine(JsonConvert.SerializeObject(result)); * } */ MemoryStream ms = new MemoryStream(); using (BsonWriter writer = new BsonWriter(ms)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, result); } Console.ReadLine(); }
private void SerializeCoordinates(BsonWriter bsonWriter, GeoJsonMultiLineStringCoordinates <TCoordinates> coordinates) { bsonWriter.WriteName("coordinates"); _coordinatesSerializer.Serialize(bsonWriter, typeof(GeoJsonMultiLineStringCoordinates <TCoordinates>), coordinates, null); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var timeSpan = (TimeSpan)value; // support RepresentationSerializationOptions for backward compatibility var representationSerializationOptions = options as RepresentationSerializationOptions; if (representationSerializationOptions != null) { options = new TimeSpanSerializationOptions(representationSerializationOptions.Representation); } var timeSpanSerializationOptions = EnsureSerializationOptions <TimeSpanSerializationOptions>(options); if (timeSpanSerializationOptions.Representation == BsonType.String) { bsonWriter.WriteString(timeSpan.ToString()); // for TimeSpan use .NET's format instead of XmlConvert.ToString } else if (timeSpanSerializationOptions.Units == TimeSpanUnits.Ticks) { var ticks = timeSpan.Ticks; switch (timeSpanSerializationOptions.Representation) { case BsonType.Double: bsonWriter.WriteDouble((double)ticks); break; case BsonType.Int32: bsonWriter.WriteInt32((int)ticks); break; case BsonType.Int64: bsonWriter.WriteInt64(ticks); break; default: var message = string.Format("'{0}' is not a valid TimeSpan representation.", timeSpanSerializationOptions.Representation); throw new BsonSerializationException(message); } } else { double interval; switch (timeSpanSerializationOptions.Units) { case TimeSpanUnits.Days: interval = timeSpan.TotalDays; break; case TimeSpanUnits.Hours: interval = timeSpan.TotalHours; break; case TimeSpanUnits.Minutes: interval = timeSpan.TotalMinutes; break; case TimeSpanUnits.Seconds: interval = timeSpan.TotalSeconds; break; case TimeSpanUnits.Milliseconds: interval = timeSpan.TotalMilliseconds; break; case TimeSpanUnits.Nanoseconds: interval = timeSpan.TotalMilliseconds * 1000.0; break; default: var message = string.Format("'{0}' is not a valid TimeSpanUnits value.", timeSpanSerializationOptions.Units); throw new BsonSerializationException(message); } switch (timeSpanSerializationOptions.Representation) { case BsonType.Double: bsonWriter.WriteDouble(interval); break; case BsonType.Int32: bsonWriter.WriteInt32((int)interval); break; case BsonType.Int64: bsonWriter.WriteInt64((long)interval); break; default: var message = string.Format("'{0}' is not a valid TimeSpan representation.", timeSpanSerializationOptions.Representation); throw new BsonSerializationException(message); } } }