Last active
December 15, 2015 12:19
-
-
Save stephengodbold/5259436 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SearchHub | |
{ | |
private readonly IEnumerable<IRepository> repositories; | |
public SearchHub(IEnumerable<IRepository> repositories) | |
{ | |
this.repositories = repositories; | |
} | |
public IEnumerable<WorkItem> Search(string criteria, ErrorLog errorLog) | |
{ | |
int identifier; | |
var tasks = int.TryParse(criteria, out identifier) ? Fetch(criteria) : Query(criteria); | |
var taskArray = tasks.ToArray(); | |
try | |
{ | |
Task.WaitAll(taskArray); | |
} | |
catch (AggregateException ex) | |
{ | |
foreach (var exception in ex.InnerExceptions) | |
{ | |
errorLog.Log(new Error(exception)); | |
} | |
} | |
var results = taskArray.Aggregate(new List<WorkItem>(), | |
(list, completedTask) => | |
{ | |
if (completedTask.Status == TaskStatus.RanToCompletion) | |
{ | |
list.AddRange(completedTask.Result.Where(result => result != null)); | |
} | |
return list; | |
}); | |
return results; | |
} | |
private IEnumerable<Task<WorkItem[]>> Query(string criteria) | |
{ | |
return repositories.Select(provider => Task.Factory.StartNew(() => provider.Search(criteria).ToArray())); | |
} | |
private IEnumerable<Task<WorkItem[]>> Fetch(string identifier) | |
{ | |
return repositories.Select(provider => Task.Factory.StartNew(() => | |
{ | |
var result = provider.Fetch(identifier); | |
return new[] { result }; | |
})); | |
} | |
} | |
[TestClass] | |
public class Test | |
{ | |
[TestMethod] | |
public void Errors_Are_Logged() | |
{ | |
const string searchText = "Search Text"; | |
var repository = new StubRepository | |
{ | |
SearchCallback = s => | |
{ | |
throw new ArgumentOutOfRangeException("s", "Testing exceptions"); | |
} | |
}; | |
var secondRepository = new StubRepository | |
{ | |
SearchCallback = s => | |
{ | |
throw new ArgumentOutOfRangeException("s", "Testing exceptions"); | |
} | |
}; | |
var searchHub = new SearchHub(new[] { repository, secondRepository }); | |
var errorLog = new MemoryErrorLog(2); | |
searchHub.Search(searchText, errorLog); | |
var errorList = new ArrayList(); | |
errorLog.GetErrors(0, 10, errorList); | |
Assert.AreEqual(2, errorList.Count); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment