The other day I was working on a site which required a pager, so I searched around a bit and I a pagerby Gunnar Peipman that looked promising. I found a few others but decided against them. Some of them loaded all of the data into memory and then paged from there, and others just flat out didn't work! In any case I had a good experience with Gunnar's. I wanted to take what Gunnar had and create a view helper using my custom view helpers. Along the way I found myself writing some code using the TagBuilderclass that just didn't sit well with me. Take a look at the snippet below which.
TagBuilder startTag = new TagBuilder("a");
startTag.Attributes.Add("href", string.Format("{0}/{1}", this.UrlPrefix, 1));
startTag.SetInnerText("<<");
startTag.Attributes.Add("title", "first page");
httpResponse.Write(startTag.ToString(TagRenderMode.Normal));

TagBuilder previous = new TagBuilder("a");
previous.Attributes.Add("href", string.Format("{0}/{1}", this.UrlPrefix, this.CurrentPage - 1));
previous.SetInnerText("<");
previous.Attributes.Add("title", "previous page");
httpResponse.Write(previous.ToString(TagRenderMode.Normal));
I didn't like the fact that I had to make a bunch of calls to the tag builder to build the HTML for me, it was just uglier than what I wanted. So I decided to create a new tag builder which places an Fluent interface on top of it (ok, maybe its just method chaining). The end result was the FluentTagBuilderclass. I couldn't extend TagBuilderbecause I wanted to change the return types, so instead I created the class to just contain one and to just pass the calls through to it. What I did was to declare all the same properties and methods that the TagBuilder had, but just change the ones who returned void to return the same object itself. So for example I created methods like.
public FluentTagBuilder AddCssClass(string value)
{
    this.TagBuilder.AddCssClass(value);
    return this;
}

public FluentTagBuilder SetInnerHtml(string innerHtml)
{
    this.TagBuilder.InnerHtml = innerHtml;
    return this;
}
With this I can chain different method calls together and create code which looks better. If you've used jQuerythen you are used to this. With this in place I was able to convert the snippet above into the following.
FluentTagBuilder startTag =
    new FluentTagBuilder("a")
    .AddAttribute("href", string.Format("{0}/{1}", this.UrlPrefix, 1))
    .SetInnerText("<<")
    .AddAttribute("title", "first page");

httpResponse.Write(startTag.ToString(TagRenderMode.Normal));

FluentTagBuilder previous =
    new FluentTagBuilder("a")
    .AddAttribute("href", string.Format("{0}/{1}", this.UrlPrefix, this.CurrentPage - 1))
    .SetInnerText("<")
    .AddAttribute("title", "previous page");

httpResponse.Write(previous.ToString(TagRenderMode.Normal));
To me this is a lot easier to read, and to create. If you agree you can grab the class and include it in your projects. Links to full source files are below.
  1. FluentTagBuilder.cs
  2. Pager.cs
Sayed Ibrahim Hashimi

Comment Section

Comments are closed.


Today a friend of mine asked me to explain (via email) a few things to another developer regarding some things I have done with the Entity Framework (EF). I figured since I already typed it up I might as well share it here as well. So here it is.

I have had 2 issues with using EF4 which I have found creative and effective work around for.

Externalizing filters

The first issue, which also exists when using other frameworks, is that you end up with an explosion of methods (and usually a lot of duplicated code). For instance let’s say you have a table to store users. This table has an ID, and Email field and, and let’s and OpenIdUrl. So you end up with the following methods.

User GetUserById(long id)

User GetUserByEmail(string email)

User GetUserByOpenIdUrl(string openIdUrl)

Usually you’ll find that each of these methods have the exact same implementation except a different where clause. Now there is a bigger problem in the fact that you cannot anticipate everything that the user may want to filter on. Because of this and the dynamic nature of IQueryable I have employed a technique using Expression Trees to allow the user to declare the exact filter to be used via a lambda expression. So for the users it’s very slick. For example I could create the following method

public User GetUser(Expression> filter)
{
    if (filter == null)
    {
        filter = Const.LinqExpression.LinqExpressionFuncAlwaysTrue;
    }

    User foundUser = null;
    using (InlineTasksContext dbContext = new InlineTasksContext())
    {
        dbContext.Connection.Open();
        foundUser = dbContext.Users.Where(filter).SingleIfExists();
    }

    return foundUser;
}

In this case I’m allowing the user to pass in a filter that is applied to the query. Here is how I could implement those three if I chose to as well.

public User GetUserById(long id)
{
    return this.GetUser(user => user.Id == id);
}
public User GetUserByEmail(string email)
{
    if (email == null) { throw new System.ArgumentNullException("email"); }

    return GetUser(user => user.Email == email);
}
public User GetUserByOpenIdUrl(string openIdUrl)
{
    if (string.IsNullOrEmpty(openIdUrl)) { throw new ArgumentNullException("openIdUrl"); }

    return GetUser(user => user.OpenIdUrl == openIdUrl);
}

Note in the first method I am using some other helpers I created. Specifically the Const.LinqExpression.LinqExpressionFuncAlwaysTrue as well as the SingleIfExists

extension method. I use the AlwaysTrue expression so that way I don’t have to be worried about doing an if and having to maintain 2 select statements. And the other (SingleIfExists) is used to just return null instead of blowing up if no elements exist in the sequence.

Since they are not the purpose of this email I’ve just put them at the bottom so that you can read if you are interested.

As Keith mentioned to me a while back Expression trees are not serializable so you still end up with this problem if you are using a service based solution. But you could try and use the sample Expression Tree Serialization to take care of this for you, I’ve never tried it, but it’s on my TODO list.

.Include

My next issue is that you are forced to declare what navigation properties (i.e. table links) should be included in the query. This is done using the .Include method. So back to our GetUser example, how can a framework know what tables values should be extracted for? The end result is that the framework creator just includes a bunch of tables and 90% of the time the result is just wasted resources because the other data is never touched. Better is to provide a default which only includes the most commonly used tables and another method that allows them to specify what they want. Here is a sample for a GetTasksByUserId method

public IList GetTasksByUserId(long userId, IEnumerable includeList)
{
    using (InlineTasksContext dbContext = new InlineTasksContext())
    {
        var result = (from t in dbContext.Tasks
                        .Include(includeList)
                        .Where(t=>t.User.Id == 1)
                        select t)
                        .ToList();
        return result;
    }
}
 In this example I’m using an extension method for.Include which is defined as follows.
public static ObjectQuery Include(this ObjectQuery query, IEnumerable includes)
{
    if (query == null) { throw new System.ArgumentNullException("query"); }

    if (includes != null)
    {
        foreach (string include in includes)
        {
            query.Include(include);
        }
    }
    return query;
}

So the idea is to create a framework which is both robust and easy to use, but at the same time is not overly assumptive about what the users want. I think a lot more can be done with EF and its dynamic nature.

Does that cover what you were intending Keith? Any questions/comments please send them my way.

Here are those methods I mentioned above.

public static class LinqExtensions
{
    public static T SingleIfExists(this IQueryable query)
    {
        if (query == null) { throw new System.ArgumentNullException("query"); }

        T result = default(T);
        if (query.Count() > 0)
        {
            result = query.Single();
        }

        return result;
    }
}
//----------------------------------------------------------------------------------------------------
public class Const
{
    public static class Predicate
    {
        public static Predicate AlwaysTrue
        {
            get
            {
                return x => true;
            }
        }

        public static Predicate AlwaysFalse
        {
            get
            {
                return x => false;
            }
        }
    }

    public class LinqExpression
    {
        public static Expression> LinqExpressionFuncAlwaysTrue
        {
            get
            {
                return x => true;
            }
        }
    }
}
Sayed Ibrahim Hashimi

Comment Section

Comments are closed.


The story around routing in ASP.NET MVC is pretty good. When a resource is requested the action that it is routed to is determined and the parameters to the action are initialized. Counter to that when you build a link you specify the argument values and it creates the url for you. So if your routes happen to change your application shouldn’t be bothered by that. One area which can be problematic for this is if you are making any ajax requests. What I’ve done to minimize the impact of route changes to Ajax requests is to have the script make a call to determine the correct route. In the most trivial case this is extremely easy. You call an action, which has a known route, passing into it the name of the action and controller. It returns to you the url for the route. This works really good, but the problem is when your routes have parameters, how do you handle those?

First let’s take a look at the Javascript and then the definition of the action method which it calls.

// wire up the event for the enter button
$("#searchText").keypress(function (event) {
    if (event.keyCode == 13) {
        // grab the text that is inside the box
        var text = $("#searchText").val();

        var routData = {
            controllerName: 'Search',
            actionName: 'Search',
            paramValues: "{ criteria: '" + text + "' }"
        };

        $.ajax({
            url: "/Home/MapRoute",
            data: routData,
            success: function (data) {
                window.location.href = data;
            },
            error: function (data) {
                alert('there was a failure on the internets');
            }
        });

    }
});

Here I am building a Javascript object named routeData. This is declared in JSON. One thing to pay attention to is the fact that the value for paramValues is a string containing JSON. This is passed to the controller action.

I’m using jQuery to make an Ajax request to /Home/MapRoute. This maps to the method shown below.

public JsonResult MapRoute(string actionName, string controllerName, string paramValues)
{
    JavaScriptSerializer jss = new JavaScriptSerializer();

    Dictionary parameters = jss.Deserialize>(paramValues);

    RouteValueDictionary rd = new RouteValueDictionary();
    foreach (string key in parameters.Keys)
    {
        rd.Add(key, parameters[key]);
    }

    UrlHelper urlHelper = new UrlHelper(this.Request.RequestContext);
    string url = urlHelper.Action(actionName, controllerName, rd);

    return Json(url, JsonRequestBehavior.AllowGet);
}

Here I’m using the JavaScriptSerializer to convert the JSON string into a dictionary, with string as key and value. I use that dictionary to create a RouteValueDictionary which is passed, along with other parameters, into the UrlHelper to generate the url. When you return the Json result you must specify JsonRequestBehavior.AllowGet, otherwise a 500 internal service error will be returned. I think this is new with ASP.NET 2.

When the action method returns, you can use that url. The drawback to this approach is that you will make an extra request to determine the url, but you will be sure that those urls are correct. Also you could cache the results with Output Caching since the routes won’t change.

Sayed Ibrahim Hashimi


Comment Section

Comments are closed.


Have you seen those text boxes on the web that have a hint contained inside of it and wondered how you could implement that? It's pretty easy with jQuery, and there already exist some plugins that you can use, for example here is one. When I set out to do this I didn’t even look to see what was out there because I wanted to write a jQuery plugin, but the solution that I can up with is not that different from that one.

Here is how I wanted the plugin to behave

  1. Add a specified hint to the text box, if the input element was not focused and empty
  2. When the text box was focused, the hint should disappear
  3. When a form is submitted all hints should be removed prior to ensure that they are not incorrectly submitted

First what I did was to create the a file named jquery.sedotech.inputWithHint.js. You should name your plugins using this naming convention

jquery.customString.pluginName.js

Here is the source for the plugin

(function ($) {
    var hintClassName = 'inputWithTextHint';

    $.fn.addHint = function (hint) {
        var filteredSet = this.filter('input:text, textarea');
        filteredSet.each(function () {
            // In here 'this' refers to an individual element
            doAddHint($(this), hint);
        });

        // Find all forms and update the pre post to remove the hint
        $('form input:submit').click(function () {
            $('input:text, textarea').each(function () {
                if ($(this).hasClass(hintClassName) && $(this).attr('hint')
                && $(this).val() == $(this).attr('hint')) {
                    $(this).val('');
                }
            });
        });
    }

    function doAddHint(target, hint) {
        // Only add hint if the target is empty
        if (target.val() == '') {
            addHintToInput(target, hint);

            target.focus(function () {
                // If the target has the hint class on it then a hint must be showing
                //  when hint is showing put cursor at the begining
                if ($(this).hasClass(hintClassName)) {
                    // remove the hint
                    $(this).val('');
                    // remove class
                    $(this).removeClass(hintClassName);
                }
            });

            target.blur(function () {
                // If no text then add hint class back
                if ($(this).val() == '') {
                    addHintToInput(target, hint);
                }
            });
        }
    }

    function addHintToInput(target, hint) {
        target.val(hint);
        target.addClass(hintClassName);
        // add attribute to the target to store hint
        target.attr('hint', hint);
    }
})(jQuery);
Some things to take note of. When you are creating a plugin in you should use the pattern
(function ($) {
    // plugin code here
})(jQuery);

Take note of the ($) as the parameter and (jQuery) at the end. What is happening here is that you are defining an anonymous function declaring a parameter named $ and then invoking that function passing in the jQuery object. You do this because when you are authoring plugins the $ variable is not available, you have to use the other alias jQuery, but that’s just way too difficult. If you use the pattern you are ensured that the $ alias is available and it won’t conflict with other Javascript libraries.

Beyond this all I’m doing is filtering the list of items which are passed in, with the expression var filteredSet = this.filter('input:text, textarea'), to make sure that the plugins doesn’t touch elements which it is not familiar with modifying. After I add the hint, by calling doAddHint on each element in the filtered set, I make sure that the forms on the page are not submitted with those hints.

Resource Links

Sayed Ibrahim Hashimi


Comment Section

Comments are closed.


I'm working on an application right now which uses some mock classes which were "hand written" instead of using a mock framework. I haven't had much experience with using mock frameworks, but I've wanted to learn more about them. There are many mock frameworks out there, I chose to use moq because the test cases for ASP.NET MVC use moq. What I wanted to do was replace the mock class that I created with a moq class. If you have ever created mock classes before then you probably know that they are pretty annoying to maintain. What I mean is that if you add a method/property to the interface which the mock class implements then you have to update the mock just to get it to build. This is annoying and kinda makes people not to use the mock which then ends up in ignoring/commenting out test cases. To avoid all of this most mock frameworks, including moq, just require you to specify behavior for methods/properties which you are ready to exercise in your test cases. Now I’d like to show you the mock class that I had. This interface that it is mocking is used to abstract the data store.

internal class MockModelContext :IModelContext
{
    public User CreateUser(User user)
    {
        // if id is not set, set it and just return it
        if (user.Id <= 0)
        {
            user.Id = 1;
        }

        return user;
    }

    public User GetUserByEmail(string email)
    {
        if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException("email"); }

        User user = CreateDummyUser();
        user.Email = email;

        return user;
    }

    public User GetUser(Expression> filter)
    {
        return CreateDummyUser();
    }

    public IList GetRecentTasks()
    {
        IList tasks = new List()
        {
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description ="Description 01 here",
                Headline="Headline 01 here",
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = "Name here",
                NumViews = 3,
                Script = @"script",
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email ="one@hotmail.com",
                    FirstName="First",
                    Id=2,
                    LastName="Last",
                    MiddleName="Middle",
                }
            },
            new Task()
            {
                CreatedDate = new DateTime(2010,1,1,1,1,1),
                CreatorId = 1,
                //Description ="Description 02 here",
                Headline="Headline 02 here",
                Id = 1,
                LastEditedDate= new DateTime(2010,1,1,1,1,1),
                LastEditOwnerId=1,
                Name = "Name here",
                NumViews = 3,
                Script = @"script2",
                // TODO: Tags
                // TODO: TaskComments
                User = new User()
                {
                    Email ="one@hotmail.com",
                    FirstName="First",
                    Id=2,
                    LastName="Last",
                    MiddleName="Middle",
                }
            }
        };

        return tasks;
    }
    protected internal User CreateDummyUser()
    {
        User user = new User()
        {
            Email = "email",
            FirstName = "First",
            LastName = "Last",
            MiddleName = "Middle"
        };

        return user;
    }
    public User GetUserByOpenIdUrl(string openIdUrl)
    {
        throw new NotImplementedException();
    }
    public IList GetRecentTasks(IEnumerable includeList)
    {
        throw new NotImplementedException();
    }
    public Task AddTask(Task task)
    {
        throw new NotImplementedException();
    }
    public User GetUserById(long id)
    {
        User user = this.CreateDummyUser();
        user.Id = id;

        return user;
    }
    public User SaveUser(User user)
    {
        throw new NotImplementedException();
    }
    public Task GetTaskById(long id)
    {
        throw new NotImplementedException();
    }
}

Take notice of the methods which just throw a NotImplementedException, these are methods that I just added to the interface and haven’t yet written test cases for. (Yeah I know I’m not following true TDD, but I never claimed to be either). Now you can compare that to these methods which use moq to create the mock.

private Mock CreateMockModelContext()
{
    var context = new Mock();

    context.Setup(c => c.CreateUser(It.IsAny()))
        .Returns(user =>
        {
            if (user.Id <= 0)
            {
                user.Id = 1;
            }
            return user;
        });

    context.Setup(c => c.GetUserByEmail(It.IsAny()))
        .Returns(email =>
            {
                if (email == null) { throw new ArgumentNullException("email"); }

                User user = this.CreateDummyUser();
                user.Email = email;

                return user;
            }); ;

    context.Setup(c => c.GetUserById(It.IsAny()))
        .Returns(id => 
        {
            User user = new User();
            user.Id = id;
            return user;
        });

    context.Setup(c => c.GetRecentTasks())
        .Returns(() =>
        {
            IList tasks = new List()
            {
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description ="Description 01 here",
                    Headline="Headline 01 here",
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = "Name here",
                    NumViews = 3,
                    Script = @"script",
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email ="one@hotmail.com",
                        FirstName="First",
                        Id=2,
                        LastName="Last",
                        MiddleName="Middle",
                    }
                },
                new Task()
                {
                    CreatedDate = new DateTime(2010,1,1,1,1,1),
                    CreatorId = 1,
                    //Description ="Description 02 here",
                    Headline="Headline 02 here",
                    Id = 1,
                    LastEditedDate= new DateTime(2010,1,1,1,1,1),
                    LastEditOwnerId=1,
                    Name = "Name here",
                    NumViews = 3,
                    Script = @"script2",
                    // TODO: Tags
                    // TODO: TaskComments
                    User = new User()
                    {
                        Email ="one@hotmail.com",
                        FirstName="First",
                        Id=2,
                        LastName="Last",
                        MiddleName="Middle",
                    }
                }

            };
            return tasks;
        });

    return context;
}
protected internal User CreateDummyUser()
{
    User user = new User()
    {
        Email = "email",
        FirstName = "First",
        LastName = "Last",
        MiddleName = "Middle"
    };

    return user;
}

Since I’m just mocking methods all I’m really doing here is using the moq Setup method (formerly known as Expect), and the Returns method to implement the behavior that I needed. The key to note here is that if you need to access the parameter(s) passed into the method, then you will have to used Returns and pass in a lambda expression that contains the behavior. In that lamdba you can name the parameter anything you want, but I would suggest you name it the same name that the method you are mocking names it. This makes it much more understandable what you are actually doing.

Sayed Ibrahim Hashimi


Comment Section

Comments are closed.


<< Older Posts | Newer Posts >>