/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue GetValue() { BsonValue mValue = null; switch (cmbDataType.SelectedIndex) { case 0: mValue = new BsonString(txtBsonValue.Text); break; case 1: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case 2: mValue = new BsonDateTime(dateTimePicker.Value); break; case 3: mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False; break; case 4: mValue = _mBsonArray; break; case 5: mValue = _mBsonDocument; break; case 6: mValue = new BsonDouble(Convert.ToDouble(NumberPick.Text)); break; } return mValue; }
public void TestBsonDoubleEquals() { var left = new BsonDouble(double.NaN); var right = new BsonDouble(double.NaN); Assert.IsFalse(left == right); Assert.IsTrue(left != right); Assert.IsTrue(left.Equals(right)); }
public void CompareTo_BsonInt32_should_return_expected_result(double doubleValue, int otherInt32Value, int expectedResult) { var subject = new BsonDouble(doubleValue); var other = new BsonInt32(otherInt32Value); var result = subject.CompareTo(other); result.Should().Be(expectedResult); }
public void CompareTo_BsonDecimal128_should_return_expected_result(double doubleValue, double otherDoubleValue, int expectedResult) { var subject = new BsonDouble(doubleValue); var other = new BsonDecimal128((Decimal128)(decimal)otherDoubleValue); var result = subject.CompareTo(other); result.Should().Be(expectedResult); }
public void CompareTo_BsonDouble_should_return_expected_result(long int64Value, double otherDoubleValue, int expectedResult) { var subject = new BsonInt64(int64Value); var other = new BsonDouble(otherDoubleValue); var result = subject.CompareTo(other); result.Should().Be(expectedResult); }
public void TestBsonDoubleEquals() { var a = new BsonDouble(1.0); var b = new BsonDouble(1.0); var c = new BsonInt32(1); var d = new BsonInt64(1L); var e = new BsonDouble(2.0); var f = new BsonInt32(2); var g = new BsonInt64(2L); var n = (BsonDouble)null; var nan = new BsonDouble(double.NaN); Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(object.Equals(a, d)); Assert.IsFalse(object.Equals(a, e)); Assert.IsFalse(object.Equals(a, f)); Assert.IsFalse(object.Equals(a, g)); Assert.IsFalse(object.Equals(a, BsonNull.Value)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsFalse(a.Equals(nan)); Assert.IsTrue(nan.Equals(nan)); Assert.IsTrue(a == b); Assert.IsTrue(a == c); Assert.IsTrue(a == d); Assert.IsFalse(a == e); Assert.IsFalse(a == f); Assert.IsFalse(a == g); Assert.IsFalse(a == BsonNull.Value); Assert.IsFalse(a == null); Assert.IsFalse(null == a); Assert.IsTrue(n == null); Assert.IsTrue(null == n); Assert.IsFalse(a == nan); Assert.IsFalse(nan == a); Assert.IsFalse(nan == double.NaN); Assert.IsFalse(double.NaN == nan); Assert.IsFalse(a != b); Assert.IsFalse(a != c); Assert.IsFalse(a != d); Assert.IsTrue(a != e); Assert.IsTrue(a != f); Assert.IsTrue(a != g); Assert.IsTrue(a != BsonNull.Value); Assert.IsTrue(a != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); Assert.IsTrue(a != nan); Assert.IsTrue(nan != a); Assert.IsTrue(nan != double.NaN); Assert.IsTrue(double.NaN != nan); }
public void TestMapBsonDouble() { var value = new BsonDouble(1.2); var bsonValue = (BsonDouble)BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double); Assert.AreSame(value, bsonDouble); }
public void CompareTo_null_should_return_expected_result() { var subject = new BsonDouble(0.0); var result1 = subject.CompareTo((BsonDouble)null); var result2 = subject.CompareTo((BsonValue)null); result1.Should().Be(1); result2.Should().Be(1); }
public void CompareTo_BsonDouble_should_return_expected_result(double doubleValue, double otherDoubleValue, int expectedResult) { var subject = new BsonDouble(doubleValue); var other = new BsonDouble(otherDoubleValue); var result1 = subject.CompareTo((BsonDouble)other); var result2 = subject.CompareTo((BsonValue)other); result1.Should().Be(expectedResult); result2.Should().Be(expectedResult); }
/// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static BsonValue NullableDouble(object value) { double?val = (double?)value; if (val == null) { return(BsonNull.Value); } return(BsonDouble.Create(val)); }
private static void WriteDouble(SqlDataReader dr, int index, BsonDocument document) { if (dr.GetValue(index) != DBNull.Value) { BsonDouble bsonDouble = BsonDouble.Create(dr.GetValue(index)); document.Add(dr.GetName(index), bsonDouble); } else { document.Add(dr.GetName(index), BsonNull.Value); } }
/// <summary>Try to convert the string to a <see cref="BsonDouble"/>.</summary> /// <param name="value">The value to convert.</param> /// <param name="bsonValue">The BsonValue result.</param> /// <returns><c>true</c> if the value was converted; otherwise <c>false</c>.</returns> public static bool TryDouble(this string value, out BsonValue bsonValue) { bsonValue = null; if (value == null) return false; double result; var r = double.TryParse(value, out result); if (r) bsonValue = new BsonDouble(result); return r; }
private static void WriteDouble(PropertyInfo property, object o, BsonDocument document) { if (property.GetValue(o, null) != null) { BsonDouble bsonDouble = BsonDouble.Create(property.GetValue(o, null)); document.Add(property.Name, bsonDouble); } else { document.Add(property.Name, BsonNull.Value); } }
public void TestCompareDifferentTypeOnes() { var n1 = new BsonInt32(1); var n2 = new BsonInt64(1); var n3 = new BsonDouble(1.0); Assert.IsTrue(n1 == n2); Assert.IsTrue(n1 == n3); Assert.IsTrue(n2 == n1); Assert.IsTrue(n2 == n3); Assert.IsTrue(n3 == n1); Assert.IsTrue(n3 == n2); }
public void TestIsNumeric() { BsonValue d128 = new BsonDecimal128(1.0M); BsonValue d = new BsonDouble(1.0); BsonValue i32 = new BsonInt32(1); BsonValue i64 = new BsonInt64(1L); BsonValue s = new BsonString(""); Assert.True(d128.IsNumeric); Assert.True(d.IsNumeric); Assert.True(i32.IsNumeric); Assert.True(i64.IsNumeric); Assert.False(s.IsDecimal128); }
/// <summary> /// 批量插入数据 /// </summary> /// <param name="collectionName">视图或者表名</param> /// <param name="dtb">表数据</param> /// <param name="t">类别</param> /// <param name="errorMsg">出错信息</param> /// <returns>批量插入是否成功</returns> public bool BatchInsertTable(string collectionName, SqlDataReader dataReader, Type t, out string errorMsg) { errorMsg = string.Empty; if (dataReader == null || !dataReader.HasRows) { return(true); } MongoCollection collection = GetMongoCollection(collectionName); List <BsonDocument> docList = new List <BsonDocument>(); while (dataReader.Read()) { BsonDocument bsonDocument = new BsonDocument(); for (int i = 0; i < dataReader.FieldCount; i++) { if (dataReader[i] == DBNull.Value || dataReader[i] == null) { continue; } BsonValue bsonValue; if (dataReader[i] is Decimal) { bsonValue = BsonDouble.Create(Convert.ToDouble(dataReader[i])); } else { bsonValue = BsonValue.Create(dataReader[i]); } bsonDocument.Add(dataReader.GetName(i), bsonValue); } docList.Add(bsonDocument); if (docList.Count >= DataAccessConsts.OneBatchCount) { System.Console.WriteLine(string.Format("{0}:开始同步{1}条记录", DateTime.Now, docList.Count)); OneBatchInsert(t, docList, collection, out errorMsg); System.Console.WriteLine(string.Format("{0}:已同步{1}条记录", DateTime.Now, docList.Count)); docList.Clear(); } } dataReader.Close(); dataReader.Dispose(); return(OneBatchInsert(t, docList, collection, out errorMsg)); }
public void TestBsonDocumentWithBsonDoubleId() { _collection.RemoveAll(); var doc = new BsonDocument { { "_id", BsonDouble.Create(0.0) }, { "X", 1 } }; _collection.Insert(doc); doc = new BsonDocument { { "_id", BsonDouble.Create(1.0) }, { "X", 1 } }; _collection.Insert(doc); }
public void ParseConditionValueForDoubleTest() { PrivateObject p = new PrivateObject(typeof(MongoDataSource.MongoDataSource)); string value = "12" + System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + "34"; BsonDouble expected = new BsonDouble(Double.Parse(value)); object parsedValue = p.Invoke("ParseConditionValue", new object[] { value, DataType.DT_R8 }); Assert.AreEqual(expected, parsedValue); parsedValue = p.Invoke("ParseConditionValue", new object[] { value, DataType.DT_R4 }); Assert.AreEqual(expected, parsedValue); }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue value = new BsonString(string.Empty); switch (mBsonType) { case BasicType.BsonString: value = new BsonString(mBsonString); break; case BasicType.BsonInt32: value = new BsonInt32(mBsonInt32); break; case BasicType.BsonInt64: value = new BsonInt64(mBsonInt64); break; case BasicType.BsonDecimal128: value = new BsonDecimal128(mBSonDecimal128); break; case BasicType.BsonDouble: value = new BsonDouble(mBsonDouble); break; case BasicType.BsonDateTime: value = new BsonDateTime(mBsonDateTime); break; case BasicType.BsonBoolean: value = mBsonBoolean ? BsonBoolean.True : BsonBoolean.False; break; case BasicType.BsonMaxKey: value = BsonMaxKey.Value; break; case BasicType.BsonMinKey: value = BsonMinKey.Value; break; case BasicType.BsonBinary: value = new BsonBinaryData(mBsonBinary); break; } return(value); }
private BsonValue GetValue(object value) { if (value is DBNull || value == null) { return(BsonNull.Value); } else if (value is string) { return(BsonString.Create(value)); } else if (value is bool) { return(BsonBoolean.Create(value)); } else if (value is int || value is short || value is byte) { return(BsonInt32.Create(value)); } else if (value is long) { return(BsonInt64.Create(value)); } else if (value is decimal) { return(BsonDecimal128.Create(value)); } else if (value is double || value is float) { return(BsonDouble.Create(value)); } else if (value is DateTime) { return(BsonDateTime.Create(value)); } else if (value is char c) { return(BsonString.Create("" + c)); } else if (value is byte[]) { return(BsonBinaryData.Create(value)); } else { return(BsonString.Create(value.ToString())); } }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue GetValue(BsonValueEx.BasicType DataType) { BsonValue mValue = null; switch (DataType) { case BsonValueEx.BasicType.BsonString: mValue = new BsonString(txtBsonValue.Text); break; case BsonValueEx.BasicType.BsonInt32: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonInt64: mValue = new BsonInt64(Convert.ToInt64(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDecimal128: mValue = new BsonDecimal128(Convert.ToDecimal(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDouble: mValue = new BsonDouble(Convert.ToDouble(txtBsonValue.Text)); break; case BsonValueEx.BasicType.BsonDateTime: mValue = new BsonDateTime(dateTimePicker.Value); break; case BsonValueEx.BasicType.BsonBoolean: mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False; break; case BsonValueEx.BasicType.BsonArray: case BsonValueEx.BasicType.BsonGeo: mValue = _mBsonArray; break; case BsonValueEx.BasicType.BsonDocument: mValue = _mBsonDocument; break; } return(mValue); }
/// <summary>Try to convert the string to a <see cref="BsonDouble"/>.</summary> /// <param name="value">The value to convert.</param> /// <param name="bsonValue">The BsonValue result.</param> /// <returns><c>true</c> if the value was converted; otherwise <c>false</c>.</returns> public static bool TryDouble(this string value, out BsonValue bsonValue) { bsonValue = null; if (value == null) { return(false); } double result; var r = double.TryParse(value, out result); if (r) { bsonValue = new BsonDouble(result); } return(r); }
private static BsonValue ToBsonValue(this TypedItem item) { BsonValue bson = null; Type type = item.Value.GetType(); switch (type.Name.ToLower()) { case "string": bson = new BsonString(item.Value.ToString()); break; case "datetime": bson = new BsonDateTime((DateTime)item.Value); break; case "int16": case "int32": bson = new BsonInt32((Int32)item.Value); break; case "int64": bson = new BsonInt64((Int64)item.Value); break; case "double": bson = new BsonDouble((double)item.Value); break; case "boolean": bson = new BsonBoolean((bool)item.Value); break; case "byte[]": bson = new BsonObjectId((byte[])item.Value); break; default: bson = new BsonString(item.Value.ToString()); break; } return(bson); }
public void TestClassWithBsonDoubleId() { _collection.RemoveAll(); var doc = new ClassWithBsonDoubleId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonDoubleId { Id = BsonDouble.Create(0.0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonDoubleId { Id = BsonDouble.Create(1.0), X = 1 }; _collection.Insert(doc); }
// public methods /// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(BsonDouble)); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { return(BsonDouble.Create((double)DoubleSerializer.Instance.Deserialize(bsonReader, typeof(double), options))); } }
public void TestBsonDouble() { var value = BsonDouble.Create(1.5); Assert.AreEqual(true, Convert.ToBoolean(value)); Assert.AreEqual(2, Convert.ToByte(value)); Assert.Throws <InvalidCastException>(() => Convert.ToChar(value)); Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value)); Assert.AreEqual(1.5m, Convert.ToDecimal(value)); Assert.AreEqual(1.5, Convert.ToDouble(value)); Assert.AreEqual(2, Convert.ToInt16(value)); Assert.AreEqual(2, Convert.ToInt32(value)); Assert.AreEqual(2, Convert.ToInt64(value)); Assert.AreEqual(2, Convert.ToSByte(value)); Assert.AreEqual(1.5F, Convert.ToSingle(value)); Assert.AreEqual("1.5", Convert.ToString(value, CultureInfo.InvariantCulture)); Assert.AreEqual(2, Convert.ToUInt16(value)); Assert.AreEqual(2, Convert.ToUInt32(value)); Assert.AreEqual(2, Convert.ToUInt64(value)); }
public void TestBsonDouble() { var value = new BsonDouble(1.5); Assert.AreSame(value, ((IConvertible)value).ToType(typeof(object), null)); Assert.AreEqual(true, Convert.ToBoolean(value)); Assert.AreEqual(2, Convert.ToByte(value)); Assert.Throws <InvalidCastException>(() => Convert.ToChar(value)); Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value)); Assert.AreEqual(1.5m, Convert.ToDecimal(value)); Assert.AreEqual(1.5, Convert.ToDouble(value)); Assert.AreEqual(2, Convert.ToInt16(value)); Assert.AreEqual(2, Convert.ToInt32(value)); Assert.AreEqual(2, Convert.ToInt64(value)); Assert.AreEqual(2, Convert.ToSByte(value)); Assert.AreEqual(1.5F, Convert.ToSingle(value)); Assert.AreEqual("1.5", Convert.ToString(value, CultureInfo.InvariantCulture)); Assert.AreEqual(2, Convert.ToUInt16(value)); Assert.AreEqual(2, Convert.ToUInt32(value)); Assert.AreEqual(2, Convert.ToUInt64(value)); }
public void TestCompareDifferentTypeOnes() { var n1 = new BsonInt32(1); var n2 = new BsonInt64(1); var n3 = new BsonDouble(1.0); Assert.IsTrue(n1 == n2); Assert.IsTrue(n1 == n3); Assert.IsTrue(n2 == n1); Assert.IsTrue(n2 == n3); Assert.IsTrue(n3 == n1); Assert.IsTrue(n3 == n2); var v1 = (BsonValue)new BsonInt32(1); var v2 = (BsonValue)new BsonInt64(1); var v3 = (BsonValue)new BsonDouble(1.0); Assert.IsTrue(v1 == v2); Assert.IsTrue(v1 == v3); Assert.IsTrue(v2 == v1); Assert.IsTrue(v2 == v3); Assert.IsTrue(v3 == v1); Assert.IsTrue(v3 == v2); }
private static BsonValue GetValueDifferenceAsBsonValue(IMemberDirtyTracker memberTracker) { BsonValue currentValue = memberTracker.CurrentValue, originalValue = memberTracker.OriginalValue; if (currentValue.BsonType != originalValue.BsonType) { throw new InvalidOperationException("BSON type of current value does not equal the original value"); } BsonValue incrementBy; switch (currentValue.BsonType) { case BsonType.Double: incrementBy = new BsonDouble(currentValue.AsDouble - originalValue.AsDouble); break; case BsonType.Int32: incrementBy = new BsonInt32(currentValue.AsInt32 - originalValue.AsInt32); break; case BsonType.Int64: incrementBy = new BsonInt64(currentValue.AsInt64 - originalValue.AsInt64); break; case BsonType.Decimal128: incrementBy = new BsonDecimal128(currentValue.AsDecimal - originalValue.AsDecimal); break; default: throw new InvalidOperationException( $"BSON type {memberTracker.CurrentValue.BsonType} cannot be incrementally updated"); } return(incrementBy); }
public void TestCompareDifferentTypeOnes() { var n1 = new BsonInt32(1); var n2 = new BsonInt64(1); var n3 = new BsonDouble(1.0); Assert.IsTrue(n1 == n2); Assert.IsTrue(n1 == n3); Assert.IsTrue(n2 == n1); Assert.IsTrue(n2 == n3); Assert.IsTrue(n3 == n1); Assert.IsTrue(n3 == n2); var v1 = (BsonValue) new BsonInt32(1); var v2 = (BsonValue) new BsonInt64(1); var v3 = (BsonValue) new BsonDouble(1.0); Assert.IsTrue(v1 == v2); Assert.IsTrue(v1 == v3); Assert.IsTrue(v2 == v1); Assert.IsTrue(v2 == v3); Assert.IsTrue(v3 == v1); Assert.IsTrue(v3 == v2); }
private BsonValue ParseConditionValue(String value, DataType dt) { BsonValue parsedValue = value; if (dt == DataType.DT_DATE | dt == DataType.DT_DBTIMESTAMPOFFSET | dt == DataType.DT_DBTIMESTAMP) { if ("now".Equals(value, StringComparison.CurrentCultureIgnoreCase) || "today".Equals(value, StringComparison.CurrentCultureIgnoreCase)) { parsedValue = new BsonDateTime(DateTime.Now); } else if ("yesterday".Equals(value, StringComparison.CurrentCultureIgnoreCase)) { parsedValue = new BsonDateTime(DateTime.Now.AddDays(-1)); } else if (value.StartsWith("-")) { int noOfDays = Int16.Parse(value); parsedValue = new BsonDateTime(DateTime.Now.AddDays(noOfDays)); } else { parsedValue = new BsonDateTime(DateTime.Parse(value)); } } else if (dt == DataType.DT_I8 || dt == DataType.DT_I4) { parsedValue = new BsonInt64(Int64.Parse(value)); } else if (dt == DataType.DT_R8 || dt == DataType.DT_R4) { parsedValue = new BsonDouble(Double.Parse(value)); } return(parsedValue); }
public void operator_equals_with_BsonInt32_should_return_expected_result(double lshDoubleValue, int rhsInt32Value, bool expectedResult) { var lhs = new BsonDouble(lshDoubleValue); var rhs = new BsonInt32(rhsInt32Value); var result = lhs == rhs; result.Should().Be(expectedResult); }
public void operator_equals_with_BsonDouble_should_return_expected_result(long lhsInt64Value, double rhsDoubleValue, bool expectedResult) { var lhs = new BsonInt64(lhsInt64Value); var rhs = new BsonDouble(rhsDoubleValue); var result = lhs == rhs; result.Should().Be(expectedResult); }
public void ToDecimal128_should_return_expected_result(double doubleValue) { var subject = new BsonDouble(doubleValue); var result = subject.ToDecimal128(); result.Should().Be((Decimal128)(decimal)doubleValue); }
// private methods private void ReadValue() { object jsonDotNetValue; switch (_wrappedReader.GetCurrentBsonType()) { case BsonType.Array: _wrappedReader.ReadStartArray(); SetCurrentToken(Newtonsoft.Json.JsonToken.StartArray); return; case BsonType.Binary: var bsonBinaryData = _wrappedReader.ReadBinaryData(); switch (bsonBinaryData.SubType) { case BsonBinarySubType.UuidLegacy: var guidRepresentation = GuidRepresentation.Unspecified; var bsonReader = _wrappedReader as BsonReader; if (bsonReader != null) { guidRepresentation = bsonReader.Settings.GuidRepresentation; } jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, guidRepresentation); break; case BsonBinarySubType.UuidStandard: jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, GuidRepresentation.Standard); break; default: jsonDotNetValue = bsonBinaryData.Bytes; break; } SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, jsonDotNetValue, bsonBinaryData); return; case BsonType.Boolean: var booleanValue = _wrappedReader.ReadBoolean(); SetCurrentToken(Newtonsoft.Json.JsonToken.Boolean, booleanValue, (BsonBoolean)booleanValue); return; case BsonType.DateTime: var bsonDateTime = new BsonDateTime(_wrappedReader.ReadDateTime()); if (bsonDateTime.IsValidDateTime) { jsonDotNetValue = bsonDateTime.ToUniversalTime(); } else { jsonDotNetValue = bsonDateTime.MillisecondsSinceEpoch; } SetCurrentToken(Newtonsoft.Json.JsonToken.Date, jsonDotNetValue, bsonDateTime); return; case BsonType.Document: _wrappedReader.ReadStartDocument(); SetCurrentToken(Newtonsoft.Json.JsonToken.StartObject); return; case BsonType.Double: var bsonDouble = new BsonDouble(_wrappedReader.ReadDouble()); switch (FloatParseHandling) { case Newtonsoft.Json.FloatParseHandling.Decimal: jsonDotNetValue = Convert.ToDecimal(bsonDouble); break; case Newtonsoft.Json.FloatParseHandling.Double: jsonDotNetValue = bsonDouble.Value; break; default: throw new NotSupportedException(string.Format("Unexpected FloatParseHandling value: {0}.", FloatParseHandling)); } SetCurrentToken(Newtonsoft.Json.JsonToken.Float, jsonDotNetValue, bsonDouble); return; case BsonType.Int32: var bsonInt32 = (BsonInt32)_wrappedReader.ReadInt32(); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, (long)bsonInt32.Value, bsonInt32); return; case BsonType.Int64: var bsonInt64 = (BsonInt64)_wrappedReader.ReadInt64(); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonInt64.Value, bsonInt64); return; case BsonType.JavaScript: { var code = _wrappedReader.ReadJavaScript(); var bsonJavaScript = new BsonJavaScript(code); SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScript); } return; case BsonType.JavaScriptWithScope: { var code = _wrappedReader.ReadJavaScriptWithScope(); var context = BsonDeserializationContext.CreateRoot(_wrappedReader); var scope = BsonDocumentSerializer.Instance.Deserialize <BsonDocument>(context); var bsonJavaScriptWithScope = new BsonJavaScriptWithScope(code, scope); SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScriptWithScope); } return; case BsonType.MaxKey: _wrappedReader.ReadMaxKey(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMaxKey.Value); return; case BsonType.MinKey: _wrappedReader.ReadMinKey(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMinKey.Value); return; case BsonType.Null: _wrappedReader.ReadNull(); SetCurrentToken(Newtonsoft.Json.JsonToken.Null, null, BsonNull.Value); return; case BsonType.ObjectId: var bsonObjectId = new BsonObjectId(_wrappedReader.ReadObjectId()); SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, bsonObjectId.Value.ToByteArray(), bsonObjectId); return; case BsonType.RegularExpression: var bsonRegularExpression = _wrappedReader.ReadRegularExpression(); var pattern = bsonRegularExpression.Pattern; var options = bsonRegularExpression.Options; jsonDotNetValue = "/" + pattern.Replace("/", "\\/") + "/" + options; SetCurrentToken(Newtonsoft.Json.JsonToken.String, jsonDotNetValue, bsonRegularExpression); return; case BsonType.String: var stringValue = _wrappedReader.ReadString(); SetCurrentToken(Newtonsoft.Json.JsonToken.String, stringValue, (BsonString)stringValue); return; case BsonType.Symbol: var bsonSymbol = BsonSymbolTable.Lookup(_wrappedReader.ReadSymbol()); SetCurrentToken(Newtonsoft.Json.JsonToken.String, bsonSymbol.Name, bsonSymbol); return; case BsonType.Timestamp: var bsonTimestamp = new BsonTimestamp(_wrappedReader.ReadTimestamp()); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonTimestamp.Value, bsonTimestamp); return; case BsonType.Undefined: _wrappedReader.ReadUndefined(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonUndefined.Value); return; default: var message = string.Format("Unexpected BsonType: {0}.", _wrappedReader.GetCurrentBsonType()); throw new Newtonsoft.Json.JsonReaderException(message); } }
public void TestBsonDouble() { var value = new BsonDouble(1.5); Assert.AreSame(value, ((IConvertible)value).ToType(typeof(object), null)); Assert.AreEqual(true, Convert.ToBoolean(value)); Assert.AreEqual(2, Convert.ToByte(value)); Assert.Throws<InvalidCastException>(() => Convert.ToChar(value)); Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(value)); Assert.AreEqual(1.5m, Convert.ToDecimal(value)); Assert.AreEqual(1.5, Convert.ToDouble(value)); Assert.AreEqual(2, Convert.ToInt16(value)); Assert.AreEqual(2, Convert.ToInt32(value)); Assert.AreEqual(2, Convert.ToInt64(value)); Assert.AreEqual(2, Convert.ToSByte(value)); Assert.AreEqual(1.5F, Convert.ToSingle(value)); Assert.AreEqual("1.5", Convert.ToString(value, CultureInfo.InvariantCulture)); Assert.AreEqual(2, Convert.ToUInt16(value)); Assert.AreEqual(2, Convert.ToUInt32(value)); Assert.AreEqual(2, Convert.ToUInt64(value)); }
// private methods private void ReadValue() { object jsonDotNetValue; switch (_wrappedReader.GetCurrentBsonType()) { case BsonType.Array: _wrappedReader.ReadStartArray(); SetCurrentToken(Newtonsoft.Json.JsonToken.StartArray); return; case BsonType.Binary: var bsonBinaryData = _wrappedReader.ReadBinaryData(); switch (bsonBinaryData.SubType) { case BsonBinarySubType.UuidLegacy: var guidRepresentation = GuidRepresentation.Unspecified; var bsonReader = _wrappedReader as BsonReader; if (bsonReader != null) { guidRepresentation = bsonReader.Settings.GuidRepresentation; } jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, guidRepresentation); break; case BsonBinarySubType.UuidStandard: jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, GuidRepresentation.Standard); break; default: jsonDotNetValue = bsonBinaryData.Bytes; break; } SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, jsonDotNetValue, bsonBinaryData); return; case BsonType.Boolean: var booleanValue = _wrappedReader.ReadBoolean(); SetCurrentToken(Newtonsoft.Json.JsonToken.Boolean, booleanValue, (BsonBoolean)booleanValue); return; case BsonType.DateTime: var bsonDateTime = new BsonDateTime(_wrappedReader.ReadDateTime()); if (bsonDateTime.IsValidDateTime) { jsonDotNetValue = bsonDateTime.ToUniversalTime(); } else { jsonDotNetValue = bsonDateTime.MillisecondsSinceEpoch; } SetCurrentToken(Newtonsoft.Json.JsonToken.Date, jsonDotNetValue, bsonDateTime); return; case BsonType.Document: _wrappedReader.ReadStartDocument(); SetCurrentToken(Newtonsoft.Json.JsonToken.StartObject); return; case BsonType.Double: var bsonDouble = new BsonDouble(_wrappedReader.ReadDouble()); switch (FloatParseHandling) { case Newtonsoft.Json.FloatParseHandling.Decimal: jsonDotNetValue = Convert.ToDecimal(bsonDouble); break; case Newtonsoft.Json.FloatParseHandling.Double: jsonDotNetValue = bsonDouble.Value; break; default: throw new NotSupportedException(string.Format("Unexpected FloatParseHandling value: {0}.", FloatParseHandling)); } SetCurrentToken(Newtonsoft.Json.JsonToken.Float, jsonDotNetValue, bsonDouble); return; case BsonType.Int32: var bsonInt32 = (BsonInt32)_wrappedReader.ReadInt32(); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, (long)bsonInt32.Value, bsonInt32); return; case BsonType.Int64: var bsonInt64 = (BsonInt64)_wrappedReader.ReadInt64(); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonInt64.Value, bsonInt64); return; case BsonType.JavaScript: { var code = _wrappedReader.ReadJavaScript(); var bsonJavaScript = new BsonJavaScript(code); SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScript); } return; case BsonType.JavaScriptWithScope: { var code = _wrappedReader.ReadJavaScriptWithScope(); var context = BsonDeserializationContext.CreateRoot(_wrappedReader); var scope = BsonDocumentSerializer.Instance.Deserialize<BsonDocument>(context); var bsonJavaScriptWithScope = new BsonJavaScriptWithScope(code, scope); SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScriptWithScope); } return; case BsonType.MaxKey: _wrappedReader.ReadMaxKey(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMaxKey.Value); return; case BsonType.MinKey: _wrappedReader.ReadMinKey(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMinKey.Value); return; case BsonType.Null: _wrappedReader.ReadNull(); SetCurrentToken(Newtonsoft.Json.JsonToken.Null, null, BsonNull.Value); return; case BsonType.ObjectId: var bsonObjectId = new BsonObjectId(_wrappedReader.ReadObjectId()); SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, bsonObjectId.Value.ToByteArray(), bsonObjectId); return; case BsonType.RegularExpression: var bsonRegularExpression = _wrappedReader.ReadRegularExpression(); var pattern = bsonRegularExpression.Pattern; var options = bsonRegularExpression.Options; jsonDotNetValue = "/" + pattern.Replace("/", "\\/") + "/" + options; SetCurrentToken(Newtonsoft.Json.JsonToken.String, jsonDotNetValue, bsonRegularExpression); return; case BsonType.String: var stringValue = _wrappedReader.ReadString(); SetCurrentToken(Newtonsoft.Json.JsonToken.String, stringValue, (BsonString)stringValue); return; case BsonType.Symbol: var bsonSymbol = BsonSymbolTable.Lookup(_wrappedReader.ReadSymbol()); SetCurrentToken(Newtonsoft.Json.JsonToken.String, bsonSymbol.Name, bsonSymbol); return; case BsonType.Timestamp: var bsonTimestamp = new BsonTimestamp(_wrappedReader.ReadTimestamp()); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonTimestamp.Value, bsonTimestamp); return; case BsonType.Undefined: _wrappedReader.ReadUndefined(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonUndefined.Value); return; default: var message = string.Format("Unexpected BsonType: {0}.", _wrappedReader.GetCurrentBsonType()); throw new Newtonsoft.Json.JsonReaderException(message); } }
private BsonValue ParseConditionValue(String value, DataType dt) { BsonValue parsedValue = value; if (dt == DataType.DT_DATE | dt == DataType.DT_DBTIMESTAMPOFFSET | dt == DataType.DT_DBTIMESTAMP) { if ("now".Equals(value, StringComparison.CurrentCultureIgnoreCase) || "today".Equals(value, StringComparison.CurrentCultureIgnoreCase)) { parsedValue = new BsonDateTime(DateTime.Now); } else if ("yesterday".Equals(value, StringComparison.CurrentCultureIgnoreCase)) { parsedValue = new BsonDateTime(DateTime.Now.AddDays(-1)); } else if (value.StartsWith("-")) { int noOfDays = Int16.Parse(value); parsedValue = new BsonDateTime(DateTime.Now.AddDays(noOfDays)); } else { parsedValue = new BsonDateTime(DateTime.Parse(value)); } } else if (dt == DataType.DT_I8 || dt == DataType.DT_I4) { parsedValue = new BsonInt64(Int64.Parse(value)); } else if (dt == DataType.DT_R8 || dt == DataType.DT_R4) { parsedValue = new BsonDouble(Double.Parse(value)); } return parsedValue; }
// This process monitor and updates redundancy control of the driver instance in mongodb static async void ProcessRedundancyMongo(JSONSCADAConfig jsConfig) { do { try { var lastActiveNodeKeepAliveTimeTag = DateTime.MinValue; var countKeepAliveUpdates = 0; var countKeepAliveUpdatesLimit = 4; var Client = ConnectMongoClient(jsConfig); var DB = Client.GetDatabase(jsConfig.mongoDatabaseName); // read and process instances configuration var collinsts = DB .GetCollection <protocolDriverInstancesClass >(ProtocolDriverInstancesCollectionName); do { bool isMongoLive = DB .RunCommandAsync((Command <BsonDocument>) "{ping:1}") .Wait(1000); if (!isMongoLive) { throw new Exception("Error on MongoDB connection "); } var collconns = DB .GetCollection <IEC10X_connection >(ProtocolConnectionsCollectionName); var instances = collinsts .Find(inst => inst.protocolDriver == ProtocolDriverName && inst.protocolDriverInstanceNumber == ProtocolDriverInstanceNumber) .ToList(); var foundinstance = false; foreach (protocolDriverInstancesClass inst in instances) { foundinstance = true; var nodefound = false; foreach (var name in inst.nodeNames) { if (JSConfig.nodeName == name) { nodefound = true; } } if (!nodefound) { Log("Node '" + JSConfig.nodeName + "' not found in instances configuration!"); Environment.Exit(-1); } if (inst.activeNodeName == JSConfig.nodeName) { if (!Active) // will go active { Log("Redundancy - ACTIVATING this Node!"); } Active = true; countKeepAliveUpdates = 0; } else { if (Active) // will go inactive { // wait a random time Log("Redundancy - DEACTIVATING this Node (other node active)!"); countKeepAliveUpdates = 0; Random rnd = new Random(); Thread.Sleep(rnd.Next(1000, 5000)); } Active = false; if (lastActiveNodeKeepAliveTimeTag == inst.activeNodeKeepAliveTimeTag) { countKeepAliveUpdates++; } lastActiveNodeKeepAliveTimeTag = inst.activeNodeKeepAliveTimeTag; if (countKeepAliveUpdates > countKeepAliveUpdatesLimit) { // time exceeded, be active Log("Redundancy - ACTIVATING this Node!"); Active = true; } } if (Active) { Log("Redundancy - This node is active."); // update keep alive time var filter1 = Builders <protocolDriverInstancesClass> .Filter .Eq(m => m.protocolDriver, ProtocolDriverName); var filter2 = Builders <protocolDriverInstancesClass> .Filter .Eq(m => m.protocolDriverInstanceNumber, ProtocolDriverInstanceNumber); var filter = Builders <protocolDriverInstancesClass> .Filter .And(filter1, filter2); var update = Builders <protocolDriverInstancesClass> .Update .Set(m => m.activeNodeName, JSConfig.nodeName) .Set(m => m.activeNodeKeepAliveTimeTag, DateTime.Now); var options = new FindOneAndUpdateOptions <protocolDriverInstancesClass, protocolDriverInstancesClass >(); options.IsUpsert = false; await collinsts .FindOneAndUpdateAsync(filter, update, options); // update statistics for connections foreach (IEC10X_connection srv in IEC10Xconns) { if (!(srv.connection is null)) { var stats = srv.connection.GetStatistics(); var filt = new BsonDocument(new BsonDocument("protocolConnectionNumber", srv.protocolConnectionNumber)); var upd = new BsonDocument("$set", new BsonDocument { { "stats", new BsonDocument { { "nodeName", JSConfig.nodeName }, { "timeTag", BsonDateTime.Create(DateTime.Now) }, { "isConnected", BsonBoolean.Create(srv.connection.IsRunning) }, { "rcvdMsgCounter", BsonDouble.Create(stats.RcvdMsgCounter) }, { "sentMsgCounter", BsonDouble.Create(stats.SentMsgCounter) }, { "rcvdTestFrActCounter", BsonDouble.Create(stats.RcvdTestFrActCounter) }, { "rcvdTestFrConCounter", BsonDouble.Create(stats.RcvdTestFrConCounter) } } }, }); var res = collconns.UpdateOneAsync(filt, upd); } } } else { if (inst.activeNodeName != "") { Log("Redundancy - This node is INACTIVE! Node '" + inst.activeNodeName + "' is active, wait..."); } else { Log("Redundancy - This node is INACTIVE! No node is active, wait..."); } } break; // process just first result } if (!foundinstance) { if (Active) // will go inactive { // wait a random time Log("Redundancy - DEACTIVATING this Node (no instance found)!"); countKeepAliveUpdates = 0; Random rnd = new Random(); Thread.Sleep(rnd.Next(1000, 5000)); } Active = false; } Thread.Sleep(5000); }while (true); } catch (Exception e) { Log("Exception Mongo"); Log(e); Log(e .ToString() .Substring(0, e.ToString().IndexOf(Environment.NewLine))); System.Threading.Thread.Sleep(3000); } }while (true); }
public void TestBsonInt64Equals() { var a = new BsonInt64(1L); var b = new BsonInt64(1L); var c = new BsonInt32(1); var d = new BsonDouble(1.0); var e = new BsonInt64(2L); var f = new BsonInt32(2); var g = new BsonDouble(2.0); var n = (BsonInt64)null; Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(object.Equals(a, d)); Assert.IsFalse(object.Equals(a, e)); Assert.IsFalse(object.Equals(a, f)); Assert.IsFalse(object.Equals(a, g)); Assert.IsFalse(object.Equals(a, BsonNull.Value)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsTrue(a == b); Assert.IsTrue(a == c); Assert.IsTrue(a == d); Assert.IsFalse(a == e); Assert.IsFalse(a == f); Assert.IsFalse(a == g); Assert.IsFalse(a == BsonNull.Value); Assert.IsFalse(a == null); Assert.IsFalse(null == a); Assert.IsTrue(n == null); Assert.IsTrue(null == n); Assert.IsFalse(a != b); Assert.IsFalse(a != c); Assert.IsFalse(a != d); Assert.IsTrue(a != e); Assert.IsTrue(a != f); Assert.IsTrue(a != g); Assert.IsTrue(a != BsonNull.Value); Assert.IsTrue(a != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); }
public void operator_equals_with_BsonDecimal128_should_return_expected_result(double lhsDoubleValue, double rhsDoubleValue, bool expectedResult) { var lhs = new BsonDouble(lhsDoubleValue); var rhs = new BsonDecimal128(double.IsNaN(rhsDoubleValue) ? Decimal128.QNaN : (Decimal128)(decimal)rhsDoubleValue); var result = lhs == rhs; result.Should().Be(expectedResult); }
/// <summary> /// 各种基本类型的初始值 /// </summary> /// <param name="DataType"></param> /// <returns></returns> public static BsonValue GetInitValue(BsonValueEx.BasicType DataType) { BsonValue InitValue = BsonNull.Value; switch (DataType) { case BasicType.BsonString: InitValue = new BsonString(string.Empty); break; case BasicType.BsonInt32: InitValue = new BsonInt32(0); break; case BasicType.BsonInt64: InitValue = new BsonInt64(0); break; case BasicType.BsonDecimal128: InitValue = new BsonDecimal128(0); break; case BasicType.BsonDouble: InitValue = new BsonDouble(0); break; case BasicType.BsonDateTime: InitValue = new BsonDateTime(DateTime.Now); break; case BasicType.BsonBoolean: InitValue = BsonBoolean.False; break; case BasicType.BsonArray: InitValue = new BsonArray(); break; case BasicType.BsonDocument: InitValue = new BsonDocument(); break; case BasicType.BsonLegacyPoint: InitValue = new BsonArray() { 0, 0 }; break; case BasicType.BsonGeoJSON: InitValue = new BsonDocument("type", "Point"); InitValue.AsBsonDocument.Add("coordinates", new BsonArray() { 0, 0 }); break; case BasicType.BsonMaxKey: InitValue = BsonMaxKey.Value; break; case BasicType.BsonMinKey: InitValue = BsonMinKey.Value; break; case BasicType.BsonBinary: InitValue = new BsonBinaryData(new byte[0]); break; default: break; } return InitValue; }
public void TestMapBsonDouble() { var value = new BsonDouble(1.2); var bsonValue = (BsonDouble) BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonDouble = (BsonDouble) BsonTypeMapper.MapToBsonValue(value, BsonType.Double); Assert.AreSame(value, bsonDouble); }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue value = new BsonString(string.Empty); switch (mBsonType) { case BasicType.BsonString: value = new BsonString(mBsonString); break; case BasicType.BsonInt32: value = new BsonInt32(mBsonInt32); break; case BasicType.BsonInt64: value = new BsonInt64(mBsonInt64); break; case BasicType.BsonDecimal128: value = new BsonDecimal128(mBSonDecimal128); break; case BasicType.BsonDouble: value = new BsonDouble(mBsonDouble); break; case BasicType.BsonDateTime: value = new BsonDateTime(mBsonDateTime); break; case BasicType.BsonBoolean: value = mBsonBoolean ? BsonBoolean.True : BsonBoolean.False; break; case BasicType.BsonMaxKey: value = BsonMaxKey.Value; break; case BasicType.BsonMinKey: value = BsonMinKey.Value; break; case BasicType.BsonBinary: value = new BsonBinaryData(mBsonBinary); break; } return value; }
public void ParseConditionValueForDoubleTest() { MongoDataSource_Accessor target = new MongoDataSource_Accessor(); string value = "12.34"; BsonDouble expected = new BsonDouble(Double.Parse(value)); object parsedValue = target.ParseConditionValue(value, DataType.DT_R8); Assert.AreEqual(expected, parsedValue); parsedValue = target.ParseConditionValue(value, DataType.DT_R4); Assert.AreEqual(expected, parsedValue); }
public void TestClassWithBsonValueId() { // repeats all tee TestClassWithBsonXyzId tests using ClassWithBsonValueId { // same as TestClassWithBonArrayId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = new BsonArray(), X = 1 }; Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); }); doc = new ClassWithBsonValueId { Id = new BsonArray { 1, 2, 3 }, X = 1 }; Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); }); } { // same as TestClastWithBsonBinaryDataId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBinaryData.Create(new byte[] { }), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBinaryData.Create(new byte[] { 1, 2, 3 }), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonBooleanId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBoolean.Create(false), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonBoolean.Create(true), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonDocumentId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = new BsonDocument(), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = new BsonDocument { { "A", 1 }, { "B", 2 } }, X = 3 }; _collection.Insert(doc); } { // same as TestClassWithBsonDateTimeId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDateTime.Create(DateTime.MinValue), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDateTime.Create(DateTime.UtcNow), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDateTime.Create(DateTime.MaxValue), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonDoubleId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDouble.Create(0.0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonDouble.Create(1.0), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonInt32Id _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt32.Create(0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt32.Create(1), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonInt64Id _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt64.Create(0), X = 1 }; _collection.Insert(doc); doc = new ClassWithBsonValueId { Id = BsonInt64.Create(1), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonMaxKeyId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.AreEqual(null, doc.Id); doc = new ClassWithBsonValueId { Id = BsonMaxKey.Value, X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonMinKeyId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.AreEqual(null, doc.Id); doc = new ClassWithBsonValueId { Id = BsonMinKey.Value, X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonNullId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.AreEqual(null, doc.Id); doc = new ClassWithBsonValueId { Id = BsonNull.Value, X = 1 }; Assert.Throws <MongoSafeModeException>(() => { _collection.Insert(doc); }); } { // same as TestClassWithBsonObjectId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.IsNull(doc.Id); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue doc = new ClassWithBsonValueId { Id = BsonObjectId.Empty, X = 1 }; _collection.Insert(doc); Assert.AreEqual(ObjectId.Empty, doc.Id.AsObjectId); // BsonObjectIdGenerator is not invoked when nominalType is BsonValue doc = new ClassWithBsonValueId { Id = BsonObjectId.GenerateNewId(), X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonStringId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.IsNull(doc.Id); doc = new ClassWithBsonValueId { Id = "", X = 1 }; _collection.Insert(doc); Assert.AreEqual("", doc.Id.AsString); doc = new ClassWithBsonValueId { Id = "123", X = 1 }; _collection.Insert(doc); } { // same as TestClassWithBsonTimestampId _collection.RemoveAll(); var doc = new ClassWithBsonValueId { Id = null, X = 1 }; _collection.Insert(doc); Assert.IsNull(doc.Id); doc = new ClassWithBsonValueId { Id = BsonTimestamp.Create(0, 0), X = 1 }; _collection.Insert(doc); Assert.AreEqual(BsonTimestamp.Create(0, 0), doc.Id); doc = new ClassWithBsonValueId { Id = BsonTimestamp.Create(1, 2), X = 1 }; _collection.Insert(doc); } }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue value = new BsonString(string.Empty); switch (MBsonType) { case "BsonString": value = new BsonString(MBsonString); break; case "BsonInt32": value = new BsonInt32(MBsonInt32); break; case "BsonDateTime": value = new BsonDateTime(MBsonDateTime); break; case "BsonBoolean": value = MBsonBoolean ? BsonBoolean.True : BsonBoolean.False; break; case "BsonDouble": value = new BsonDouble(MBsonDouble); break; } return value; }
public TestClass( BsonDouble value ) { this.B = value; this.V = value; }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue GetValue(BsonValueEx.BasicType DataType) { BsonValue mValue = null; switch (DataType) { case BsonValueEx.BasicType.BsonString: mValue = new BsonString(txtBsonValue.Text); break; case BsonValueEx.BasicType.BsonInt32: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonInt64: mValue = new BsonInt64(Convert.ToInt64(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDecimal128: mValue = new BsonDecimal128(Convert.ToDecimal(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDouble: mValue = new BsonDouble(Convert.ToDouble(txtBsonValue.Text)); break; case BsonValueEx.BasicType.BsonDateTime: mValue = new BsonDateTime(dateTimePicker.Value); break; case BsonValueEx.BasicType.BsonBoolean: mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False; break; case BsonValueEx.BasicType.BsonArray: case BsonValueEx.BasicType.BsonLegacyPoint: mValue = _mBsonArray; break; case BsonValueEx.BasicType.BsonGeoJSON: case BsonValueEx.BasicType.BsonDocument: mValue = _mBsonDocument; break; case BsonValueEx.BasicType.BsonMaxKey: mValue = BsonMaxKey.Value; break; case BsonValueEx.BasicType.BsonMinKey: mValue = BsonMinKey.Value; break; case BsonValueEx.BasicType.BsonBinary: mValue = new BsonBinaryData(Encoding.Default.GetBytes(txtBsonValue.Text)); break; } return mValue; }
// This process updates acquired values in the mongodb collection for realtime data static public async void ProcessMongo(JSONSCADAConfig jsConfig) { do { try { var Client = ConnectMongoClient(jsConfig); var DB = Client.GetDatabase(jsConfig.mongoDatabaseName); var collection = DB.GetCollection <rtData>(RealtimeDataCollectionName); var collection_cmd = DB .GetCollection <rtCommand>(CommandsQueueCollectionName); Log("MongoDB Update Thread Started..."); var listWrites = new List <WriteModel <rtData> >(); do { //if (LogLevel >= LogLevelBasic && OPCDataQueue.Count > 0) // Log("MongoDB - Data queue size: " + OPCDataQueue.Count, LogLevelBasic); // Log("1"); bool isMongoLive = DB .RunCommandAsync((Command <BsonDocument>) "{ping:1}") .Wait(1000); if (!isMongoLive) { throw new Exception("Error on MongoDB connection "); } // Log("2"); IEC_CmdAck ia; if (OPCCmdAckQueue.Count > 0) { while (OPCCmdAckQueue.TryDequeue(out ia)) { var filter1 = Builders <rtCommand> .Filter .Eq(m => m.protocolSourceConnectionNumber, ia.conn_number); var filter2 = Builders <rtCommand> .Filter .Eq(m => m.protocolSourceObjectAddress, ia.object_address); var filter = Builders <rtCommand> .Filter .And(filter1, filter2); var update = Builders <rtCommand> .Update .Set(m => m.ack, ia.ack) .Set(m => m.ackTimeTag, ia.ack_time_tag); // sort by priority then by insert order var sort = Builders <rtCommand> .Sort.Descending("$natural"); var options = new FindOneAndUpdateOptions <rtCommand, rtCommand >(); options.IsUpsert = false; options.Sort = sort; await collection_cmd .FindOneAndUpdateAsync(filter, update, options); } } // Log("3"); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); OPC_Value iv; while (!OPCDataQueue.IsEmpty && OPCDataQueue.TryPeek(out iv) && OPCDataQueue.TryDequeue(out iv)) { // Log("3.1"); DateTime tt = DateTime.MinValue; BsonValue bsontt = BsonNull.Value; try { if (iv.hasSourceTimestamp) { bsontt = BsonValue.Create(iv.sourceTimestamp); } } catch { tt = DateTime.MinValue; bsontt = BsonNull.Value; } BsonDocument valJSON = new BsonDocument(); try { valJSON = BsonDocument.Parse(iv.valueJson); } catch (Exception e) { Log(iv.conn_name + " - " + e.Message); } // Log("3.2"); if (iv.selfPublish) { string tag = TagFromOPCParameters(iv); if (!InsertedTags.Contains(tag)) { // look for the tag var task = await collection.FindAsync <rtData>(new BsonDocument { { "tag", TagFromOPCParameters(iv) } }); List <rtData> list = await task.ToListAsync(); // await Task.Delay(10); //Thread.Yield(); //Thread.Sleep(1); InsertedTags.Add(tag); if (list.Count == 0) { Log(iv.conn_name + " - INSERT - " + iv.address); // hash to create keys var id = HashStringToInt(iv.address); var insert = newRealtimeDoc(iv, id); int conn_index = 0; // normal for loop for (int index = 0; index < OPCUAconns.Count; index++) { if (OPCUAconns[index].protocolConnectionNumber == iv.conn_number) { conn_index = index; } } insert.protocolSourcePublishingInterval = OPCUAconns[conn_index].autoCreateTagPublishingInterval; insert.protocolSourceSamplingInterval = OPCUAconns[conn_index].autoCreateTagSamplingInterval; insert.protocolSourceQueueSize = OPCUAconns[conn_index].autoCreateTagQueueSize; listWrites .Add(new InsertOneModel <rtData>(insert)); } } } //below code will update one record of the data var update = new BsonDocument { { "$set", new BsonDocument { { "sourceDataUpdate", new BsonDocument { { "valueBsonAtSource", valJSON }, { "valueAtSource", BsonDouble .Create(iv.value) }, { "valueStringAtSource", BsonString .Create(iv.valueString) }, { "asduAtSource", BsonString .Create(iv.asdu.ToString()) }, { "causeOfTransmissionAtSource", BsonString.Create(iv.cot.ToString()) }, { "timeTagAtSource", bsontt }, { "timeTagAtSourceOk", BsonBoolean .Create(iv.hasSourceTimestamp) }, { "timeTag", BsonValue .Create(iv .serverTimestamp) }, { "notTopicalAtSource", BsonBoolean .Create(false) }, { "invalidAtSource", BsonBoolean .Create(!iv .quality ) }, { "overflowAtSource", BsonBoolean .Create(false) }, { "blockedAtSource", BsonBoolean .Create(false) }, { "substitutedAtSource", BsonBoolean .Create(false) } } } } } }; var filt = new rtFilt { protocolSourceConnectionNumber = iv.conn_number, protocolSourceCommonAddress = iv.common_address, protocolSourceObjectAddress = iv.address }; Log("MongoDB - ADD " + iv.address + " " + iv.value, LogLevelDebug); // Log("3.3"); listWrites .Add(new UpdateOneModel <rtData>(filt .ToBsonDocument(), update)); if (listWrites.Count >= BulkWriteLimit) { break; } if (stopWatch.ElapsedMilliseconds > 400) { break; } // Log("3.4 - Write buffer " + listWrites.Count + " Data " + OPCDataQueue.Count); // give time to breath each 250 dequeues //if ((listWrites.Count % 250)==0) //{ // await Task.Delay(10); //Thread.Yield(); //Thread.Sleep(1); //} } // Log("4"); if (listWrites.Count > 0) { Log("MongoDB - Bulk write " + listWrites.Count + " Data " + OPCDataQueue.Count); var bulkWriteResult = await collection.BulkWriteAsync(listWrites); listWrites.Clear(); //Thread.Yield(); //Thread.Sleep(1); } if (OPCDataQueue.IsEmpty) { await Task.Delay(250); } // Log("6"); }while (true); } catch (Exception e) { Log("Exception Mongo"); Log(e); Log(e .ToString() .Substring(0, e.ToString().IndexOf(Environment.NewLine))); Thread.Sleep(1000); while (OPCDataQueue.Count > DataBufferLimit // do not let data queue grow more than a limit ) { Log("MongoDB - Dequeue Data", LogLevelDetailed); OPC_Value iv; OPCDataQueue.TryDequeue(out iv); } } }while (true); }
static public int AutoKeyMultiplier = 1000000; // maximum number of points on each connection self-published (auto numbered points) // This process updates acquired values in the mongodb collection for realtime data static public async void ProcessMongo(JSONSCADAConfig jsConfig) { do { try { var Client = ConnectMongoClient(jsConfig); var DB = Client.GetDatabase(jsConfig.mongoDatabaseName); var collection = DB.GetCollection <rtData>(RealtimeDataCollectionName); var collectionId = DB.GetCollection <rtDataId>(RealtimeDataCollectionName); var collection_cmd = DB .GetCollection <rtCommand>(CommandsQueueCollectionName); Log("MongoDB Update Thread Started..."); var listWrites = new List <WriteModel <rtData> >(); do { //if (LogLevel >= LogLevelBasic && OPCDataQueue.Count > 0) // Log("MongoDB - Data queue size: " + OPCDataQueue.Count, LogLevelBasic); bool isMongoLive = DB .RunCommandAsync((Command <BsonDocument>) "{ping:1}") .Wait(2500); if (!isMongoLive) { throw new Exception("Error on MongoDB connection "); } Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); OPC_Value iv; while (!OPCDataQueue.IsEmpty && OPCDataQueue.TryPeek(out iv) && OPCDataQueue.TryDequeue(out iv)) { DateTime tt = DateTime.MinValue; BsonValue bsontt = BsonNull.Value; try { if (iv.hasSourceTimestamp) { bsontt = BsonValue.Create(iv.sourceTimestamp); } } catch { tt = DateTime.MinValue; bsontt = BsonNull.Value; } BsonDocument valJSON = new BsonDocument(); try { valJSON = BsonDocument.Parse(iv.valueJson); } catch (Exception e) { Log(iv.conn_name + " - " + e.Message); } if (iv.selfPublish) { // find the json-scada connection for this received value int conn_index = 0; for (int index = 0; index < OPCUAconns.Count; index++) { if (OPCUAconns[index].protocolConnectionNumber == iv.conn_number) { conn_index = index; } } string tag = TagFromOPCParameters(iv); if (!OPCUAconns[conn_index].InsertedTags.Contains(tag)) { // tag not yet inserted // put the tag in the list of inserted, then insert it OPCUAconns[conn_index].InsertedTags.Add(tag); Log(iv.conn_name + " - INSERT NEW TAG: " + tag + " - Addr:" + iv.address); // find a new freee _id key based on the connection number if (OPCUAconns[conn_index].LastNewKeyCreated == 0) { Double AutoKeyId = iv.conn_number * AutoKeyMultiplier; var results = collectionId.Find <rtDataId>(new BsonDocument { { "_id", new BsonDocument { { "$gt", AutoKeyId }, { "$lt", (iv.conn_number + 1) * AutoKeyMultiplier } } } }).Sort(Builders <rtDataId> .Sort.Descending("_id")) .Limit(1) .ToList(); if (results.Count > 0) { OPCUAconns[conn_index].LastNewKeyCreated = results[0]._id.ToDouble() + 1; } else { OPCUAconns[conn_index].LastNewKeyCreated = AutoKeyId; } } else { OPCUAconns[conn_index].LastNewKeyCreated = OPCUAconns[conn_index].LastNewKeyCreated + 1; } var id = OPCUAconns[conn_index].LastNewKeyCreated; // will enqueue to insert the new tag into mongo DB var insert = newRealtimeDoc(iv, id); insert.protocolSourcePublishingInterval = OPCUAconns[conn_index].autoCreateTagPublishingInterval; insert.protocolSourceSamplingInterval = OPCUAconns[conn_index].autoCreateTagSamplingInterval; insert.protocolSourceQueueSize = OPCUAconns[conn_index].autoCreateTagQueueSize; listWrites .Add(new InsertOneModel <rtData>(insert)); // will imediatelly be followed by an update below (to the same tag) } } // update one existing document with received tag value (realtimeData) var update = new BsonDocument { { "$set", new BsonDocument { { "sourceDataUpdate", new BsonDocument { { "valueBsonAtSource", valJSON }, { "valueAtSource", BsonDouble .Create(iv.value) }, { "valueStringAtSource", BsonString .Create(iv.valueString) }, { "asduAtSource", BsonString .Create(iv.asdu.ToString()) }, { "causeOfTransmissionAtSource", BsonString.Create(iv.cot.ToString()) }, { "timeTagAtSource", bsontt }, { "timeTagAtSourceOk", BsonBoolean .Create(iv.hasSourceTimestamp) }, { "timeTag", BsonValue .Create(iv .serverTimestamp) }, { "notTopicalAtSource", BsonBoolean .Create(false) }, { "invalidAtSource", BsonBoolean .Create(!iv .quality ) }, { "overflowAtSource", BsonBoolean .Create(false) }, { "blockedAtSource", BsonBoolean .Create(false) }, { "substitutedAtSource", BsonBoolean .Create(false) } } } } } }; // update filter, avoids updating commands that can have the same address as supervised points var filt = new rtFilt { protocolSourceConnectionNumber = iv.conn_number, protocolSourceObjectAddress = iv.address, origin = "supervised" }; Log("MongoDB - ADD " + iv.address + " " + iv.value, LogLevelDebug); listWrites .Add(new UpdateOneModel <rtData>(filt .ToBsonDocument(), update)); if (listWrites.Count >= BulkWriteLimit) { break; } if (stopWatch.ElapsedMilliseconds > 400) { break; } // Log("Write buffer " + listWrites.Count + " Data " + OPCDataQueue.Count); // give time to breath each 250 dequeues //if ((listWrites.Count % 250)==0) //{ // await Task.Delay(10); //Thread.Yield(); //Thread.Sleep(1); //} } if (listWrites.Count > 0) { Log("MongoDB - Bulk writing " + listWrites.Count + ", Total enqueued data " + OPCDataQueue.Count); var bulkWriteResult = await collection.BulkWriteAsync(listWrites); listWrites.Clear(); Log($"MongoDB - OK:{bulkWriteResult.IsAcknowledged} - Inserted:{bulkWriteResult.InsertedCount} - Updated:{bulkWriteResult.ModifiedCount}"); //Thread.Yield(); //Thread.Sleep(1); } if (OPCDataQueue.IsEmpty) { await Task.Delay(250); } }while (true); } catch (Exception e) { Log("Exception Mongo"); Log(e); Log(e .ToString() .Substring(0, e.ToString().IndexOf(Environment.NewLine))); Thread.Sleep(1000); while (OPCDataQueue.Count > DataBufferLimit // do not let data queue grow more than a limit ) { Log("MongoDB - Dequeue Data", LogLevelDetailed); OPC_Value iv; OPCDataQueue.TryDequeue(out iv); } } }while (true); }
public static BsonValue Create(this BsonType bsonType, object o) { BsonValue value = BsonNull.Value; try { switch (bsonType) { case BsonType.EndOfDocument: break; case BsonType.Double: value = BsonDouble.Create(o); break; case BsonType.String: value = BsonString.Create(o); break; case BsonType.Document: value = BsonDocument.Create(o); break; case BsonType.Array: value = BsonArray.Create(o); break; case BsonType.Binary: value = BsonBinaryData.Create(o); break; case BsonType.Undefined: break; case BsonType.ObjectId: value = BsonObjectId.Create(o); break; case BsonType.Boolean: value = BsonBoolean.Create(o); break; case BsonType.DateTime: value = BsonDateTime.Create(o); break; case BsonType.Null: value = BsonNull.Value; break; case BsonType.RegularExpression: value = BsonRegularExpression.Create(o); break; case BsonType.JavaScript: value = BsonJavaScript.Create(o); break; case BsonType.Symbol: value = BsonSymbol.Create(o); break; case BsonType.JavaScriptWithScope: value = BsonJavaScriptWithScope.Create(o); break; case BsonType.Int32: value = BsonInt32.Create(o); break; case BsonType.Timestamp: value = BsonTimestamp.Create(o); break; case BsonType.Int64: value = BsonInt64.Create(o); break; case BsonType.MaxKey: value = BsonValue.Create(o); break; case BsonType.MinKey: value = BsonValue.Create(o); break; } } catch { } return(value); }