Skip to content
Browse files

Better array handling

Binary data type support
More fault tolerant open method for PairedConnection contributed by Andrew Kempe
  • Loading branch information...
1 parent 759a7d5 commit 337cda355dea1aaafa0bd84b52ae140cfae9eb40 Samuel Corder committed
View
1 .gitignore
@@ -14,6 +14,7 @@
*.usertasks
test-results/*.xml
+MongoDB.Net-Tests/bin/*
MongoDB.Net-Tests/test-results/MongoDB.Driver.Tests.csproj.test-cache
MongoDB.Linq.Tests/test-results/MongoDB.Linq.Tests.csproj.test-cache
View
28 MongoDB.Net-Tests/Bson/TestBsonArray.cs 100644 → 100755
@@ -69,6 +69,32 @@ public class TestBsonArray
ikey++;
}
}
-
+ [Test]
+ public void TestToNativeProducesArrayWithAllValuesTheSameType(){
+ Document[] songs = new[] {
+ new Document().Append("title", "Let The Music Set You Free").Append("length", "5:15"),
+ new Document().Append("title", "Sally Likes to Run").Append("length", "4:06"),
+ new Document().Append("title", "Deliveries After Dark").Append("length", "4:17"),
+ new Document().Append("title", "Theme From The Godfather").Append("length", "3:06"),
+ new Document().Append("title", "Grown Man Crying Blues").Append("length", "8:09"),
+ };
+ BsonArray ba = new BsonArray();
+ ba.Add(1,"A");
+ ba.Add(2,"B");
+ ba.Add(3,"C");
+ Object obj = ba.ToNative();
+ Assert.AreEqual(typeof(string[]),obj.GetType());
+ }
+
+ [Test]
+ public void TestElementsSameType(){
+ BsonArray ba = new BsonArray();
+ ba.Add(1,"A");
+ ba.Add(2,"B");
+ ba.Add(3,"C");
+
+ Assert.IsTrue(ba.ElementsSameType());
+
+ }
}
}
View
132 MongoDB.Net-Tests/Bson/TestBsonBinary.cs 100644 → 100755
@@ -1,31 +1,121 @@
-using System;
+using System;
using System.IO;
using NUnit.Framework;
+using MongoDB.Driver;
+
namespace MongoDB.Driver.Bson
{
- [TestFixture]
+ [TestFixture]
public class TestBsonBinary
{
- [Test]
- public void TestBinary()
- {
-
- byte[] data = File.ReadAllBytes(@"test-data\tests.binary.txt");
- BsonBinary binaryIn = new BsonBinary(new Binary(data));
- MemoryStream stream = new MemoryStream();
- BsonWriter bsonWriter = new BsonWriter(stream);
- binaryIn.Write(bsonWriter);
+ [Test]
+ public void TestRoundTrip(){
+ Document idoc = new Document();
+ idoc.Add("b",new Binary(new byte[]{(byte)1,(byte)2}));
+ BsonDocument bidoc = BsonConvert.From(idoc);
+
+ MemoryStream stream = new MemoryStream();
+ BsonWriter writer = new BsonWriter(stream);
+ bidoc.Write(writer);
+
+ stream.Seek(0,SeekOrigin.Begin);
+ BsonReader reader = new BsonReader(stream);
+ BsonDocument bodoc = new BsonDocument();
+ bodoc.Read(reader);
+ Document odoc = (Document) bodoc.ToNative();
+
+ Assert.AreEqual(idoc.ToString(), odoc.ToString());
+ }
+
+ [Test]
+ public void TestBinaryRead ()
+ {
+ string hex = "28000000075f6964004b1971811d8b0f00c0000000056461746100070000000203000000e188b400";
+
+ byte[] data = DecodeHex (hex);
+ MemoryStream inmem = new MemoryStream (data);
+ BsonReader inreader = new BsonReader (inmem);
+ BsonDocument indoc = new BsonDocument ();
+ indoc.Read (inreader);
+
+ MemoryStream outmem = new MemoryStream ();
+ BsonWriter outwriter = new BsonWriter (outmem);
+ indoc.Write (outwriter);
+ byte[] outdata = outmem.ToArray ();
+ String outhex = BitConverter.ToString (outdata);
+ outhex = outhex.Replace ("-", "");
+
+ Assert.AreEqual (hex, outhex.ToLower());
+
+ }
+
+ [Test]
+ public void TestSimpleBinaryStorage(){
+ Binary b = new Binary();
+ byte[] data = new byte[2];
+ data[0] = (byte)1;
+ data[1] = (byte)2;
+ b.Subtype = Binary.TypeCode.General;
+
+ BsonBinary binaryIn = new BsonBinary (new Binary (data));
+ MemoryStream stream = new MemoryStream ();
+ BsonWriter bsonWriter = new BsonWriter (stream);
+ binaryIn.Write (bsonWriter);
+
+ string hex = BitConverter.ToString (stream.ToArray());
+ hex = hex.Replace ("-", "");
+ Assert.AreEqual("0600000002020000000102",hex);
+
+ }
+
+ [Test]
+ public void TestSimpleBinaryRead(){
+ string hex = "0600000002020000000102";
+ byte[] data = DecodeHex (hex);
+ MemoryStream stream = new MemoryStream (data);
+
+ BsonReader reader = new BsonReader(stream);
+ BsonBinary binaryOut = new BsonBinary ();
+ int read = binaryOut.Read(reader);
+ Assert.AreEqual(hex.Length/2,read);
+ Assert.AreEqual((byte)2,binaryOut.Subtype);
+ Assert.AreEqual(2,binaryOut.Val.Length);
+ Assert.AreEqual(hex.Length/2, binaryOut.Size);
+
+ }
+
+ [Test]
+ public void TestSimpleUnknownRead(){
+ string hex = "0600000001020000000102";
+ byte[] data = DecodeHex (hex);
+ MemoryStream stream = new MemoryStream (data);
- stream.Position = 0;
- BsonReader reader = new BsonReader(stream);
- BsonBinary binaryOut = new BsonBinary();
- int size = reader.ReadInt32();
- binaryOut.Subtype = reader.ReadByte();
- binaryOut.Val = reader.ReadBytes(size);
- Assert.AreEqual(binaryIn.Val, binaryOut.Val);
- Assert.AreEqual(binaryIn.Subtype, binaryOut.Subtype);
- Assert.AreEqual(data.Length, binaryOut.Size);
- }
+ BsonReader reader = new BsonReader(stream);
+ BsonBinary binaryOut = new BsonBinary ();
+ int read = binaryOut.Read(reader);
+ Assert.AreEqual(hex.Length/2,read);
+ Assert.AreEqual((byte)1,binaryOut.Subtype);
+ Assert.AreEqual(6,binaryOut.Val.Length);
+ Assert.AreEqual(hex.Length/2, binaryOut.Size);
+
+ }
+
+ protected static byte[] DecodeHex (string val)
+ {
+ int numberChars = val.Length;
+
+ byte[] bytes = new byte[numberChars / 2];
+ for (int i = 0; i < numberChars; i += 2) {
+ try {
+ bytes[i / 2] = Convert.ToByte (val.Substring (i, 2), 16);
+ } catch {
+ //failed to convert these 2 chars, they may contain illegal charracters
+ bytes[i / 2] = 0;
+ }
+ }
+ return bytes;
+ }
+
}
}
View
10 MongoDB.Net-Tests/Bson/TestBsonConvert.cs
@@ -75,6 +75,16 @@ public class TestBsonConvert
BsonType t = BsonConvert.From(letters);
Assert.AreEqual(typeof(BsonArray),t.GetType());
+ }
+ [Test]
+ public void TestFromDocumentWithDocumentArray(){
+ var doc = new Document().Append("foo", new[] {
+ new Document().Append("a", 1),
+ new Document().Append("b", 2),
+ new Document().Append("c", 3),
+ });
+ BsonType t = BsonConvert.From(doc);
+ Assert.AreEqual(t.Size,60);
}
}
}
View
26 MongoDB.Net-Tests/MongoDB.Driver.Tests.csproj
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -29,6 +29,7 @@
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
+ <RootNamespace>MongoDB.Driver.Tests</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -47,21 +48,13 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
- <Reference Include="MongoDB.Driver, Version=1.0.3560.34266, Culture=neutral, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\MongoDBDriver\bin\Debug\MongoDB.Driver.dll</HintPath>
- </Reference>
- <Reference Include="nunit.core, Version=2.5.0.9122, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\..\..\..\..\..\API\NUnit\NUnit-2.5.0.9122\bin\net-2.0\lib\nunit.core.dll</HintPath>
- </Reference>
- <Reference Include="nunit.framework, Version=2.5.0.9122, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\..\..\..\..\..\API\NUnit\NUnit-2.5.0.9122\bin\net-2.0\nunit.framework.dll</HintPath>
- </Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
+ <Reference Include="nunit.framework, Version=2.4.3.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\redist\nunit.framework.dll</HintPath>
+ </Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Bson\TestBsonBinary.cs" />
@@ -93,6 +86,7 @@
<Compile Include="TestOidGenerator.cs" />
<Compile Include="TestPairedConnection.cs" />
<Compile Include="Bson\TestBsonCode.cs" />
+ <Compile Include="Bson\TestBsonArray.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDBDriver\MongoDB.Driver.csproj">
@@ -115,10 +109,10 @@
<Visible>False</Visible>
</BootstrapperPackage>
</ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
- <Content Include="test-data\tests.binary.txt">
+ <EmbeddedResource Include="test-data\tests.binary.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
- </Content>
+ </EmbeddedResource>
</ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
View
46 MongoDB.Net-Tests/TestCollection.cs 100644 → 100755
@@ -1,4 +1,4 @@
-using System;
+using System;
using NUnit.Framework;
using MongoDB.Driver.Bson;
@@ -85,27 +85,6 @@ public class TestCollection
}
[Test]
- public void TestManualWhere(){
- Document query = new Document().Append("$where", new Code("this.j % 2 == 0"));
- ICursor c = db["tests"]["reads"].Find(query);
- foreach(Document result in c.Documents){
- Assert.IsNotNull(result);
- Object j = result["j"];
- Assert.IsTrue((double)j % 2 == 0);
- }
- }
-
- [Test]
- public void TestWhere(){
- ICursor c = db["tests"]["reads"].Find("this.j % 2 == 0");
- foreach(Document result in c.Documents){
- Assert.IsNotNull(result);
- Object j = result["j"];
- Assert.IsTrue((double)j % 2 == 0);
- }
- }
-
- [Test]
public void TestFindOneObjectContainingUKPound(){
Document query = new Document();
Document result = db["tests"]["charreads"].FindOne(query);
@@ -178,6 +157,29 @@ public class TestCollection
}
[Test]
+ public void TestInsertOfArray(){
+ OidGenerator ogen = new OidGenerator();
+ IMongoCollection inserts = db["tests"]["inserts"];
+ Document album = new Document();
+ album["_id"] = ogen.Generate();
+ album["artist"] = "Popa Chubby";
+ album["title"] = "Deliveries After Dark";
+ album["songs"] = new[] {
+ new Document().Append("title", "Let The Music Set You Free").Append("length", "5:15").Append("_id", ogen.Generate()),
+ new Document().Append("title", "Sally Likes to Run").Append("length", "4:06").Append("_id", ogen.Generate()),
+ new Document().Append("title", "Deliveries After Dark").Append("length", "4:17").Append("_id", ogen.Generate()),
+ new Document().Append("title", "Theme From The Godfather").Append("length", "3:06").Append("_id", ogen.Generate()),
+ new Document().Append("title", "Grown Man Crying Blues").Append("length", "8:09").Append("_id", ogen.Generate()),
+ };
+ inserts.Insert(album);
+
+ Document result = inserts.FindOne(new Document().Append("songs.title","Deliveries After Dark"));
+ Assert.IsNotNull(result);
+
+ Assert.AreEqual(album.ToString(), result.ToString());
+ }
+
+ [Test]
public void TestDelete(){
IMongoCollection deletes = db["tests"]["deletes"];
Document doc = new Document();
View
4 MongoDB.Net-Tests/TestOid.cs
@@ -1,4 +1,4 @@
-
+
using System;
@@ -58,7 +58,7 @@ public class TestOid
string hex = "4a7067c30a57000000008ecb";
Oid oid = new Oid(hex);
- Assert.AreEqual(hex,"ObjectId(\"" + oid.ToString() + "\")");
+ Assert.AreEqual("ObjectId(\"" + hex + "\")", oid.ToString());
}
[Test]
View
19 MongoDBDriver/Binary.cs
@@ -1,11 +1,18 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Text;
namespace MongoDB.Driver
{
- public class Binary
- {
+ public class Binary{
+ public enum TypeCode:byte{
+ Unknown = 0,
+ General = 2,
+ Uuid = 3,
+ Md5 = 5,
+ UserDefined = 80
+ }
+
private byte[] bytes;
public byte[] Bytes{
get { return this.bytes; }
@@ -13,8 +20,8 @@ public class Binary
}
- private byte subtype;
- public byte Subtype{
+ private Binary.TypeCode subtype;
+ public Binary.TypeCode Subtype{
get { return this.subtype; }
set { this.subtype = value; }
}
@@ -23,7 +30,7 @@ public class Binary
public Binary(byte[] value){
this.Bytes = value;
- this.Subtype = (byte)2;
+ this.Subtype = TypeCode.General;
}
View
169 MongoDBDriver/Bson/BsonArray.cs 100644 → 100755
@@ -1,67 +1,102 @@
-/*
- * User: scorder
- */
-using System;
-
-namespace MongoDB.Driver.Bson
-{
- /// <summary>
- /// Description of BsonArray.
- /// </summary>
- public class BsonArray : BsonDocument{
-
- public BsonArray(){}
-
- public override byte TypeNum {
- get {return (byte)BsonDataType.Array;}
- }
- public override BsonElement this[ String key ] {
- get{
- return (BsonElement)Dictionary[key];
- }
- set{
- int t;
- if(int.TryParse(key,out t) == false)throw new ArgumentOutOfRangeException(String.Format("Key '{0}' isn't numeric", key));
- if(orderedKeys.Contains(key) == false){
- string lastkey = string.Empty;
- if(orderedKeys.Count > 0) lastkey = orderedKeys[orderedKeys.Count -1];
- orderedKeys.Add(key);
- if(lastkey != string.Empty && int.Parse(key) < int.Parse(lastkey)){
- orderedKeys.Sort();
- }
- }
- Dictionary[key] = value;
- }
- }
-
- public void Add(int key, BsonElement value){
- this.Add(key.ToString(),value);
- }
-
- public void Add(int key, BsonType val){
- this.Add(new BsonElement(key.ToString(), val));
- }
-
- public void Add(int key, Object val){
- this.Add(new BsonElement(key.ToString(), BsonConvert.From(val)));
- }
-
- public BsonDocument Append(int key, BsonElement value){
- this.Add(key.ToString(),value);
- return this;
- }
- public BsonElement this[ int key ] {
- get{
- return (BsonElement)Dictionary[key.ToString()];
- }
- set{
- string skey = key.ToString();
- if(orderedKeys.Contains(skey) == false){
- orderedKeys.Add(skey);
- }
- Dictionary[skey] = value;
- }
- }
-
- }
-}
+using System;
+
+namespace MongoDB.Driver.Bson
+{
+ /// <summary>
+ /// Class to translate between Mongo and .net arrays.
+ /// </summary>
+ public class BsonArray : BsonDocument{
+
+ public BsonArray(){}
+
+ public override byte TypeNum {
+ get {return (byte)BsonDataType.Array;}
+ }
+ public override BsonElement this[ String key ] {
+ get{
+ return (BsonElement)Dictionary[key];
+ }
+ set{
+ int t;
+ if(int.TryParse(key,out t) == false)throw new ArgumentOutOfRangeException(String.Format("Key '{0}' isn't numeric", key));
+ if(orderedKeys.Contains(key) == false){
+ string lastkey = string.Empty;
+ if(orderedKeys.Count > 0) lastkey = orderedKeys[orderedKeys.Count -1];
+ orderedKeys.Add(key);
+ if(lastkey != string.Empty && int.Parse(key) < int.Parse(lastkey)){
+ orderedKeys.Sort();
+ }
+ }
+ Dictionary[key] = value;
+ }
+ }
+
+ public void Add(int key, BsonElement value){
+ this.Add(key.ToString(),value);
+ }
+
+ public void Add(int key, BsonType val){
+ this.Add(new BsonElement(key.ToString(), val));
+ }
+
+ public void Add(int key, Object val){
+ this.Add(new BsonElement(key.ToString(), BsonConvert.From(val)));
+ }
+
+ public BsonDocument Append(int key, BsonElement value){
+ this.Add(key.ToString(),value);
+ return this;
+ }
+ public BsonElement this[ int key ] {
+ get{
+ return (BsonElement)Dictionary[key.ToString()];
+ }
+ set{
+ string skey = key.ToString();
+ if(orderedKeys.Contains(skey) == false){
+ orderedKeys.Add(skey);
+ }
+ Dictionary[skey] = value;
+ }
+ }
+ public override object ToNative(){
+ if(this.ElementsSameType() == true){
+ return this.ToArray();
+ }else{
+ return base.ToNative();
+ }
+ }
+
+ public bool ElementsSameType(){
+ if(this.Keys.Count < 1) return false;
+ byte comp = 0;
+ foreach(String key in this.Keys){
+ BsonElement be = this[key];
+ byte test = be.Val.TypeNum;
+ if(comp == 0){
+ comp = test;
+ }else{
+ if(comp != test) return false;
+ }
+ }
+ return true;
+ }
+
+ public object ToArray(){
+ Type arrayType = null;
+ Array ret = null;
+ int idx = 0;
+ foreach(String key in this.Keys){
+ if(ret == null){
+ int length = this.Keys.Count;
+ arrayType = this[key].Val.ToNative().GetType();
+ ret = Array.CreateInstance(arrayType,length);
+ }
+ BsonElement be = this[key];
+ ret.SetValue(be.Val.ToNative(), idx);
+ idx++;
+ }
+ return ret;
+ }
+ }
+}
View
21 MongoDBDriver/Bson/BsonBinary.cs 100644 → 100755
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Text;
namespace MongoDB.Driver.Bson
@@ -20,7 +20,7 @@ public class BsonBinary:BsonType
public BsonBinary(Binary binary){
this.val = binary.Bytes;
- this.subtype = binary.Subtype;
+ this.subtype = (byte)binary.Subtype;
}
private byte subtype;
@@ -33,7 +33,7 @@ public class BsonBinary:BsonType
get {
int size = 4; //size int
size += 1; //subtype
- if(this.Subtype == 2){
+ if(this.Subtype == (byte)Binary.TypeCode.General){
size += 4; //embedded size int
}
size += this.Val.Length;
@@ -51,7 +51,7 @@ public class BsonBinary:BsonType
int bytesRead = 4;
this.Subtype = reader.ReadByte();
bytesRead += sizeof(byte);
- if(this.Subtype == 2){
+ if(this.Subtype == (byte)Binary.TypeCode.General){
size = reader.ReadInt32();
bytesRead += 4;
}
@@ -61,11 +61,14 @@ public class BsonBinary:BsonType
}
public void Write(BsonWriter writer){
- writer.Write(this.Size);
- writer.Write(this.Subtype);
- if(this.Subtype ==2){
- writer.Write(this.Val.Length);
- }
+ if(this.Subtype == (byte)Binary.TypeCode.General){
+ writer.Write(this.val.Length + sizeof(Int32));
+ writer.Write(this.Subtype);
+ writer.Write(this.Val.Length);
+ }else{
+ writer.Write(this.val.Length);
+ writer.Write(this.Subtype);
+ }
writer.Write(this.Val);
}
View
2 MongoDBDriver/Bson/BsonConvert.cs
@@ -50,7 +50,7 @@ public static class BsonConvert
}else if(t == typeof(MongoDBNull)){
ret = From((MongoDBNull)val);
}else if(t == typeof(Binary)){
- ret = From((BsonBinary)val);
+ ret = From((Binary)val);
}else if(val is IEnumerable){
ret = From((IEnumerable)val);
}else{
View
2 MongoDBDriver/Bson/BsonDocument.cs
@@ -124,7 +124,7 @@ public class BsonDocument : System.Collections.DictionaryBase, BsonType
return bytesRead;
}
- public object ToNative(){
+ public virtual object ToNative(){
//FIXME Duplication. Decide if this is best or to just convert to a document and then call the IsDBRef(doc) on the native type.
if(this.isDBRef()) return ToDBRef();
return ToDocument();
View
1 MongoDBDriver/Collection.cs
@@ -1,4 +1,3 @@
-<<<<<<< HEAD:MongoDBDriver/Collection.cs
using System;
using System.Collections.Generic;
using System.IO;
View
178 MongoDBDriver/PairedConnection.cs
@@ -1,87 +1,91 @@
-using System;
-using System.Net.Sockets;
-
-namespace MongoDB.Driver
-{
- /// <summary>
- /// Connection object that connects to a replica pair.
- /// </summary>
- public class PairedConnection : Connection
- {
- private String slaveHost;
- public string SlaveHost {
- get { return slaveHost; }
- }
-
- private int slavePort;
- public int SlavePort {
- get { return slavePort; }
- }
-
- private bool slaveOk;
- public bool SlaveOk {
- get { return slaveOk; }
- set { slaveOk = value; }
- }
-
- private Document masterInfo;
- public bool Paired {
- get { return this.masterInfo != null && (string)this.masterInfo["msg"] != "not paired"; }
- }
-
- public bool ConnectedToMaster {
- get { return this.masterInfo != null && (int)this.masterInfo["ismaster"] == 1; }
- }
-
- public PairedConnection(String leftHost, String rightHost):this(leftHost, DEFAULTPORT, rightHost, DEFAULTPORT){}
-
- public PairedConnection(String leftHost, int leftPort, String rightHost, int rightPort):this(leftHost,leftPort,rightHost,rightPort,false){}
-
- public PairedConnection(String leftHost, int leftPort, String rightHost, int rightPort, bool slaveOk):base(leftHost,leftPort){
- slaveHost = rightHost;
- slavePort = rightPort;
- this.SlaveOk = slaveOk;
- }
-
- public override void Open(){
- try{
- TryOpen();
- }catch(SocketException){
- //Couldn't connect. Try to connect to the slave instance.
- SwapHosts();
- this.Close();
- this.TryOpen();
- }
- }
-
- private void TryOpen(){
- base.Open();
- this.masterInfo = QueryMaster();
- if(Paired && !ConnectedToMaster && !SlaveOk){
- if(this.masterInfo.Contains("remote") == false){
- //FIXME Is this the right exception?
- throw new MongoCommException("No master found",this);
- }
- SwapHosts();
- this.Close();
- this.TryOpen();
- }
- }
-
- public Document QueryMaster(){
- Database admin = new Database(this,"admin");
- Document master = admin["$cmd"].FindOne(new Document().Append("ismaster", 1.0));
- return master;
- }
-
- private void SwapHosts(){
- int tport = this.Port;
- string tHost = this.Host;
- port = this.SlavePort;
- host = this.slaveHost;
- slavePort = tport;
- slaveHost = tHost;
- }
-
- }
-}
+using System;
+using System.Net.Sockets;
+
+namespace MongoDB.Driver
+{
+ /// <summary>
+ /// Connection object that connects to a replica pair.
+ /// </summary>
+ public class PairedConnection : Connection
+ {
+ private String slaveHost;
+ public string SlaveHost {
+ get { return slaveHost; }
+ }
+
+ private int slavePort;
+ public int SlavePort {
+ get { return slavePort; }
+ }
+
+ private bool slaveOk;
+ public bool SlaveOk {
+ get { return slaveOk; }
+ set { slaveOk = value; }
+ }
+
+ private Document masterInfo;
+ public bool Paired {
+ get { return this.masterInfo != null && (string)this.masterInfo["msg"] != "not paired"; }
+ }
+
+ public bool ConnectedToMaster {
+ get { return this.masterInfo != null && (int)this.masterInfo["ismaster"] == 1; }
+ }
+
+ public PairedConnection(String leftHost, String rightHost):this(leftHost, DEFAULTPORT, rightHost, DEFAULTPORT){}
+
+ public PairedConnection(String leftHost, int leftPort, String rightHost, int rightPort):this(leftHost,leftPort,rightHost,rightPort,false){}
+
+ public PairedConnection(String leftHost, int leftPort, String rightHost, int rightPort, bool slaveOk):base(leftHost,leftPort){
+ slaveHost = rightHost;
+ slavePort = rightPort;
+ this.SlaveOk = slaveOk;
+ }
+
+ public override void Open(){
+ try{
+ TryOpen();
+ }catch(Exception ex){
+ if (ex is SocketException || ex is System.IO.IOException){
+ //Couldn't connect. Try to connect to the slave instance.
+ SwapHosts();
+ this.Close();
+ this.TryOpen();
+ }else{
+ throw;
+ }
+ }
+ }
+
+ private void TryOpen(){
+ base.Open();
+ this.masterInfo = QueryMaster();
+ if(Paired && !ConnectedToMaster && !SlaveOk){
+ if(this.masterInfo.Contains("remote") == false){
+ //FIXME Is this the right exception?
+ throw new MongoCommException("No master found",this);
+ }
+ SwapHosts();
+ this.Close();
+ this.TryOpen();
+ }
+ }
+
+ public Document QueryMaster(){
+ Database admin = new Database(this,"admin");
+ Document master = admin["$cmd"].FindOne(new Document().Append("ismaster", 1.0));
+ return master;
+ }
+
+ private void SwapHosts(){
+ int tport = this.Port;
+ string tHost = this.Host;
+ port = this.SlavePort;
+ host = this.slaveHost;
+ slavePort = tport;
+ slaveHost = tHost;
+ }
+
+ }
+}

0 comments on commit 337cda3

Please sign in to comment.
Something went wrong with that request. Please try again.