Thursday, October 4, 2012

It's easy to get back a collection from MongoDB filtered by a match on a property.

The middle method below does the deed:

using System.Collections.Generic;
using System.Configuration;
using MongoDB.Driver;
using MongoLogin.Core;
using MongoLogin.Core.Interfaces.DataIntegration;
using MongoDB.Driver.Builders;
namespace MongoLogin.Infrastructure.DataIntegration
{
   public class UserAccountRepository : IUserAccountRepository
   {      
      public int GetCountOfExistingUserAccounts()
      {
         var server =
               MongoServer.Create(ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[0]]);
         var database =
               server.GetDatabase(ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[1]]);
         var allRecords = database.GetCollection<UserAccountDataTransferObject>
               (ConfigurationManager.AppSettings[CommonMagicStrings.
               WebConfigAppSettings()[2]]);
         var query = Query.Matches(CommonMagicStrings.Status(),
               CommonMagicStrings.StatusRegularExpression());
         var legitimateResults = allRecords.Find(query);
         return (int)legitimateResults.Count();
      }
      
      public List<UserAccount> GetUserAccountsForEmailAddress(string email)
      {
         var server =
               MongoServer.Create(ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[0]]);
         var database =
               server.GetDatabase(ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[1]]);
         var allRecords = database.GetCollection<UserAccountDataTransferObject>
               (ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[2]]);
         var query = Query.Matches(CommonMagicStrings.Email(), email);
         var legitimateResults = allRecords.Find(query);
         List<UserAccount> userAccounts = new List<UserAccount>(){};
         foreach (UserAccountDataTransferObject userAccount in legitimateResults)
         {
            userAccounts.Add(new UserAccount(userAccount.Email,userAccount
                  .Password,userAccount.Status));
         }
         return userAccounts;
      }
      
      public void SaveNewUserAccount(UserAccount userAccount)
      {
         var server =
               MongoServer.Create(ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[0]]);
         var database =
               server.GetDatabase(ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[1]]);
         var allRecords = database.GetCollection<UserAccountDataTransferObject>
               (ConfigurationManager.AppSettings[
               CommonMagicStrings.WebConfigAppSettings()[2]]);
         var dto = new UserAccountDataTransferObject
                                 {
                                    Email = userAccount.Email,
                                    Password = userAccount.Password,
                                    Status = userAccount.Status.ToString()
                                 };
         allRecords.Insert(dto);
         allRecords.Save(dto);
      }
   }
}

 
 

This is an expansion on this code I've been writing. My interface now looks as such:

using System.Collections.Generic;
namespace MongoLogin.Core.Interfaces.DataIntegration
{
   public interface IUserAccountRepository
   {
      int GetCountOfExistingUserAccounts();
      void SaveNewUserAccount(UserAccount userAccount);
      List<UserAccount> GetUserAccountsForEmailAddress(string email);
   }
}

 
 

My repository wrapper:

using System.Collections.Generic;
using MongoLogin.Core.Interfaces.DataIntegration;
namespace MongoLogin.Core.InfrastructureWrappers.DataIntegration
{
   public class UserAccountRepositoryWrapper
   {
      public IUserAccountRepository Repository { get; set; }
      
      public UserAccountRepositoryWrapper(IUserAccountRepository repository)
      {
         Repository = repository;
      }
      
      public string
            AttemptToSaveNewUserAccountReturningEitherSerializationOrError(
            UserAccount userAccount)
      {
         int numberOfUsers = Repository.GetCountOfExistingUserAccounts();
         if (numberOfUsers == 0) userAccount.Status = UserStatus.Administrative;
         List<UserAccount> preexistingComparableAccounts =
               Repository.GetUserAccountsForEmailAddress(userAccount.Email);
         if (preexistingComparableAccounts.Count > 0)
         {
            return CommonMagicStrings.UserAccountAlreadyExists();
         } else {
            Repository.SaveNewUserAccount(userAccount);
            return userAccount.FlattenUserAccount();
         }
      }
   }
}

 
 

The wrapper's test:

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoLogin.Core.InfrastructureWrappers.DataIntegration;
using MongoLogin.Core.Tests.InterfaceTestingHelpers.DataIntegration;
namespace MongoLogin.Core.Tests.InfrastructureWrapperTests.DataIntegration
{
   [TestClass]
   public class UserAccountRepositoryWrapperTests
   {
      [TestMethod]
      public void SaveNewUserAccountUpdatesUserStatusWhenAppropriateTest()
      {
         UserAccount userAccount = new UserAccount("tomjaeschke@tomjaeschke.com",
               "foo");
         StubbedUserAccountRepository stub = new StubbedUserAccountRepository();
         stub.ValueToReturnForGetCountOfExistingUserAccounts = 0;
         stub.UserAccountsToReturnFromAnAttemptedEmailMatch = new
               List<UserAccount>() { };
         UserAccountRepositoryWrapper repository = new
               UserAccountRepositoryWrapper(stub);
         string serialization = repository
               .AttemptToSaveNewUserAccountReturningEitherSerializationOrError(
               userAccount);
         Assert.AreEqual(stub.UserAccountHandedIntoSaveNewUserAccount.Status,
               UserStatus.Administrative);
         Assert.AreEqual(serialization,
               "tomjaeschke@tomjaeschke.com|foo|Administrative");
         
         userAccount = new UserAccount("fevercheese@gmail.com", "bar");
         stub = new StubbedUserAccountRepository();
         stub.ValueToReturnForGetCountOfExistingUserAccounts = 1;
         stub.UserAccountsToReturnFromAnAttemptedEmailMatch = new
               List<UserAccount>() { };
         repository = new UserAccountRepositoryWrapper(stub);
         serialization = repository
               .AttemptToSaveNewUserAccountReturningEitherSerializationOrError(
               userAccount);
         Assert.AreEqual(stub.UserAccountHandedIntoSaveNewUserAccount.Status,
               UserStatus.Awaiting);
         Assert.AreEqual(serialization, "fevercheese@gmail.com|bar|Awaiting");
         
         userAccount = new UserAccount("fevercheese@gmail.com", "bar");
         stub = new StubbedUserAccountRepository();
         stub.ValueToReturnForGetCountOfExistingUserAccounts = 1;
         stub.UserAccountsToReturnFromAnAttemptedEmailMatch = new
               List<UserAccount>() { new UserAccount(
               "fevercheese@gmail.com", "bar") };
         repository = new UserAccountRepositoryWrapper(stub);
         string error = repository.
               AttemptToSaveNewUserAccountReturningEitherSerializationOrError(
               userAccount);
         Assert.AreEqual(error, CommonMagicStrings.UserAccountAlreadyExists());
      }
   }
}

 
 

The wrapper test's stub for the repository interface:

using System.Collections.Generic;
using MongoLogin.Core.Interfaces.DataIntegration;
namespace MongoLogin.Core.Tests.InterfaceTestingHelpers.DataIntegration
{
   public class StubbedUserAccountRepository : IUserAccountRepository
   {
      public int ValueToReturnForGetCountOfExistingUserAccounts { get; set; }
      public List<UserAccount> UserAccountsToReturnFromAnAttemptedEmailMatch {
            get; set; }
      public UserAccount UserAccountHandedIntoSaveNewUserAccount { get; set; }
      
      public int GetCountOfExistingUserAccounts()
      {
         return ValueToReturnForGetCountOfExistingUserAccounts;
      }
      
      public List<UserAccount> GetUserAccountsForEmailAddress(string email)
      {
         return UserAccountsToReturnFromAnAttemptedEmailMatch;
      }
      
      public void SaveNewUserAccount(UserAccount userAccount)
      {
         UserAccountHandedIntoSaveNewUserAccount = userAccount;
      }
   }
}

 
 

And finally, magic strings:

namespace MongoLogin.Core
{
   public static class CommonMagicStrings
   {
      public static string AtSymbol()
      {
         return "@";
      }
      
      public static string Email()
      {
         return "Email";
      }
      
      public static string EmailRegularExpression()
      {
         return @"^\w+([-+.']\w+)*@\w+([-+.']\w+)*\.\w+([-+.']\w+)*$";
      }
      
      public static string EmailRegularExpressionFailure()
      {
         return "The email address was not valid.";
      }
      
      public static string Metadata()
      {
         return "Metadata";
      }
      
      public static string Password()
      {
         return "Password";
      }
      
      public static string PasswordConfirmationFailure()
      {
         return "The two passwords provided did not match.";
      }
      
      public static string PasswordRegularExpression()
      {
         return @"^[a-zA-Z0-9]{6,20}$";
      }
      
      public static string PasswordRegularExpressionFailure()
      {
         return "Passwords should be six to twenty characters and contain only capital
               letters, lowercase letters, and digits.";
      }
      
      public static string PipeSymbol()
      {
         return "|";
      }
      
      public static string Status()
      {
         return "Status";
      }
      
      public static string StatusRegularExpression()
      {
         return "/^([A].*)$/";
      }
      
      public static string UserAccountAlreadyExists()
      {
         return "An account with the email address specified already exists.";
      }
      
      public static string[] WebConfigAppSettings()
      {
         return new string[]
               {
                  "MongoLoginConnection",
                  "MongoLoginDatabase",
                  "MongoLoginCollection"
               };
      }
   }
}

No comments:

Post a Comment