Skip to content
Browse files

Add connectionstring builder with tests.

  • Loading branch information...
1 parent c6a8895 commit 70b1e92c61c2ea3c89bb43337e6bf4616fcb1de8 @lanwin lanwin committed Feb 27, 2010
View
5 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,7 +29,7 @@
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
- <RootNamespace>MongoDB.Driver.Tests</RootNamespace>
+ <RootNamespace>MongoDB.Driver</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -63,6 +63,7 @@
<Compile Include="Bson\TestBsonReader.cs" />
<Compile Include="IO\TestQueryMessage.cs" />
<Compile Include="TestCollection.cs" />
+ <Compile Include="TestConnectionStringBuilder.cs" />
<Compile Include="TestCursor.cs" />
<Compile Include="TestDatabase.cs" />
<Compile Include="TestDatabaseMetaData.cs" />
View
84 MongoDB.Net-Tests/TestConnectionStringBuilder.cs
@@ -0,0 +1,84 @@
+using System.Collections.Generic;
+using NUnit.Framework;
+
+namespace MongoDB.Driver
+{
+ [TestFixture()]
+ public class TestConnectionStringBuilder
+ {
+ [Test]
+ public void TestCreateEmptyInstance()
+ {
+ new MongoConnectionStringBuilder();
+ }
+
+ [Test]
+ public void TestDefaults()
+ {
+ var builder = new MongoConnectionStringBuilder();
+ Assert.IsNull(builder.Username);
+ Assert.IsNull(builder.Password);
+
+ var servers = new List<MongoServerEndPoint>(builder.Servers);
+ Assert.AreEqual(1,servers.Count);
+ Assert.AreEqual(MongoServerEndPoint.DefaultPort, servers[0].Port);
+ Assert.AreEqual(MongoServerEndPoint.DefaultHost, servers[0].Host);
+ }
+
+ [Test]
+ public void TestConnectionStringParsing()
+ {
+ var builder = new MongoConnectionStringBuilder("Username=testuser;Passwort=testpassword;Server=testserver:555");
+ Assert.AreEqual("testuser", builder.Username);
+ Assert.AreEqual("testpassword", builder.Password);
+
+ var servers = new List<MongoServerEndPoint>(builder.Servers);
+ Assert.AreEqual(1,servers.Count);
+ Assert.AreEqual("testserver", servers[0].Host);
+ Assert.AreEqual(555, servers[0].Port);
+ }
+
+ [Test]
+ public void TestConnectionStringParsingServerWithoutPort()
+ {
+ var builder = new MongoConnectionStringBuilder("Username=testuser;Passwort=testpassword;Server=testserver");
+ Assert.AreEqual("testuser", builder.Username);
+ Assert.AreEqual("testpassword", builder.Password);
+
+ var servers = new List<MongoServerEndPoint>(builder.Servers);
+ Assert.AreEqual(1, servers.Count);
+ Assert.AreEqual("testserver", servers[0].Host);
+ Assert.AreEqual(MongoServerEndPoint.DefaultPort, servers[0].Port);
+ }
+
+ [Test]
+ public void TestToStringOutput()
+ {
+ var builder = new MongoConnectionStringBuilder
+ {
+ Password = "testpassword",
+ Username = "testusername"
+ };
+ builder.AddServer("testserver",555);
+
+ Assert.AreEqual("Username=testusername;Passwort=testpassword;Server=testserver:555", builder.ToString());
+ }
+
+ [Test]
+ public void TestToStringOutputWithoutUsernameAndPasswort()
+ {
+ var builder = new MongoConnectionStringBuilder();
+ builder.AddServer("testserver", 555);
+
+ Assert.AreEqual("Server=testserver:555", builder.ToString());
+ }
+
+ [Test]
+ public void TestToStringOutputWithDefaultServerPort()
+ {
+ var builder = new MongoConnectionStringBuilder();
+ builder.AddServer("testserver");
+ Assert.AreEqual("Server=testserver", builder.ToString());
+ }
+ }
+}
View
211 MongoDBDriver/MongoConnectionStringBuilder.cs
@@ -0,0 +1,211 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace MongoDB.Driver
+{
+ [Serializable]
+ public class MongoConnectionStringBuilder
+ {
+ private static readonly Regex PairRegex = new Regex(@"^\s*(.*)\s*=\s*(.*)\s*$");
+ private static readonly Regex ServerRegex = new Regex(@"\s*([^:]+)(?::(\d+))?\s*$");
+
+ private readonly List<MongoServerEndPoint> _servers = new List<MongoServerEndPoint>();
+
+ /// <summary>
+ /// Initializes a new instance of the
+ /// <see cref = "MongoConnectionStringBuilder" />
+ /// class.
+ /// </summary>
+ public MongoConnectionStringBuilder()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the
+ /// <see cref = "MongoConnectionStringBuilder" />
+ /// class.
+ /// </summary>
+ /// <param name = "connectionString">The connection string.</param>
+ public MongoConnectionStringBuilder(string connectionString)
+ {
+ Parse(connectionString);
+ }
+
+ /// <summary>
+ /// Gets the servers.
+ /// </summary>
+ /// <value>The servers.</value>
+ public IEnumerable<MongoServerEndPoint> Servers
+ {
+ get
+ {
+ if(_servers.Count == 0)
+ yield return MongoServerEndPoint.Default;
+
+ foreach(var server in _servers)
+ yield return server;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the password.
+ /// </summary>
+ /// <value>The password.</value>
+ public string Password { get; set; }
+
+ /// <summary>
+ /// Gets or sets the username.
+ /// </summary>
+ /// <value>The username.</value>
+ public string Username { get; set; }
+
+ /// <summary>
+ /// Parses the specified connection string.
+ /// </summary>
+ /// <param name = "connectionString">The connection string.</param>
+ private void Parse(string connectionString)
+ {
+ if(connectionString == null)
+ throw new ArgumentNullException("connectionString");
+
+ var segments = connectionString.Split(';');
+
+ foreach(var segment in segments)
+ {
+ var pairMatch = PairRegex.Match(segment);
+ if(!pairMatch.Success)
+ throw new FormatException(string.Format("Invalid connection string on: {0}", pairMatch.Value));
+
+ var key = pairMatch.Groups[1].Value;
+ var value = pairMatch.Groups[2].Value;
+
+ switch(key)
+ {
+ case "Username":
+ case "User Id":
+ case "User":
+ {
+ Username = value;
+ break;
+ }
+ case "Passwort":
+ {
+ Password = value;
+ break;
+ }
+ case "Server":
+ case "Servers":
+ {
+ var servers = value.Split(',');
+
+ foreach(var server in servers)
+ {
+ var serverMatch = ServerRegex.Match(server);
+ if(!serverMatch.Success)
+ throw new FormatException(string.Format("Invalid server in connection string: {0}", serverMatch.Value));
+
+ var serverHost = serverMatch.Groups[1].Value;
+
+ int port;
+ if(int.TryParse(serverMatch.Groups[2].Value,out port))
+ AddServer(serverHost,port);
+ else
+ AddServer(serverHost);
+ }
+
+ break;
+ }
+ default:
+ throw new FormatException(string.Format("Unknown connection string option: {0}", key));
+ }
+ }
+ }
+
+ /// <summary>
+ /// Adds the server.
+ /// </summary>
+ /// <param name="endPoint">The end point.</param>
+ public void AddServer(MongoServerEndPoint endPoint)
+ {
+ if(_servers.Count == 1)
+ throw new InvalidOperationException("Currently is only server supported.");
+
+ _servers.Add(endPoint);
+ }
+
+ /// <summary>
+ /// Clears the servers.
+ /// </summary>
+ public void ClearServers()
+ {
+ _servers.Clear();
+ }
+
+ /// <summary>
+ /// Adds the server with the given host and default port.
+ /// </summary>
+ /// <param name="host">The host.</param>
+ public void AddServer(string host)
+ {
+ AddServer(new MongoServerEndPoint(host));
+ }
+
+ /// <summary>
+ /// Adds the server with the given host and port.
+ /// </summary>
+ /// <param name="host">The host.</param>
+ /// <param name="port">The port.</param>
+ public void AddServer(string host, int port)
+ {
+ AddServer(new MongoServerEndPoint(host,port));
+ }
+
+ /// <summary>
+ /// Returns a
+ /// <see cref = "System.String" />
+ /// that represents this instance.
+ /// </summary>
+ /// <returns>A
+ /// <see cref = "System.String" />
+ /// that represents this instance.</returns>
+ public override string ToString()
+ {
+ var builder = new StringBuilder();
+
+ if(!string.IsNullOrEmpty(Username))
+ {
+ builder.AppendFormat("Username={0}", Username);
+ builder.Append(';');
+ }
+
+ if(!string.IsNullOrEmpty(Password))
+ {
+ builder.AppendFormat("Passwort={0}", Password);
+ builder.Append(';');
+ }
+
+ if(_servers.Count>0)
+ {
+ builder.Append("Server=");
+
+ foreach(var server in _servers)
+ {
+ builder.Append(server.Host);
+
+ if(server.Port != MongoServerEndPoint.DefaultPort)
+ builder.AppendFormat(":{0}", server.Port);
+
+ builder.Append(';');
+ }
+
+ }
+
+ // remove last ;
+ builder.Remove(builder.Length - 1, 1);
+
+ return builder.ToString();
+ }
+ }
+}
View
2 MongoDBDriver/MongoDB.Driver.csproj
@@ -100,6 +100,7 @@
<Compile Include="Cursor.cs" />
<Compile Include="MongoCommandException.cs" />
<Compile Include="MongoCommException.cs" />
+ <Compile Include="MongoConnectionStringBuilder.cs" />
<Compile Include="MongoDBNull.cs" />
<Compile Include="MongoDuplicateKeyException.cs" />
<Compile Include="MongoDuplicateKeyUpdateException.cs" />
@@ -108,6 +109,7 @@
<Compile Include="MongoMaxKey.cs" />
<Compile Include="MongoMinKey.cs" />
<Compile Include="MongoOperationException.cs" />
+ <Compile Include="MongoServerEndPoint.cs" />
<Compile Include="Oid.cs" />
<Compile Include="IO\DeleteMessage.cs" />
<Compile Include="IO\UpdateMessage.cs" />
View
105 MongoDBDriver/MongoExceptions.cs
@@ -1,105 +0,0 @@
-using System;
-
-namespace MongoDB.Driver
-{
- /// <summary>
- /// Base class for all Mongo Exceptions
- /// </summary>
- public class MongoException : Exception
- {
- public MongoException(string message, Exception inner):base(message,inner){}
- public MongoException(string message):base(message){}
- }
-
- public class MongoCommException : MongoException
- {
- private string host;
- public string Host {
- get { return host; }
- }
-
- private int port;
- public int Port {
- get { return port; }
- }
-
- public MongoCommException(string message, Connection conn):this(message,conn,null){}
- public MongoCommException(string message, Connection conn, Exception inner):base(message,inner){
- this.host = conn.Host;
- this.port = conn.Port;
- }
- }
-
- public class MongoOperationException : MongoException
- {
- private Document error;
- public Document Error {
- get {return error;}
- }
- public MongoOperationException(string message, Document error):this(message, error,null){}
- public MongoOperationException(string message, Document error, Exception e):base(message,e){
- this.error = error;
- }
- }
- /// <summary>
- /// Raised when an action causes a unique constraint violation in an index.
- /// </summary>
- public class MongoDuplicateKeyException : MongoOperationException
- {
- public MongoDuplicateKeyException(string message, Document error):base(message, error,null){}
- public MongoDuplicateKeyException(string message, Document error, Exception e):base(message, error,e){}
- }
-
- /// <summary>
- /// Raised when an update action causes a unique constraint violation in an index.
- /// </summary>
- /// <remarks>
- /// It is only another class because Mongo makes a distinction and it may be helpful.
- /// </remarks>
- public class MongoDuplicateKeyUpdateException : MongoDuplicateKeyException
- {
- public MongoDuplicateKeyUpdateException(string message, Document error)
- :base(message,error){}
- public MongoDuplicateKeyUpdateException(string message, Document error, Exception e):base(message, error,e){}
- }
-
- /// <summary>
- /// Raised when a command returns a failure message.
- /// </summary>
- public class MongoCommandException : MongoException
- {
- private Document error;
- public Document Error {
- get {return error;}
- }
-
- private Document command;
- public Document Command{
- get {return command;}
- }
-
- public MongoCommandException(string message, Document error, Document command):base(message,null){
- this.error = error;
- this.command = command;
- }
- public MongoCommandException(string message, Document error, Document command, Exception e):base(message,e){
- this.error = error;
- this.command = command;
- }
- }
-
- /// <summary>
- /// Raised when a map reduce call fails.
- /// </summary>
- public class MongoMapReduceException : MongoCommandException
- {
- private MapReduce.MapReduceResult mrr;
- public MapReduce.MapReduceResult MapReduceResult{
- get{return mrr;}
- }
-
- public MongoMapReduceException(MongoCommandException mce, MapReduce mr):base(mce.Message,mce.Error, mce.Command){
- mrr = new MapReduce.MapReduceResult(mce.Error);
- }
- }
-}
View
72 MongoDBDriver/MongoServerEndPoint.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Net;
+
+namespace MongoDB.Driver
+{
+ /// <summary>
+ /// Represents a mongodb server with host and port.
+ /// </summary>
+ [Serializable]
+ public class MongoServerEndPoint : EndPoint
+ {
+ public const string DefaultHost = "localhost";
+ public const int DefaultPort = 27017;
+
+ /// <summary>
+ /// The default MongoServerEndPoint.
+ /// </summary>
+ public static readonly MongoServerEndPoint Default = new MongoServerEndPoint();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MongoServerEndPoint"/> class.
+ /// </summary>
+ public MongoServerEndPoint()
+ : this(DefaultHost, DefaultPort)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MongoServerEndPoint"/> class.
+ /// </summary>
+ /// <param name="host">The host.</param>
+ public MongoServerEndPoint(string host)
+ : this(host, DefaultPort)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MongoServerEndPoint"/> class.
+ /// </summary>
+ /// <param name="port">The port.</param>
+ public MongoServerEndPoint(int port)
+ : this(DefaultHost, port)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MongoServerEndPoint"/> class.
+ /// </summary>
+ /// <param name="host">The host.</param>
+ /// <param name="port">The port.</param>
+ public MongoServerEndPoint(string host, int port)
+ {
+ if(host == null)
+ throw new ArgumentNullException("host");
+
+ Host = host;
+ Port = port;
+ }
+
+ /// <summary>
+ /// Gets or sets the host.
+ /// </summary>
+ /// <value>The host.</value>
+ public string Host { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the port.
+ /// </summary>
+ /// <value>The port.</value>
+ public int Port { get; private set; }
+ }
+}

0 comments on commit 70b1e92

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