Alexander Beletsky's Development Blog: 2010-08

JavaScript, HTML and CSS.. I need it!

I've never been working close to UI during my career, neither as Win32 developer nor as Web developer. I was focused on business logic and architecture rather than user interfaces, moreover developing UI was not the best things that I liked to do.

In my previous job I met javascript first time. It wasn't in context of web application, but rather a custom logic for desktop software. It was very unusual to me, since I've had few experience with dynamic languages. But as I met javascript closer, more and more and like it. I find dynamic languages are more flexible to describe objects. With no static check you could not rely on messages from complier, if you have a mistake on you code, it is only runtime than you catch it, so it forces you to do unit tests. Unit testing in dynamic languages is more simple and easy to use. You can do any type of mocking, construct a tests objects in run time, easy emulate user interface events.

As soon as you good C# developer, understand ASP.net/MVC, RDBMS, enterprise applications design, your values is less, than you lack a HTML/CSS when you do web. I've never treated HTML/CSS as important skill, thinking as I needed I could learn it in 1 day. I was wrong, it not so easy as I thought. Of cause, they are declarative, with no logic, conditions, runtime, but they are languages and requires respect. Sure, it is not so difficult to start with some HTML/CSS than with C#/ASP.net, but as always - experience matters.

Some years ago, I've started to play a guitar a bit. Tuning of guitar was the greatest problem I had, before I've been presented with tuner device. With a little bit experience I was able to tune slightly untuned guitar.. so if some string is close to tune, I could adjust it. But if it is totally untuned, I just could not catch it up. I'm having the same issue with HTML/CSS and JavaScript now. I could do fixes, create something simple, add something to existing application. So, I could adjust. Problems begins then I try to do something from scratch. I spend to much time, looking for examples and tutorials to do really simple things (especially with CSS). I could not tune.

I want to improve my knowledge in this area, now I understand that I really need it.

I want to ask you today, what resources, books, online tutorials you use and recommend for HTML/CSS/JavaScript area. What was you experience of education it it?

Failed to generate user instance of SQL Server exception

If you just switched from ASP.net development server to IIS, you might appear to see such exception from data access layer of application:

Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed.

Don't panic, it is easy to fix. Go to Internet Information Services (IIS) Manager console panel. Check out what Application Pool is set for your application, in Basic settings. It would probably be ASP.NET 4.0 Classic. Go to Application Pools section, select ASP.NET 4.0 Classic and go to Advanced Settings. In Advanced Settings. In Process Model, Identity - ApplicationPoolIdentiry would be selected.

You must change it with a credentials of user that has physical access to App_Data folder of application.

You should restart IIS and start application again.

Does TDD find bugs?

No, of cause not. TDD doesn't find bugs in your application. This is a very frequent misconception about TDD, I would like to shed a light on it today.

Why tests do not find bugs? Why applications created with TDD still has bugs?

Tests are replication of developers mind. As good as problem understood, as good it could be tested, as good it could be solved. That means that tests and code are very subjective. It all depends on developer. If the requirement is treated wrong, or implemented not completely it will be a bug, even if all tests are passing. If developer is not aware of existing of some problem he won't be able to create a corresponding case/fix.

Tests are limited. It is just not possible to test everything. Especially in middle/big size applications. Even having a 100% coverage metrics, does not guarantee that code is 100% tested, it only means that existing test suite runs each line at least ones. There always be a corner cases, that are not really seen during requirements/implementation phase and could appear only on acceptance or maintanance. There are high chances to miss something important during development.

Tests have a quality. We frequently hear term code quality. Code quality is some measure that shows how easy code could be understood, changed. We all know that usage of design patterns, enterprise libraries, refactoring.. all of this aimed to improve code quality. Tests are also code, but easy to read and maintain is not primary test quality factors. Test quality is some measure of how good test code is executing and asserting against production code. Number of asserts is a simplest metric. As soon as tests doesn't have any assert in it, tests have no sence.. it useless. Quality highly depends on actual scenario of test, as much smarter scenario is as much quality test is.

Tests are not intelligent. Tests are code, created by developer, proves that functionality created works as expected at the current moment on time. Test suite is something that could produce a snapshot of particular functionality. They become very useful than they are created before code, because it guides through to solve problem and reach the goal, as well as they are useful after the code is created, minifying the risk of regression during any of code changes (fixes, refactoring, new functionality etc.). But test itself could not give any new information.

Why TDD is still important, you might ask? Even if TDD still leave a room for bugs, it radically decreases overall number of bugs. First of all because many silly mistakes are being found during creation of tests and first tests runs. Second, that good number of tests creates a kind of bounds that helps to keep existing functionality in it.

Web development: Lightweight AJAX thought jQuery, JSon.net and HttpHandlers

If you are about to start using AJAX in your ASP.net application, you will be pointed to some existing frameworks, like: ASP.net AJAX, Anthem.net or something else. That is a probably a good idea to use time-proven things, but you also might have a reasons not do that. First of all, if you are new to AJAX and you need to educate yourself with it, using frameworks in not good, because it hides a lot of details of "how it works". Second reason, that you might not want to overhead with additional frameworks, to make it as lightweight as possible. If you are about to implement some simple AJAX operations, then jQuery for client code, Json.net to handle JSON on server side and ASP.net HttpHandler is all that you need!

Let's briefly review each of these components:

  • jQuery - everybody knows jQuery, it is the best javascript framework, created by John Resig.
  • Json.net - just create and easy to use framework of serialize/deserialize .net objects to JSON, created by James Newton-King.
  • Generic Handlers - part of ASP.net framework. With some level of simplicity HttpHanlers could be called a page without any overhead (like a Page with no HTML code and only Page_Load method), that is ideally serves as a handler for AJAX calls.

Preparation

We going to create a simple admin page that could: get list of all users registered in system and quick new user. I'll use the same project that I used in my previous web development articles, called Concept, so as always you could get a source code on github.

Generic Handler implementation

I web project I've added new folder, called handlers that would contain all handlers code we wish to have. Add new "Generic Handker" item into this folder, and call it users.ashx.

The skeleton code of handler will look like that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Company.Product.DAL;
using Company.Product.BLL;

namespace WebApplication.handlers
{
  /// <summary>
  /// Summary description for users
  /// </summary>
  public class users : IHttpHandler
  {
    private UsersOperations _operations = new UsersOperations(new UsersRepository());

    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "application/json";
      var respose = string.Empty;

      var function = context.Request["function"];
      switch (function)
      {
        case "list":
          respose = CreateListReponse(context);
          break;

        case "add":
          respose = CreateAddUserResponse(context);
          break;
      }

      context.Response.Write(respose);
    }

    private string CreateAddUserResponse(HttpContext context)
    {
      return _operations.InsertUser(context.Request["Email"], context.Request["SecretPhrase"], context.Request["Password"]);
    }

    private string CreateListReponse(HttpContext context)
    {
      return _operations.GetAllUsers();
    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}


* This source code was highlighted with Source Code Highlighter.

Two important thing here: first, we declare context.Response.ContentType = "application/json"; meaning that body response will contain json code. Second, request will contain a function parameter, that would contain exact function name we want to call. It our case it will be just 2 functions, list and add.

Serialization of data

Json.net made a serialization of .NET objects to Json very easy. It supports all main types and collections, it also extendable for your custom needs. Code that returns the list of all users:

namespace Company.Product.BLL
{
  public class UsersOperations
  {
    private IUsersRepository _data;

    public UsersOperations(IUsersRepository data)
    {
      _data = data;
    }

    public string GetAllUsers()
    {
      return JsonConvert.SerializeObject(new { status = "success", data = _data.GetAll() });
    }

    public string InsertUser(string email, string secret, string password)
    {
      var user = new User { Email = email, SecretPhrase = secret, Password = password };
      _data.InsertUser(user);

      return JsonConvert.SerializeObject(new { status = "success", data = user.Id });
    }
  }
}

* This source code was highlighted with Source Code Highlighter.

Users repository GetAll() method returns IEnumerable of User. JsonConvert understands such data types, so able to perform serialization not problem.

Aspx code

In aspx I utilize functionality of $.ajax call, as well as very nice component called blockUI, that works upon jQuery and helping to block interaction during AJAX calls, as well as creation of simple modal dialogs.

<%@ Page Title="" Language="C#" MasterPageFile="~/Concept.Master" AutoEventWireup="true"
  CodeBehind="UserOperations.aspx.cs" Inherits="WebApplication.UserOperationsView" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
  <script type="text/javascript">
    function listOfUsers() {
      $.ajax(
      {
        url: "/handlers/users.ashx?function=list",
        beforeSend: function () {
          $("#results").slideUp();
          $.blockUI();
        },
        cache: false,
        success: function (response) {
          $.unblockUI();
          if (response.status == "success") {
            listOfUserCallback(response);
          }
        }
      });
      return false;
    }

    function listOfUserCallback(response) {
      var html = "<ul>";
      for (var key in response.data) {
        html += "<li>" + response.data[key].Id + ": " + response.data[key].Email + "</li>";
      }
      html += "</ul>";
      $("#results").html(html);
      $("#results").slideDown();
    }

    function showDialog() {
      $.blockUI({ message: $("#adduserdialog") });
      return false;
    }

    function closeDialog() {
      $.unblockUI();
    }

    function addUser() {
      var user = {};

      user.Email = $("input#email").val();
      user.Password = $("input#password").val();
      user.SecretPhrase = $("input#phrase").val();

      $.ajax(
      {
        url: "/handlers/users.ashx?function=add",
        beforeSend: function () {
          $.blockUI({ message: "<h1>Adding new user, please wait...</h1>" });
        },
        data: user,
        success: function (response) {
          $.unblockUI();
          if (response.status == "success") {
            addUserCallback(response);
          }
        }
      });
      return false;
    }

    function addUserCallback(response) {
      //renew list of user:
      listOfUsers();
    }

    $().ready(function () {
      $("#results").hide();

      //setup handlers
      $("a#list").click(listOfUsers);
      $("a#add").click(showDialog);

      //setup dialog
      $("input#adduser").click(addUser);
      $("input#cancel").click(closeDialog);
    }
    );
  </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
  <div id="content">
    <div id="adduserdialog" style="display: none; cursor: default">
      <label>
        Email:</label>
      <input id="email" type="text" />
      <label>
        Secret phrase:</label>
      <input id="phrase" type="text" />
      <label>
        Password:</label>
      <input id="password" type="password" />

      <input type="button" id="adduser" value="Add user" />
      <input type="button" id="cancel" value="Cancel" />
    </div>
    <div id="left">
      <div id="box">
        <p>
          Admin operations:
        </p>
        <a id="list" href="#">List of users</a><br />
        <a id="add" href="#">Add new user</a>
      </div>
    </div>
    <div id="right">
      <div id="results">
      </div>
    </div>
  </div>
</asp:Content>

* This source code was highlighted with Source Code Highlighter.

Putting all together

Now let's review everything in conjuction. We have generic handler, that receives http request. It uses request "function" to understand what function is requested by user. Based on function type it delegates the call to business object, called UsersOperations. UserOperations relies on UserRepository to work with data, so it get or insert the data and return results as JSON strings. JSON is created by serialization of .NET objects into JSON objects by means of Json.net library. Client receives the output in asynchronous callbacks, checks the status of operation and dynamically creates HTML code. blockUI component help to block user interaction with UI during asynchronous calls, also "create new user" modal dialog is created by means of blockUI.

Such approach serves really great for simple AJAX applications, on pure ASP.net, jQuery. Check out sources on Github.

7 links challenge from Problogger.net

I'm not doing blogging for a long time, event if I started on march of 2008 I had a great pause in it. Originally I started a blog in Russian, but later I've decided to switch to English, mainly because I wanted to my colleagues from Denmark to read my blog.. and probably got bit wider audience.

Problogger.net is a great place for bloggers. Even if you don't plan to get money from your blog (as me) there are great number of tips/tricks for bloggers, as well as some inspiring information. I've started to read it recently I found it very interesting.

Daren Rowse is a man behing Problogger.net, professional blogger who live in Melbourne, Australia. He announced 7 Links challenge. I also decided to pick it up. Here we go:

  • First post - Первое сообщение it was a small introduction of myself to the world, as well as setting up objectives for this blog. It was in Russian, so what I said there is that I going to write about challenges that I met in my development course everyday, to keep and share the knowledge I got. I still doing that.. I think.
  • The post I enjoyed writing the most - I have a lot of fun during my blogging (even if sometimes it is hard to finish up some post) I enjoyed the GitHub Social coding the most. It was my first, not so technical, with elements of philosophy post.. I liked that!
  • A post which had a great discussion - I haven't created a post that really attracted big attention and discussion. I'm OK with that, I still think I create one.
  • A post on someone else’s blog that you wish you’d written - This is the one that Anton Litvinenko created recently, called The biggest demotivator for programmer. Nicely written and describing very actual things for every developer. It is not only me, who liked that it was in top of dzone.com for several days.
  • A post with a title I am proud of - Hard to say may be No back up... Fail!. Don't know why, but I liked the most.
  • A post that you wish more people had read - It might be the set of my first blog posts, related to TDD. I've tried to describe my vision of TDD and why I like it. It was in Russian and my first bloggin experience.. but anyway Разработка ведомая тестированием. Часть 1. Описание. And also I tried to find some ideas in Blogging with a GitHub and Blogspot? Ideas?.
  • My most helpful/visited post - so far it is DDD, Implementation of Repository pattern with Linq to SQL that I created after discussion of Repositories on asp.net forum that I try to read/write periodically.

This is it.. You can also join such challenge, please do that.

Happy blogging!