Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

January 2, 2010 Book Reviews No comments

I just finished reading book “Applying Domain-Driven Design and Patterns: With Examples in C# and .NET” and I liked it.
This book talks about modern key concepts needed
to develop successful product of enterprise level. It describes how to build
your project without losing business needs out of view – you just start with
your Domain level. You develop with TDD and describing behavior of application.
Things with which you are operating are Customer and Order, but not
TBL_CUSTOMER and TBL_ORDER – this is one of key aspects, which means hiding
your infrastructure level and interacting with database from developer’s eyes,
which can be easily accomplished with NHibernate.
Book is excellent in examples which Jimmy presents. I haven’t seen
so good explanation of the State design pattern as it is in this book.
Book covers a lot of other interesting things like IoC, AOP, SOP,
MVC and so on… really lot of stuff under another light you ever seen. You need
to read this book if you are going to grow and keeping on track.
P.S. BTW as you see I read it in Russian (not my native language also :) but I have it paper variant). 


No comments


Where Do You Want to Be In a Year?

January 1, 2010 Success, YearPlanReport 3 comments

Right now is the first time in this year when I opened google reader and found one interesting post Where Do You Want to Be In a Year? by Tim Barcz. When I read it I realized that I had read book The 7 Habits of Highly Effective People also.

In general all books on Success says that you need to “Begin with the end in mind“, this means that you must have your plan.

At first you need to find out you goal for whole life. That is your target and main thing you need to get. Then you need to do breakdown of tasks you need to accomplish in your life, having them in few levels of term scope like 10 years term, 5 years term and 1 year term… and so on. So question:

Where Do You Want to Be In a Year?

My answer: 

By the end of 2010 I want:

1. Get Microsoft Certification:
  * MCTS (Exams: 70-536 and 70-505)
  * MCPD 70-563 and 70-565 (this one is big fish, but I need such!)
2. Read at least 24 books.
3. Become known employee in my company, sharing knowledge and doing presentations, so will have much more authority among co-workers.
4. Familiarize with Java and contribute research and development work to Kohonen Maps world.
5. to be Senior Developer and continue growing…
6. Improve my English skills to have at least upper-intermediate strong level (according to my company graduating)
7. Gather good capital and looking for investments of money.

Write down your answer in comments or give me link to your blog!


3 comments


Ensure that your Unit Test is true inspector of bad code

December 29, 2009 UnitTesting No comments

Few days ago I did refactoring and as I’m quite sure that we have good coverage I checked-in my code after all tests passed.
But today QA from my team stated that he/she cannot save new Customer. I dived into log files and found that exception occured on SaveCustomer method.
Ok, I moved to the appropriate UT. (Note: it passes ok.) Which looked like:

[Test, Category(“Integration”)]
public void SaveCustomer_EnsureWeCanCreateNewCustomer()
{
    Customer customer = new Customer();
    //some another setup code here…
    try
    {
    //we hit database to save newly created customer
        savedCustomer = CustomerRepository.SaveCustomer(customer);

    //now we fetch customer from database requesting with the ID of just saved customer
        fetchedCustomer = CustomerRepository.FetchCustomer(savedCustomer.ID);

    //if fetched customer is not null we are ok!
        Assert.That( fetchedCustomer, Is.Not.Null );
    }
    catch
    {
        //do nothing here….
    }
    finally
    {
        if ( fetchedCustomer != null )
        {
        //we want to leave our database clear after test run
            CustomerRepository.Delete( fetchedCustomer );
        }
    }  
}

This Unit Test will be succeded anyway, because
Assert.That(fetchedCustomer, Is.Not.Null) and similar asserts generates AssertionException.
Honestly I’m not aware why there was that catch{} piece, but anyway you could put there two catch blocks if it is really needed – one specific for the AssertionException and another for all cases of our life.
When you write your Unit Test you need to see it in both states – first
in failure and then in success. After that you can allow yourself
commit that code.

Main idea is:

You always need to keep one’s eye on quality of you Unit Tests and be sure that your Unit Test will fail when that is needed.


No comments


How to create and apply a patch with Tortoise SVN

December 27, 2009 SVN No comments

What is patch?
Patch is text file which contains only differences you did to code, so it will contain changed and new lines as well as removed all in one bulk text file (*.diff or *.patch).
Why to use it?
There could be few cases when you would need patch. Next are three that I see:
1. For example it is possible that you do not have write access in SVN in case if you are contributor to some open source project. So you can send you changes as patch to those who have rights.
2. Another case could be when you lost your connection on one machine but want to port your changes to another machine easily and then commit them. (I faced with this one).
3. One another interesting usage could be establishing code reviews via patches. It could be that you have command that works remotely, and to ensure that we commit only good code your code reviewer would like to have your changes on his machine quickly and easily. Of course it it ugly to sent him all files you have changed and with screenshots of differences.
Create patch
You just need to be sure that you have latest code, that your changes are done and after that just right click on folder on which you want to create patch with selecting “Create patch…” like above. This will take you to dialog where you select files you want to include into your patch and then will take to save file dialog. So you could get file like validationRules_CodeReview.patch.
Apply patch 
Applying patch is also very easy, just pick up “Apply patch…” from the context menu of TortoiseSVN of folder needed (should be same folder as patch was created). After you selected patch file you will get two windows – one is TortoiseMerge on background and another is File patches. File patches window is list of files to patch. Double click on file from list opens differences in background window, so you could review them. And to apply you just need right click and select “Patch all” or “Patch selected“.

Quick google with “How to create and apply a patch with Tortoise SVN” gives me next: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-patch.html so maybe this will make more sense for you :)


No comments


Quick Verification if row exists in database with Nhibernate

December 23, 2009 NHibernate No comments

Next SQL, which verifies if customer row exists in database:

SELECT customer0_.CUSTOMER_ID AS x0_0_
FROM   T_CUSTOMER customer0_
WHERE  (customer0_.CUSTOMER_ID = 123456)

Will be generated with next NHibernate Query:

public bool CustomerExistsInDatabase(Int32 customerId)
{
    var result = Session.CreateQuery(string.Format(“select c.CustomerID from Customer c where c.CustomerID = {0}”, customerId)).UniqueResult<Int32?>();

    return result.HasValue;
}

Please note, that you could use not only primary key, but any other property in your where condition.


No comments


Regex Quick Example

December 22, 2009 .NET, Regex No comments

This is just another quick example of Regex pattern.

Next pattern matches “at least one symbol which is letter or digit at the begging and then exactly one delimiter ‘|’ and then at least one symbol which is letter or digit in the end“:

var valuePattern = new Regex(@”^w+|w+$”);
bool isValid = valuePattern.IsMatch(someStringValue);

Valid is:

ab123|cde45

Not valid are:

|ad
df|
adf||adf

and so on…

Links I’ve used:

Verify your Regex:  
http://www.pagecolumn.com/tool/regtest.htm
Cheat Sheet:
http://www.addedbytes.com/download/regular-expressions-cheat-sheet-v2/pdf/


No comments


Code Review: try – catch

December 22, 2009 CodeReview 2 comments

Sometimes it is hard to convince that catch(…) is not so good!

Today I provided code review to one of my colleague and he was totally sure the he need try{/*code*/}catch(){} in few places.

First looked like:

try
{
   int someValueId = Convert.ToInt32(value);
   if (someValueId > 0)
   {
     return new ValidationResult(true, “Valid”);
   }
}
catch{}

I rewrote code to:

int serviceId;
Int32.TryParse(value, out serviceId);
if (serviceId > 0)
{
  return new ValidationResult(true, “Valid”);
}

Then I spent few minutes to convince him that this code is ok and that this is not good to have catch for everything.

Another code looked like:

string result = string.Empty;
try
{
    result = documentContent.Descendants(“SomeValueCode”).FirstOrDefault().Value;
}
catch (Exception)
{
    //He was trying to ensure me that since we are doing validation we should not throw an exception
}
//do some work here

Now I tried to explain that FirstOrDefault() returns us either first element of collection OR null, so if we got null we just need to do some another stuff,
but if some exception will occur we should allow it fly out OR write some specific catch for exceptions that could be thrown. Code which I propose looks like:

var resultElement = documentContent.Descendants(“SomeValueCode”).FirstOrDefault();
if(interventionCodeElement != null)
{
    var result = resultElement.Value;
    //do some work here
}

After conversation we decided that try(/*code*/)catch() is not so good.


2 comments


AssertDatesAreEqual

December 21, 2009 UnitTesting No comments

Have you ever faced with UT that failed once and then you always see it succeeded?

One of such tests could be test where you verify that date properties of some newly created entity are equal if they take DateTime.Now for that.

Today Hudson showed me that some test failed in project I worked near half a year ago, so test looked like:

var item1 = new Item();
var item2 = new Item();
//…
Assert.AreEqual(item1.CreatedDate, item2.CreatedDate);

Test failed because time difference between dates was greater than few milliseconds. This could occur when processor is too occupied.

So I changed assert call to more realistic:

public void AssertDatesAreEqual(DateTime dateTimeLeft, DateTime dateTimeRight)
{
     Assert.IsTrue(Math.Abs((dateTimeLeft – dateTimeRight).Milliseconds) < 100,
    “TimeSpan difference between dates is greater than 100 milliseconds.”);
}


No comments


NHibernate: The column name COLUMN_ID is specified more than once in the SET clause

December 9, 2009 NHibernate 4 comments

Sometime ago I faced with NHibernate issue and spent much time on figuring out how to resolve it. Issue was with saving complicated entity.
Error:

The column name ‘RESOURCE_ID’ is specified more than once in the SET clause. A column cannot be assigned more than one value in the same SET clause. Modify the SET clause to make sure that a column is updated only once. If the SET clause updates columns of a view, then the column name ‘RESOURCE_ID’ may appear twice in the view definition.

With NHibernate Profiler I found that this fails on the next SQL: 

UPDATE SOME_TABLE SET SOME_COLUMN1 = ?, SOME_COLUMN2 = ?, RESOURCE_ID = ?, SOMETHING_ELSE = ?, RESOURCE_ID = ? WHERE SOME_TABLE_ID = ?

With better look you will see that there two times RESOURCE_ID mentioned so this looks like wrong mapping. But I was sure that everything is ok there.

This two References are wrong.
At first glance do you see why? At that moment I was not able also.

References(x => x.Resource)
        .Access.AsCamelCaseField(Prefix.Underscore)
        .WithForeignKey(“RESOURCE_ID”).TheColumnNameIs(“RESOURCE_ID”)
        .FetchType.Join();

References(x => x.ResourceRole)
        .Access.AsCamelCaseField(Prefix.Underscore)
        .WithColumns(“RESOURCE_ROLE_ID”, “RESOURCE_ID”)
        .FetchType.Join();

Here Resource has key (RESOURCE_ID).
ResourceRole has composite key (
ROLE_ID and RESOURCE_ID).

After long searching and many tries I found why mapping is not correct. Even have my explanation for it.

When we reference ResourceRole we already use RESOURCE_ID field, so when we setup Resource and say “Hey, there is one more RESOURCE_ID“, then NHibernate cannot find out how to update all this correctly.

Solution:
insert=”false” update=”false” attributes for one of references solves the issue.

In Fluent NHibernate it looks like:

.SetAttribute(“update”, “false”);


4 comments


NHibernate Criteria for Nullable property

December 7, 2009 NHibernate 2 comments

Image that you want to fetch friends from database by the First Name, Last Name and Age, which are properties of your class Friend. With NHibernate you could write query which will look like:

public IList<Friend> GetFriends(string firstName, string lastName, int? age)
{
    IList<Friend> friends = Session.CreateCriteria(typeof(Friend))
        .Add(Expression.Eq(“FirstName”, firstName))
        .Add(Expression.Eq(“LastName”, lastName))
        .Add(Expression.Eq(“Age”, age))
        .List<Friend>();

    return friends;
}

But it is wrong. Since Age is the Nullable type (int?), your call GetFriends(“Andriy”,”Buday”,null) will not get my record even if there is such in database and the column AGE is NULL there. So to request you need this: ageExpression = Expression.IsNull(“Age”); but it will not work for not null age.
For our luck there is AbstractCriterion so we can generalize our Expressions like here:

public IList<Friend> GetFriends(string firstName, string lastName, int? age)
{
    AbstractCriterion ageExpression;
    if (age == null)
    {
        ageExpression = Expression.IsNull(“Age”);
    }
    else
    {
        ageExpression = Expression.Eq(“Age”, age);
    }

    IList<Friend> friends = Session.CreateCriteria(typeof(Friend))
        .Add(Expression.Eq(“FirstName”, firstName))
        .Add(Expression.Eq(“LastName”, lastName))
        .Add(ageExpression)
        .List<Friend>();

    return friends;
}


2 comments