Thursday, December 5, 2013

Outgrow the “Unread mail” disease

You!

Yes you!

Be honest and admit it!

Your mail is open!

It is open all the time!

You have to ready every mail as soon as it hits your mailbox!

It’s a bad – it makes you context switch all the time and not be truly focused on your work. Even if you just delete the new mail you have still lost focus on your current work, it will take you few seconds to come back to the same state of mind as before. Now multiply those seconds by the number of your incoming emails every day. Some of those mails will take more than just few seconds, they can make you work for several minutes in order to reply (or just read that not important stuff that your boss writes).

That is a huge waste!!! And why?

“Maybe that is an important mail?”

“Maybe my replay is essential immediately?”

No! If it was really important and your reply was truly essential as soon as possible you would be called to your cellphone or someone would even come and meet you face to face in your office.

The levels of ‘Important’:

1.       End of the world important message and the reply as essential right now– meet that person face to face

2.       End of the world important message and the reply as essential right now (impossible to meet face to face) – call his or her cellphone

3.       Very important message and reply is important as soon as possible– call the office

4.       Very important message but the reply is not essential right now – send a text message

5.       The reply is not essential right away – send an email

You see? Someone will email you if he doesn’t need your reply right away. Now then you know it – CLOSE IT!
Your outlook or whatever email should be open only 4 times a day:

1.       When you come to your office in the morning

2.       Before you hit lunch

3.       After you come back from lunch

4.       Before you go home

During all the other time in your day – keep it closed!
It's ok that you have unread email. You got 4 times a day to sort it and read it. It's more than enough.

Good.

Back to work ;)

Friday, November 1, 2013

The Pyramid of Tests

Recently I’ve been talking a lot about testing, all kind of testing. It surprised me that most of the people don’t know what kind of tests are there (Yes! It’s not just unit tests and integration tests).
The obvious
I hope that you already know that if your code’s build is successful that doesn’t necessary mean that it works. You’ve got to test it!
- How do we do that?
- We unit test!
That is correct. However, just unit testing your code is not enough. In this post I will describe all the six different types of tests.
Unit Test
A unit test tests a “unit of work” without relying on its dependencies.
   1: public class BankAccount

   2: {

   3:     public double Balance { get; set; }

   4:  

   5:     public bool TryWithdrawMoney(double amount)

   6:     {

   7:         if (Balance > amount)

   8:         {

   9:             Balance = - amount;

  10:             return true;

  11:         }

  12:  

  13:         return false;

  14:     }

  15: }

The BankAccount entity is independent so unit testing the “TryWithdrawMoney” is quite simple.


   1: public class BankAccountInformationService

   2: {

   3:     private readonly IAuthorizeUser _userAuthorization;

   4:     private readonly ISession _session;

   5:     private readonly ILogger _log;

   6:  

   7:     public BankAccountInformationService(IAuthorizeUser userAuthorization, ISession session, ILogger log)

   8:     {

   9:         _userAuthorization = userAuthorization;

  10:         _session = session;

  11:         _log = log;

  12:     }

  13:  

  14:     public BankOperationResult WithdrawMoney(int accountNumber, double amount)

  15:     {

  16:         if (_userAuthorization.IsAccountFrozen(accountNumber))

  17:             return new BankOperationResult { Success = false, Message = "Cannot perform operations on a frozen account" };

  18:             

  19:         var userBankAccount = _session.Load<BankAccount>(accountNumber);

  20:  

  21:         _log.Write(string.Format("Attempt to withdraw {0} NIS from account number {1}", amount, accountNumber));

  22:  

  23:         var withdrawSucceeded = userBankAccount.TryWithdrawMoney(amount);

  24:  

  25:         return new BankOperationResult { Success =  withdrawSucceeded};

  26:     }

  27: }

The BankAccountInformationService on the other hand has some dependencies that are part of the unit of work. In order to test the class we will mock them.
- Bug types: business logic bugs.
So far so good. But is it enough?
Can I rely on my NHibernate mappings? Or my logger? Or that “userAuthorization” dependency? All of above aren’t really ordinary classes as the BankAccount – the mappings work against a DB, the logger writes to file system or wherever, the authorization thing works against Active Directory. If I mock their real behavior (mock a real insert to the DB) I won’t really test anything.
Bugs can be found in every single piece of code that I write! The mappings can be incorrect (wrong cascade usage, uniqueness etc), the logger doesn’t actually write wherever it supposed to and the active directory access implementation is simply incorrect. By unit testing these components I won’t be able to find the bugs they potentially have.
Component Tests
NHibernate is a component in my application to test it I will actually insert a mapped entity to the DB, get it back and check that all the properties were mapped correctly. Same thing with any other component I have – let them do their actual job and test it.
Notice that although these type of tests access the DB or the file system they are called component tests and not integration (we’ll get there).
- Bug types: different component access/usage bugs.
So we tested the components and unit tests our class? Is this enough? The answer is still no. Despite the fact we tested each class independently we cannot assume that they collaborate together. We need to make sure that our whole system works. We want to check that our service uses its dependencies correctly and handles their real (not mocked) behavior as expected.
System Tests
No mocking included! This is the real deal. I want to verify that my service which I expose to the world actually works so I call it with real parameters and test that it actually does what it supposed to. The challenge with these tests is to create the proper environment for the test and clean all the test data after the test.
By the way these tests can later be used as load tests.
- Bug types: Components collaboration bugs, loads failure.
Integration Tests
Integration is the collaboration of two systems. Meaning if we have a client that contributes my service an integration test will test how the client handles the service behavior.
- Bug types: communication faults, security issues and data contract mismatches.
UI Tests
After validation the integration of the client and the service it’s time to validate the client itself. You need to actually play with the client, click the buttons, enter input and validate the output and the UI logic (disable/enabled buttons etc). You need to create real test cases that match the real operations that your user will perform on the client. You can do it manually or automatically using coded UI tests.
- Bug types: UI logic bugs.
Smoke Tests
The last kind of tests is when you deploy your application and you want to verify that the installation was successful. Validate the DB schema was created, the IIS services are up and so on. These tests don’t check any business logic just that the different components of your application were installed correctly and that the application is ready for the user.
- Bug types: deployment configuration and installation bugs.
There you have it! The Pyramid of Tests:
clip_image002
If you ignore a step in your app then finding why a test has failed will take much longer as every test is responsible for different bug types, plus you won’t be able to test your application in cases that cannot be prepared like not enough space in the file system or a DB failure.
Be safe. Until next time.


































Tuesday, September 3, 2013

Sending email from your app

Let’s say that your app needs to have the ability to send an email, “New order has arrived” kind of email.
Let me introduce you “Fluent Email” – a nice library for making your life easy when sending emails for your app.
Fluent Email is available in the nearest nugget server so go ahead and install this package.
Before we send the email we need to configure our email smpt server in our configuration file:
  <system.net>
  <mailSettings>
    <smtp>
      <network enableSsl="true" host="smtp.gmail.com" port="587" userName="nerush.dennis@gmail.com" password="*****" defaultCredentials="false" />
    </smtp>
  </mailSettings>
  </system.net>
All the above values are different when using different smpt servers. If you want gmail to be your email server then you have to specify the port as 587 and set enableSsl to true.

The API

Email.From (myEmail)
     .To(sendToEmail)
     .Subject("New order has arrived!")
     .Body("The order details are…")  
     .Send();

Pretty straight forward.

If you are not willing to wait until the email is being sent you can use the Sendsync method:
Email.From (myEmail)
     .To(sendToEmail)
     .Subject("New order has arrived!")
     .Body("The order details are…")  
     .Sendsync(MailDeliveredCallback);
  
You can specify the “from” email value in the config file:
<system.net>
  <mailSettings>
    <smtp from=”Nerush.dennis@gmail.com”>

And then you can use the “FromDefault” method:
Email.FromDefault()
     .To(sendToEmail)
     .Subject("New order has arrived!")
     .Body("The order details are…")  
     .Send();

Templates

Another cool feature is the templates. Let’s say that you want to send a nice email to your users which has not only simple text but a table, a picture and some more stuff. You can create an HTML template and use it for your mail:

Template.cshtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body dir="rtl">
    <h1>New user has signed in for the website!</h1>
    <p>New user’s name:<b>@Model.Name</b>
        <br/>
        The new user email: <b>@Model.Email</b>
        <br/>
        <u>
The message text:
        </u>
        @Model.Text
    </p>
    <br/>
    <p>Have a great day!</p>
</body>
</html>

Notice the @Model? Those are parameters that you can pass for the template from the API:

Email.FromDefault()
     .To(sendToEmail)
     .Subject("New user has signed in!")
     .UsingTemplate(tempalte, new {Name = message.Name,
       Email = message.Email,
       Text = message.Text})

     .Send();

Culture support

In the last commits of the project Eyal Luxenburg added another cool feature for the library – the ability to use a template based on the current culture. The method is calledUsingCultureTemplateFromFile. This is the methods signature:
UsingCultureTemplateFromFile<T>(string filename, T model, CultureInfo culture = null, bool isHtml = true)

If you specify a culture it will try to load the template file which has the matching culture extension (same way as with the resource files). Specifying the He-IL culture will force fluent email to look for a template file that has the culture extension: template.he-IL.cshtml. This way you can create email templates for all the languages that your app supports.

Email.FromDefault()
     .To(sendToEmail)
     .Subject("See you in the next post")
           .UsingCultureTemplateFromFile(template, emailModel, hebrewCulture)
     .Send();





Wednesday, April 24, 2013

HTML 5 – full guide: What is HTML 5?


I want to focus on the new stuff that most of you are not familiar with so the intro will be pretty short.

HTML5 is the latest version of that markup language which includes new features and improvements to existing ones. It’s been designed to run on any platform (as long as the browser supports it), it’s compatible with older browsers and no IE 6 is not old – it’s ancient!
The purpose of this upgrade is to redefine existing markup elements and create new ones to allow the web designers build clean and clear markups and use common functionalities instead of rewriting them over and over again. Furthermore HTML5 allows to add audio and video elements the same way you add an image (using the <img> tag), it enables advanced drawing capabilities using the <canvas> tag and many more.

Page structure

 
 This is the old html page structure.












This is the new html5 page structure.

Look at the <DOCTYPE> tag. This tag simply tells the browser what kind of document this is. The old version also tells what HTML version the document is using.
HTML5 <DOCTYPE> simply tells the browser that the document is an HTML file even without mentioning the version because the browsers are supposed to support all HTML versions.  It’s not  a huge change but that’s what HTML5 is all about – making the page cleaner and clear as much as possible.







The script tag reminds me the “var” keyword in C#. No more redundant declaration like “type=javascript”, just open the <script> tag and add the source of the script. The browser will parse the section and treat it as javascript based on the script file included. The <style> tag acts the same.

New elements

So far for the intro. From now on I’ll be reviewing the new and improved HTML5 markup elements. In this post I’ll review the header, footer, nav and aside tags.
Why did the creators of HTML5 choose these elements? Before building the new markups the creators searched the web to find the elements that are most commonly used. They searched the id and the class attributes (<div id=”header”/class=”footer”) and here are the results.


Header

The first of the new elements is the header element which represents the header of our page (where the logo goes), however header is not restricted to appear just once in a page – it can represent any header of content inside the page.
How do you know when to use it? Every time you’ve used <div id=”header”> or when you have content that can be considered as a header.



The header of the youtube page

Footer

The footer element is the section that is usually the end of some content like share buttons, copyrights and etc. Same as header the footer element can appear more than once in a single page.











This is a part of a youtube page. The views count and the date is the footer of the video content but not the end of the whole page.

Nav

The nav element represents a group of navigation links like a menu.
It’s not recommended to use nav on every group of links like the links in the copyright section (footer?) or group of links like the facebook chat friends. Only links that are responsible for navigation inside your application should be wrapped with the nav element.



Facebook menu – group of navigation links

Aside

The aside element is a part of the page that is separated of the main content. Its content can stand on its own in every page but has to be part of a bigger content. Same as all the other elements that I’ve mentioned before, the aside doesn’t have any styling functions – it can be “on the side” of the page, under the header or even above it like a banner on the very top of the page.











The “popular on youtube” is not the main content of the page, it’s a group of links (nav?) that is perfect on the side of the page.

All the elements I've covered so far don't add new functionalists, using them only makes your web pages cleaner and more readable for other developers (one day someone else will have to maintain your application) by creating meaningful separation of your content.

That’s it for the stuff that most of you know. In my next post I’ll show you the less known elements like the article, section, mark, meter, time and progress elements.