Sunday, November 22, 2009

A jQuery Dashboard

So I've been working on a dashboard type page utilising the jqueryui controls and thought I'd share how I went about it.

I went through a few iterations getting the css working but it finally panned out the way I wanted it.

There are basically three components, the styles, the javascript, and the actual html.

Here I'm setting out the structure of the table that the dashboard is going to represent.
.table
{
    float: left;
    width: 100%;
}
.table-row
{
    float: left;
    width: 100%;
}
.table-cell
{
    margin: 0;
    float: left;
    width: 24%;
    min-height: 15em;
    padding: 0.3em;
}
.item
{
    width: 10em; 
    display: inline; 
    float: left; 
    cursor: move; 
    margin-right: 0.4em;
}

Here's the script behind the page.
$(document).ready(function() {

    function EqualiseHeight(row) {        //remove the previous height
        $(row).children().removeAttr("style");        //set the new height
        $(row).equalHeights(true);
    }

    function moveTask(task, region) {
        task.fadeOut(function() {
            task.appendTo(region).fadeIn();
            EqualiseHeight($(region).parent());
        });
    }

    function makeDraggable(task) {
        var uniqueid = $(task).parent().attr("uniqueid");

        $(task).draggable({
            cancel: '.action',
            revert: 'invalid',
            containment: 'div[uniqueid =' + uniqueid + ']',
            helper: 'clone',
            cursor: 'move'
        });
    }

    $(".table-row").each(function() {
        //EqualiseHeight(this);
        $(this).equalHeights(true);
        //make children into draggable objects
        $(this).children().children().each(function() {
            makeDraggable(this);
        });
    });

    $("ul").droppable({
        accept: 'li',
        hoverClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            moveTask(ui.draggable, this);
        }
    });
});
So we have a function, EqualiseHeight, that takes an element representing a row (funnily enough) it makes sure that any style attribute for each of the rows direct child elements has been removed. It then utilised the equalHeights function as provided by filament group.
We then have a function, moveTask, that is responsible for that actual moving of an item by fading it out and then appending it to the region it was dropped in.
Next we have, makeDraggable, that takes an item and makes it draggable.

Now that we have some functions predefined, we start setting the page elements that will draggable items and the area that will be droppable.

Next comes the html...
<div class="table">
    <div storyid="1" class="table-row">
        <ul storyid="1" class="table-cell ui-widget ui-widget-content">
            <li class="item ui-widget ui-widget-content ui-corner-all">
                <h6 class="ui-widget-header">Task 1</h6>
                <div class="details">Task one details.</div>
                <a href="#" class="ui-icon action" title="do something">actions</a></li>
            <li class="item ui-widget ui-widget-content ui-corner-all">
                <h6 class="ui-widget-header">Task 2</h6>
                <div class="details">Task two details.</div>
                <a href="#" class="ui-icon action" title="do something">actions</a></li>
            <li class="item ui-widget ui-widget-content ui-corner-all">
                <h6 class="ui-widget-header">Task 4</h6>
                <div class="details">Task one details.</div>
                <a href="#" class="ui-icon action" title="do something">actions</a></li>
            <li class="item ui-widget ui-widget-content ui-corner-all">
                <h6 class="ui-widget-header">Task 5</h6>
                <div class="details">Task two details.</div>
                <a href="#" class="ui-icon action" title="do something">actions</a></li>
            <li class="item ui-widget ui-widget-content ui-corner-all">
                <h6 class="ui-widget-header">Task 6</h6>
                <div class="details">Task one details.</div>
                <a href="#" class="ui-icon action" title="do something">actions</a></li>
        </ul>
        <ul storyid="1" class="table-cell ui-widget ui-widget-content">
            <li class="item ui-widget ui-widget-content ui-corner-all">
                <h6 class="ui-widget-header">Task 3</h6>
                <div class="details">Task three details.</div>
                <a href="#" class="ui-icon action" title="do something">actions</a></li>
        </ul>
        <ul storyid="1" class="table-cell ui-widget ui-widget-content">cell content</ul>
        <ul storyid="1" class="table-cell ui-widget ui-widget-content">cell content</ul>
    </div>
</div>

And there you have it.

References:
1. jQuery
2. jQuery ui

Friday, November 13, 2009

Setting Equal Heights with jQuery

I've been experimenting with jquery and jqueryui and trying to build a dashboard type page.

Everything was going quite well until I wanted to make the cells within a row the same height.

With a little searching I found this, setting equal heights with jquery. Absolutely brilliant!

Thank you filament group

Tuesday, November 10, 2009

Poker - Planning Poker

Had my first game of Planning Poker not long ago. Even though I'd been working with Scrum for the last three years never had I performed planning of this type before. For those who are/ have been in a similar situation to myself you're probably asking, what they heck is this all about?

As the term poker suggests, there is a deck of cards involved, how ever this is no ordinary deck of cards. Each player has the following set of cards... ?, 0, 1/2, 1, 2, 3, 5, 8, 13, 20, 40, 100, infinity.

So how does it work you may be asking?
Firstly we should explain when the game is played. This game is played when the project team is estimating the effort required for each of the user stories in the product backlog. But how do the numbers listed above work? You need to keep in mind that you are not trying to estimate the number of hours a user story is going to take, you are just giving an indication of how much effort you think is going to be required to complete the task in relation to the other tasks. The other major benefit of playing is that it generates discussion amongst the team.

Anyway rather then going on and on, read here: Planning Poker Estimating in Detail

Here's another very good read on Planning Poker - Agile Estimating

Hope this is helpful

Tuesday, October 20, 2009

Cross Table Querying using the Repository Pattern

So I've implemented the Repository Pattern in my application which was easy enough with all the simple CRUD functionality, however when I came to refactoring the following code things were not so simple.
public void LoadMonthCategorySummary()
    {
        List<monthsummary> MonthSummaryList;
        using ( budgetEntities = new BudgetEntities() )
        {
            var initial = from m in budgetEntities.SpendingSet
                          join mc in budgetEntities.MthCategorySet on m.MthCategory.MthCategoryId equals mc.MthCategoryId
                          join c in budgetEntities.CategorySet on mc.Category.CategoryId equals c.CategoryId
                          where m.DateSpent.Month == DateTime.Now.Month && m.DateSpent.Year == DateTime.Now.Year
                          select new
                          {
                              CategoryName = c.CategoryName,
                              BudgetAmount = mc.BudgetAmount,
                              AmountSpent = m.Amount
                          };

            var list = from i in initial
                       group i by i.CategoryName into g
                       orderby g.Key ascending
                       select new
                       {
                           CategoryName = g.Key,
                           AmountSpent = g.Sum( ms => ms.AmountSpent ),
                           MonthSummary = g.FirstOrDefault()
                       };

            MonthSummaryList = ( from ms in list
                                 select new MonthSummary
                                 {
                                     CategoryName = ms.CategoryName,
                                     AmountSpent = ms.AmountSpent,
                                     BudgetAmount = ms.MonthSummary.BudgetAmount
                                 } ).ToList();
     }
     gvMonthSummary.DataSource = MonthSummaryList;
     gvMonthSummary.DataBind();
}

As you can see this is not your simple CRUD functionality with joins across three different tables.

So what approach did I take to resolve this?
Firstly, you need to understand that each data service is dependent on a corresponding repository. For example, the SpendingsDataService is dependent on IRepository<Spending>.

My first approach was to try and expose the datacontext, but it occurred to me that this was actually breaking the repository pattern.

The only other alternative was to introduce a second IRepository<T> object, which meant that I needed to create a second constructor.

The code I ended up with looks something like this...
public IList<MonthSummary> GetMonthCategorySummary( DateTime analysisDate )
{
    IList<MonthSummary> mcSummaryList;

    using ( sRepo )
    {
        using ( mcRepo )
        {
            var initial = from s in sRepo.Query()
                          join mc in mcRepo.Query() on s.MthCategoryId equals mc.MthCategoryId
                          where s.DateSpent.Month == analysisDate.Month && m.DateSpent.Year == analysisDate.Year
                          select new
                          {
                              CategoryName = mc.Category.CategoryName,
                              BudgetAmount = mc.BudgetAmount,
                              AmountSpent = s.Amount
                          };
            var list = from i in initial
                       group i by i.CategoryName into g
                       orderby g.Key ascending
                       select new
                       {
                           CategoryName = g.Key,
                           AmountSpent = g.Sum( ms => ms.AmountSpent ),
                           MonthSummary = g.FirstOrDefault()
                       };

            mcSummaryList = ( from ms in list
                              select new MonthSummary
                              {
                                  CategoryName = ms.CategoryName,
                                  AmountSpent = ms.AmountSpent,
                                  BudgetAmount = ms.MonthSummary.BudgetAmount
                              } ).ToList();
        }
    }

    return mcSummaryList;
}

Thursday, October 15, 2009

Budget App - Part 4 : Test Driven Development with Moq - An New .Net Mocking Framework

I recently found a relatively new Mocking Framework called Moq. Daniel Cazzulino provides a nice introduction and reason for developing the new framework. Considering that this is built on the concept of Linq to Mock and that I enjoy working with Linq I thought I'd give it ago as I continue to develop the data services to my Budget application with a TDD approach.

I'm going to following the principles of TDD as I understand them:
  1. Write the test first - it'll probably not compile.
  2. Get the test to compile.
  3. Get the test to pass - with the least amount of code.
  4. Create another test that will cause your code to fail.
  5. Refactor your class so that both tests pass.
Write the test first
As I've been refactoring my code I've come across the follow functionality...

private bool DoesMonthYearExis( int month, int year )
{
    bool exists = false;

    var months = ( from m in budgetEntities.MthSet
                   where m.Month == month && m.Year == year
                   select m ).ToList();

    if ( months.Count > 0 )
    {
        exists = true;
    }

    return exists;
}

There will obviously be a number of steps involved in turning this into a WCF Service call, but the first step is to ensure that the DataService will do what it's suppose to do. So how do we do this using a TDD approach? Firstly we write our test.



So here we have our first test using the new Moq framework. As you can see the data service interface doesn't have a definition for a method called DoesMonthYearExist(...) hence it won't compile, which leads to...

Getting the test to compile
To get this to compile we need to update the Interface as well as it's implementing class. We need to remember that we write the least amount of code as possible.



This obviously isn't very useful, but it should give you point. The test will now compile however it will fail. If you look at the test above there we have set up a number of expectations with Moq and these aren't being met. Now let's...

Get the test to pass
Don't forget to write as little code as possible.


You can see that the expectations will now be met with repo.Query() returning a value and the repo object being disposed.

This is all good, but we know that the code is not really doing what we need it to do and this is when we...

Create another test that will cause your code to fail
Not a huge difference, but it's enough.


We've changed the year being tested for and are now expecting that the combination of month and year will not be found.

Refactor your class so that both tests pass
Here we make our implementation do what it's supposed to do.



What does this leave us with? A well tested method that has good coverage

Moq
I must say that I do like not having to indicate what expectations have to be recorded and then play them back, you just say this object has certain expectations and that's it.

Despite simple examples Moq looks like a nice mocking framework to work with.

Enjoy!

Wednesday, October 14, 2009

Agile Development - Made Easy

While I've developed in a Scrum environment for the last three years, I was never really exposed to the construction of the product backlog. Now though, I've recently started on a project in it's infancy stages and this is all changing.

The client practises Scrum actively and they go about creating the backlog by writing User Stories. User Stories? I'm thinking. What are they really?

Thankfully Google pointed me in the right direction => http://www.agile-software-development.com/.

Here you will find an awesome array of information on the Principles of Agile development, implementing Scrum, user stories, estimating within an agile environment, agile project management and a number of eBooks and presentations.

Enjoy!

Wednesday, September 2, 2009

Budget App - Part 3 : Unit Testing Data Services with Rhino Mocks

Repository Pattern
The nest step in building my Budget application was ensuring that it could be unit tested. In my googling I came to realise the my design could be improved somewhat. I have now introduced the repository pattern with the interface looking like this...

IRepository.cs
public interface IRepository<T> : IDisposable
{
    IQueryable<T> Query();
    void Add( T entity );
    void Attach( T entity );
    void Remove( T entity );
    void SubmitChanges();
}

and its implementation looking like this...

BudgetRepository.cs
public class BudgetRepository<T> : IDisposable, IRepository where T : class
{
    private BudgetDataContext context;

    public BudgetRepository( BudgetDataContext ctxt )
    {
        context = ctxt;
    }

    public IQueryable<T> Query()
    {
        return context.GetTable<T>();
    }

    public void Add( T entity )
    {
        context.GetTable<T>().InsertOnSubmit( entity );
    }

    public void Attach( T entity )
    {
        context.GetTable<T>().Attach( entity );
    }

    public void Remove( T entity )
    {
        context.GetTable<T>().DeleteOnSubmit( entity );
    }

    public void SubmitChanges()
    {
        context.SubmitChanges();
    }

    public void Dispose()
    {
        context.Dispose();
    }
}

The repository is obviously providing access to an individual table via the generic type used. Now all that is needed is to write some services to utilise the repository. The first service to be written was an IncomeDataService.

IncomeDataService.cs
public class IncomeDataService
{
    private IRepository<Income> incomeRepository;

    public IncomeDataService( IRepository<Income> repository )
    {
        incomeRepository = repository;
    }

    public IList<Income> GetAll()
    {
        IList<Income> incomes;
        using ( incomeRepository )
        {
            incomes = ( from i in incomeRepository.Query()
                        orderby i.Description
                        select i ).ToList();
        }
        return incomes;
    }

    public Income GetById( int ID )
    {
        Income income;
        using ( incomeRepository )
        {
            income = incomeRepository.Query().Where( i => i.IncomeId == ID ).FirstOrDefault();
        }
        return income;
    }

    public void Save( Income entity )
    {
        using ( incomeRepository )
        {
            if ( entity.IncomeId > 0 )
            {
                incomeRepository.Attach( entity );
            }
            else
            {
                incomeRepository.Add( entity );
            }
            incomeRepository.SubmitChanges();
        }
    }
}

Unit Testing with Rhino Mocks
Before continuing with all my services, I really want to be able to Unit Test my services to for a number of reasons. Firstly, if any potential employer views any of these posts then I can demonstrate good practises and secondly unit testing is a sure way to ensure that you code is doing what it should be doing.

I actually had a little bit of difficulty mocking my DataService but I finally got it out. I'd read a number of blogs on mocking the IQueryable object and that was easy but I was getting a number of odd errors once I passed my mocked repository into my service. Eventually I ended up with the following. Not sure what it was that clicked, but something did.

[TestMethod()]
public void GetIncomeByIdTest()
{
    // setup test collection
    IList<Income> incomeList = new List<Income>();
    Income expectedIncome = new Income() { IncomeId = 1 };
    Income unexpectedIncome = new Income() { IncomeId = 2 };
    incomeList.Add( expectedIncome );
    incomeList.Add( unexpectedIncome );

    MockRepository mocks = new MockRepository();
    IRepository repository = mocks.StrictMock<IRepository<Income>>();
    IncomeDataService svc = new IncomeDataService( repository );

    int actualID = 1;

    using ( mocks.Record() )
    {
        repository.Expect( repo => repo.Query() ).Return( incomeList.AsQueryable<Income>() );
        repository.Expect( repo => repo.Dispose() );
    }

    using ( mocks.Playback() )
    {
        Income actualIncome = svc.GetById( actualID );
        Assert.AreEqual( expectedIncome.IncomeId, actualIncome.IncomeId );
    }
}

So what is actually going on here?

This unit test is is aimed at testing the IncomeDataService class. The issue we face is that it requires an instance of a repository, but we obviously don't want to use the database for testing, hence we use Rhino Mocks to create a mock object of a repository.

We use the the statement using ( mocks.Record() ) to indicate what we expect to occur when the service calls the method GetById(...). So what do we expect to occur? That the repository will return the incomeList collection as an IQueryable collection and then call it's Dispose() method. Then the statement using (mocks.Playback() ) ensures that the expectations set out during the recording are used. So if we look at the GetById method...
using ( incomeRepository )
{
    income = incomeRepository.Query().Where( i => i.IncomeId == ID ).FirstOrDefault();
}
when the incomeRepository.Query() is called Rhino Mocks ensures that the List of Income objects setup at the beginning of the test are returned. Likewise when we exit the using statement the Dispose() method is called next.

Hope this helps!
Enjoy

Saturday, August 29, 2009

Budget App - Part 2 : Introducing WCF Into The Picture

Considering that I've been looking at the job market for almost a month now one commonality that all the jobs have had is the requirement for WCF experience. Unfortunately this is something that I haven't had the luck of working with commercially. Even though I've been confident that it would be easy enough to get up to speed, it's difficult to persuade potential employers to see things the same way.

Hence the first thing I wanted to add to my budget application was some WCF services for data access. While my intent is not to go into too much detail on what the ABC's are of WCF services, each of these will, hopefully, be illustrated as I describe how I built and deployed my first WCF services.

Firstly, let's quickly have a look at the changes that were made to the folder structure of the solution.


A number of new projects have been added to the solution, namely: Budget.Business, Budget.DataAccess, and Budget.WCF.

Upon adding a WCF Service Application Visual Studio kindly starts things off for you by including an interface and corresponding class file. It's these files that make up part of the Contract. The interface has the attribute [ServiceContract] and each method definition has the attribute [OperationContract]. Here's what mine looks like.

[ServiceContract]
public interface IIncomeService
{
    ///
    /// Gets all Income objects
    ///
    [OperationContract]
    IList GetAll();
    ///
    /// Gets a single Income object by it's ID
    ///
    [OperationContract]
    Income GetIncomeById( int ID );
    ///
    /// Saves a single Income object, either inserting or updating the records values
    ///
    [OperationContract]
    void Save( Income income );
}

Without these the service will not work. Now you may be wondering what the other part of the contract is? We've now defined what the service can do, now we need to define what can be passed through to the service. This is achieved by adding some new attributes to our data objects. Each class that is to be passed through must have the attribute [DataContract] and each property that is to be access within the class must have the attribute [DataMember]. The data classes to be used were defined in my Linq-to-SQL file which is automatically generated, so any modifications manually made to it would be lost the next time the file refreshed itself. This next bit would have taken me quite a while to figure out were it not for google. You can set the attributes against all the Linq objects by setting the SerializationMode of your DataContext object to Unidirectional.



You will then end up with generated code similar to this:
[Table(Name="dbo.Income")]
[DataContract()]
public partial class Income : INotifyPropertyChanging, INotifyPropertyChanged
{
    ...
    ...
    ...
    [Column(Storage="_IncomeId", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
    [DataMember(Order=1)]
    public int IncomeId
    {

Once the Contract has been defined the next step is to use them. Here is where all the configuration in the web.config is required. Thankfully as you add services to your project the app.config file is automatically updated by the WCF Service Application project. All you need to do is copy the <system.servicemodel> tag into the appropriate location in the your web.config file.

You should now be able to add the WCF service into your main application via a Service Reference, how ever this is not what I wanted to do. I wanted an extra layer to any business logic I may need and possibly to perform my validation there. Just add another class library, add a Service Reference to this. The app.config file of this new project also contains some extra tags that should be copied over to the web.config of you main app.

Providing you use the WCF Test Client and the default Visual Studio WCF Service Host you should now be able develop your services to your hearts content.

Enjoy!

Thursday, August 27, 2009

Budget App - Part 1

One thing I seem to find a hassle is conjuring up some sort of realistic application to apply all the really cool technologies and techniques to.

I figure that something that I'm really bad at is budgeting. Whether this is due to my wife (I hope she doesn't read this) or it's just me no one will ever know. A small budget application was in order and considering that I actually want to use this soon I thought I'd whip a little budget up and then slowly enhance it with some of the technologies I haven't had the luck of working with yet, such as WCF. I'll apply development techniques such as Test Driven Development (TDD) as much as I can and let you know what sort of issues I face.

Here's a snap-shot of the little application.


So what features/technologies have I used include:
ADO.Net Entity FrameworkLinqDevExpress web controls v2009 vol2

Data Access
Having used the Linq-SQL before I thought I'd initially have a play around with the ADO.Net Entity Framework for this app. I must say though (without knowing all the nuances of the Entity Framework) that I prefer Linq-SQL.



using ( budgetEntities = new BudgetEntities() )
{
    spendings = ( from s in budgetEntities.SpendingSet
                  where s.DateSpent.Month == DateTime.Now.Month && s.DateSpent.Year == DateTime.Now.Year
                  orderby s.DateSpent descending, s.Timestamp descending
                  select new SpendingView
                  {
                      SpendingId = s.SpendingId,
                      Description = s.Description,
                      Amount = s.Amount,
                      DateSpent = s.DateSpent,
                      Category = s.MthCategory.Category.CategoryId
                  } ).ToList();
}

Here I am directly accessing the Data Context from the UI. This will be changed in the next post. What pattern will be used I'm not entirely sure, but it will definitely involved WCF.

User Interface
I've decided to try out the Developer Express suit of user controls for this. I've used others in the past but they just didn't cut the cake and considering that DevEx are always winning first place for all the 3rd Party Control categories I figured they'd be the best bet.

The controls that I used were the ASPXGridView, the ASPxTabControl, the ASPxRoundPanel and the ASPxCallbackPanel.



I started out using their v2009 vol1 release, but have since upgraded it to v2009 vol2.

Enjoy!

TFK

Friday, July 31, 2009

A Beginning

Well, I thought it was about time to start a blog. Why?

Being made redundant in these times really makes you think about what you've been doing and what you want to do.

So, what have I been doing? Working in as a Developer/Team Leader, doing a bit of this and a bit of that. While I enjoyed my time there and the job was an improvement from the previous place I was at, it became quite easy to get lost in the management side of leading.
Now, what do I want to do? While I'm told that I lead teams well, I really want to get my technical skills back to where they should be.

So, how am I going to do that? Well I assume most techo's learn best by doing things, I'm going to build a little app and then make it better.

So, what to expect from this blog? In the long run, besides a bit of personal stuff, I don't really know, but in the short term it's going to be my little journey of discovery.

Enjoy!


Matt