Represents a BSON writer to a TextWriter (in JSON format).
Inheritance: BsonWriter
        public void TestNoCircularReference()
        {
            var c2 = new C { X = 2 };
            var c1 = new C { X = 1, NestedDocument = c2 };

            var json = c1.ToJson();
            var expected = "{ 'X' : 1, 'NestedDocument' : { 'X' : 2, 'NestedDocument' : null, 'BsonArray' : { '_csharpnull' : true } }, 'BsonArray' : { '_csharpnull' : true } }".Replace("'", "\"");
            Assert.AreEqual(expected, json);

            var memoryStream = new MemoryStream();
            using (var writer = new BsonBinaryWriter(memoryStream))
            {
                BsonSerializer.Serialize(writer, c1);
                Assert.AreEqual(0, writer.SerializationDepth);
            }

            var document = new BsonDocument();
            using (var writer = new BsonDocumentWriter(document))
            {
                BsonSerializer.Serialize(writer, c1);
                Assert.AreEqual(0, writer.SerializationDepth);
            }

            var stringWriter = new StringWriter();
            using (var writer = new JsonWriter(stringWriter))
            {
                BsonSerializer.Serialize(writer, c1);
                Assert.AreEqual(0, writer.SerializationDepth);
            }
        }
Esempio n. 2
0
        static void Poco(string[] args)
        {
            var conventionPack = new ConventionPack();
            conventionPack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camelCase", conventionPack, t => true);

            BsonClassMap.RegisterClassMap<Person>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(x => x.Name).SetElementName("name");
            });

            var person = new Person
            {
                Name = "Jones",
                Age = 30,
                Colors = new List<string> { "red", "blue" },
                Pets = new List<Pet> { new Pet { Name = "Fluffy", Type = "Pig" } },
                ExtraElements = new BsonDocument("anotherName", "anotherValue")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }
        }
 public void Constructor_should_not_throw_if_only_jsonWriter_is_provided()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new GetMoreMessageJsonEncoder(null, jsonWriter);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_with_two_parameters_should_not_throw_if_only_jsonWriter_is_provided()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new JsonMessageEncoderFactory(null, jsonWriter);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_with_jsonWriter_parameter_should_not_throw_if_jsonWriter_is_not_null()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new JsonMessageEncoderFactory(jsonWriter);
         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();
     }
 }
 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 InsertMessageJsonEncoder<BsonDocument>(jsonReader, jsonWriter, __serializer);
         action.ShouldNotThrow();
     }
 }
        static async Task classBarmoloMetodusConventionPack()
        {
            var conventionPack = new ConventionPack();
            conventionPack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camelCase", conventionPack, t => true);           

            var person = new Person
            {
                Name = "Jones",
                Age = 34,
                //Colors = new List<string> { "red", "green" },
                //Pets = new List<Pet> { new Pet { Name = "Fluffy", Type = "Pig" } },
                //ExtraElements = new BsonDocument("anotherName", "anotherValue")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }
        }
Esempio n. 9
0
        static async Task classBarmoloMetodusClassMap()
        {

            BsonClassMap.RegisterClassMap<Person>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(x => x.Name).SetElementName("név");
            });

            var person = new Person
            {
                Name = "Jones",
                Age = 34,
                //Colors = new List<string> { "red", "green" },
                //Pets = new List<Pet> { new Pet { Name = "Fluffy", Type = "Pig" } },
                //ExtraElements = new BsonDocument("anotherName", "anotherValue")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }
        }
 public void WriteMessage_should_write_a_message()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         var subject = new GetMoreMessageJsonEncoder(null, jsonWriter);
         subject.WriteMessage(__testMessage);
         var json = stringWriter.ToString();
         json.Should().Be(__testMessageJson);
     }
 }
 public void WriteMessage_should_throw_if_message_is_null()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         var subject = new GetMoreMessageJsonEncoder(null, jsonWriter);
         Action action = () => subject.WriteMessage(null);
         action.ShouldThrow<ArgumentNullException>();
     }
 }
 public void ReadMessage_should_throw_if_jsonReader_was_not_provided()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         var subject = new GetMoreMessageJsonEncoder(null, jsonWriter);
         Action action = () => subject.ReadMessage();
         action.ShouldThrow<InvalidOperationException>();
     }
 }
 public void Constructor_should_not_throw_if_only_jsonWriter_is_provided()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         Action action = () => new ReplyMessageJsonEncoder<BsonDocument>(null, jsonWriter, __serializer);
         action.ShouldNotThrow();
     }
 }
Esempio n. 14
0
        /// <summary>
        /// [MONGODB-DEMO] The mapping from POCOs to Bson in run-time (!! this might help to break off relationship between a particular DB and Model classes).
        /// </summary>
        private static void PocoPlainSerialization()
        {
            // A convention that sets the element name the same as the class-member name with the first character lower cased.
            var conventionPack = new ConventionPack();
            conventionPack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camelCase", conventionPack, type => type.IsPublic);

            // Register BsonClassMap for the concrete class.
            // The same you can achieve with using of attributes. See class Person.
            BsonClassMap.RegisterClassMap<PersonPlain>(cm =>
            {
                cm.AutoMap();
                cm.MapMember(c => c.Name).SetElementName("new_name");
                cm.MapMember(c => c.Age).SetIgnoreIfDefault(true);
            });

            var person = new PersonPlain
            {
                Id = ObjectId.GenerateNewId(),
                Name = "Benny",
                Age = 0, // 33,
                Colors = new List<string> { "red", "blue" },
                Pets = new List<PetPlain>
                    {
                        new PetPlain { Name = "Fluffy",    Type = "dog" },
                        new PetPlain { Name = "Garfield",  Type = "cat" }
                    },
                ExtraElements = new BsonDocument("additionalName", "Name2")
            };

            using (var writer = new JsonWriter(Console.Out))
            {
                BsonSerializer.Serialize(writer, person);
            }

            Console.WriteLine();
        }
 public void GetDeleteMessageEncoder_should_return_a_DeleteMessageJsonEncoder()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         var encoderFactory = new JsonMessageEncoderFactory(null, jsonWriter);
         var encoder = encoderFactory.GetDeleteMessageEncoder();
         encoder.Should().BeOfType<DeleteMessageJsonEncoder>();
     }
 }
Esempio n. 16
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 WriteMessage_should_write_a_query_failure_message()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         var subject = new ReplyMessageJsonEncoder<BsonDocument>(null, jsonWriter, __serializer);
         subject.WriteMessage(__queryFailureMessage);
         var json = stringWriter.ToString();
         json.Should().Be(__queryFailureMessageJson);
     }
 }
 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>();
     }
 }
 public void GetReplyMessageEncoder_should_return_a_ReplyMessageJsonEncoder()
 {
     using (var stringWriter = new StringWriter())
     using (var jsonWriter = new JsonWriter(stringWriter))
     {
         var encoderFactory = new JsonMessageEncoderFactory(null, jsonWriter);
         var encoder = encoderFactory.GetReplyMessageEncoder<BsonDocument>(BsonDocumentSerializer.Instance);
         encoder.Should().BeOfType<ReplyMessageJsonEncoder<BsonDocument>>();
     }
 }