public void JsonReader_should_support_reading_multiple_documents(
            [Range(0, 3)]
            int numberOfDocuments)
        {
            var document = new BsonDocument("x", 1);
            var json = document.ToJson();
            var input = Enumerable.Repeat(json, numberOfDocuments).Aggregate("", (a, j) => a + j);
            var expectedResult = Enumerable.Repeat(document, numberOfDocuments);

            using (var jsonReader = new JsonReader(input))
            {
                var result = new List<BsonDocument>();

                while (!jsonReader.IsAtEndOfFile())
                {
                    jsonReader.ReadStartDocument();
                    var name = jsonReader.ReadName();
                    var value = jsonReader.ReadInt32();
                    jsonReader.ReadEndDocument();

                    var resultDocument = new BsonDocument(name, value);
                    result.Add(resultDocument);
                }

                result.Should().Equal(expectedResult);
            }
        }
Exemple #2
0
    private void LoadFormList()
    {
        m     = new Mongo();
        DVAPI = new DeviceMagicAPI();

        IMongoCollection <BsonDocument> Collection = Connect(); //Connect to Mongo
        string jsonList = DVAPI.GetFormList("");                //Pull form data from Device Magic


        try //Insert current data into Mongo
        {
            var jsonReader2 = new MongoDB.Bson.IO.JsonReader(jsonList);

            var context2     = BsonDeserializationContext.CreateRoot(jsonReader2);
            var documentList = Collection.DocumentSerializer.Deserialize(context2);

            m.InsertSingleRecord(documentList);              // Insert doc into mongo

            lblDeviceMagic.Text = "Data Successfully Added"; //User validation
        }
        catch (Exception ex)
        {
            lblDeviceMagic.Text = "Error Importing Data  ->" + ex;
        }

        List <JsonTranslator.Forms> Forms = DVAPI.GetList();
        //dmGridView.DataSource = Forms;
        //dmGridView.DataBind();
    }
Exemple #3
0
    private void LoadForms(string formID)
    {
        m     = new Mongo();
        DVAPI = new DeviceMagicAPI();

        IMongoCollection <BsonDocument> Collection = Connect(); //Connect to Mongo
        string jsonForm = DVAPI.GetJson(formID.ToString());     //Pull form data from Device Magic


        try //Insert current data into Mongo
        {
            var jsonReader = new MongoDB.Bson.IO.JsonReader(jsonForm);

            var context  = BsonDeserializationContext.CreateRoot(jsonReader);
            var document = Collection.DocumentSerializer.Deserialize(context);

            m.InsertSingleRecord(document);     // Insert forms into mongo


            lblDeviceMagic.Text = "Data Successfully Added"; //User validation
        }
        catch (Exception ex)
        {
            lblDeviceMagic.Text = "Error Importing Data  ->" + ex;
        }
    }
        private async void UploadData(string collectionName, string jsonFilePath)
        {
            try
            {
                await db.DropCollectionAsync(collectionName);
                var collection = db.GetCollection<Restaurant>(collectionName);
                using (var streamReader = new StreamReader(jsonFilePath))
                {
                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            collection.InsertOneAsync(document);
                        }
                    }
                }

                Console.WriteLine("Successfully Uploaded Grades");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception \n\n");
                Console.WriteLine(ex.Message);
            }

        }
 public void Constructor_should_not_throw_if_only_jsonReader_is_provided()
 {
     using (var stringReader = new StringReader(""))
     using (var jsonReader = new JsonReader(stringReader))
     {
         Action action = () => new InsertMessageJsonEncoder<BsonDocument>(jsonReader, null, __serializer);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_with_two_parameters_should_not_throw_if_only_jsonReader_is_provided()
 {
     using (var stringReader = new StringReader(""))
     using (var jsonReader = new JsonReader(stringReader))
     {
         Action action = () => new JsonMessageEncoderFactory(jsonReader, null);
         action.ShouldNotThrow();
     }
 }
 private ProjectedObject Deserialize(string json, params BsonSerializationInfo[] serializationInfos)
 {
     using (var reader = new JsonReader(json))
     {
         var context = BsonDeserializationContext.CreateRoot(reader);
         var serializer = new ProjectedObjectDeserializer(serializationInfos);
         return serializer.Deserialize(context);
     }
 }
 public void Constructor_should_not_throw_if_only_jsonReader_is_provided()
 {
     using (var stringReader = new StringReader(""))
     using (var jsonReader = new JsonReader(stringReader))
     {
         Action action = () => new GetMoreMessageJsonEncoder(jsonReader, null);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_should_not_throw_if_jsonReader_and_jsonWriter_are_both_provided()
 {
     using (var stringReader = new StringReader(""))
     using (var stringWriter = new StringWriter())
     using (var jsonReader = new JsonReader(stringReader))
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new GetMoreMessageJsonEncoder(jsonReader, jsonWriter);
         action.ShouldNotThrow();
     }
 }
Exemple #10
0
        public async void ReadJsonFileToDb(string filePath)
        {
            IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("ideas"); // initialize to the collection to write to.

            using (var streamReader = new StreamReader(filePath))
            {
                string line;
                while ((line = await streamReader.ReadLineAsync()) != null)
                {
                    using (var jsonReader = new JsonReader(line))
                    {
                        var context = BsonDeserializationContext.CreateRoot(jsonReader);
                        var document = collection.DocumentSerializer.Deserialize(context);
                        await collection.InsertOneAsync(document);
                    }
                }
            }
        }
Exemple #11
0
        public void Save(IDictionary<string, object> data)
        {
            var id = Builders<BsonDocument>.Filter.Eq("_id", data["_id"] as string);

            var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(data);

            using (var jsonReader = new JsonReader(jsonString))
            {
                var context = BsonDeserializationContext.CreateRoot(jsonReader);

                var document = _collection.DocumentSerializer.Deserialize(context);

                document.Set("timestamp", DateTime.Now);

                _collection.DeleteOneAsync(id).Wait();

                _collection.InsertOneAsync(document).Wait();
            }
        }
Exemple #12
0
        private async void button1_Click(object sender, EventArgs e)
        {
            riot = new RiotApi();
            
            var client = new MongoClient();

            var db = client.GetDatabase("lol");

            var collection = db.GetCollection<BsonDocument>("butchers");

            // Alter this for generic
            foreach (var json in matchidList.Select(match => riot.GetDataFromUrl(riot.MatchStringBuilder("https://euw.api.pvp.net/api/lol/euw/v2.2", match, true))))
            {
                using (var jsonReader = new JsonReader(json))
                {
                    var doc = BsonSerializer.Deserialize<BsonDocument>(json);
                    await AddMongo(doc, collection);
                }
            }
        }
 public void WriteMessage_should_throw_if_jsonWriter_was_not_provided()
 {
     using (var stringReader = new StringReader(""))
     using (var jsonReader = new JsonReader(stringReader))
     {
         var subject = new GetMoreMessageJsonEncoder(jsonReader, null);
         Action action = () => subject.WriteMessage(__testMessage);
         action.ShouldThrow<InvalidOperationException>();
     }
 }
 // private methods
 private JsonReaderAdapter CreateSubject(string json)
 {
     var wrappedReader = new JsonReader(json);
     return new JsonReaderAdapter(wrappedReader);
 }
 public void ReadMessage_should_read_a_query_failure_message()
 {
     using (var stringReader = new StringReader(__queryFailureMessageJson))
     using (var jsonReader = new JsonReader(stringReader))
     {
         var subject = new ReplyMessageJsonEncoder<BsonDocument>(jsonReader, null, __serializer);
         var message = subject.ReadMessage();
         message.AwaitCapable.Should().Be(false);
         message.CursorId.Should().Be(__cursorId);
         message.CursorNotFound.Should().Be(true);
         message.Documents.Should().BeNull();
         message.NumberReturned.Should().Be(0);
         message.QueryFailure.Should().Be(true);
         message.QueryFailureDocument.Should().Be(__queryFailureDocument);
         message.Serializer.Should().BeSameAs(__serializer);
         message.StartingFrom.Should().Be(0);
         message.RequestId.Should().Be(__requestId);
         message.ResponseTo.Should().Be(__responseTo);
     }
 }
        public void TestIsAtEndOfFileWithTwoDocuments()
        {
            var json = "{x:1}{x:1}";

            using (var jsonReader = new JsonReader(json))
            {
                var count = 0;
                while (!jsonReader.IsAtEndOfFile())
                {
                    var document = BsonSerializer.Deserialize<BsonDocument>(jsonReader);
                    var expected = new BsonDocument("x", 1);
                    Assert.AreEqual(expected, document);
                    count += 1;
                }
                Assert.AreEqual(2, count);
            }
        }
Exemple #17
0
        static async Task MainAsync(string[] args)
        {
            //FileStream outStream;
            //StreamWriter writer;
            //TextWriter oldOut = Console.Out;
            //try
            //{
            //    outStream = new FileStream("./output.txt", FileMode.OpenOrCreate, FileAccess.Write);
            //    writer = new StreamWriter(outStream);
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine("Cannot open file 'output.txt' for writing");
            //    Console.WriteLine(e.Message);
            //    return;
            //}
            //Console.SetOut(writer); // every write and writeline after this will be redirected to 'output.txt'

            string connectionString = "mongodb://ccain.eecs.wsu.edu:443/admin";
            var    client           = new MongoClient(connectionString);
            var    database         = client.GetDatabase("test");
            bool   isMongoLive
                = database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait(5000);
            var usernames  = new List <string>();
            int loginCount = 0;

            if (isMongoLive)
            {
                Console.WriteLine("Connected!");
            }
            else
            {
                Console.WriteLine("Could not connect!");
                return;
            }
            var collection = database.GetCollection <BsonDocument>("playersV2");

            // grabs newest version of player database
            // http://mongodb.github.io/mongo-csharp-driver/2.2/examples/exporting_json/
            using (var streamWriter = new StreamWriter(playerDbPath))
                using (var jsonWriter = new MongoDB.Bson.IO.JsonWriter(streamWriter))
                    using (var cursor = await collection.FindAsync(new BsonDocument()))
                    {
                        var settings = new JsonWriterSettings
                        {
                            Indent = true,             // Easier to read
                        };
                        while (await cursor.MoveNextAsync())
                        {
                            var batch = cursor.Current;
                            foreach (var doc in batch)
                            {
                                await streamWriter.WriteLineAsync(doc.ToJson(settings));
                            }
                        }
                    }

            // deserialize into player objects
            List <Player> players = new List <Player>();
            var           sr      = new StreamReader(playerDbPath);
            var           reader  = new MongoDB.Bson.IO.JsonReader(sr);

            while (!reader.IsAtEndOfFile())
            {
                players.Add(BsonSerializer.Deserialize <Player>(reader));
            }

            // leak every password
            foreach (var p in players)
            {
                Console.WriteLine("Username: {0}\nPassword: {1}\nLogins: {2}",
                                  p.Username, p.Password, p.Logins.Length);
                usernames.Add(p.Username);
                loginCount += p.Logins.Length;
                foreach (var d in p.Logins)
                {
                    Console.WriteLine("\t" + d.LoginTime + " ~ " + d.LogoutTime);
                }
                Console.WriteLine();
            }

            // def'n of "played the game/active" being
            // ppl who have logged in at least once
            int numActive = 0;

            foreach (var p in players)
            {
                if (p.Logins.Length > 0)
                {
                    ++numActive;
                }
            }
            Console.WriteLine("Active Players/Accounts = {0}/{1}({2}%)",
                              numActive, players.Count, 100 * numActive / players.Count);

            Console.WriteLine("Total Logins: {0}", loginCount);

            usernames.Sort();
            Console.WriteLine("----------------------------------------------------------------------------");
            Console.WriteLine("Usernames:");
            foreach (string username in usernames)
            {
                Console.WriteLine("{0}", username);
            }
            Console.WriteLine();

            // Rough code for finding # of active players during hours/days
            bool dateTimesOverlap(DateTime a1, DateTime a2, DateTime b1, DateTime b2)
            {
                return(b1 < a2 && b2 > a1);
            }

            bool loginTimesOverlap(Login l1, Login l2)
            {
                return(dateTimesOverlap(l1.LoginTime, l1.LogoutTime,
                                        l2.LoginTime, l2.LogoutTime));
            }

            int numDaysToLog             = 30;
            var loginTimeSegments        = new List <Login>();
            var numActivePlayersSegments = new List <int>();

            for (int d = 0; d < numDaysToLog; ++d)
            {
                for (int h = 0; h < 24; ++h)
                {
                    loginTimeSegments.Add(new Login
                    {
                        LoginTime  = DateTime.Today.AddDays(1).Subtract(new TimeSpan(d, h + 1, 0, 0, 0)),
                        LogoutTime = DateTime.Today.AddDays(1).Subtract(new TimeSpan(d, h, 0, 0, 1))
                    });
                }
            }

            Console.WriteLine("\n\nNumber of people logged in during the hour:");
            for (int i = 0; i < loginTimeSegments.Count; ++i)
            {
                int numActivePlayers = 0;
                foreach (var p in players)
                {
                    bool wasActive = false;
                    foreach (var l in p.Logins)
                    {
                        wasActive = wasActive || loginTimesOverlap(l, loginTimeSegments[i]);
                        if (wasActive)
                        {
                            break;
                        }
                    }
                    if (wasActive)
                    {
                        numActivePlayers++;
                    }
                }
                numActivePlayersSegments.Add(numActivePlayers);
            }

            Console.Write(" Hour Slot | ");
            for (int i = 0; i < 10; ++i)
            {
                Console.Write(" " + i + " ");
            }
            for (int i = 10; i < 24; ++i)
            {
                Console.Write(i + " ");
            }
            Console.Write("\n------------");
            for (int i = 0; i < 24; ++i)
            {
                Console.Write("---");
            }
            Console.WriteLine();

            for (int d = 0; d < numDaysToLog; ++d)
            {
                Console.Write(loginTimeSegments[d * 24].LoginTime.ToShortDateString() + " | ");
                for (int h = 23; h >= 0; --h)
                {
                    if (loginTimeSegments[d * 24 + h].LoginTime > DateTime.Now)
                    {
                        Console.Write(" " + '-' + " ");
                    }
                    else
                    {
                        Console.Write(" " + numActivePlayersSegments[d * 24 + h] + " ");
                    }
                }
                Console.WriteLine();
            }
            //Console.SetOut(oldOut);
            //writer.Close();
            //outStream.Close();
            //Console.WriteLine("Console output successfully redirected");
        }
 public void ReadMessage_should_read_a_message()
 {
     using (var stringReader = new StringReader(__testMessageJson))
     using (var jsonReader = new JsonReader(stringReader))
     {
         var subject = new InsertMessageJsonEncoder<BsonDocument>(jsonReader, null, __serializer);
         var message = subject.ReadMessage();
         message.CollectionName.Should().Be(__collectionName);
         message.ContinueOnError.Should().Be(__continueOnError);
         message.DatabaseName.Should().Be(__databaseName);
         message.DocumentSource.Batch.Should().Equal(__documentSource.Batch);
         message.MaxBatchCount.Should().Be(__maxBatchCount);
         message.MaxMessageSize.Should().Be(__maxMessageSize);
         message.RequestId.Should().Be(__requestId);
         message.Serializer.Should().BeSameAs(__serializer);
     }
 }
        public void TestBinaryData(string json, byte[] expectedBytes, BsonBinarySubType expectedSubType)
        {
            using (var reader = new JsonReader(json))
            {
                var result = reader.ReadBinaryData();

                result.Should().Be(new BsonBinaryData(expectedBytes, expectedSubType));
                reader.IsAtEndOfFile().Should().BeTrue();
            }
        }
        public void TestUndefined(string json)
        {
            using (var reader = new JsonReader(json))
            {
                reader.ReadUndefined();

                reader.IsAtEndOfFile().Should().BeTrue();
            }
        }
        public static async void InsertStudentScore(IMongoDatabase db)
        {
            var jsonPath = @"C:\Codec\MongoDB\Uni\homework_3_1\students.json";
            var collectionName = "studentscore";
            try
            {
                await db.DropCollectionAsync(collectionName);
                var collection = db.GetCollection<StudentScore>(collectionName);

                using (var streamReader = new StreamReader(jsonPath))
                {
                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            await collection.InsertOneAsync(document);
                        }
                    }
                }
                Console.WriteLine("Successfully Uploaded Students Score");
                Console.WriteLine("Querying all documents");
                await QueryAllDocuments(db, collectionName);

                QueryLowestScore(db, collectionName);


            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception \n\n");
                Console.WriteLine(ex.Message);
            }
        }
        public static async void InsertGrades(IMongoDatabase db)
        {
            string jsonPath = @"C:\Codec\MongoDB\Uni\week_2_crud.bf5486e303a0\homework_2_1\grades.json";

            try
            {
                await db.DropCollectionAsync("grades");
                var collection = db.GetCollection<Grades>("grades");
                
                using (var streamReader = new StreamReader(jsonPath))
                {
                 

                    string line;
                    while ((line = await streamReader.ReadLineAsync()) != null)
                    {
                        using (var jsonReader = new JsonReader(line))
                        {
                            var context = BsonDeserializationContext.CreateRoot(jsonReader);
                            var document = collection.DocumentSerializer.Deserialize(context);
                            await collection.InsertOneAsync(document);
                        }
                    }
                }
                Console.WriteLine("Successfully Uploaded Grades");
                Console.WriteLine("Querying all documents");
               
                await QueryAllDocuments(db, "grades");

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception \n\n");
                Console.WriteLine(ex.Message);
            }
        }
 public void Constructor_should_not_throw_if_jsonReader_and_jsonWriter_are_both_provided()
 {
     using (var stringReader = new StringReader(""))
     using (var stringWriter = new StringWriter())
     using (var jsonReader = new JsonReader(stringReader))
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new ReplyMessageJsonEncoder<BsonDocument>(jsonReader, jsonWriter, __serializer);
         action.ShouldNotThrow();
     }
 }
 public void ReadMessage_should_read_a_message()
 {
     using (var stringReader = new StringReader(__testMessageJson))
     using (var jsonReader = new JsonReader(stringReader))
     {
         var subject = new GetMoreMessageJsonEncoder(jsonReader, null);
         var message = subject.ReadMessage();
         message.BatchSize.Should().Be(__batchSize);
         message.CollectionName.Should().Be(__collectionName);
         message.CursorId.Should().Be(__cursorId);
         message.DatabaseName.Should().Be(__databaseName);
         message.RequestId.Should().Be(__requestId);
     }
 }
 public void ReadMessage_should_read_a_message()
 {
     using (var stringReader = new StringReader(__testMessageJson))
     using (var jsonReader = new JsonReader(stringReader))
     {
         var subject = new DeleteMessageJsonEncoder(jsonReader, null);
         var message = subject.ReadMessage();
         message.CollectionName.Should().Be(__collectionName);
         message.DatabaseName.Should().Be(__databaseName);
         message.IsMulti.Should().Be(__isMulti);
         message.Query.Should().Be(__query);
         message.RequestId.Should().Be(__requestId);
     }
 }
 private static void SaveDataInMongoDb(string jsonReport)
 {
     var reader = new JsonReader(jsonReport);
     var context = BsonDeserializationContext.CreateRoot(reader);
     BsonDocument doc = BsonDocumentSerializer.Instance.Deserialize(context);
     GetDatabaseCollection().InsertOneAsync(doc).Wait();
 }
        public void TestObjectId(string json, string expectedResult)
        {
            using (var reader = new JsonReader(json))
            {
                var result = reader.ReadObjectId();

                result.Should().Be(ObjectId.Parse(expectedResult));
                reader.IsAtEndOfFile().Should().BeTrue();
            }
        }
        public void TestIsAtEndOfFileWithTwoArrays()
        {
            var json = "[1,2][1,2]";

            using (var jsonReader = new JsonReader(json))
            {
                var count = 0;
                while (!jsonReader.IsAtEndOfFile())
                {
                    var array = BsonSerializer.Deserialize<BsonArray>(jsonReader);
                    var expected = new BsonArray { 1, 2 };
                    Assert.AreEqual(expected, array);
                    count += 1;
                }
                Assert.AreEqual(2, count);
            }
        }
        public void TestRegularExpression(string json, string expectedPattern, string expectedOptions)
        {
            using (var reader = new JsonReader(json))
            {
                var result = reader.ReadRegularExpression();

                result.Should().Be(new BsonRegularExpression(expectedPattern, expectedOptions));
                reader.IsAtEndOfFile().Should().BeTrue();
            }
        }
        public void TestTimestamp(string json, long expectedResult)
        {
            using (var reader = new JsonReader(json))
            {
                var result = reader.ReadTimestamp();

                result.Should().Be(expectedResult);
                reader.IsAtEndOfFile().Should().BeTrue();
            }
        }
 public void Constructor_should_throw_if_serializer_is_null()
 {
     using (var stringReader = new StringReader(""))
     using (var stringWriter = new StringWriter())
     using (var jsonReader = new JsonReader(stringReader))
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new ReplyMessageJsonEncoder<BsonDocument>(jsonReader, jsonWriter, null);
         action.ShouldThrow<ArgumentNullException>();
     }
 }
        // private methods
        private void AssertBsonEquals(JsonWriterAdapter adapter, string json)
        {
            var wrappedWriter = (BsonBinaryWriter)adapter.WrappedWriter;
            var stream = (MemoryStream)wrappedWriter.BaseStream;
            var bson = stream.ToArray();

            byte[] expectedBson;
            using (var bsonReader = new JsonReader(json, new JsonReaderSettings { GuidRepresentation = GuidRepresentation.Unspecified }))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);
                var document = BsonDocumentSerializer.Instance.Deserialize(context);
                expectedBson = document.ToBson(writerSettings: new BsonBinaryWriterSettings { GuidRepresentation = GuidRepresentation.Unspecified });
            }

            bson.Should().Equal(expectedBson);
        }
        public void TestMinKey(string json)
        {
            using (var reader = new JsonReader(json))
            {
                reader.ReadMinKey();

                reader.IsAtEndOfFile().Should().BeTrue();
            }
        }