// 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(T[, , ])); var bsonType = bsonReader.CurrentBsonType; string message; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Array: bsonReader.ReadStartArray(); var outerList = new List <List <List <T> > >(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { bsonReader.ReadStartArray(); var middleList = new List <List <T> >(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { bsonReader.ReadStartArray(); var innerList = new List <T>(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var element = BsonSerializer.Deserialize <T>(bsonReader); innerList.Add(element); } bsonReader.ReadEndArray(); middleList.Add(innerList); } bsonReader.ReadEndArray(); outerList.Add(middleList); } bsonReader.ReadEndArray(); var length1 = outerList.Count; var length2 = (length1 == 0) ? 0 : outerList[0].Count; var length3 = (length2 == 0) ? 0 : outerList[0][0].Count; var array = new T[length1, length2, length3]; for (int i = 0; i < length1; i++) { var middleList = outerList[i]; if (middleList.Count != length2) { message = string.Format("Middle list {0} is of length {1} but should be of length {2}.", i, middleList.Count, length2); throw new FileFormatException(message); } for (int j = 0; j < length2; j++) { var innerList = middleList[j]; if (innerList.Count != length3) { message = string.Format("Inner list {0} is of length {1} but should be of length {2}.", j, innerList.Count, length3); throw new FileFormatException(message); } for (int k = 0; k < length3; k++) { array[i, j, k] = innerList[k]; } } } return(array); case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); // skip over discriminator bsonReader.ReadName("_v"); var value = Deserialize(bsonReader, actualType, actualType, options); bsonReader.ReadEndDocument(); return(value); default: message = string.Format("Can't deserialize a {0} from BsonType {1}.", actualType.FullName, bsonType); throw new FileFormatException(message); } }
//you could also just serialize the class to a string and save it through player prefs //keep in mind that this is jsut a way to do it public void Load() { GameObject tut = GameObject.Find("Tutorial"); loaded = false; PlayerData data = new PlayerData(); bool isNew = false; var query = new QueryDocument("username", username); foreach (var document in playercollection.Find(query)) { username = document["username"].ToString(); isNew = document["new"].ToBoolean(); data = BsonSerializer.Deserialize <PlayerData>(document["data"].ToBson()); } if (!isNew) { string json; if (File.Exists(Application.persistentDataPath + "/playerInfo.json")) { json = File.ReadAllText(Application.persistentDataPath + "/playerInfo.json", System.Text.Encoding.Unicode); } // if(data != null) // data = JsonUtility.FromJson<PlayerData>(json); gold = data.gold; shards = data.shards; vitality = data.vitality; strength = data.strength; xp = data.xp; inventoryItems.Clear(); equippedItems.Clear(); foreach (var itemData in data.inventoryItems) { Item item = itemDatabase.GetItemCopy(itemData.id); item.level = itemData.level; inventoryItems.Add(item); } foreach (var itemData in data.equippedItems) { EquippableItem item = (EquippableItem)itemDatabase.GetItemCopy(itemData.id); item.level = itemData.level; equippedItems.Add(item); } Scene m_Scene; string sceneName; m_Scene = SceneManager.GetActiveScene(); sceneName = m_Scene.name; if (sceneName == "town") { InventoryManager.im.Fill(); tut.GetComponent <Image>().enabled = false; tut.GetComponent <Button>().enabled = false; } if (InventoryManager.im.inventory != null) { InventoryManager.im.inventory.RefreshUI(); } hasSave = true; } else { Debug.Log("New"); hasSave = false; tut.GetComponent <Image>().enabled = true; tut.GetComponent <Button>().enabled = true; phone = GameObject.Find("Phone"); phone.SetActive(false); BsonDocument result = playercollection.FindOne(query); if (result != null) { result["new"] = false; playercollection.Save(result); // playercollection.Remove(Query.EQ("username", username)); } } loaded = true; }
private async Task MainAsync() { var connStr = "mongodb://*****:*****@"handouts\homework_2_1"; string inputFileName = "grades.json"; string inputFilePath = Path.Combine(assignmentDir, inputFileName); using (var streamReader = new StreamReader(inputFilePath)) { string line; while ((line = await streamReader.ReadLineAsync()) != null) { var doc = BsonSerializer.Deserialize <Student>(line); await col.InsertOneAsync(doc); } } var agg1 = col.Aggregate() .Group(x => x.Student_Id, g => new { StudentId = g.Key, Average = g.Average(x => x.Score) }) .SortByDescending(x => x.Average) .Limit(1) ; var results1 = await agg1.ToListAsync(); foreach (var doc in results1) { Debug.Assert(doc.StudentId == 164); Debug.Assert(Math.Round(doc.Average, 1) == 89.3); break; } var agg2 = col.Aggregate() .Match(x => x.Score >= 65) .SortBy(x => x.Score) .Limit(1) ; var results2 = await agg2.ToListAsync(); foreach (var doc in results2) { Debug.Assert(doc.Student_Id == 22); break; } var list = await col .Find(x => x.Type == "homework") .SortBy(x => x.Student_Id) .ThenBy(x => x.Score) .ToListAsync() ; int prev = -1; foreach (var doc in list) { if (doc.Student_Id != prev) { prev = doc.Student_Id; await col.DeleteOneAsync(x => x.Id == doc.Id); } } var results3 = await agg1.ToListAsync(); foreach (var doc in results3) { Console.WriteLine("Answer:{0}", doc.StudentId); break; } }
static void Main(string[] args) { List <BsonDocument> result = new List <BsonDocument>(); WebClient webClient = new WebClient(); Stream stream = webClient.OpenRead("http://houstontx.gov/heatmaps/datafiles/floodingheatmap12m.txt"); using (StreamReader reader = new StreamReader(stream)) { int line = 0; while (reader.Peek() >= 0) { string[] stringData = reader.ReadLine().Split('|'); line++; if (line > 2) { FlodData floodData = new FlodData(); if (stringData.Count() > 8) { floodData.Cordinate[0] = decimal.Parse(stringData[2]); //Longitud floodData.Cordinate[1] = decimal.Parse(stringData[1]); //Latitud floodData.Address = stringData[3].Trim(); floodData.CreateDate = DateTime.Parse(stringData[4]); if (stringData[5].Trim() != "NULL") { floodData.ClosedDate = DateTime.Parse(stringData[5]); } floodData.SourceType = "311"; floodData.MetaData.CaseType = stringData[7]; floodData.MetaData.CaseNumber = long.Parse(stringData[8]); using (MemoryStream jsonStream = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(FlodData)); serializer.WriteObject(jsonStream, floodData); jsonStream.Position = 0; StreamReader sr = new StreamReader(jsonStream); string post = sr.ReadToEnd(); result.Add(BsonSerializer.Deserialize <BsonDocument>(post)); } } } } } var connectionString = "mongodb://*****:*****@ds023432.mlab.com:23432/drydriver"; var client = new MongoClient(connectionString); var database = client.GetDatabase("drydriver"); var collection = database.GetCollection <BsonDocument>("events"); //collection.InsertMany(result); //Console.ReadKey(); /// /// FWS Data Post /// Console.WriteLine("Getting Harris County Bayou Levels"); result.Clear(); HarrisFWS FWSobj = new HarrisFWS(); //you can change this to GetFWSjsonStreamCurrent(7) to get current data Task <string> task1 = FWSobj.GetFWSjsonStreamHistorical("4/18/2016 3:18:15 PM", 1440); JavaScriptSerializer jss = new JavaScriptSerializer(); var d = jss.Deserialize <dynamic>(task1.Result); var sites = d["Sites"]; foreach (var site in sites) { FlodData floodData = new FlodData(); if (site["StreamData"] != null) //sometimes null { decimal currentLevel = site["StreamData"][0]["CurrentLevel"]; decimal TOB = site["StreamData"][0]["ChannelInfo"]["TOB"]; if (currentLevel > TOB) { Console.WriteLine(site["Location"] + " IS OVERFLOWING"); floodData.Cordinate[0] = site["Longitude"]; floodData.Cordinate[1] = site["Latitude"]; floodData.Address = site["Location"]; floodData.CreateDate = DateTime.Now; //floodData.ClosedDate = DateTime.Parse(stringData[5]); need to consider this somehow floodData.SourceType = "FWS"; floodData.MetaData.CaseType = "Flooding"; floodData.MetaData.CaseNumber = site["SiteId"]; //Console.WriteLine(site["StreamData"][0]["CurrentLevel"]); //Console.WriteLine(site["StreamData"][0]["ChannelInfo"]["TOB"]); using (MemoryStream jsonStream = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(FlodData)); serializer.WriteObject(jsonStream, floodData); jsonStream.Position = 0; StreamReader sr = new StreamReader(jsonStream); string post = sr.ReadToEnd(); result.Add(BsonSerializer.Deserialize <BsonDocument>(post)); } } } } //write to Mongo collection.InsertMany(result); }
// querying for average TOFs uses different code - this is because of the need to keep // memory consumption under control, and the urge to re-use the old averaging code. // The result is that the averaging must be done at the TOFChannelSet level. public string processJSONQueryAverage(string jsonQuery) { BlockStoreQuery query = BsonSerializer.Deserialize <BlockStoreQuery>(jsonQuery); return(processBlockQueryAverage(query.BlockQuery, query.BlockIDs).ToJson <BlockStoreBlockResponse>()); }
public ActionResult UpdateDriverInfo([FromBody] ExampleModel_DriverInfo data, string username, string driverId) { try { if (data != null && username != null && driverId != null) { if (data.DriverName != null) { var updateDefinition = Builders <BsonDocument> .Update.Set("DriverName", data.DriverName); update = MH.UpdateSingleObject(driverinfo_collection, "DriverId", driverId, null, null, updateDefinition); } if (data.ContactNo != null) { var updateDefinition = Builders <BsonDocument> .Update.Set("ContactNo", data.ContactNo); update = MH.UpdateSingleObject(driverinfo_collection, "DriverId", driverId, null, null, updateDefinition); } if (data.Address != null) { var updateDefinition = Builders <BsonDocument> .Update.Set("Address", data.Address); update = MH.UpdateSingleObject(driverinfo_collection, "DriverId", driverId, null, null, updateDefinition); } if (data.IsActive != null) { var updateDefinition = Builders <BsonDocument> .Update.Set("IsActive", data.IsActive); update = MH.UpdateSingleObject(driverinfo_collection, "DriverId", driverId, null, null, updateDefinition); } if (update != null) { AL.CreateLog(username, "UpdateDriverInfo", BsonSerializer.Deserialize <DriverInfo>(update), data, activitylog_collection); return(Ok(new ResponseData { Code = "200", Message = "Updated" })); } else { return(BadRequest(new ResponseData { Code = "404", Message = "Driver info not found" })); } } else { return(BadRequest(new ResponseData { Code = "401", Message = "Bad request" })); } } catch (Exception ex) { SL.CreateLog("DriverController", "UpdateDriverInfo", ex.Message); return(BadRequest(new ResponseData { Code = "400", Message = "Failed", Data = ex.Message })); } }
public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { var client = new MongoClient("mongodb://*****:*****@cluster0-shard-00-00-bj19b.azure.mongodb.net:27017,cluster0-shard-00-01-bj19b.azure.mongodb.net:27017,cluster0-shard-00-02-bj19b.azure.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority"); var db = client.GetDatabase("ReservationManagement"); var coll = db.GetCollection <BsonDocument>("Reservation"); Console.WriteLine($"Consuming Message"); Console.WriteLine(string.Concat("Message received from the exchange ", exchange)); Console.WriteLine(string.Concat("Consumer tag: ", consumerTag)); Console.WriteLine(string.Concat("Delivery tag: ", deliveryTag)); Console.WriteLine(string.Concat("Routing tag: ", routingKey)); Console.WriteLine(string.Concat("Message: ", Encoding.UTF8.GetString(body))); if (exchange.Equals("request.reservation")) { //MongoConn if (routingKey.Equals("reservation.get.by.id")) { Console.WriteLine("get ReservationID " + Encoding.UTF8.GetString(body)); var filter = Builders <BsonDocument> .Filter.Eq("_id", ObjectId.Parse(Encoding.UTF8.GetString(body))); var reservationSearched = coll.Find(filter).FirstOrDefault(); var myReservation = BsonSerializer.Deserialize <Reservation>(reservationSearched); Console.WriteLine("myReservation LocID " + myReservation.LocationID); // Console.WriteLine("myReservation CurrencyID" + myReservation.CurrencyExchangeRate); Console.WriteLine("myReservation StartDate " + myReservation.StartDate); Console.WriteLine("myReservation EndDate " + myReservation.EndDate); Console.WriteLine("myReservation categoryID " + myReservation.CurrencyExchangeRate); //TODO send GW } else { if (routingKey.Equals("reservation.create")) { Reservation reservationConsumed = JsonConvert.DeserializeObject <Reservation>(Encoding.UTF8.GetString(body)); //EXAMPLE exchange request //step 1 - create request RpcRequest request = new RpcRequest { fromCCY = "USD", toCCY = "EUR" }; //step 2 - send request RpcResponse testResponse = Task.Run(async() => await RpcCurrencyConverter.GetRpcResult(request)).Result; //step 3 - read response double exchangeRate = testResponse.exchangeRate; //ReservationInsert var insert = new BsonDocument { { "CarID", reservationConsumed.CarID }, { "CategoryID", reservationConsumed.CategoryID }, { "LocationID", reservationConsumed.LocationID }, { "CustomerID", reservationConsumed.CustomerID }, // TODO get CurrencyExchangeRate from PALOS Microservice { "Price", reservationConsumed.Price *exchangeRate }, { "CurrencyID", reservationConsumed.CurrencyID }, { "CurrencyExchangeRate", reservationConsumed.CurrencyExchangeRate }, { "StartDate", reservationConsumed.StartDate }, { "EndDate", reservationConsumed.EndDate } }; coll.InsertOneAsync(insert); DirectMessageToGateway ds = new DirectMessageToGateway(); ds.SendMessage(insert.ToString()); Console.WriteLine("inserted"); } else if (routingKey.Equals("reservation.delete")) { string reservationId = JsonConvert.DeserializeObject <string>(Encoding.UTF8.GetString(body)); coll.DeleteOneAsync(reservationId); DirectMessageToGateway ds = new DirectMessageToGateway(); ds.SendMessage("true"); Console.WriteLine("deleted"); } } } }
public void CanParseNullable() { BsonSerializer.Deserialize <Test>(new BsonDocument(new BsonElement("NullableLocalDate", BsonNull.Value))).NullableLocalDate.Should().BeNull(); }
public UsuarioModel Delete(FilterDefinition <UsuarioModel> filter, UpdateDefinition <UsuarioModel> up, string collection) { var col = _database.GetCollection <UsuarioModel>(collection); return(BsonSerializer.Deserialize <UsuarioModel>(col.DeleteOne(filter).ToBsonDocument())); }
public void CanParseNullable() { BsonSerializer.Deserialize <Test>(new BsonDocument(new BsonElement("OffsetNullable", BsonNull.Value))).OffsetNullable.Should().BeNull(); }
public void ThrowsWhenDateIsInvalid() { Assert.Throws <FormatException>(() => BsonSerializer.Deserialize <Test>(new BsonDocument(new BsonElement("LocalDate", "bleh")))); Assert.Throws <FormatException>(() => BsonSerializer.Deserialize <Test>(new BsonDocument(new BsonElement("LocalDate", BsonNull.Value)))); }
public void ThrowsWhenValueIsInvalid() { Assert.Throws <FormatException>(() => BsonSerializer.Deserialize <Test>(new BsonDocument(new BsonElement("Duration", "bleh")))); }
public void TestDeserializeAll() { var info = new SystemProfileInfo { Abbreviated = "abbreviated", Client = "client", Command = new BsonDocument("command", 1), CursorId = 1, Duration = TimeSpan.FromMilliseconds(2), Error = "err", Exception = "exception", ExceptionCode = 3, Exhaust = true, FastMod = true, FastModInsert = true, IdHack = true, Info = "info", KeyUpdates = 4, LockStatistics = new SystemProfileLockStatistics { TimeAcquiring = new SystemProfileReadWriteLockStatistics { DatabaseReadLock = TimeSpan.FromMilliseconds(10), DatabaseWriteLock = TimeSpan.FromMilliseconds(20), GlobalReadLock = TimeSpan.FromMilliseconds(30), GlobalWriteLock = TimeSpan.FromMilliseconds(40) }, TimeLocked = new SystemProfileReadWriteLockStatistics { DatabaseReadLock = TimeSpan.FromMilliseconds(50), DatabaseWriteLock = TimeSpan.FromMilliseconds(60), GlobalReadLock = TimeSpan.FromMilliseconds(70), GlobalWriteLock = TimeSpan.FromMilliseconds(80) } }, Moved = true, Namespace = "ns", NumberMoved = 11, NumberReturned = 5, NumberScanned = 6, NumberToReturn = 7, NumberToSkip = 8, NumberUpdated = 9, NumberOfYields = 10, Op = "op", Query = new BsonDocument("query", 1), ResponseLength = 9, ScanAndOrder = true, Timestamp = new DateTime(2011, 10, 7, 1, 2, 3, DateTimeKind.Utc), UpdateObject = new BsonDocument("updateObject", 1), Upsert = true, User = "******" }; var json = info.ToJson(new JsonWriterSettings { Indent = true }); var rehydrated = BsonSerializer.Deserialize <SystemProfileInfo>(json); Assert.Equal(info.Abbreviated, rehydrated.Abbreviated); Assert.Equal(info.Client, rehydrated.Client); Assert.Equal(info.Command, rehydrated.Command); Assert.Equal(info.CursorId, rehydrated.CursorId); Assert.Equal(info.Duration, rehydrated.Duration); Assert.Equal(info.Error, rehydrated.Error); Assert.Equal(info.Exception, rehydrated.Exception); Assert.Equal(info.ExceptionCode, rehydrated.ExceptionCode); Assert.Equal(info.Exhaust, rehydrated.Exhaust); Assert.Equal(info.FastMod, rehydrated.FastMod); Assert.Equal(info.FastModInsert, rehydrated.FastModInsert); Assert.Equal(info.IdHack, rehydrated.IdHack); Assert.Equal(info.Info, rehydrated.Info); Assert.Equal(info.KeyUpdates, rehydrated.KeyUpdates); Assert.Equal(info.LockStatistics.RawDocument, rehydrated.LockStatistics.RawDocument); Assert.Equal(info.LockStatistics.TimeAcquiring.DatabaseReadLock, rehydrated.LockStatistics.TimeAcquiring.DatabaseReadLock); Assert.Equal(info.LockStatistics.TimeAcquiring.DatabaseWriteLock, rehydrated.LockStatistics.TimeAcquiring.DatabaseWriteLock); Assert.Equal(info.LockStatistics.TimeAcquiring.GlobalReadLock, rehydrated.LockStatistics.TimeAcquiring.GlobalReadLock); Assert.Equal(info.LockStatistics.TimeAcquiring.GlobalWriteLock, rehydrated.LockStatistics.TimeAcquiring.GlobalWriteLock); Assert.Equal(info.LockStatistics.TimeLocked.DatabaseReadLock, rehydrated.LockStatistics.TimeLocked.DatabaseReadLock); Assert.Equal(info.LockStatistics.TimeLocked.DatabaseWriteLock, rehydrated.LockStatistics.TimeLocked.DatabaseWriteLock); Assert.Equal(info.LockStatistics.TimeLocked.GlobalReadLock, rehydrated.LockStatistics.TimeLocked.GlobalReadLock); Assert.Equal(info.LockStatistics.TimeLocked.GlobalWriteLock, rehydrated.LockStatistics.TimeLocked.GlobalWriteLock); Assert.Equal(info.Moved, rehydrated.Moved); Assert.Equal(info.Namespace, rehydrated.Namespace); Assert.Equal(info.NumberMoved, rehydrated.NumberMoved); Assert.Equal(info.NumberReturned, rehydrated.NumberReturned); Assert.Equal(info.NumberScanned, rehydrated.NumberScanned); Assert.Equal(info.NumberToReturn, rehydrated.NumberToReturn); Assert.Equal(info.NumberToSkip, rehydrated.NumberToSkip); Assert.Equal(info.NumberUpdated, rehydrated.NumberUpdated); Assert.Equal(info.NumberOfYields, rehydrated.NumberOfYields); Assert.Equal(info.Op, rehydrated.Op); Assert.Equal(info.Query, rehydrated.Query); Assert.Equal(info.ResponseLength, rehydrated.ResponseLength); Assert.Equal(info.ScanAndOrder, rehydrated.ScanAndOrder); Assert.Equal(info.Timestamp, rehydrated.Timestamp); Assert.Equal(info.UpdateObject, rehydrated.UpdateObject); Assert.Equal(info.Upsert, rehydrated.Upsert); Assert.Equal(info.User, rehydrated.User); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject item = JObject.Load(reader); return(BsonSerializer.Deserialize(item.ToString(), objectType)); }
public static T Deserialize <T>(this BsonDocument doc) { return(BsonSerializer.Deserialize <T>(doc)); }
public static T FromJson <T>(string str) { return(BsonSerializer.Deserialize <T>(str)); }
public ActionResult InsertDriverInfo([FromBody] DriverInfo data, string username) { try { if (data != null && username != null) { var checkDriver = MH.GetSingleObject(driverinfo_collection, "DriverName", data.DriverName, "Address", data.Address).Result; if (checkDriver != null) { return(BadRequest(new ResponseData { Code = "401", Message = "Driver with same driver name and address is already added" })); } else { #region Calculate driver id var getDrivers = MH.GetListOfObjects(driverinfo_collection, null, null, null, null).Result; if (getDrivers.Count == 0) { data.DriverId = "DR-1"; } else { List <long> idList = new List <long>(); foreach (var driver in getDrivers) { DriverInfo driverInfo = BsonSerializer.Deserialize <DriverInfo>(driver); long seperatedId = Convert.ToInt64(driverInfo.DriverId.Substring(driverInfo.DriverId.LastIndexOf('-') + 1)); idList.Add(seperatedId); } var maxId = idList.Max(); data.DriverId = "DR-" + (maxId + 1); } #endregion data.IsActive = true; var insert = MH.InsertNewDriverInfo(data, driverinfoCollection); if (insert == true) { AL.CreateLog(username, "InsertDriverInfo", null, data, activitylog_collection); return(Ok(new ResponseData { Code = "200", Message = "Inserted", Data = data })); } else { return(BadRequest(new ResponseData { Code = "402", Message = "Driver info with same id is already added" })); } } } else { return(BadRequest(new ResponseData { Code = "403", Message = "Bad Request" })); } } catch (Exception ex) { SL.CreateLog("DriverController", "InsertDriverInfo", ex.Message); return(BadRequest(new ResponseData { Code = "400", Message = "Failed", Data = ex.Message })); } }
public static object FromJson(Type type, string str) { return(BsonSerializer.Deserialize(str, type)); }
public AndConstraint<BsonArrayAssertions> NotBe(string json, string because = "", params object[] reasonArgs) { var expected = json == null ? null : BsonSerializer.Deserialize<BsonArray>(json); return NotBe(expected, because, reasonArgs); }
public static object FromBson(Type type, byte[] bytes) { return(BsonSerializer.Deserialize(bytes, type)); }
/// <summary> /// Gets the inline results as TDocuments. /// </summary> /// <param name="documentType">The type of the documents.</param> /// <returns>The documents.</returns> public IEnumerable <object> GetInlineResultsAs(Type documentType) { return(InlineResults.Select(document => BsonSerializer.Deserialize(document, documentType))); }
public static Object Deserialize(BsonDocument doc, Type type) { return(BsonSerializer.Deserialize(doc, type)); }
public string processJSONQuery(string jsonQuery) { BlockStoreQuery query = BsonSerializer.Deserialize <BlockStoreQuery>(jsonQuery); return(processQuery(query).ToJson <BlockStoreResponse>()); }
public Lazy <T> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var value = context.Reader.ReadString(); return(new Lazy <T>(() => BsonSerializer.Deserialize <T>(value))); }
public void AddBlocksJSON(string jsonPaths) { string[] paths = BsonSerializer.Deserialize <string[]>(jsonPaths); AddBlocks(paths); }
public static void loadFromDirThenDeserializeFromJsonThenSaveToDb(IMongoDatabase db, IExportImportPathInfoProvider pathInfoProvider, ISimmpleProgressReporter progressReporter = null, CodeApproachType codeApproach = CodeApproachType.AsyncFunctional) { var dirPath = $@"{pathInfoProvider.RootPath}\{pathInfoProvider.WorkingDirName}"; if (Directory.Exists(dirPath) && db != null) { var localFunctions = new Dictionary <CodeApproachType, Action>() { { CodeApproachType.AsyncFunctional, doItAsync }, { CodeApproachType.SyncFunctional, doItSync }, { CodeApproachType.SyncNotFunctional, doItSyncAndNotFuncional } }; progressReporter?.Start($"Start importing data from {dirPath} to {db.DatabaseNamespace.DatabaseName}"); localFunctions[codeApproach].Invoke(); progressReporter?.End($"All data from {dirPath} was loaded successfully"); } #region Local functions void doItAsync() => Directory.EnumerateFiles(dirPath, $"*.{pathInfoProvider.FileExtension}", SearchOption.TopDirectoryOnly) .AsParallel() .Select(fullPath => new { Name = Path.GetFileNameWithoutExtension(fullPath), Lines = readLinesFromFile(fullPath) }) .Select(file => new { Collection = dropThenCreateCollection(db, file.Name), Documents = file.Lines.Select(deserializeFunc) }) .ForAll(async deserialized => { var name = deserialized.Collection.CollectionNamespace.CollectionName; progressReporter?.Report($"Loading {name}"); await deserialized.Collection.InsertManyAsync(deserialized.Documents); progressReporter?.Report($"Complete {name}"); }); void doItSync() => Directory.EnumerateFiles(dirPath, $"*.{pathInfoProvider.FileExtension}", SearchOption.TopDirectoryOnly) .Select(fullPath => new { Name = Path.GetFileNameWithoutExtension(fullPath), Lines = readLinesFromFile(fullPath) }) .Select(file => new { Collection = dropThenCreateCollection(db, file.Name), Documents = file.Lines.Select(deserializeFunc) }) .ToList() .ForEach(deserialized => { var name = deserialized.Collection.CollectionNamespace.CollectionName; progressReporter?.Report($"Loading {name}"); deserialized.Collection.InsertMany(deserialized.Documents); progressReporter?.Report($"Complete {name}"); }); void doItSyncAndNotFuncional() { foreach (var fullPath in Directory.EnumerateFiles(dirPath, $"*.{pathInfoProvider.FileExtension}", SearchOption.TopDirectoryOnly)) { var collectionName = Path.GetFileNameWithoutExtension(fullPath); var collection = dropThenCreateCollection(db, collectionName); progressReporter?.Report($"Loading {collectionName}"); using (var streamReader = new StreamReader(fullPath)) { string line; while ((line = streamReader.ReadLine()) != null) { var document = BsonSerializer.Deserialize <BsonDocument>(line); collection.InsertOne(document); } } progressReporter?.Report($"Complete {collectionName}"); } } BsonDocument deserializeFunc(string line) => BsonSerializer.Deserialize <BsonDocument>(line); #endregion }
/// <summary> /// OK /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmdOK_Click(object sender, EventArgs e) { //不支持中文 JIRA ticket is created : SERVER-4412 //SERVER-4412已经在2013/03解决了 //collection names are limited to 121 bytes after converting to UTF-8. if (txtCollectionName.Text == string.Empty) { return; } CollectionName = txtCollectionName.Text.Trim(); try { string errMessage; RuntimeMongoDbContext.GetCurrentDataBase().IsCollectionNameValid(txtCollectionName.Text, out errMessage); if (errMessage != null) { MyMessageBox.ShowMessage("Create Collection", "Argument Exception", errMessage, true); return; } if (chkAdvance.Checked) { var option = new CollectionOptionsBuilder(); if (chkIsCapped.Checked) { if (numMaxSize.Value == 0 || numMaxDocument.Value == 0) { MyMessageBox.ShowMessage("Create Collection", "Argument Exception", "Please Input MaxSize Or MaxDocument When IsCapped", true); return; } option.SetCapped(chkIsCapped.Checked); if (numMaxSize.Value != 0) { option.SetMaxSize((long)numMaxSize.Value); } if (numMaxDocument.Value != 0) { option.SetMaxDocuments((long)numMaxDocument.Value); } } //CappedCollection Default is AutoIndexId After MongoDB 2.2.2 option.SetAutoIndexId(chkIsAutoIndexId.Checked); if (chkValidation.Checked) { //Start From MongoDB 3.2.0 BsonDocument query = BsonSerializer.Deserialize <BsonDocument>(txtValidation.Text); QueryDocument queryDoc = new QueryDocument(query); option.SetValidator(queryDoc); //Validation Level if (radLevel_off.Checked) { option.SetValidationLevel(DocumentValidationLevel.Off); } if (radLevel_strict.Checked) { option.SetValidationLevel(DocumentValidationLevel.Strict); } if (radLevel_moderate.Checked) { option.SetValidationLevel(DocumentValidationLevel.Moderate); } //Validation Action if (radAction_error.Checked) { option.SetValidationAction(DocumentValidationAction.Error); } if (radAction_warn.Checked) { option.SetValidationAction(DocumentValidationAction.Warn); } } Result = Operater.CreateCollectionWithOptions(StrSvrPathWithTag, txtCollectionName.Text, option, RuntimeMongoDbContext.GetCurrentDataBase()); } else { Result = Operater.CreateCollection(StrSvrPathWithTag, txtCollectionName.Text, RuntimeMongoDbContext.GetCurrentDataBase()); } Close(); } catch (ArgumentException ex) { Utility.ExceptionDeal(ex, "Create MongoDatabase", "Argument Exception"); Result = false; } }
public static void ClassInit(XElement xe) { __useUrlCache = xe.zXPathValue("UseUrlCache").zTryParseAs(false); __cacheDirectory = xe.zXPathValue("CacheDirectory"); __useMongo = xe.zXPathValue("UseMongo").zTryParseAs(__useMongo); __mongoServer = xe.zXPathValue("MongoServer", __mongoServer); __mongoDatabase = xe.zXPathValue("MongoDatabase"); __mongoCollectionName = xe.zXPathValue("MongoCollection"); __mongoDocumentItemName = xe.zXPathValue("MongoDocumentItemName"); IDocumentStore_v3 <int, IEnumDataPages_v2 <int, IHeaderData_v2> > documentStore = null; if (__useMongo) { MongoDocumentStore_v3 <int, IEnumDataPages_v2 <int, IHeaderData_v2> > mongoDocumentStore = new MongoDocumentStore_v3 <int, IEnumDataPages_v2 <int, IHeaderData_v2> >(__mongoServer, __mongoDatabase, __mongoCollectionName, __mongoDocumentItemName); mongoDocumentStore.DefaultSort = "{ 'download.id': 1 }"; mongoDocumentStore.GetDataKey = headerPage => headerPage.GetKey(); mongoDocumentStore.Deserialize = document => (IEnumDataPages_v2 <int, IHeaderData_v2>)BsonSerializer.Deserialize <Ebookdz_HeaderPage>(document); documentStore = mongoDocumentStore; } __currentLoadHeaderPagesManager = new Ebookdz_LoadHeaderPagesManager(new Ebookdz_LoadHeaderPageFromWebManager(GetUrlCache()), documentStore); }
/// <summary> /// Gets the modified document as a TDocument. /// </summary> /// <param name="documentType">The nominal type of the modified document.</param> /// <returns>The modified document.</returns> public object GetModifiedDocumentAs(Type documentType) { var document = ModifiedDocument; return((document == null) ? null : BsonSerializer.Deserialize(document, documentType)); }
public void Document_Create() { var now = DateTime.Now; var cid = Guid.NewGuid(); // create a typed object var orderObject = new Order { OrderKey = 123, CustomerId = cid, Date = now, Items = new List <OrderItem>() { new OrderItem { Qtd = 3, Description = "Package", Unit = 99m } } }; // create same object, but using BsonDocument var orderDoc = new BsonDocument(); orderDoc.Id = 123; orderDoc["CustomerId"] = cid; orderDoc["Date"] = now; orderDoc["Items"] = new BsonArray(); var i = new BsonObject(); i["Qtd"] = 3; i["Description"] = "Package"; i["Unit"] = 99m; orderDoc["Items"].AsArray.Add(i); // serialize both and get indexKey for each one var bytesObject = BsonSerializer.Serialize(orderObject); var keyObject = new IndexKey(BsonSerializer.GetIdValue(orderObject)); var bytesDoc = BsonSerializer.Serialize(orderDoc); var keyDoc = new IndexKey(BsonSerializer.GetIdValue(orderDoc)); // lets revert objects (create a object from Document and create a Document from a object) var revertObject = BsonSerializer.Deserialize <Order>(keyDoc, bytesDoc); var revertDoc = BsonSerializer.Deserialize <BsonDocument>(keyObject, bytesObject); // lets compare properties Assert.AreEqual(revertObject.OrderKey, revertDoc.Id); Assert.AreEqual(revertObject.CustomerId, revertDoc["CustomerId"].AsGuid); Assert.AreEqual(revertObject.Date, revertDoc["Date"].AsDateTime); Assert.AreEqual(revertObject.Items[0].Unit, revertDoc["Items"][0]["Unit"].AsDecimal); // get some property Assert.AreEqual(now, BsonSerializer.GetFieldValue(revertObject, "Date")); Assert.AreEqual(now, BsonSerializer.GetFieldValue(revertDoc, "Date")); Assert.AreEqual(cid, BsonSerializer.GetFieldValue(revertObject, "CustomerId")); Assert.AreEqual(cid, BsonSerializer.GetFieldValue(revertDoc, "CustomerId")); Assert.AreEqual(null, BsonSerializer.GetFieldValue(revertObject, "Date2")); Assert.AreEqual(null, BsonSerializer.GetFieldValue(revertDoc, "Date2")); }