This developer's chronicles

Web development using Scrum, C#, AngularJS and the like

Author: Harold Rodriguez (page 2 of 5)

Understanding delegates and when to use them in C# ASP.NET

This blog post is aimed at beginner developers or someone who have just not fully grasped delegates or don’t really understand what problem do they solve and a good example of when they can be used.

What is actually a delegate?

A delegate is a method signature (pretty much a reference to a method) hence it will have to match the signature of the method it wants to reference, an example below:

Let’s say we have a method called MergeCustomerDetails which takes a couple of strings and returns a string, pretty simple:

Now, if we want to use a delegate to call that method we need to create a delegate whose signature matches the signature of the method (that means that the return type and the parameter types must be the same):

If you see the delegate definition above, it matches the MergeCustomerDetails’ method signature (both return a string, and both take 2 arguments of type string). parameter names don’t have to match though (I’ve used different parameter names to highlight that)

The next step is to initialize the delegate and ‘point’ it to the require method:

So instead of calling MergeCustomerDetails we can call our delegate!

When can I use delegates?

We can use delegates whenever we need to pass methods as parameters to another functions so that they can be executed at runtime from there (although a bit complex to grasp an example may be the best way to understand it).

I found the following example in Stack Overflow where there is an excellent use for delegates, which will be explained below. Let’s see the problem and how delegates helped solve it.

We have three functions with the exact same signature (IsChild, IsAdult and IsSenior), if we wanted to execute any of those methods from inside another method we would have to do it manually as there is no way to pass a method as parameter to another method (without using delegate, that is). That would mean writing almost the same code again and again every time we want to call one of the methods.

Fortunately with the use of delegates we can ‘point’ them to those methods and then pass them as parameters.

Let’s start by defining a Person class and the three methods (note that they all have the same method signature):

Now  let’s define a delegate to see how it matches the methods’ signature:

And the method that will take a delegate as parameter:

Finally let’s add the code to the Main function which will call the ‘DisplayPeople’ method passing all the different methods (IsChild, IsAdult and IsSenior)

 

Thanks, any feedback is appreciated !

Bundling and Minification in ASP.NET MVC

Bundling and Minification are two tools available since  ASP.NET 4 that will make your application load faster as they reduce the number of files to be downloaded (bundling) as well as removing all white spaces / comments and shortening the variable names (when possible) so that file sizes get smaller.

This is specially important as when a page is loaded most browsers will limit the amount of resources that are retrieved down to 6 (so it retrieves maximum 6 files simultaneously) so by reducing the number of files to be downloaded we can guarantee a faster load time (and we all love that, don’t we?)

Let’s see what a page load looks like in chrome when no bundling or minification occurs:

bundling and minification ASP.NET MVC

As expected chrome will only download a maximum of 6 resources at the time  and anything else is put into a queue and it will be downloaded once one of the 6 files is completed. in the above example we can see how some .js files had to wait for previous files to be finished downloading.

And to make it worse, as the number of files grow in your application this will cost your visitors valuable time waiting for all files to be downloaded (even worse they may not even come back!).

How can I speed up my website load?

One of the first steps to optimize your website is to set up bundling and minification, fortunately this is really easy in .NET.

Before we continue there are a couple of files that will have to be modified, as follow:

  • Web.config: this is the file where most of the configuration is done for a web site/application
  • Bundle.config: Found in the App_Start folder (web applications)

The first thing you’ll need to do is enable bundle and minification, this can be done by setting the value of the compilation element to true in your web.config file

Alternatively you can specify the Bundle.EnableOptimizations property to true inside the Bundle.Config file (which takes precedence over web.config file):

Once bundling and minification has been set up we now need to tell the ASP.NET framework which files we want bundled and minified, very similar to the above code but now adding the to-be bundled/minified files:

The above will bundle the specified 12 files into one and will minimize it was well (awesome !)

Lastly we’ll need to add a reference to it on the page (master page / layout) where we want those scripts to be rendered:

Now let’s run the application and open up the developer tools (F12) to check out the new bundles:

bundling and minification enabled ASP.NET MVC

Neat !, now we have it bundled, one a closer inspection (clicking on the bundled file) we can see what a minified file looks like:

ASP.NET minified javascript file

It is important to note that you would only want to do this on your production site, as you don’t want to debug your code on a minified file, ewww

 

Understanding AngularJS $q service and promises

Update 16/07/2015: Fixed promise object not being returned thanks to Zhuinden’s comment and added plunker.

Before diving into AngularJS $q service it is essential to understand what a promise is but most importantly why we need it.

What is a promise?

A promise in the Javascript and AngularJS world is an assurance that we will get a result from an action at some point in the future, let’s see the two possible results of a promise:

  • A promise is said to be fulfilled when we get a result from that action (meaning that we get a response, regardless of whether the response is good or bad)
  • A promise is said to be rejected when we don’t get a response(for instance if we were retrieving some data from an API and for some reason we never got a response because the API endpoint was down etc.)

Why do we need promises?

We need promises because we need to make decisions based on the possible results of our call (or the possibility that we don’t get a response from that call at all), probably an example will better help describe this:

Our program contacts an external API to get the list of clients
while the response is received the program works on something else
Once the response is received (if received) the program displays the client info on the screen
If the response was not received (the API was down) then we display a message to the end user.
Here is a really good example of what promises are and it’s explained as cartoon

Using Angular’s $q service to deal with promises

Angular JS provides a service called $q which allows you to work with asynchronous functions and user their return values when the execution has been completed, and what its really cool about it is that it will let you write your custom promises as well (so you can resolve or reject a promise when appropriate).

Let’s have a look at a simple example

 

Now let’s have a look at how this would be implemented inside an AngularJS service:

 

Finally, the AngularJS controller will use the service and either display the results on the page (if the promise was fulfilled and the data received)  or will display a message indicating that there was an error when attempting to retrieve the data from github

A plunker with a copy of the code can be found here

Using Test Driven Development TDD to solve FizzBuzz

The first time I saw the FizzBuzz problem was when watching a Pluralsight video authored by Jesse Liberty quite a while ago and today as part of my TDD training at the FireBootCamp I get to solve it by using my new tool (TDD)

Defining the problem

Before we start, and for the ones who are not familiar with the FizzBuzz problem, the idea is to display integers from 1 to 100, but for multiples of three we’ll display the word ‘Fizz’ instead of the integer, for multiples of five we’ll output ‘Buzz’ instead of the integer and for multiples of 3 and 5 we’ll display FizzBuzz, an example of the output below:

1
2
Fizz
4
Buzz
Fizz
7

94
Buzz
Fizz
97
98
Fizz
Buzz

Defining the tool

TDD is basically a methodology or a software development process that is based on the repetition of the following tasks:

  • Write a simple test that defines an expected functionality/outcome
  • Make the test fail (it will fail as we haven’t written any code just yet!)
  • Write your code as simple as possible to make your test pass
  • Refactor your code and run the same test again (it should pass as even though is refactored the functionality should be the same.

Let’s get started ! (aka iteration 1)

We’ll start by writing the most simple unit test of all, a unit test that will output the first two integers of the list

 

An important thing to notice here: to compare Lists we must use CollectionAssert.AreEqual (instead of Assert.AreEqual)

And the method (which will make the test fail) is below:

 

Now let’s write the simplest possible code to make the test pass:

 

Iteration 2

Well, that was easy !, but not quite there yet, let’s now get the first three integers of the list, but as the third item is multiple of 3 we’ll have to output Fizz instead of the number 3

That means we have to take into account the following:

  • Instead of expecting a list of integers we’ll now expect a list of strings (something like “1”, “2”, “Fizz” so we can happily have them living in the same list)
  • We need to pass a number to our GetFizzBuzz method which will act as the ceiling

Remember always write the unit test first !

 

Now our code is not even compiling (as GetFizzBuzz doesn’t take any parameters yet), let’s fix that in both our first unit test (which will now test for a list of strings) and our GetFizzBuzz method which will take an argument as the ceiling:

 

 

Wow !, our two unit tests pass and we’re getting the first three items correctly, next step is to get the first 5 items (yes you got it: “1”, “2”, “Fizz”, “4”, “Buzz”)

Iteration 3

 

After running our test it fails, this is the message from our unit test framework:

TestFizzBuzz unit test fails

The expected list was “1”, “2”, “Fizz”, “4” and “Buzz” but we received “1”, “2”, “Fizz”, “4”, “5”, (hence the element at index 4 didn’t match). We know what do !, lets write the simplest code we can to make the test pass!

 

Good stuff, our three tests pass but our code is getting harder and harder to read (this is where the last step in each iteration comes on board: refactoring), refactoring means rearranging our code so its easily readable by us (humans); so how can we make this easier to read? I’m thinking of extracting some of the code to another function, let’s try that:

 

Isn’t this easier to read? Yes !, and running our unit tests confirm that we haven’t broken anything as all of them still pass !

Iteration 4

Ok, things are looking better now, the next challenge is to get the FizzBuzz output whenever a multiple of 3 and 5 is found (that is 15, 30, 45, 60, 75 and 90), let’s write the unit test first

 

As expected, our test fails, we get “Fizz” in the 15th position (14th if we talk about the 0-index lists) instead of “FizzBuzz”, let’s fix that.

 

Yes, it doesn’t look like the nicest code but remember we can always make it better in the refactoring part of the iteration.

After running all unit tests we can see that they all pass !

all unit tests pass

 

We can always run additional unit tests but I’m confident that these unit tests are enough to prove how TDD works and hopefully you’ll have a better idea on how this process can make your code more robust and modular at the same time.

Thanks for reading (a very long blog post) !

What makes a good unit test?

If you come across this post it may be because you’ve only started reading about unit tests and are thinking of implementing them (way to go!), or perhaps want a clearer definition of what it is and what it actually makes a good unit test, whatever your reason is I will hopefully be able to shed some light on it.

What is actually a unit test?

In plain English, a unit test can be defined as a short piece of code that we write in order to test another method/function by specifying a known input and obtaining an expected output.

Well, that may not have been the best definition but maybe an example would help.

Show me the code!

Let’s say we have a method that is meant to provide us with some sort of calculation (i.e. the total price after a 10% discount has been applied).

How do we know this code works as expected? (I know this is a really simple example but let’s image there are some complicated calculations involved). To test it we could for example have a web page that at the click of a button calls this function and displays the results, or have a console application that can call that function and display the results on the console (wow that sounds like a lot of effort, I think I’ll pass)

How about running a unit test? writing a unit test should not take long and we can get instant feedback, let’s give that a go

After running this unit test we can see that it fails !, but why? because in my CalculateTotalPrice method I’m returning the total discounted value, not the total price after the discount has been applied (yes silly mistake)

 

unit_test_fails

unit test fails

 

See what I mean by instant feedback? had I not run this unit test I would probably have received a call later on from my boss, and certainly not a happy one.

After fixing my method I re-run the unit test and I get a nice green mark, hooray!

unit test passes

unit test passes

 

So… What makes a good unit test?

You’ve probably guessed a couples of answers to this question by this point, let’s enumerate them:

  • Unit tests should be easy to write
  • Unit tests should be automated: (even though we didn’t cover automated unit tests in this blog they can run automatically as part of your build)
  • Unit tests should be repeatable: kind of what we just said above, it just means that we can run it over and over again with each build
  • Unit tests should add value to the product/project: Don’t just write unit tests for the sake of it, test the business logic of your application and not a function that adds up two numbers (that makes my example a bad unit test but you get the idea)
  • Unit tests should be independent to all others: if a unit test depends on another, then is not a unit test
  • Unit tests should test a unit of work (that is a single isolated method/function) and not more than that (otherwise it may be an integration test)
  • Unit tests should be clearly named following a pre-define naming convention (here is an example of unit test naming conventions)

 

P.S. we didn’t talk about TDD (Test Driven Development) as this would extend the original scope to this blog post but I will publish a blog post about that soon.

In the meantime, do you have any other ideas of what makes a good unit test?

Older posts Newer posts