Example #1
0
 public void BsonSingleValue()
 {
     var document = new BsonDocument();
     document["test"] = 2;
     var data = document.ToByteArray();
     var readDocument = BsonDocument.Read(data);
     Assert.AreEqual(2, readDocument["test"].Value);
 }
Example #2
0
 public void BsonArray()
 {
     var document = new BsonDocument();
     document["test"] = new BsonItem(new string[] { "testing", "123" });
     var data = document.ToByteArray();
     var readDocument = BsonDocument.Read(data);
     Assert.AreEqual(2, readDocument["test"].Count);
     Assert.AreEqual("testing", readDocument["test"][0].Value);
     Assert.AreEqual("123", readDocument["test"][1].Value);
 }
Example #3
0
 public void BsonByteAccurate()
 {
     // the example document: { "number": 2 } in bson
     var document = new BsonDocument();
     document["number"] = 2;
     var data = document.ToByteArray();
     File.WriteAllBytes("TestOutput.bson", data); // write the data for debugging purposes
     var exampleData = File.ReadAllBytes("TestFile.bson");
     CompareByteArrays(data, exampleData);
 }
Example #4
0
 public void BsonArrayOfObjects()
 {
     var document = new BsonDocument();
     var item1 = new BsonItem();
     item1["prop"] = true;
     var item2 = new BsonItem();
     item2["pro2"] = false;
     document["test"] = new BsonItem(new BsonItem[] { item1, item2 });
     var data = document.ToByteArray();
     var readDocument = BsonDocument.Read(data);
     Assert.AreEqual(2, readDocument["test"].Count);
     Assert.AreEqual(true, readDocument["test"][0]["prop"].Value);
 }
Example #5
0
 public void BsonComplexByteAccurate()
 {
     var document = new BsonDocument();
     document["number"] = 2;
     document["object"] = new BsonItem();
     document["object"]["array"] = new BsonItem(new BsonItem[]
     {
         "string",
         "another_string",
         2,
         5.2
     });
     document["object"]["float"] = 4.2223;
     document["str"] = "string";
     var data = document.ToByteArray();
     File.WriteAllBytes("ComplexTestOutput.bson", data);
     var exampleData = File.ReadAllBytes("ComplexTestFile.bson");
     CompareByteArrays(data, exampleData);
 }
Example #6
0
 private static BsonItem ReadItem(byte code, BsonDocument document, EasyReader reader)
 {
     object val = null;
     switch (code)
     {
         case 0x01: // double
             val = reader.ReadDouble();
             break;
         case 0x02: // string
             val = reader.ReadString(Encoding.UTF8).TrimEnd('\x00');
             if (document.StringTableMode == BsonStringTableMode.KeysAndValues)
                 val = document.ReverseStringTable[int.Parse((string)val)];
             break;
         case 0x03: // document
             val = Read(reader, document).Top;
             break;
         case 0x04: // array
             val = Read(reader, document, true).Top;
             break;
         case 0x05: // binary
             var length = reader.ReadInt32();
             var subtype = reader.ReadByte();
             if (subtype != 0x00)
                 throw new NotSupportedException("BSON subtypes other than 'generic binary data' are not supported.");
             val = reader.ReadBytes(length);
             break;
         case 0x06: // undefined
             break;
         case 0x07: // ObjectId
             // why does this parser support ObjectIds and not other binary data?
             // shhhhh
             val = Encoding.ASCII.GetString(reader.ReadBytes(12));
             break;
         case 0x08: // boolean
             val = reader.ReadBoolean();
             break;
         case 0x09: // UTC datetime
             val = reader.ReadInt64();
             break;
         case 0x0A: // null
             break;
         case 0x0B: // regex
             // why are you using regex in a Rant package?
             throw new NotSupportedException("Regular expressions are not supported.");
         case 0x0C: // db pointer
             throw new NotSupportedException("DB pointers are not supported.");
         case 0x0D: // Javascript code
         case 0x0F: // JS code with scope
             throw new NotSupportedException("Javascript in BSON is not supported.");
         case 0x0E: // depreceated
             val = reader.ReadString(Encoding.UTF8);
             break;
         case 0x10: // 32 bit integer
             val = reader.ReadInt32();
             break;
         case 0x11: // timestamp
         case 0x12: // 64 bit integer
             val = reader.ReadInt64();
             break;
         case 0xFF: // min key
         case 0x7F: // max key
             // we don't care about these so let's just skip em
             break;
     }
     if (!(val is BsonItem))
         return new BsonItem(val) { Type = code };
     var i = (BsonItem)val;
     i.Type = code;
     return i;
 }
Example #7
0
        /// <summary>
        /// Reads a BSON document from the specified EasyReader.
        /// </summary>
        /// <param name="reader">The reader that will be used to read this document.</param>
        /// <returns>The document that was read.</returns>
        internal static BsonDocument Read(EasyReader reader, BsonDocument parent = null, bool inArray = false)
        {
            var stringTableMode = BsonStringTableMode.None;
            Dictionary<int, string> stringTable = null;
            if (parent == null)
            {
                var includesStringTable = reader.ReadBoolean();
                if (includesStringTable)
                {
                    stringTable = new Dictionary<int, string>();
                    stringTableMode = (BsonStringTableMode)reader.ReadByte();
                    var version = reader.ReadByte();
                    if (version != STRING_TABLE_VERSION)
                        throw new InvalidDataException("Unsupported string table version: " + version);
                    var tableLength = reader.ReadInt32();
                    var tableEntries = reader.ReadInt32();
                    for (var i = 0; i < tableEntries; i++)
                    {
                        var num = reader.ReadInt32();
                        var val = reader.ReadString(Encoding.UTF8);
                        stringTable[num] = val;
                    }
                }
            }
            else
            {
                stringTable = parent.ReverseStringTable;
                stringTableMode = parent.StringTableMode;
            }
            var document = new BsonDocument(stringTableMode, stringTable);

            var length = reader.ReadInt32();
            while(!reader.EndOfStream)
            {
                var code = reader.ReadByte();
                if (code == 0x00) // end of document
                    break;
                var name = reader.ReadCString();
                if (!inArray && document.StringTableMode != BsonStringTableMode.None)
                    name = document.ReverseStringTable[int.Parse(name)];
                var data = ReadItem(code, document, reader);
                document.Top[name] = data;
            }
            return document;
        }
Example #8
0
 public void BsonDeepObject()
 {
     var document = new BsonDocument();
     document["test"] = new BsonItem();
     document["test"]["test_level2"] = new BsonItem();
     document["test"]["test_level2"]["test_level3"] = true;
     var data = document.ToByteArray();
     var readDocument = BsonDocument.Read(data);
     Assert.AreEqual(true, readDocument["test"]["test_level2"]["test_level3"].Value);
 }
Example #9
0
        /// <summary>
        /// Saves the package to the specified file path.
        /// </summary>
        /// <param name="path">The path to the file to create.</param>
        public void Save(
            string path, 
            bool compress = true, 
            BsonStringTableMode stringTableMode = BsonStringTableMode.None)
        {
            if (String.IsNullOrEmpty(Path.GetExtension(path)))
            {
                path += ".rantpkg";
            }

            using (var writer = new EasyWriter(File.Create(path)))
            {
                var doc = new BsonDocument(stringTableMode);
                var info = doc.Top["info"] = new BsonItem();
                info["title"] = new BsonItem(_title);
                info["id"] = new BsonItem(_id);
                info["description"] = new BsonItem(Description);
                info["tags"] = new BsonItem(Tags);
                info["version"] = new BsonItem(Version.ToString());
                info["authors"] = new BsonItem(Authors);
				info["dependencies"] = new BsonItem(_dependencies.Select(dep =>
				{
					var depObj = new BsonItem();
					depObj["id"] = dep.ID;
					depObj["version"] = dep.Version.ToString();
					depObj["allow-newer"] = dep.AllowNewer;
					return depObj;
				}).ToArray());
                
                var patterns = doc.Top["patterns"] = new BsonItem();
                if(_patterns != null)
                    foreach(var pattern in _patterns)
                        patterns[pattern.Name] = new BsonItem(pattern.Code);

                var tables = doc.Top["tables"] = new BsonItem();
	            if (_tables != null)
	            {
					foreach (var table in _tables)
					{
						var t = tables[table.Name] = new BsonItem();
						t["name"] = new BsonItem(table.Name);
						t["subs"] = new BsonItem(table.Subtypes);
						t["language"] = new BsonItem(table.Language);
						t["hidden"] = new BsonItem(table.HiddenClasses.ToArray());
						t["hints"] = new BsonItem(0);
						var entries = new List<BsonItem>();
						foreach (var entry in table.GetEntries())
						{
							var e = new BsonItem();
							if (entry.Weight != 1)
								e["weight"] = new BsonItem(entry.Weight);
							var requiredClasses = entry.GetRequiredClasses().ToArray();
							if (requiredClasses.Length > 0)
								e["classes"] = new BsonItem(requiredClasses);
							var optionalClasses = entry.GetOptionalClasses().ToArray();
							if (optionalClasses.Length > 0)
								e["optional_classes"] = new BsonItem();
							var terms = new List<BsonItem>();
							foreach (var term in entry.Terms)
							{
								var et = new BsonItem();
								et["value"] = new BsonItem(term.Value);
								if (term.Pronunciation != "")
									et["pron"] = new BsonItem(term.Pronunciation);
								terms.Add(et);
							}
							e["terms"] = new BsonItem(terms.ToArray());
							entries.Add(e);
						}
						t["entries"] = new BsonItem(entries.ToArray());
					}
				}

                var data = doc.ToByteArray(stringTableMode != BsonStringTableMode.None);
                if (compress)
                    data = EasyCompressor.Compress(data);
                writer.Write(Encoding.ASCII.GetBytes("RANT"));
                writer.Write((uint)2);
                writer.Write(compress);
                writer.Write(data.Length);
                writer.Write(data);
            }
        }