Make a list of POCOs into a list of the Guids for the POCOs painlessly like so:
var bar = foo.Select(p => p.Id);
Make a list of POCOs into a list of the Guids for the POCOs painlessly like so:
var bar = foo.Select(p => p.Id);
Today's the last at AMD for Mark Reynolds. Mark, it was very good working with you. Gina Bendel takes over from him in running testing.
This is belated, but while I'm thinking about it: Welcome to our team and AMD to Rafael Torres, Emma Arce, and Bhavani Akole!
var foo = bars.Where(b => b.bazes.Any(bz => quxIds.Contains(bz.Id)));
var ids = foo.Concat(bar).Concat(baz).Concat(qux).Distinct().ToList();
When an attribute colors an action like so, what is it doing?
[MyActionAttribute("this","that")]
public ActionResult Index()
{
Let's take a look. We can hand in variables, mess with them, and then hand them back to the action by way of the ViewBag! Using OnActionExecuting and OnAuthorization to do the same thing here is likely overkill. You'd probably just pick one or the other. This touches on these some.
namespace MyApp.Web.UI.ActionFilters
{
public class MyActionAttribute : ActionFilterAttribute, IAuthorizationFilter
{
private List<string> _stuff;
public MyActionAttribute(params string[] stringBits)
{
this._stuff = new List<string>();
for (int i = 0; i < stringBits.Length; i++)
{
_stuff.Add(stringBits[i].ToUpper());
}
_stuff.Add("I'm always here.");
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Authorize(filterContext);
}
public void OnAuthorization(AuthorizationContext filterContext)
{
Authorize(filterContext);
}
public void Authorize(ControllerContext filterContext)
{
if (filterContext.HttpContext.Session == null)
{
throw new NullReferenceException("You're session is null.");
}
filterContext.Controller.ViewBag.Whatever = _stuff;
}
}
}
...if this would work with NHibernate!?
IQueryable<Foo> bar = queryOne.AsQueryable().Concat(queryTwo.AsQueryable()));
var foo = GetAll().Where(f => bar.Contains(f.Id));
...is going to crash if bar has no items. It's not enough for the collection to be not null. A collection with zero records causes an error.
While I am thinking about it, Kar-khan wrote the following extension for LinqSpecs:
using LinqSpecs;
namespace AMD.Avalanche.Core.Utils
{
public class SpecificationBuilder<T>
{
private Specification<T> _spec;
public SpecificationBuilder() { }
public void AddAnd(Specification<T> specification)
{
if (_spec == null)
_spec = specification;
else
_spec = new AndSpecification<T>(_spec, specification);
}
public void AddOr(Specification<T> specification)
{
if (_spec == null)
_spec = specification;
else
_spec = new OrSpecification<T>(_spec, specification);
}
public Specification<T> ToSpecification()
{
return _spec;
}
}
}
Use it like so...
var specBuilder = new SpecificationBuilderlt;Foogt;();
specBuilder.AddAnd(MySpecs.NameCriteria(whatever));
LinqSpecs is proving tough to use. There is probably a good reason too. Jorge has noticed that it is in alpha and Craig has noticed that it hasn't been updated in over a year. Boo. We struggled to find a way to append a spec to an existing IQueryable and the class below does allow for that, however, when the query concerns get complicated enough NHibernate fails. Perhaps it is crafting HQL it cannot execute???
public class FooLinqSpecHelper : Specification<Foo>
{
private readonly Foo Foo;
public IQueryable<Foo> ConcatenateQuery(IQueryable<Foo> existingQuery,
Specification<Foo> specification)
{
IQueryable<Foo> concatenatedQuery =
existingQuery.Where(specification.IsSatisfiedBy());
return concatenatedQuery;
}
public IQueryable<Guid> ConcatenateQueryThenReturnOnlyIds(IQueryable<Foo>
existingQuery, Specification<Foo> specification)
{
IQueryable<Guid> concatenatedQuery =
existingQuery.Where(specification.IsSatisfiedBy()).Select(p => p.Id);
return concatenatedQuery;
}
public override Expression<Func<Foo, bool>> IsSatisfiedBy()
{
return c => c == Foo;
}
}
No sooner did I write a blog posting on how to Sort a Dictionary than I found this suggesting that you cannot Sort a Dictionary. I disagree however. The means mentioned earlier works. One may move "half" of a dictionary out to a list to inspect the order within it.
foreach (KeyValuePair<Guid,string> pair in foo)
{
myList.Add(pair.Value);
}
Here is the same thing in the shape of a Lambda utilizing .AddRange:
myList.AddRange(foo.Select(pair => pair.Value));
Verify the sorting with testing by pulling the "half" of the Dictionary you want out to a list and looking at the order of the list:
Assert.AreEqual(3, foo.Count);
Assert.AreEqual("a", myList[0]);
Assert.AreEqual("b", myList[1]);
Assert.AreEqual("c", myList[2]);
This shows how to sort a Dictionary like so:
var sortedDict = (from entry in myDict orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
Put this at the top of the document.
<style>
span a {color:#7BC243;}
span a:hover {color:#7BC243;}
.stylegreen a {color:#7BC243;}
.stylegreen a:hover {color:#7BC243;}
</style>
Links look like this:
<span><a class="stylegreen" style="color:#7BC243; a {color:#7BC243;} a:hover {color:#7BC243;}" href="http://www.example.com/" target="_blank">Touch Me»</a></span>
The a and a:hover stuff above might be unneeded. I haven't troubleshot that yet.
this post should have shown this
foreach (Program program in programs) foreach (ProgramPlan programPlan in program.ProgramPlans) programPlans.Add(programPlan);
refactored to this
programPlans.AddRange(programs.SelectMany(program => program.ProgramPlans));
it's a good thing I practice TDD
I'm still not great at lambdas. I don't find them intuitive. Resharper found that I could refine this...
foreach(Program program in programs) foreach(ProgramPlan programPlan in programPlans) programPlans.Add(programPlan);
...to this...
foreach (ProgramPlan programPlan in programs.SelectMany(program => programPlans)) programPlans.Add(programPlan);
...but I wouldn't have seen it by myself. I'm also frustrated by var and having to reverse engineer what a variable really is. I guess I'm trapped in 2005. :(
Here are some notes to explain what I was attempting here.
[TestClass]
public class MyTest
{
A FooBuilder will return a Qux when its Build method is called.
A FooBuilder will have getsetters for BarRepository and BazService like so:
public IBarRepository BarRepository { get; set; }
public IBazService BazService { get; set; }
The getsetters will host external dependencies
private FooBuilder fooBuilder;
[TestInitialize]
public void Setup()
{
Joel Holder wrote SessionObjectCache which wraps Session and when
used in test merely stores things in a Dictionary allowing Session to be mocked.
SessionObjectCache.Remove(CachedEntries.USER_CONTEXT);
MocksRegistry will have getsetters like so...
public Mock<IBarRepository> BarRepositoryMock { get; set; }
public Mock<IBazService> BazServiceMock { get; set; }
...that will be populated with dummy repositories and services
var registry = new MocksRegistry();
The next two lines mock methods calls that will be encountered when
the Build method on FooBuilder runs. Instead of actually running the
methods when the test runs, the methods will be monkey-patched to
return specifications based on the these two lines of code.
registry.BarRepositoryMock.Setup(repo =>
repo.GetAll()).Returns(new List<Bar>().AsQueryable());
registry.BazServiceMock.Setup(repo =>
repo.DoesMatchAnyBazForBars(It.IsAny<List<Bar>>()));
Let's instantiate our FooBuilder while telling it how to conditional
behave so as not to really need external dependencies.
fooBuilder = new FooBuilder
{
BarRepository = registry.BarRepositoryMock.Object,
BazService = registry.BazServiceMock.Object
};
var testServices = new Dictionary<string, object>();
testServices[AppCtxIds.FOO_BUILDER] = fooBuilder;
Here we are monkey-patching ServiceLocator so that when an IoC
attempt to wire up IBarRepository to an BarRepository occurs the
true ServiceLocator will be sidestepped in favor of our fake one.
ServiceLocator.LookupSource = () => testServices;
}
In our test we will test the Qux of a UserContext. In the name of
making a Qux will must deal with two calls to external dependencies.
We are dealing with the dependencies by way of mocking.
[TestMethod]
public void LetsTest()
{
var qux = BuildQux("Tom");
var userContext = SessionObjectCache.LazyGet<UserContext>
(CachedEntries.USER_CONTEXT,
new Func<UserContext>(() =>
{
return new UserContext { Qux = qux };
}));
Assert.IsTrue(SessionObjectCache.Exists(CachedEntries.USER_CONTEXT));
Assert.AreEqual("Tom", SessionObjectCache.Get<UserContext>
(CachedEntries.USER_CONTEXT).Qux.Name);
}
private Qux BuildQux(string whatever)
{
return fooBuilder.Build(whatever);
}
private class TestController : Controller
{
}
}
further prep steps at Visual Studio
[TestClass]
public class MyTest
{
private FooBuilder fooBuilder;
[TestInitialize]
public void Setup()
{
SessionObjectCache.Remove(CachedEntries.USER_CONTEXT);
var registry = new MocksRegistry();
registry.BarRepositoryMock.Setup(repo =>
repo.GetAll()).Returns(new List<Bar>().AsQueryable());
registry.BazServiceMock.Setup(repo =>
repo.DoesMatchAnyBazForBars(It.IsAny<List<Bar>>()));
fooBuilder = new FooBuilder
{
BarRepository = registry.BarRepositoryMock.Object,
BazService = registry.BazServiceMock.Object
};
var testServices = new Dictionary<string, object>();
testServices[AppCtxIds.FOO_BUILDER] = fooBuilder;
ServiceLocator.LookupSource = () => testServices;
}
[TestMethod]
public void LetsTest()
{
var qux = BuildQux("Tom");
var userContext = SessionObjectCache.LazyGet<UserContext>
(CachedEntries.USER_CONTEXT,
new Func<UserContext>(() =>
{
return new UserContext { Qux = qux };
}));
Assert.IsTrue(SessionObjectCache.Exists(CachedEntries.USER_CONTEXT));
Assert.AreEqual("Tom", SessionObjectCache.Get<UserContext>
(CachedEntries.USER_CONTEXT).Qux.Name);
}
private Qux BuildQux(string whatever)
{
return fooBuilder.Build(whatever);
}
private class TestController : Controller
{
}
}
I'm trying to do something like this in this post in the name of figuring out how to model bind collections. My approach is more ghetto. I have three objects:
using System.Collections.Generic;
namespace MvcApplication.Models
{
public class Foo
{
public string Whatever { get; set; }
public List<Bar> SomeCollection { get; set; }
}
}
namespace MvcApplication.Models
{
public class Bar
{
public int Number { get; set; }
}
}
namespace MvcApplication.Models
{
public class Baz
{
public string Question { get; set; }
}
}
Alright, here is a view that uses a list of Baz as a its model and will bind to a Foo:
@using MvcApplication.Models
@model List<Baz>
@{
ViewBag.Title = "Home Page";
Int32 counter = 0;
}
<h2>@ViewBag.Message</h2>
<form method="post" action="/home/about/">
<input type="test" name="Whatever" />
@foreach(Baz baz in Model)
{
<br/>
<br/>
@baz.Question
<table>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="0" />
</td>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="1" />
</td>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="2" />
</td>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="3" />
</td>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="4" />
</td>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="5" />
</td>
<td>
<input type="radio" name="SomeCollection[@counter].Number" value="6" />
</td>
</tr>
</table>
counter++;
}
<input type="submit" value="submit" />
</form>
Check to see if a key exists in a Dictionary or, in this case, a HashTable:
if(myDictionary.ContainsKey("whatever")) {
We have two ways of mocking with MOQ for the two different approaches to inversion of control. For Dependency Injection:
IQueryable<Foo> foos = TestObjects.BuildFooCollection().AsQueryable();
mockFooRepository = new Mock<IFooRepository>();
mockFooRepository.Setup(repo => repo.GetAll()).Returns(foos);
fakeFooRepo = mockFooRepository.Object;
In the situation above, fakeFooRepo would be handed to a FooRepository getsetter on a controller in lieu allowing dependency inject to put a real FooRepository there. Alternatively... For Service Locator:
registry = new MocksRegistry();
ServiceLocator.LookupSource = () =>
{
return registry;
};
IQueryable<Bar> bars = TestObjects.BuildFooCollection().AsQueryable();
registry.BarRepositoryMock.Setup(repo => repo.GetAll()).Returns(bars);