public Player(string id) { Id = id; Ratings = new Ratings(); RememberMe = true; Created = new BsonDateTime(DateTime.Now); }
/// <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: if (radTrue.Checked) { mValue = BsonBoolean.True; } else { mValue = BsonBoolean.False; } break; case 4: mValue = mBsonArray; break; case 5: mValue = mBsonDocument; break; } return mValue; }
public void TestAsLocalTime() { var now = DateTime.Now; var nowTruncated = now.AddTicks(-(now.Ticks % 10000)); var bsonDateTime = new BsonDateTime(now); var localDateTime = bsonDateTime.AsLocalTime; Assert.AreEqual(DateTimeKind.Local, localDateTime.Kind); Assert.AreEqual(nowTruncated, localDateTime); }
public void TestAsUniversalTime() { var utcNow = DateTime.UtcNow; var utcNowTruncated = utcNow.AddTicks(-(utcNow.Ticks % 10000)); var bsonDateTime = new BsonDateTime(utcNow); var utcDateTime = bsonDateTime.AsUniversalTime; Assert.AreEqual(DateTimeKind.Utc, utcDateTime.Kind); Assert.AreEqual(utcNowTruncated, utcDateTime); }
public void TestAsLocalTime() { var now = DateTime.Now; var nowTruncated = now.AddTicks(-(now.Ticks % 10000)); var bsonDateTime = new BsonDateTime(now); var localDateTime = bsonDateTime.ToLocalTime(); Assert.AreEqual(DateTimeKind.Local, localDateTime.Kind); Assert.AreEqual(nowTruncated, localDateTime); }
public void TestMapBsonDateTime() { var value = new BsonDateTime(DateTime.UtcNow); var bsonValue = (BsonDateTime)BsonTypeMapper.MapToBsonValue(value); Assert.Same(value, bsonValue); var bsonDateTime = (BsonDateTime)BsonTypeMapper.MapToBsonValue(value, BsonType.DateTime); Assert.Same(value, bsonDateTime); }
public void TestAsUniversalTime() { var utcNow = DateTime.UtcNow; var utcNowTruncated = utcNow.AddTicks(-(utcNow.Ticks % 10000)); var bsonDateTime = new BsonDateTime(utcNow); var utcDateTime = bsonDateTime.ToUniversalTime(); Assert.AreEqual(DateTimeKind.Utc, utcDateTime.Kind); Assert.AreEqual(utcNowTruncated, utcDateTime); }
public IList <string> History(DateTimeOffset?since = null) { var clauses = new List <IMongoQuery>(); if (since != null) { clauses.Add(MonQ.Query.GT(Field.WHEN, BsonDateTime.Create(since))); } return(FetchPrimaryKeys(clauses)); }
public async Task <Snapshot> History(HistoryParameters parameters) { var clauses = new List <FilterDefinition <BsonDocument> >(); if (parameters.Since != null) { clauses.Add(Builders <BsonDocument> .Filter.Gt(Field.WHEN, BsonDateTime.Create(parameters.Since))); } return(CreateSnapshot(await FetchPrimaryKeysAsync(clauses).ConfigureAwait(false), parameters.Count)); }
public Users(Users user) { this.Id = user.Id; this.Fullname = user.Fullname; this.Email = user.Email; this.Password = user.Password; this.Gender = user.Gender; this.DOB = user.DOB; this.Disabled = user.Disabled; this.TimeStamp = user.TimeStamp; }
public Snapshot History(HistoryParameters parameters) { var clauses = new List <FilterDefinition <BsonDocument> >(); if (parameters.Since != null) { clauses.Add(Builders <BsonDocument> .Filter.Gt(Field.WHEN, BsonDateTime.Create(parameters.Since))); } return(CreateSnapshot(FetchPrimaryKeys(clauses), parameters.Count)); }
public Snapshot History(HistoryParameters parameters) { var clauses = new List <IMongoQuery>(); if (parameters.Since != null) { clauses.Add(MongoDB.Driver.Builders.Query.GT(Field.WHEN, BsonDateTime.Create(parameters.Since))); } return(CreateSnapshot(FetchPrimaryKeys(clauses), parameters.Count)); }
public IEnumerable <Uri> History(DateTimeOffset?since = null) { var clauses = new List <IMongoQuery>(); if (since != null) { clauses.Add(MonQ.Query.GT(Field.VERSIONDATE, BsonDateTime.Create(since))); } return(FetchKeys(clauses)); }
protected override void Assert(List <BsonDocument> filesCollectionDocuments, List <BsonDocument> chunks, List <BsonDocument> expectedFilesCollectionDocuments, List <BsonDocument> expectedChunks) { var filesCollectionDocument = filesCollectionDocuments.Single(e => e["_id"] == _result); var actualUploadDate = filesCollectionDocument["uploadDate"].AsBsonDateTime; var expectedUploadDateMin = new BsonDateTime(_startTime); var expectedUploadDateMax = new BsonDateTime(_endTime); actualUploadDate.MillisecondsSinceEpoch.Should().BeInRange(expectedUploadDateMin.MillisecondsSinceEpoch, expectedUploadDateMax.MillisecondsSinceEpoch); base.Assert(filesCollectionDocuments, chunks, expectedFilesCollectionDocuments, expectedChunks); }
public IEnumerable <Uri> History(string resource, DateTimeOffset?since = null) { var clauses = new List <IMongoQuery>(); clauses.Add(MonQ.Query.EQ(Collection.RESOURCE, resource)); if (since != null) { clauses.Add(MonQ.Query.GT(Field.VERSIONDATE, BsonDateTime.Create(since))); } return(FetchKeys(clauses)); }
/// <summary>Try to convert the string to a <see cref="BsonDateTime"/>.</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 TryDateTime(this string value, out BsonValue bsonValue) { bsonValue = null; if (value == null) return false; DateTime result; var r = DateTime.TryParse(value, out result); if (r) bsonValue = new BsonDateTime(result); return r; }
public Trade_Old(String symbol, Double openPrice, Double closePrice, Double open, Double close, Double quantity, BsonDateTime timeOpen, BsonDateTime timeClose, Double pl) { Symbol = symbol; OpenPrice = openPrice; ClosePrice = closePrice; Open = open; Close = close; Quantity = quantity; TimeOpen = timeOpen; TimeClose = timeClose; PL = pl; }
public void IsNotAfterFutureTime(int change, int range) { var fixedDate = DateTime.UtcNow; var date = new BsonDateTime(fixedDate); var dateMock = new Mock <IDateExtra>(); dateMock.Setup(d => d.UtcNow) .Returns(fixedDate.AddSeconds(change)); Assert.False(date.IsAfter(dateMock.Object, range), "IsAfter is true when the date is expired."); }
/// <summary> /// Gets amount of correct answers in a given time range. /// </summary> /// <param name="timeRange"></param> /// <returns></returns> public async Task<int> GetAmountCorrectAsync(ITimeRange timeRange) { var start = new BsonDateTime(timeRange.Start); var end = new BsonDateTime(timeRange.End); var answersSuccessful = await _repository.Find( a => a.Correct == Convert.ToInt32(true) && a.SubmitDateTime > start && a.SubmitDateTime < end); return answersSuccessful.Count(); }
public IEnumerable <IAvailableSpot> GetAvailableSpotsInCity(string city, BsonDateTime starDateTime, BsonDateTime endDateTime) { try { var spots = GetSpotObjects(city, starDateTime, endDateTime); return(GetAvailableSpotObject(spots)); } catch (Exception) { throw new Exception("Failed to perform atomic action GetAvailableSpotsInCity - " + " SpotCore work."); } }
/// <summary> /// 将数据放入TreeNode里进行展示 /// </summary> /// <param name="treeNode"></param> /// <param name="doc"></param> public static void AddBsonDocToTreeNode(TreeNode treeNode, BsonDocument doc) { foreach (var item in doc.Elements) { if (item.Value.IsBsonDocument) { var newItem = new TreeNode(item.Name); AddBsonDocToTreeNode(newItem, item.Value.ToBsonDocument()); newItem.Tag = item; treeNode.Nodes.Add(newItem); } else { if (item.Value.IsBsonArray) { //虽然TreeNode的Text属性带有Array_Mark,表示的时候则会屏蔽掉, //必须要加上,不然FullPath会出现错误 var newItem = new TreeNode(item.Name + ConstMgr.ArrayMark); AddBsonArrayToTreeNode(item.Name, newItem, item.Value.AsBsonArray); newItem.Tag = item; treeNode.Nodes.Add(newItem); } else { var elementNode = new TreeNode(item.Name); elementNode.Tag = item; treeNode.Nodes.Add(elementNode); if (item.Value.IsObjectId) { //objId的展开 ObjectId oid = item.Value.AsObjectId; var oidCreateTime = new TreeNode("CreationTime"); oidCreateTime.Tag = BsonDateTime.Create(oid.CreationTime); var oidMachine = new TreeNode("Machine"); oidMachine.Tag = BsonInt32.Create(oid.Machine); var oidPid = new TreeNode("Pid"); oidPid.Tag = BsonInt32.Create(oid.Pid); var oidIncrement = new TreeNode("Increment"); oidIncrement.Tag = BsonInt32.Create(oid.Increment); var oidTimestamp = new TreeNode("Timestamp"); oidTimestamp.Tag = BsonInt32.Create(oid.Timestamp); elementNode.Nodes.Add(oidCreateTime); elementNode.Nodes.Add(oidMachine); elementNode.Nodes.Add(oidPid); elementNode.Nodes.Add(oidIncrement); elementNode.Nodes.Add(oidTimestamp); } } } } }
public Snapshot History(IKey key, HistoryParameters parameters) { var clauses = new List <IMongoQuery>(); clauses.Add(MongoDB.Driver.Builders.Query.EQ(Field.TYPENAME, key.TypeName)); clauses.Add(MongoDB.Driver.Builders.Query.EQ(Field.RESOURCEID, key.ResourceId)); if (parameters.Since != null) { clauses.Add(MongoDB.Driver.Builders.Query.GT(Field.WHEN, BsonDateTime.Create(parameters.Since))); } return(CreateSnapshot(FetchPrimaryKeys(clauses), parameters.Count)); }
private static void WriteDateTime(SqlDataReader dr, int index, BsonDocument document) { if (dr.GetValue(index) != DBNull.Value) { DateTime dateTime = dr.GetDateTime(index); BsonDateTime bsonDateTime = BsonDateTime.Create(dateTime); document.Add(dr.GetName(index), bsonDateTime); } else { document.Add(dr.GetName(index), BsonNull.Value); } }
private BsonValue ParseDateTimeTenGen() { VerifyToken("("); var valueToken = PopToken(); if (valueToken.Type != JsonTokenType.Int32 && valueToken.Type != JsonTokenType.Int64) { var message = string.Format("JSON reader expected an integer but found: '{0}'", valueToken.Lexeme); throw new FileFormatException(message); } VerifyToken(")"); return(BsonDateTime.Create(valueToken.Int64Value)); }
private static void WriteDateTime(PropertyInfo property, object o, BsonDocument document) { if (property.GetValue(o, null) != null) { DateTime dateTime = DateTime.Parse(property.GetValue(o, null).ToString()); BsonDateTime bsonDateTime = BsonDateTime.Create(dateTime); document.Add(property.Name, bsonDateTime); } else { document.Add(property.Name, BsonNull.Value); } }
public IList <string> List(string resource, DateTimeOffset?since = null) { var clauses = new List <IMongoQuery>(); clauses.Add(MonQ.Query.EQ(Field.TYPENAME, resource)); if (since != null) { clauses.Add(MonQ.Query.GT(Field.WHEN, BsonDateTime.Create(since))); } clauses.Add(MonQ.Query.EQ(Field.STATE, Value.CURRENT)); return(FetchPrimaryKeys(clauses)); }
public IList <string> History(IKey key, DateTimeOffset?since = null) { var clauses = new List <IMongoQuery>(); clauses.Add(MonQ.Query.EQ(Field.TYPENAME, key.TypeName)); clauses.Add(MonQ.Query.EQ(Field.RESOURCEID, key.ResourceId)); if (since != null) { clauses.Add(MonQ.Query.GT(Field.WHEN, BsonDateTime.Create(since))); } return(FetchPrimaryKeys(clauses)); }
public Snapshot History(IKey key, HistoryParameters parameters) { var clauses = new List <FilterDefinition <BsonDocument> >(); clauses.Add(Builders <BsonDocument> .Filter.Eq(Field.TYPENAME, key.TypeName)); clauses.Add(Builders <BsonDocument> .Filter.Eq(Field.RESOURCEID, key.ResourceId)); if (parameters.Since != null) { clauses.Add(Builders <BsonDocument> .Filter.Gt(Field.WHEN, BsonDateTime.Create(parameters.Since))); } return(CreateSnapshot(FetchPrimaryKeys(clauses), parameters.Count)); }
public static BsonDocument Preprocess(this BsonDocument bson) { if (bson == null || bson.Elements == null || bson.ElementCount < 1) { return(bson); } foreach (var element in bson.Elements.ToList()) { if (element.Value is BsonArray array) { for (var i = 0; i < array.Count; i++) { if (!(array[i] is BsonDocument arrayDocument)) { continue; } if (arrayDocument.ElementCount == 1 && arrayDocument.ElementAt(0).Name == "$nowPlusSeconds" && arrayDocument.ElementAt(0).Value is BsonInt32 arrayDeltaSeconds) { array[i] = new BsonDateTime(DateTime.UtcNow + TimeSpan.FromSeconds(arrayDeltaSeconds.Value)); } else { arrayDocument.Preprocess(); } } } if (!(element.Value is BsonDocument document)) { continue; } if (document.ElementCount == 1 && document.ElementAt(0).Name == "$nowPlusSeconds" && document.ElementAt(0).Value is BsonInt32 deltaSeconds) { bson.Set(element.Name, new BsonDateTime(DateTime.UtcNow + TimeSpan.FromSeconds(deltaSeconds.Value))); } else { document.Preprocess(); } } return(bson); }
public IEnumerable <Uri> List(string resource, DateTimeOffset?since = null) { var clauses = new List <IMongoQuery>(); clauses.Add(MonQ.Query.EQ(Collection.RESOURCE, resource)); if (since != null) { clauses.Add(MonQ.Query.GT(Field.VERSIONDATE, BsonDateTime.Create(since))); } clauses.Add(MonQ.Query.EQ(Field.STATE, Value.CURRENT)); clauses.Add(MonQ.Query.NE(Field.ENTRYTYPE, typeof(DeletedEntry).Name)); return(FetchKeys(clauses)); }
public IEnumerable <string> GetOccupiedSpotIds(string city, BsonDateTime startDateTime, BsonDateTime endDateTime) { var spots = new List <string>(); var builder = Builders <Models.Event.Event> .Filter; var filter = builder.Lt(e => e.StartDateTime, endDateTime) & builder.Gt(e => e.EndDateTime, startDateTime) & builder.Eq(e => e.City, city); var events = MongoContext.Collection.Find(filter).ToList(); events.ForEach(s => spots.Add(s.SpotId.ToString())); return(spots); }
public bool IsSpotOccupied(ISpot spot, BsonDateTime starDateTime, BsonDateTime endDateTime) { var events = _eventRepository.GetEventsBySpotId(spot.Id); foreach (var @event in events) { if (IsThereOverlapping(@event, starDateTime, endDateTime)) { return(true); } } return(false); }
public void Write(String parameterName, Period period) { BsonDocument value = new BsonDocument(); if (period.StartElement != null) { value.Add(new BsonElement("start", BsonDateTime.Create(period.StartElement.LowerBound()))); } if (period.EndElement != null) { value.Add(new BsonElement("end", BsonDateTime.Create(period.EndElement.UpperBound()))); } document.Write(parameterName, value); }
public static void Test_MongoDB_DateTime_01() { Trace.WriteLine("Test_MongoDB_DateTime_01"); //1383830499961 long l = 1383830499961; BsonDateTime dt = new BsonDateTime(l); Trace.WriteLine("BsonDateTime {0} - {1}", l, dt); dt = new BsonDateTime(DateTime.Now); Trace.WriteLine("BsonDateTime now {0}", dt); Trace.WriteLine("BsonDateTime now.ToLocalTime() {0}", dt.ToLocalTime()); Trace.WriteLine("BsonDateTime now (DateTime) {0}", (DateTime)dt); Trace.WriteLine("DateTime now {0}", DateTime.Now); }
public void unesiKomentar(string comment, int ArticleId) { var komentar = new BsonDocument { { "timestamp", BsonDateTime.Create(DateTime.Now) }, { "commentar", comment } }; var collection = _database.GetCollection <BsonDocument>("articles"); var filter = Builders <BsonDocument> .Filter.Eq("_id", ArticleId); var update = Builders <BsonDocument> .Update .Push("comment", komentar); collection.UpdateOneAsync(filter, update); }
// 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(DateTimeOffset)); var dateTimeSerializationOptions = EnsureSerializationOptions <DateTimeSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); DateTimeOffset value; switch (bsonType) { case BsonType.DateTime: // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly value = BsonDateTime.Create(bsonReader.ReadDateTime()).Value; break; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadDateTime("DateTimeUTC"); // ignore value (use Ticks instead) value = new DateTime(bsonReader.ReadInt64("Ticks"), DateTimeKind.Utc); bsonReader.ReadEndDocument(); break; case BsonType.Int64: value = new DateTime(bsonReader.ReadInt64(), DateTimeKind.Utc); break; case BsonType.String: // note: we're not using XmlConvert because of bugs in Mono if (dateTimeSerializationOptions.DateOnly) { value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc); } else { var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" }; value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); } break; default: var message = string.Format("Cannot deserialize DateTimeOffset from BsonType {0}.", bsonType); throw new FormatException(message); } return(value); }
public bool TryMapToBsonValue(object value, out BsonValue bsonValue) { try { var date = (DateTime) typeof (Date).GetField("_Date", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(value); bsonValue = new BsonDateTime(date); return true; } catch (Exception exception) { bsonValue = null; return false; } }
public void TestDateTimeMinValue() { foreach (var kind in new[] { DateTimeKind.Local, DateTimeKind.Unspecified, DateTimeKind.Utc }) { var bsonDateTime = new BsonDateTime(DateTime.SpecifyKind(DateTime.MinValue, kind)); Assert.AreEqual(BsonConstants.DateTimeMinValueMillisecondsSinceEpoch, bsonDateTime.MillisecondsSinceEpoch); var utcDateTime = bsonDateTime.AsUniversalTime; Assert.AreEqual(DateTimeKind.Utc, utcDateTime.Kind); Assert.AreEqual(DateTime.MinValue, utcDateTime); var localDateTime = bsonDateTime.AsLocalTime; Assert.AreEqual(DateTimeKind.Local, localDateTime.Kind); Assert.AreEqual(DateTime.MinValue, localDateTime); } }
public void TestConvertMultipleToObjectViaJson() { BsonDocument person1 = new BsonDocument(); BsonDocument person2 = new BsonDocument(); List<BsonDocument> people = new List<BsonDocument>(); const string id1 = "51ca5da43d1b18cc15000000"; const string name1 = "Luke Skywalker"; const string gender1 = "Male"; DateTime dateOfBirth1 = new DateTime(1977, 5, 25); person1["_id"] = new BsonObjectId(new ObjectId(id1)); person1["Name"] = new BsonString(name1); person1["Gender"] = new BsonString(gender1); person1["DateOfBirth"] = new BsonDateTime(dateOfBirth1); people.Add(person1); const string id2 = "52cb5da43d1f17cc15000000"; const string name2 = "Princess Leia"; const string gender2 = "Female"; DateTime dateOfBirth2 = new DateTime(1973, 5, 25); person2["_id"] = new BsonObjectId(new ObjectId(id2)); person2["Name"] = new BsonString(name2); person2["Gender"] = new BsonString(gender2); person2["DateOfBirth"] = new BsonDateTime(dateOfBirth2); people.Add(person2); List<Person> personList = BsonConverter.ConvertToObjectViaJson<List<Person>>(people); for (var i = 0; i < personList.Count; i++) { var person = personList[i]; var personToUse = i == 0 ? person1 : person2; Assert.AreEqual(person.Id, personToUse["_id"].ToString()); Assert.AreEqual(person.Name, personToUse["Name"]); Assert.AreEqual(person.Gender, personToUse["Gender"]); Assert.AreEqual(person.DateOfBirth.ToUniversalTime(), personToUse["DateOfBirth"].ToUniversalTime()); Assert.IsNull(person.DateOfDeath); } }
/// <summary> /// Gets all submitted answers in a time range. /// </summary> /// <param name="timeRange">The time range for which to retrieve answers.</param> /// <returns></returns> private async Task<IEnumerable<SubmittedAnswer>> GetAnswersAsync(ITimeRange timeRange) { var start = new BsonDateTime(timeRange.Start); var end = new BsonDateTime(timeRange.End); return await _repository.Find(a => a.SubmitDateTime > start && a.SubmitDateTime < end); }
public void TestConvertToObjectViaJson() { const string id = "51ca5da43d1b18cc15000000"; const string name = "Luke Skywalker"; const string gender = "Male"; DateTime dateOfBirth = new DateTime(1977, 5, 25); BsonDocument document = new BsonDocument(); document["_id"] = new BsonObjectId(new ObjectId(id)); document["Name"] = new BsonString(name); document["Gender"] = new BsonString(gender); document["DateOfBirth"] = new BsonDateTime(dateOfBirth); ////document["DateOfDeath"] = Deliberately excluded Person person = BsonConverter.ConvertToObjectViaJson<Person>(document); Assert.AreEqual(person.Id, id); Assert.AreEqual(person.Name, name); Assert.AreEqual(person.Gender, gender); Assert.AreEqual(person.DateOfBirth.ToUniversalTime(), dateOfBirth.ToUniversalTime()); Assert.IsNull(person.DateOfDeath); }
public void TestMillisecondsSinceEpochValues() { var values = new long[] { long.MinValue, long.MinValue + 1, -1, 0, 1, long.MaxValue - 1, long.MaxValue }; foreach (var value in values) { var bsonDateTime = new BsonDateTime(value); Assert.Equal(value, bsonDateTime.MillisecondsSinceEpoch); #pragma warning disable 618 Assert.Equal(value, bsonDateTime.RawValue); #pragma warning restore } }
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 TestBsonDateTime() { var dateTime = DateTime.SpecifyKind(new DateTime(2011, 1, 20), DateTimeKind.Utc); var value = new BsonDateTime(dateTime); Assert.AreSame(value, ((IConvertible)value).ToType(typeof(object), null)); Assert.Throws<InvalidCastException>(() => Convert.ToBoolean(value)); Assert.Throws<InvalidCastException>(() => Convert.ToByte(value)); Assert.Throws<InvalidCastException>(() => Convert.ToChar(value)); Assert.AreEqual(dateTime, Convert.ToDateTime(value)); Assert.Throws<InvalidCastException>(() => Convert.ToDecimal(value)); Assert.Throws<InvalidCastException>(() => Convert.ToDouble(value)); Assert.Throws<InvalidCastException>(() => Convert.ToInt16(value)); Assert.Throws<InvalidCastException>(() => Convert.ToInt32(value)); Assert.Throws<InvalidCastException>(() => Convert.ToInt64(value)); Assert.Throws<InvalidCastException>(() => Convert.ToSByte(value)); Assert.Throws<InvalidCastException>(() => Convert.ToSingle(value)); Assert.Throws<InvalidCastException>(() => Convert.ToString(value)); Assert.Throws<InvalidCastException>(() => Convert.ToUInt16(value)); Assert.Throws<InvalidCastException>(() => Convert.ToUInt32(value)); Assert.Throws<InvalidCastException>(() => Convert.ToUInt64(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; }
/// <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; }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue Value = new BsonString(""); 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": if (mBsonBoolean) { Value = BsonBoolean.True; } else { Value = BsonBoolean.False; } break; default: break; } return Value; }
// 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(DateTime)); var dateTimeSerializationOptions = EnsureSerializationOptions<DateTimeSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); DateTime value; switch (bsonType) { case BsonType.DateTime: // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly value = new BsonDateTime(bsonReader.ReadDateTime()).ToUniversalTime(); break; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadDateTime("DateTime"); // ignore value (use Ticks instead) value = new DateTime(bsonReader.ReadInt64("Ticks"), DateTimeKind.Utc); bsonReader.ReadEndDocument(); break; case BsonType.Int64: value = DateTime.SpecifyKind(new DateTime(bsonReader.ReadInt64()), DateTimeKind.Utc); break; case BsonType.String: // note: we're not using XmlConvert because of bugs in Mono if (dateTimeSerializationOptions.DateOnly) { value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc); } else { var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" }; value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); } break; default: var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType); throw new FileFormatException(message); } if (dateTimeSerializationOptions.DateOnly) { if (value.TimeOfDay != TimeSpan.Zero) { throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero."); } value = DateTime.SpecifyKind(value, dateTimeSerializationOptions.Kind); // not ToLocalTime or ToUniversalTime! } else { switch (dateTimeSerializationOptions.Kind) { case DateTimeKind.Local: case DateTimeKind.Unspecified: value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), dateTimeSerializationOptions.Kind); break; case DateTimeKind.Utc: value = BsonUtils.ToUniversalTime(value); break; } } return value; }
public bool TryMapToBsonValue( object value, out BsonValue bsonValue ) { bsonValue = new BsonDateTime(((CustomDateTime) value).DateTime); return true; }
public void TestMapBsonDateTime() { var value = new BsonDateTime(DateTime.UtcNow); var bsonValue = (BsonDateTime) BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonDateTime = (BsonDateTime) BsonTypeMapper.MapToBsonValue(value, BsonType.DateTime); Assert.AreSame(value, bsonDateTime); }
/// <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 TestMillisecondsSinceEpochValues() { var values = new long[] { long.MinValue, long.MinValue + 1, -1, 0, 1, long.MaxValue - 1, long.MaxValue }; foreach (var value in values) { var bsonDateTime = new BsonDateTime(value); Assert.AreEqual(value, bsonDateTime.MillisecondsSinceEpoch); Assert.AreEqual(value, bsonDateTime.RawValue); } }
// 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 TestValues() { var maxValueTruncated = new DateTime(9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Utc); var tests = new object[][] { new object[] { long.MinValue, false, DateTime.MinValue }, new object[] { long.MinValue + 1, false, DateTime.MinValue }, new object[] { BsonConstants.DateTimeMinValueMillisecondsSinceEpoch - 1, false, DateTime.MinValue }, new object[] { BsonConstants.DateTimeMinValueMillisecondsSinceEpoch, true, DateTime.MinValue }, new object[] { BsonConstants.DateTimeMinValueMillisecondsSinceEpoch + 1, true, DateTime.MinValue.AddMilliseconds(1) }, new object[] { -1L, true, BsonConstants.UnixEpoch.AddMilliseconds(-1) }, new object[] { 0L, true, BsonConstants.UnixEpoch }, new object[] { 1L, true, BsonConstants.UnixEpoch.AddMilliseconds(1) }, new object[] { BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch - 1, true, maxValueTruncated.AddMilliseconds(-1) }, new object[] { BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch, true, DateTime.MaxValue }, new object[] { BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch + 1, false, DateTime.MaxValue }, new object[] { long.MaxValue - 1, false, DateTime.MaxValue }, new object[] { long.MaxValue, false, DateTime.MaxValue }, }; foreach (var test in tests) { var millisecondsSinceEpoch = (long)test[0]; var expectedIsValidDateTime = (bool)test[1]; var expectedDateTime = (DateTime)test[2]; var bsonDateTime = new BsonDateTime(millisecondsSinceEpoch); if (expectedIsValidDateTime) { Assert.IsTrue(bsonDateTime.IsValidDateTime); var value = bsonDateTime.Value; Assert.AreEqual(DateTimeKind.Utc, value.Kind); Assert.AreEqual(expectedDateTime, value); } else { Assert.IsFalse(bsonDateTime.IsValidDateTime); Assert.Throws<ArgumentOutOfRangeException>(() => { var value = bsonDateTime.Value; }); } } }
// constructors /// <summary> /// Initializes a new instance of the DateTimeJsonToken class. /// </summary> /// <param name="lexeme">The lexeme.</param> /// <param name="value">The DateTime value.</param> public DateTimeJsonToken(string lexeme, BsonDateTime value) : base(JsonTokenType.DateTime, lexeme) { this.value = value; }
/// <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; default: break; } return Value; }
public TestClass( BsonDateTime value ) { this.B = value; this.V = value; }
public Player() { Ratings = new Ratings(); RememberMe = true; Created = new BsonDateTime(DateTime.Now); }
public void TestBsonDateTimeEquals() { var a = new BsonDateTime(new DateTime(2011, 10, 12, 15, 13, 1, DateTimeKind.Utc)); var b = new BsonDateTime(new DateTime(2011, 10, 12, 15, 13, 1, DateTimeKind.Utc)); var c = new BsonDateTime(new DateTime(2011, 10, 12, 15, 13, 2, DateTimeKind.Utc)); var n = (BsonDateTime)null; Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(object.Equals(a, BsonNull.Value)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsTrue(a == b); Assert.IsFalse(a == c); 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.IsTrue(a != c); Assert.IsTrue(a != BsonNull.Value); Assert.IsTrue(a != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); }
private void buttonDownload_Click(object sender, EventArgs e) { _pages.RemoveAll(); _posts.RemoveAll(); var stemmer = new Stemming(); var i = 1; while (true) { try { System.Threading.Thread.Sleep(100); var urlBase = "http://ita2010.psu.ru:81"; var url = string.Format("{0}/?page={1}", urlBase, i++); var request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "MyApplication"; var response = (HttpWebResponse)request.GetResponse(); var dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); var responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(responseFromServer); var allPosts = doc.DocumentNode.SelectNodes("//*[@id=\"blog-posts-content\"]/div"); for (int j = 1; j < allPosts.Count; j++) { System.Threading.Thread.Sleep(100); var divAdress = string.Format("//*[@id=\"blog-posts-content\"]/div[{0}]/", j); var link = doc.DocumentNode.SelectNodes(divAdress + "h2/a")[0].Attributes["href"].Value; link = urlBase + link; var requestContent = (HttpWebRequest)WebRequest.Create(link); requestContent.UserAgent = "MyApplication"; var responseContent = (HttpWebResponse)requestContent.GetResponse(); var dataStreamContent = responseContent.GetResponseStream(); var readerContent = new StreamReader(dataStreamContent); var responseFromServerContent = readerContent.ReadToEnd(); readerContent.Close(); dataStreamContent.Close(); responseContent.Close(); var docContent = new HtmlAgilityPack.HtmlDocument(); docContent.LoadHtml(responseFromServerContent); var post = new BsonDocument(); var text = docContent.DocumentNode.SelectNodes("//*[@id=\"workarea-content\"]/div[1]/div/div[2]")[0].InnerText; post["content"] = text; var allWords = text.ToLower().Split(new char[] { ' ', '.', ',', '?', ';', '!', ':', '(', ')', '[', ']', '{', '}', '$', '"', '<', '>', '"' }).Select(w => stemmer.Stem(w.Trim())); var words = new BsonArray(); allWords .GroupBy(w => w) .ToList() .ForEach(w => { var word = new BsonDocument(); word["word"] = w.Key; word["count"] = w.Count(); words.Add(word); }); post["words"] = words; post["theme"] = doc.DocumentNode.SelectNodes(divAdress + "h2/a")[0].InnerText; post["author"] = doc.DocumentNode.SelectNodes(divAdress + "div[1]/div/div[1]/a[2]")[0].InnerText; post["dt"] = new BsonDateTime(DateTime.Parse(doc.DocumentNode.SelectNodes(divAdress + "div[1]/div/div[2]/span[2]")[0].InnerText)); var tagsNode = doc.DocumentNode.SelectNodes(divAdress + "div[3]/div[3]/a"); if (tagsNode != null) { var tags = new BsonArray(); for (var k = 0; k < tagsNode.Count; k++) tags.Add(tagsNode[k].InnerText); post["tags"] = tags; } _posts.Insert(post); } var page = new BsonDocument(); page["html"] = responseFromServer; page["url"] = url; _pages.Insert(page); System.Threading.Thread.Sleep(100); } catch (WebException exeption) { MessageBox.Show("All post downloaded!"); break; } } }