28 September, 2014

varchar vs nvarchar

What are the differences between varchar and nvarchar in Microsoft SQL Server? Question quite common on the recruitment tests, but the question: when and why we should use this one or this one is not so simple.

First, let’s take a look what are varchar and nvarchar:

  • nvarchar- variable-length, it takes more space than varchar, can store any Unicode data, dependent on the database collation,
  • varchar - restricted to an 8-bit codepage (but not in every collation), single-byte character data, it takes less space than nvarchar, it cannot contain Unicode characters, the database collation determines which code page the data is using.

The next question which we should ask ourselves is: when we should use varchar and in which situations we should use nvarchar ?

nvarchar: - When your application need to be translated to e.g. Arabic, Mandarin, Hebrew, Japanese or other languages with 16-bit encoding, or at least there is a big possibility that it will be translated in the future. - When your application will use very small database, you can use nvarchar (for convenience) for every text column. - When you do care more about convenience than disk space, memory and effectiveness.

varchar: - When you will NEVER use Unicode. - When performance and effectiveness is important for you. - When you want to save some space and memory.

Before choosing one of those two types remember about the following things:

  • Changing the data type from varchar to nvarchar and vice versa is very expensive, especially if the project is in a later phase.
  • When system has a big data base and the effectiveness is important, consider using varchar – it is faster.
  • You should not do this, but … if you make JOIN on the columns with varchar and nvarchar, then there is a big performance hit.
  • When you are using nvarchar in stored procedures or scripts use prefix N (e.g. DECLARE @name = N'The name';) which prevent string type conversions at runtime.

Summarizing: choice between varchar and nvarchar depends on what type of application you are writing and what is important for you (effectiveness or convenience).

31 August, 2014

UI Holy Grails part 1 - how to set two controls in one line

Everyone, who at least once was making an UI for the web application, met this problem: how to center vertically two controls, which are in one container side by side? One of them is higher, the second one lower, and when you finally set them up correctly – the div below the container double its height! Arrrrrgh! Chill out, deep breath and continue reading this post.
Imagine you have simple div with two controls: label and input like below.
    
You want label and input to be side by side with the vertical center on the same line. Nothing simpler, isn’t it? In fact … no! In simple web applications with very small, simple CSS usually there are no problems with correct position of the controls, but when there are many style sheets, which are overwriting each other classes, then the problem with the proper location is quite common. Sometimes it is very hard to determine where is the CSS line that causes the problem is.
To fix that problem you should firstly use F12 tools to find which line in which CSS is responsible for incorrect position of the controls and then you can start customization of the CSS. On the list below I have gathered, basing on my experience, some ideas which may help you in resolving of this problem. Some of them are very simple, but I was trying to make a compilation of ideas that I have seen during last 3 years.
  • Set up vertical-align value to “middle”. It seems to be obvious, but sometimes, especially when you were using some upper (or lower) index, the value of this align might be different.
  • Take a look into the height of the container which contains our two controls. Maybe it has correct setting, but our two controls are too short. In this case try to set the height property of our two problematic controls to 100%. Sometimes filling of the container height with the controls can help, especially when the container has correct settings. Remember to check the max-height and min-height properties of the container and the controls.
  • Very popular, but not easy to use with other elements in complicated structure of HTML tags (e.g. ASPX webpage) is line-height. This property changes the height of a line (“row”) which contains the given control. Sometimes it occurs that the line-height of the controls differs between each other, so it is better to set for them the same value and remember to check the line-height of the container itself. The next thing to remember is to test if the line-height did not impact other controls on the website.
  • In some cases, a good solution is to check if there are some paddings or margins added to our problematic controls itself. Changing of the padding and margin values might be helpful, especially when the controls inherits the values from the container.
  • The last solution, which is strange but sometimes helpful is using of the float property with the value “right” or “left”. “Float” removes the control from the normal object constructions. It means that some of the properties are being turned off, when we decide to use float: left or float:right. In some cases using of this property will not fix the problem, but it will give clue where you should be looking for the problem. It might occur, that the e.g. the margin, absolute position or left / right property is a problem.

If you have more ideas for resolving this problem share it in a comment.

24 August, 2014

ForEach != foreach

It is very often that we have to make some operations on every element in the collection. The most popular ways of doing this is to use a “for” or ”foreach” loop. Here are three ways of doing this:

  • “For” loop – One of the oldest loops known to the mankind. It is the easy solution to get e.g. particular element of the array, but it is not the most efficient way of iterating over collections.
  • “foreach” loop – This is a newer type of loop which iterates over the whole collection of objects. It is easy, it is fast and you can use it on every ICollection and array.
  • "ForEach" – Public method of the generic list which, from the definition: Performs the specified action on each element of the System.Collections.Generic.List. This is considered as the fastest way of doing some operations on every element of the generic List.

At first it seems that the classic “foreach” and generic List “ForEach” are the same, there are some significant differences. Here is a very simple example of them suing the most popular collection: generic list.

Let’s create a list of strings and populate it with come Guids:

List listOfStrings = new List();
            
            for (int i = 0; i < 1000000; i++)
            {
              listOfStrings.Add(Guid.NewGuid().ToString());  
            }

Now initialize a new list which will be holding changed values from our first list:

List listOfNewStrings = new List();

And now we will do some operations on each element of the collection using classic foreach:

foreach (string s in listOfStrings)
            {
                if (s.Contains("6"))
                    continue;
                else if (s.Contains("4"))
                    return;
                else
                    listOfNewStrings.Add(string.Format(s + "{0}", "SUFIX"));
            }

Everything is ok, the code is compiling and now we will do the funny part. We will make some operations on every element of the list using the generic list ForEach method:

listOfStrings.ForEach(s => 
                {
                    if (s.Contains("6"))
                        continue;
                    else if (s.Contains("4"))
                        return;
                    else
                        listOfNewStrings.Add(string.Format(s + "{0}", "SUFIX"));
                });

And here is the surprise- the code is not compiling. We do the same operations on the same list so what is going on?

The answer is quite simple: ForEach from the System.Collections.Generic.List is not a loop, but a normal method. As it is not a loop, then we cannot break it or continue.

ForEach, as an argument, takes the System.Action delegate. This action will be performed on each element of the list. In other words: we do some operations on each element of the list, but we cannot “break” the execution or “continue” the execution, we can only exit ForEach using return. Remember that ForEach is a function, so we return only from the ForEach and pass the control to the function, that started ForEach execution and in case of “foreach” loop – return will finish execution of the whole function.

The advantages of using “ForEach” are the ease of use, readability and ForEach can modify the list over which it is iterating, so if we do not need to use break or continue inside the loop, we can use the ForEach on the generic List.

12 August, 2014

Unit testing with authentication

When we are developing an application that will be integrating with third party system, we often face the problem of testing some methods, that are using common session, which ID is being returned to us as a result of Authentication process. I have met this problem many times, when I was making integration with ERP systems, WMS's and lately, with eCommerce. I was wondering: how the hell I can write the tests of many methods, using the same session, and make them independent?

I have found some ideas on the blogs and in the articles:
  • Some developers were advising to create one huge test with many assertions, which will start with Login (Authenticate, LogOn, StartSession etc.) method and end with Logout (CloseSession, LogOff, etc). This idea is OK, but it is NOT a UNIT test.
  • Other developers were advising to use some unit testing libraries that enable passing the state between test methods. This idea is also OK, but this is the way of creating integration tests, not the unit tests!
  • The last idea was to log in before and log out after every operation in each unit test. This will also work, but you have to repeat a lot of code, which is a very bad habit.

Finally I have found a solution: IUseFixture interface in xUnit. The framework is very easy to use and unit testing of e.g. API of third party web services is very easy. Here is an example...

Imagine, you want to run some methods of a WS*, which is an API for the ERP system. You want to take some data from the WS*, but you need to be logged in and have a session id. The best way to do this is to use IUseFixture interface.
It is a generic interface, which bases on type, that must by disposable. For example if you want to create session before running each test method and close it after running of each method, you can create your base type like this:

using ThirdPartySystemTests.Service;
using System;

namespace ThirdPartySystemTests
{
    public class SessionFixture : IDisposable
    {
        private SessionHelper sessionHelper;

        public SessionHelper LogOnUser()
        {
          sessionHelper = new SessionHelper();
          sessionHelper.Client = new ThirdPartySystemClient();
          sessionHelper.SessionId = sessionHelper.Client.login
                                   (
                                    sessionHelper.LOGIN, 
                                    sessionHelper.PASSWORD
                                    );
            return sessionHelper;
        }

        public void Dispose()
        {
            bool sessionClosed = 
              sessionHelper.Client.endSession(sessionHelper.SessionId);
        }
    }

    public class SessionHelper
    {
        public ThirdPartySystemClient Client { get; set; }
        public string SessionId { get; set; }
        public string LOGIN = "User";
        public string PASSWORD = "Password";
    }
}


This disposable type has 2 methods: first method creates session on the ThirdPartySystem and the second one closes this session on disposal of the SessionFixture object.
Now it is time to implement tests of ThirdPartySystem using xUnit test with our SessionFixture.

using ThirdPartySystemTests.Service;
using System;
using Xunit;

namespace ThirdPartySystemTests
{
    public class Tests : IUseFixture
    {
        private SessionHelper sessionHelper;

        public void SetFixture(SessionFixture sessionFixture)
        {
            sessionHelper = sessionFixture.LogOnUser();
        }

        [Fact]
        private void GetProductsListTest()
        {
            Product[] products = 
               sessionHelper.Client.GetProductList(sessionHelper.SessionId);
            Assert.NotEmpty(products);
        }

        [Fact]
        private void GetCustomersListTest()
        {
            Customer[] customers = 
               sessionHelper.Client.GetCustomersList(sessionHelper.SessionId);
            Assert.NotEmpty(customers);
        }

        [Fact]
        private void CreateProductTest()
        {
            Prodcut product = new Product
            {
                Name = "Laptop",
                Price = 1000,
                Quantity = 20
            };
            int productId = 
                 sessionHelper.Client.CreateProduct(sessionHelper.SessionId, product);
            Assert.True(productId > 0);
        }
    }
}

Now the LogOnUser method will run before each execution of every test in the class, that implements IUseFixture so you have a new session every time the test runs. What is more, on disposal of the IUseFixture (it means at the end of execution of the test) the session will be closed.

As a result, you have a independent set of unit tests, which do not have any connections and can be run separately. This solution is elegant, easy, safe and it observes the principles of unit tests.

You can also use IUseFixture to e.g. run methods from the base types, create configuration of some objects in the database, prepare data for further operations etc.

04 August, 2014

Welcome to my blog!

Welcome everybody on my blog!
I was thinking about starting the blog for more then a year. Finally, I have decided to start describing solutions of some problems, that I meet in my everyday work as a software developer. I hope you like it and find it useful.