Friday 25 October 2013

Inline SelectList for MVC DropDownList

Below are examples of how to write predefined SelectList items of a DropDownList inline in ASP.NET MVC view.
@Html.DropDownListFor(model => model.IsExist,
         new SelectList(new List<Tuple<bool, string>>
         {
           new Tuple<bool, string>(false, "No"),                    
           new Tuple<bool, string>(true, "Yes"),                    
         }, "Item1", "Item2"))
@Html.DropDownListFor(model => model.IsExist,
         new SelectList(new []
         {
           new {ID=false, Name="No"},
           new {ID=true, Name="Yes"},
         }, "ID", "Name"))

Friday 18 October 2013

Arranging Extension Methods

I like to arrange my extension methods in categories based on the functionalities and also to design them to be easily tested (mocked) as described on this post.

That way the methods are grouped nicely and also displayed neatly when showed by intellisense. Below is an example of how I do that:
public interface ICategoryOne
{
 string MethodOne();
 int MethodTwo();
 int MethodThree(string value);
}

internal class RealCategoryOne : ICategoryOne
{
 private StringBuilder sb;

 public RealCategoryOne(StringBuilder sb)
 {
  this.sb = sb;
 }

 public string MethodOne()
 {
  return "method one";
 }

 public int MethodTwo()
 {
  return sb.GetHashCode();
 }

 public int MethodThree(string value)
 {
  return value.Count();
 }
}

public static class MyExtensionMethods
{
 public static Func<StringBuilder, ICategoryOne> CategoryOneFactory = sb => new RealCategoryOne(sb);

 public static ICategoryOne CategoryOne(this StringBuilder sb)
 {
  return CategoryOneFactory(sb);
 }
}  

With intellisense, the methods will be shown like:



Then to test these extension methods with Moq:
Mock<ICategoryOne> categoryOne = new Mock<ICategoryOne>();
categoryOne.Setup(c => c.MethodOne()).Returns("Moq method 1");
categoryOne.Setup(c => c.MethodTwo()).Returns(-555);
categoryOne.Setup(c => c.MethodThree(It.IsAny<string>())).Returns(-999);

StringBuilder sb = new StringBuilder();

MyExtensionMethods.CategoryOneFactory = prm => categoryOne.Object;

var test = sb.CategoryOne().MethodOne();
Assert.AreEqual(test, "Moq method 1");

Alternatively we can create a fake/dummy class for testing:
public class FakeCategoryOne : ICategoryOne
{
 private StringBuilder sb;

 public FakeCategoryOne(StringBuilder sb)
 {
  this.sb = sb;
 }

 public string MethodOne()
 {
  throw new NotImplementedException();
 }

 public int MethodTwo()
 {
  throw new NotImplementedException();
 }

 public int MethodThree(string value)
 {
  throw new NotImplementedException();
 }
}
Then we change the factory above as:
MyExtensionMethods.CategoryOneFactory = prm => new FakeCategoryOne(prm);


Reference:
http://blogs.clariusconsulting.net/kzu/how-to-mock-extension-methods/