Permalink
Browse files

Add connectionstring builder with tests.

  • Loading branch information...
lanwin committed Feb 27, 2010
1 parent c6a8895 commit 70b1e92c61c2ea3c89bb43337e6bf4616fcb1de8
@@ -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" />
@@ -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());
+ }
+ }
+}
@@ -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();
+ }
+ }
+}
@@ -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" />
Oops, something went wrong.

0 comments on commit 70b1e92

Please sign in to comment.