Monday, September 19, 2011

A New Direction

I finally decided to move on...
After working for two years at an Israeli credit card company (ICC a.k.a. C.A.L.) as a .net web developer, I think it's time for me to start something new!
Here are some of the thoughts and questions running through my head at the moment :

What did I accomplish in the past 2 years ?
My technical programming skills did improve, but not as much as I would want them too. That's exactly why I'm leaving.
I did gain experience and I feel that I did improve but not to my full potential. During these two years I had to learn a lot on my own, reading blogs on the internet, and trying to incorporate the new technologies at my work place. Most of the people at my workplace have been there for a couple of years prior to me arriving and they aren't keen on letting some new dude change the way they're used to working.
You know what they say - It's really hard to teach an old dog some new tricks... :)

What was I looking for ?
When I started looking for a job, I decided that the most important aspect to me is a place where I will advance technically and learn as much as I can from. As a programmer I believe that half the job (at least) is to always learn new technologies/frameworks/utilities that will help you become a better and more efficient developer. I believe that if the people at your current work place aren't always pushing to learn new technologies then it will be very hard to do it on your own... (If you succeed, tell me how).

Where am I going ?
After only a few interviews, I decided to start working for Sears Israel (SHC). The first thing that got me intrigued about them is that they were the only place that during the technical interviews actually asked me some questions that I didn't have a clue to the answer! During the interviews, from my first impression, it seems like the programmers there really know what they're doing and are fully dedicated to writing excellent code!
In addition to the technical stuff, the product seems interesting, and a very modern idea. It's basically a social shopping site, but with tons of interesting features. I know that the challenges they deal with are interesting - The most interesting to me is how do you create a site with great scalability?...

Some more general and honest thoughts about the new job...
Brutal truth to be said - I'm a little worried I won't live up to the standards at Sears. My new team leader sent me some subjects/frameworks to learn before I arrive so I'll feel a little more comfortable when I arrive. Some of these technologies/frameworks I haven't used much or at all in the past (like IoC & MVC3), and some (like Apache & Tomcat + Java) are totally new ground for me. But this just makes the job 10 times more interesting to me! I just hope I'll be able to learn all the new stuff fast enough so I can keep up with the pace.
But this doesn't make me put my self down, instead it just makes me want to get so much better at what I love doing (programming!). I don't have experience looking for and hiring employees, but I think that one of the most important things you should look for in a new employee is someone that loves what he does and that you know will always be open to learn new stuff from other sources. Of course you want someone that has a certain amount of programming knowledge, but someone who is very experienced but has no motivation will be a bad bet in the long run apposed to someone a little less experienced but fully motivated.
I believe I fit into the fully motivated category. I know for a fact that I love learning new stuff, and that I'm always open to changes, so I think i'm a good bet... :-p


Saturday, August 27, 2011

Unit testing FluentNHibernate...


As I recently posted, I just got back to unit testing...
I thought of a small personal project to start practicing on, and got to work. My project consisted of using Fluent NHibernate, so I wanted to create unit tests to make sure my mappings were good.

I came across an old blog post of Ayende explaining that he created a base class that exports all your mappings into an in-memory sqlite db just for testing.
This concept seemed really good to me, so I tried it myself, but ran into some small problems while trying to configure it for Fluent NHibernate, so I will post the new version to ayende's class that works for FNH :

In case you don't have the SQLite providers yet, you can download them here.

This is the class :
public class InMemoryDatabaseTest : IDisposable
{
    private static Configuration configuration;
    private static ISessionFactory SessionFactory;
    protected ISession session { get; set; }

    public InMemoryDatabaseTest(Assembly assemblyContainingMapping)
    {
        SessionFactory = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
            .ProxyFactoryFactory(typeof(ProxyFactoryFactory))
            .Mappings(m => m.FluentMappings
                            .Add(assemblyContainingMapping)
                      )
            .ExposeConfiguration(x => configuration = x)
            .BuildSessionFactory();

        session = SessionFactory.OpenSession();

        SchemaExport export = new SchemaExport(configuration);
        export.Execute(true, true, false, session.Connection, null);
    }

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

And then all you have to do to test your mapping would be something like this :
[TestClass]
public class UserTests : InMemoryDatabaseTest
{
    public UserTests() : base(typeof(UserMapping).Assembly)
    { }

    [TestMethod]
    public void UserMapping_CanSaveAndLoadUser()
    {
        object id;

        using (var tx = session.BeginTransaction())
        {
            id = session.Save(new Dal.Entities.User()
            {
                Username = "unittest",
                Password = "unittest1234",
                Email = "unittest@gmail.com"
            });

            tx.Commit();
        }

        session.Clear();

        using (var tx = session.BeginTransaction())
        {
            var user = session.Get<Dal.Entities.User>(id);

            Assert.AreEqual(user.Username, "unittest");
            Assert.AreEqual(user.Password, "unittest1234");
            Assert.AreEqual(user.Email, "unittest@gmail.com");

            tx.Commit();
        }
    }
}

It's that easy! :)

Thanks Ayende!

Monday, August 15, 2011

Beginning Unit Testing...


I finally decided to get back into Unit Testing...

I have worked once in the past for a short period of time (only a couple of months) with unit testing, and my experience is good with it. The problem is that where I currently work, my team isn't really into it, and aren't to keen on trying neither.

Since I haven't used it in a while, it feels to me as if I lost my unit testing mojo, and need to learn everything from scratch again.
At first, I though the best way to start is to actually write unit tests for projects I already wrote. This isn't TDD at all, but it's still something, and I feel as if I'm getting the "infrastructure" ready for the rest of the process...

Another thing I just thought about doing today was giving a lecture at work to my fellow team mates on unit testing, hoping that they will see the good side to it, and they'll want to know a little more on the subject!

Sometimes the best way to learn is by teaching! :)

I started building a demo project that I will show as part of a presentation i'm working on to go with my lecture. The project is just a simple calculator.

I am gathering all the points I need to discuss on this lecture, but trying to keep it simple and as convincing as possible to people who don't think it's useful or don't know what it is yet. Seems like quite a challenge, but I'm up for it!


So far this is what I got : (these are the points that are going into my presentation)

Let's say we're building a new class as part of a winform that does some calculation. How do we usually go about testing this ?
We would press f5 (debug) and play around with the UI a bit to see that everything's working...

Why is this bad ?
1. We have to do this again and again every time we change a little piece of code since we can't be sure it still works.
2. If someone else on the team changes our code, we'll need to run the tests again.
3. Someone might change a piece of code, play around with the UI and still not know about special corner-cases we were looking to handle in a specific way.
4. Time consuming!
5. In this case it's a winform and might be easy to test manually, but if we're just building a web service for example, I usually see people building these funny "tester" projects that they can send some sample input and see what happens.

Why does writing Unit Tests make life easier ?
1. By writing unit tests we are writing code that will check our functionality instead of doing it manually.
2. We can run the tests every change we make, and this will be much faster then manually testing.
3. If we write the tests properly and cover all the code we wrote, then someone else can change the code around or add some other functionality with the knowledge he didn't screw our code over!
4. Just by looking at the unit tests we can spot the corner-cases we should look out for.

What do we test and what not to test ?
1. Test all public methods in a class. If the tests are written good enough, then the private methods will be covered within these tests.
2. Make sure you're not writing tests to check the .net framework - this means you don't need to go crazy and start writing tests for each .net method!
3. Tests shouldn't need configuration. You should always be able to run the tests immediately. This means you need to avoid having your tests writing out to log files, db, network streams, etc. Instead, create mocks of these interfaces so they don't actually do this during testing.


Well, I feel like I'm new to this as well, so I'm looking for some feedback on these points I have for my presentation so far...
During the presentation I also want to show the simple demo test project I created, and how to write basic tests for it. I will show common cases when changing code can cause different behavior that might not be spotted at first by manually testing...

Seeya'...

P.S - Anyone interested in learning more about unit testing should check out these blogs : Ayende & Roy Osherove

Wednesday, July 27, 2011

Finding log4net hidden exceptions....


Recently I worked on a project that was mainly a couple of Web Services, and included a couple of more C# class libraries (e.g : a Data Access Layer, Common project with general utilities, etc..).

In the web services code, we had a lot of calls to our logging utility, which in this case used log4net. I had previous experience using log4net, so I knew (or thought i knew!) how to set it up quickly. I added what I needed in the web.config file, and thought it was enough.

Once I started testing the web services out, I realized that something was wrong with the log4net configuration. The problem was that it wasn't writing anything to any log file whatsoever. The bigger problem was that we didn't know why!?!...
log4net doesn't throw any exceptions if it doesn't work, and this way it doesn't interfere with your running application if, lets say, the log file it should write to has been deleted or is locked by another application for some reason...

However, log4net will write to a trace file, if you set one up...
This led me to the solution of my problem. All I did, was add a TextWriterTraceListener in my web.config, without even altering any code, and the log4net error was immediately written to my trace file.

In my case, I forgot to tell log4net to use Xml Configuration, but this is irrelevant. The point is that this might help you find out what your error is in the case of misconfiguration with log4net...

To set up a trace file through log4net, just add :

    
        
            
                
                
            
        
    

to your web.config file.

Trace listeners are a powerful tool when used wisely :)
You can read more about them here : MSDN - Trace Listeners

Happy Tracing...

Sunday, March 20, 2011

Generating dynamic forms :: part 1


Let me start out by saying, I know there are already a gazillion posts on the subject of generating dynamic forms using asp.net. I'm not posting this to teach the world something new, yet just to give in on the subject a little bit. This task is just so common that it's worth having a lot of examples out there and let people choose which suits them the best.

Generating dynamic forms can be done in so many different ways, and there is no 'right' way or 'wrong' way. Each way has its specific pros and cons.
I was put up to the task of creating dynamic forms from data in the db, again, this time for a web application at work. I searched the internet for articles on the subject to get ideas from and to get a direction. I saw so many different ways to do this, and got lost in all the information that i just decided to think it through on my own and give it my best shot.

I will post about the solution I came with in parts (since i'm guessing it will be long...).
In the first part, I will talk about making some basic decisions before starting to program.

Tehcnologies
I'm creating the application with asp.net. C# on the server side. For the client I'll be using javascript obviously, and leaning heavily on the jQuery framework since I know it the best.
In my DAL (Data Access Layer), I'll be using Fluent NHibernate to work with my DB (also a big fan of FNH).

Describing the forms
My forms are built like most forms - Each control is made up from a label and an input of some sort. The basic inputs are a textbox, a checkbox, a combo. Combo's for example can have multiple values, so they'll need to receive a list of values from somewhere. Each control will also need to implement validations.
I will also want to be able to implement special inputs like a datepicker which has a calendar you can choose from, or an address control which the street combo is linked cascadingly from the city combo.

So, so far, im guessing each control in the form will be described by the properties : Label, Name, Type, ListOfValues (this will be a list), Validations (also a list), CurrentValue.

Creating the forms
In my application, I want the forms to be opened in client-side dialog windows, because the user is supposed to view an available list of forms to fill out, open some of them, and fill their values. In the end, the user can choose to save all the information in the forms.
So, I will be implementing the creation of the forms on the client via javascript. I will render to the html source, all of the forms objects in json format, and when the user chooses to open a specific form, I will create it specifically in a dialog window.
I will then save the values into the json, and using ajax, send the information back to the server.

Form Interactions
Each control will have a 'Validate' method, so i can choose to call it when i want. Obviously, the best time to do this is when the user submits.
Submitting the form and a button for submition can be implemented on my own, with no connection to the form builder. I want my generic form builder to help me in the future in every situation, and i can't predict what submition scenarios i'll need in the future so i'll just implement it on my own everytime.

Submitting the form
Like stated earlier, saving the form values will go directly back into the json object where they came from. I will then send it to the server via ajax, and do the db updating on the server side.

Coming up...
In the next post I will start getting into the nitty gritty.
I will show how I built my db representation of the forms - What my entities look like, what are their properties and how they are built.

Saturday, March 5, 2011

Fluent NHibernate - Working with Database Views


So, it turns out you can work with Views with Fluent NHibernate just as you were to work with tables. All you need to is define your entity with the name of the view, instead of the table name.

example :
public class UserEntity
{
    public virtual int UserId { get; private set; }
    public virtual String FirstName { get; set; }
    public virtual String LastName { get; set; }
    public virtual int UserStatusId { get; set; }
    public virtual String UserStatus { get; set; }
}

public class UserEntityMap : ClassMap<UserEntity>
{
    public UserEntityMap()
    {
        Table("view_Users");  // this is mapped to a view, and not a table

        Id(x => x.UserId);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        Map(x => x.UserStatusId);
        Map(x => x.UserStatus);  // This field is from another table
                                 // it is from a seperate code table that describes the different statuses in the system
    }
}

An exception is thrown, when trying to update the entity that is mapped to a view. The problem is actually because when working with a view, you cannot execute an update query that updates rows on different tables. It will only work when updating rows on one table in the view.

In order to get around this, we need to tell the mapping that some properties aren't to be updated. This will solve the problem.

example :
public class UserEntityMap : ClassMap<UserEntity>
{
    public UserEntityMap()
    {
        Table("view_Users");  // this is mapped to a view, and not a table

        Id(x => x.UserId);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        Map(x => x.UserStatusId);
        Map(x => x.UserStatus).Not.Update();
    }
}

Marking the mapping class with '.Not.Update()' tells FNH to return false on the update property of this field.
Likewise, we can also mark an attribute as '.Not.Insert()' and then the field will only be updatable, or mark a field as '.ReadOnly()' and the field will act as if it has a private set.

Thursday, February 17, 2011

jQuery Templates


I am a big fan of jquery, as it is my favorite javascript framework. It has many great features already, and even more are being developed everyday. It simply makes developing responsive web applications much, much faster.

I am currently working on a large application that displays the user a lot of grids practically on every screen. The data inside the grids, as well as there basic structure can change according to different selections the user makes. It is very important for me to make this web application very responsive and fast, so it was pretty obvious from the start that I'd be using a lot of ajax and depending heavily on the client to do the rendering.

I had a standard ajax call, returning me a json object to work with. I then found myself trying to dynamically build a string that would represent the html markup of a
inside a table, appending it to the table as i iterate over the json properties.
This isn't very difficult to do at first, but will always look very messy, and will be much uglier to maintain...

Luckily, just in time, I came across the jQuery documentation of their new templates feature.
This allows you to design a small template of html, mark where the parameters will be, and bind a json object to that template.
Then, you can practically do whatever you want with it- append it to a table, or just use it as a list of data, and the best part is that the UI is seperated from the 'code', meaning it is very easy to maintain since you can change your template around freely and easily, while never changing the ajax calls nor javascripts.

I'll show some simple examples so you can see what i mean, and to help get you started on your own.

First, you obviously need to include the templates plugin into your html file (can be found here) :
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.tmpl.js"></script>

The template you want to use, could be inserted into a script tag like this :
<script id="templateStructure" type="text/x-jquery-tmpl">
    <tr>
        <td>${FirstName}</td>
        <td>${LastName}</td>
        <td>${Email}</td>
    </tr>
</script>
Notice that I gave the script an id, which we'll need soon, and the type is marked 'text/x-jquery-tmpl'.

The ${} brackets tell the jquery where to place the data of the json object we will bind. The name inside the brackets must correlate with the properties of the binded json object.
This means our json object will be an array of objects (or one object if thats all we have) that all have the properties 'FirstName', 'LastName' and 'Email'.

The template I created represents a row in a table that i will bind to, and the table im going to bind it to, looks like this :
<table border="1" id="templateTable">
    <tr>
        <td><b>First Name</b></td>
        <td><b>Last Name</b></td>
        <td><b>Email</b></td>
    </tr>
</table>
So when I add the rows, the table will be filled with data.

In order to load the template, I use the template() method :
$('#templateStructure').template('myTemplate');
This will load the template we defined in the script tag and call it 'myTemplate'.

Now, all we need to do is give the template a data source, and place it wherever we want. In our case we'll append it to the table so it 'fill' the table's data.

$(document).ready(function() {
    // our data object we will bind
    var myData = [ {FirstName:'Bob', LastName:'Jannovitz', Email:'bobby@gmail.com'},
                   {FirstName:'Howard', LastName:'Shennaniganz', Email:'howard@yahoo.com'},
                   {FirstName:'Joe', LastName:'Stoozi', Email:'joeii@hotmail.com'} ];

    // load the template and name it 'myTemplate'
    $('#templateStructure').template('myTemplate');

    // bind the data to the template and append to the table
    $.tmpl('myTemplate', myData).appendTo('#templateTable');
});

The final result will be the table with the data rendered into it.

So in conclusion...
The templates jQuery plugin can be extremely useful in binding data to an html template on the client for fast responsive applications. It also has many more great features like instructions that can cause your template to act different to different data situations.
It is important to note though, that all this is only in beta stage, and is subject to change. I however, already started using it, and so far so good... :)

I might be posting something more advanced about this soon, but until then -
You can read more about it here : http://api.jquery.com/category/plugins/templates/