Alexander Beletsky's Development Blog: 2011-02

SeleniumCamp conference in Kiev

I had a chance to be present on a SeleniumCamp conference that took place 26 of February. It was first Selenium dedicated conference in a world, so it was bad idea to miss it. Moreover, my colleague from Dnepropetrovsk Anton was coming there also, so we had a good time to meet each other again.

Event has been organized by Xp Injection group. I've been listen those guys last year on Agileee, I also read their blog from time to time, so I was pretty confident of what is going be all about. Event took place in Bratislava hotel. Here is a brief summary of stuff I heard there:

  • David Burns was the one who did open speech. He is Senior Software Engineer in Test at Mozilla working as the Automation Lead in WebQA and one of Selenium Core commiter. David was describing Selenium 2 and WebDriver ideas as primary part on Selenium 2 framework. In spite of Selenium RC, Web driver:
    • Uses native browser API, so works much more faster
    • Reduces and clear API
    • More reliable
    It means that WebDrivers should be tool of choice for functional testing in nearest future. As far as I get Selenium 2 is not officially release and currently in Beta phase.
  • Kirill Klimov did an speech about his experience of deployment Selemium in company. He shared some pros and cons of each Selenium umbrella products: from Core to Grid. They stated to use Selenium from IDE, seems the most easy scenario of using functional tests. Then they switched to Core and RC. Kirill has very good understanding of "what's going on" and summaries speech with several recommendations I think very useful:
    • Don't be hurry to start up
    • Understand the difference in tools and pick up right one
    • Try to elaborate in several years perspective
    Slides from his presentation is here
  • Mairbek Khadikov shared his own vision of web applications testing automation. Through 2 years of usage Selenium they came up with bunch of tests and realized the power of automation. Most important that value shared between business and development. He touch such important issues as performance, tests isolations. It is very important to write tests that might be read by non-technical guys. In such case tests starting to be a part of project documentation and used not only be development team. He also noticed that test should be architecture to be run in parallel as early as possible, it is just matter of time then you going to run tests by Grid (for instance) and you will meet a problem. He did several examples of Tests written on Java, so developers had a little fun to see the code. His presentation is stored here.
  • Alexey Rezhchikov did one of the most impressive speech as for me. He works on huge and high complexity project(s) for Ebay Motors (as far as I got). They are dealing with complex requirements, multicultural, high loaded sites with difficult configuration management. He clearly described problems any big project meet in a way towards Release. Nevertheless, they've implemented and successfully using solution stack based on Selenium platform (not only). Using different level of testing to meet acceptance goal, they are very flexible in decision "go or not to go with automated test" and "what kind of test is OK for this particular scenario". I also bit impressed by usage a Feature Flags as opposite way of multibranch development. . His presentation here.
  • Nikolai Alimenkov was selling ideas of using Wiki as "live" requirements. The whole approach back us to Fitnesse ideas of keeping requirements in a Wiki-style storage, placing acceptance conditions into to tables and "somehow" run Fitnesse tests against target applications. With my big respect to Robet C. Martin, original developer of Fitnesse, I don't believe that stuff works. I don't believe that Product Owner will ever work with requirements in Wiki will run them. Moreover, it seems a big overhead to me to support all that wiki's in up-to-date in world of changing requirements. Nikolai showed Fitnesse based tools as Fitnium, Selenesse and some tests examples but it was to artificial to me. You can find his presentation here.
  • Nikolai Kolesnik seems to have a good plan to describe BDD, but was quite nervous and shy that interfered him to make a good speech. Nevertheless, he expressed his understanding and application of BDD for real projects, pitfals and solutions based on Selenium RC. You can find his presentation here.

In short, I enjoyed the conference.. but I would not say it is something I expected. Most speeches I visited, was a kind of "too many word's, too few real examples". Guys, please if you are talking about product for developers - show me the code. All the idea's of ATDD, BDD, Acceptance testing, Wiki are requirements are already sold years ago, don't do the job that is already done. But, show some your projects, show real test cases, show examples.

I would like to THANK my company who make it possible to me to visit this conference.

PS. for foreign guys: Bratislava hotel is very cold, avoid it to stay on winter time :).

Github commits activity widget

The most important factor about each open source project is how much community is active around this project. It is good to understand the factor. One of the indicators of activity is of cause commits to repository. You probably want to demonstrate how much active your project is by placing some information on a web site.

Having this idea on my mind I created github.commits.widget, small javascript that could be easily integrated to your website and show something like this:

Note, it is not just html pasted.. but widget added to this blog post.

The code is really simple for that:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script src="github.commits.widget-min.js"></script>
<script>
    $(function () {
        $('#github-commits').githubInfoWidget(
      { user: 'alexanderbeletsky', repo: 'github.commits.widget', branch: 'master', last: 5 });
    });
</script>  

To configure all you need to do: specify your github account, repository and branch to watch. For more documenation, please visit project page. If you like it and want to use it on your website, you are very welcome to do it! Please just give a little feedback to either by github, twitter or mail.

Implementation of REST web service adapter on .NET

The REST web services are quite common thing nowadays. Sure, web application just expose API through HTTP protocol, basically allowing any application to be integrated with. Simple? Yes, this is the power of REST, just simple. But vendor should consume the API somehow. The environment could really be different: .NET, Java, Python, PHP etc., and it it not so convenient to work with HTTP directly from your custom application. Instead of that you expect on "native" API that you work with like the rest of application: having a model, methods that returns of change model state. You expect on having Adapter - the entity which would adapt REST HTTP methods into your platform/language methods. I'm going to give example of creation such adapter for .NET code.

Doesn't matter what language you write it the steps of adapting is quite common, here they are:

Learn the API

Let's have Trackyt.net API as an example. First thing you need to do is to learn API. REST API differs much from site to site, depending of developers tools and choice. All you need to understand the exact methods you need, their signature and data they operate with. Let's take Authenticate method: so we see, it takes 2 arguments, email and password and in response it returns JSON object, containing operation result and API token. That means:

URL: http://trackyt.net/api/v1.1/authenticate

Will be transformed in such C# method, like Authenticate that receives email and password as arguments and return ApiToken as results. Note, ApiToken is first model class we identified.

And call like this:

http://trackyt.net/api/v1.1/af005f695d300d0dfebbd574a4b1c0fa/tasks/all

Is actually transformed in something like GetAllTasks that recieves ApiToken object and returns IList<Task>. Task is yet another model class we have to deal with.

This is a kind of analysis stage of implementation, you just need to understand interface and model.

Define interface and model

After you done you are ready to define interface:

public interface ITrackytApiAdapter
{
    ApiToken Authenticate(string email, string password);

    IList<Task> GetAllTasks(ApiToken token);
    Task AddTask(ApiToken token, string description);
    int DeleteTask(ApiToken apiToken, int taskId);
    Task StartTask(ApiToken apiToken, int taskId);
    Task StopTask(ApiToken apiToken, int taskId);
    void StartAll(ApiToken apiToken);
    void StopAll(ApiToken apiToken);
}

You see that all methods, defined in documentation are reflected as interface methods, all data accepted/returned by methods are defined as POCO.

public class ApiToken
{
    public ApiToken(string token)
    {
        Value = token;
    }

    public String Value { get; private set; }
}

public class Task
{
    public int Id { set; get; }
    public string Description { set; get; }
    public DateTime CreatedDate { set; get; }
    public DateTime? StartedDate { set; get; }
    public int Status { set; get; }
}

Integration testing

Is it possible to code without tests? I don't think so. So, what we are going to do - one by one, tests all adapter methods. That's should not be "super-duper-complex" test (at least during initial implementation), but rather smoke test ones. Do the call and see that results back. Here is just a several examples of tests for Authentication and GetAllTasks.

[Test]
public void Authenticate_AuthenicationSuccess_ReturnApiToken()
{
    // arrange
    var adapter = TrackytApiAdapterFactory.CreateV11Adapter();

    // act
    var apiToken = adapter.Authenticate(_email, _password);

    // assert
    Assert.That(apiToken, Is.Not.Null);
    Assert.That(apiToken.Value, Is.Not.Null);
}

[Test]
[ExpectedException(typeof(NotAuthenticatedException))]
public void Authenticate_AuthenticationFailed_ExceptionThrown()
{
    // arrange
    var adapter = TrackytApiAdapterFactory.CreateV11Adapter();            

    // act
    var apiToken = adapter.Authenticate("nouser", "noemail");
}

Implementation

There are 2 very suitable components you might use for any REST API adapters:

  • James Newton JSON.net library - the best framework to handle JSON's in .NET (imho). I enjoy how easy to serialize and deserialize of data with JSON.net.
  • WebClient object - that is part of .NET framework and encapsulate all basic HTTP functions.

Here we go. Our task is to send HTTP request to server, check it for correctness and transform server reply to .NET objects. To do that is great to model all responses into POCO (as we did with model classes ApiToken and Task). The difference is that Responses are actually internal classes, part of implementation and adapter users should know nothing about them. For instance let's see AuthenticationResponse

class AuthenticationResponse : BaseResponse
{
    internal class ResponseData
    {
        [JsonProperty("apiToken")]
        public string ApiToken { set; get; }
    }

    [JsonProperty("data")]
    public ResponseData Data { set; get; }
}

The base response is some common part of data that every response suppose to contain. In my case:

class BaseResponse
{
    [JsonProperty("success")]
    internal bool Success { set; get; }

    [JsonProperty("message")]
    public string Message { set; get; }
}

We should deserialize responses with JSON.net and send requests with WebClient. Let's just see simple code example:

public ApiToken Authenticate(string email, string password)
{
    using (var client = new WebClient())
    {
        var authenticationJson = JsonConvert.SerializeObject(new { Email = email, Password = password });
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        var responseString = client.UploadString(ApiUrl + "authenticate", authenticationJson);
        var response = JsonConvert.DeserializeObject<AuthenticationResponse>(responseString);
        if (!response.Success)
        {
            throw new NotAuthenticatedException();
        }

        return new ApiToken(response.Data.ApiToken);
    }
}

It simply creates new WebClient instance, UploadString method perform's POST by default and places string object as POST payload. Then we receive response as string and try to deserialize to target response type. In case it could not serialize that, exception will be thrown. Next, it check result of operation and return required data back to client.

The implementation of the rest of methods is mostly the same, differing by type of HTTP request (GET, POST, DELETE, PUT) and request/response objects. Let's see GetAllTasks method that does GET request and returns all users tasks:

public IList<Task> GetAllTasks(ApiToken token)
{
    using (var client = new WebClient())
    {
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        var responseString = client.DownloadString(ApiUrl + token.Value + "/tasks/all");
        var getAllTasksResponse = JsonConvert.DeserializeObject<GetAllTasksResponse>(responseString);

        if (!getAllTasksResponse.Success)
        {
            throw new Exception("Can't get users tasks. " + getAllTasksResponse.Message); 
        }

        return getAllTasksResponse.Data.Tasks;
    }
}

As reference I'll give you implementation of trackyt.api.csharp by me and GithubSharp API by Erik Zaadi.

Refactoring to testability

Suppose you are working on some web REST API adapter. It would be basically one class with bunch of methods. Each method would represent each supported API call. Through the implementation you would probably landed with something like this,

public class ApiAdapter
{
    private HttpClient _client;
    private RequestFormatHelper _requestFormatHelper;
    private ResponseFormatHelper _responseFormatHelper;

    // ...
    
    public ApiAdapter()
    {
        _client = new HttpClient(/* ... */);
        _requestFormatHelper = RequestFormatHelper(/* ... */);
        _responseFormatHelper = ResponseFormatHelper(/* ... */);
    }

    void CreateNewTask(Task task)
    {
        // implementation
    }

    void DeleteTask(Task task)
    {
        // implementation
    }

    // rest of methods...
}

Nevertheless, the code works it has several code smells:

  • High cohesion - the relation between objects are really strong. Objects are aggregated and aggregation is the one of strongest types of links between objects.
  • Violation of Open/Closed principle - one of the SOLID object oriented design principles.
  • Lack of testability - if you decide to unit test this code, you will be in problem. Unit testing is supposed to be done in isolation. Having high cohesion code you can't get required level of isolation. Moreover it is not possible to substitute concrete class with mock object by using some famous JMock, RhinoMocks or Moq.
  • Lack of flexibility - if you decide to change implementation of some of depended objects, say ResponseFormatHelper you would probably change the implementation of ApiAdapter as well.

If you think that you code is not testable or flexible, don't waste your time.. apply the power of refactoring.

What to do? It is basically very simple to correct such code, you just need to follow this:

  • Always hide the details behind the interface - all behavior objects must conform to particular interface. Other objects must refer to another object only with knowledge of the interface. In terms of programming languages, if you pass object to client code you must always pass it by interface (e.g public SomeAction(IHttpClient client, Type type, Data data);.
  • Use dependency injection for louse coupled code - try to avoid to create depended object by new, inject the dependency by constructor of public property. (e.g public ApiAdapter(IHttpClient client, IRequestFormatHelper requestHelper, IResponseFormatHelper responseHelper).

How the code might look after refactoring:

public interface IHttpClient
{
    void WebCall(/*...*/);
}

public interface IRequestFormatHelper
{
    string Format(/*...*/);
}

public interface IResponseFormatHelper
{
    string Format(/*...*/);
}


public class ApiAdapter
{
    private IHttpClient _client;
    private IRequestFormatHelper _requestFormatHelper;
    private IResponseFormatHelper _responseFormatHelper;

    // ...

    public ApiAdapter(IHttpClient client, IRequestFormatHelper requestFormatHelper, IResponseFormatHelper responseFormatHelper)
    {
        _client = client;
        _requestFormatHelper = requestFormatHelper;
        _responseFormatHelper = requestFormatHelper;
    }

Now, you can easily test this code using mocks, like this simple test:

[Test]
public void CreateNewTask_SendPutRequest_WithJson()
{
    // arrange
    var client = new Mock<IHttpClient>();
    var requestFormatter = new Mock<IRequestFormatHelper>();
    var responseFormater = new Mock<responseFormatHelper>();

    // act 
    var api = new ApiAdapter(client, requestFormatter, responseFormater);
    api.CreateTask (new Task());

    // arrange
    client.Verify(client.WebCall(/*...*/)).Called().WithArguments(/*...*/;
}

And change any details of injected objects, without any changes in ApiAdapter. Refactoring to testablity is important, as much testable code you got as much flexible code you got.

ASP.NET MVC controller's action with name View()

If you want to have action with name View in your controller, you will meet a small problem. Base class of any controller Controller already contains a method, with same name (and it is overloaded):

protected internal ViewResult View();
protected internal ViewResult View(IView view);
protected internal ViewResult View(object model);
protected internal ViewResult View(string viewName);

So, you code like this:

public ActionResult View(string url)
{
    // some action logic...

    return View();
}

Won't complied, because you are adding method with same signature (name and parameters list). You have 2 options here: gave up to compiler and rename action, to something new like ViewPost or insist and try to make it happen.

Fortunately C# have beautiful feature for doing this. It is new Modifier. It hides the member on base class and explicitly says, that now your method is substituting it. So, everything you need is basically this:

new public ActionResult View(string url)
{
    // some action logic...

    return View();
}

It will make application compliable and work as expected.

Ninject provider as factory method

Ninject is a very nice and easy to use, open source dependency injection framework. It is very popular within ASP.net MVC developers community and de-facto framework of choice for MVC applications.

I was implementing small feature recently. As user registered on site, he receives confirmation email and registration details. Pretty common functionality along the sites. So, I add next application service INotificationService that took responsibility of sending email message to user. Nothing special, nothing complex.

namespace Trackyt.Core.Services
{
    public class NotificationService : INotificationService
    {
        private IEMailService _emailService;

        public NotificationService(IEMailService emailService)
        {
            _emailService = emailService;
        }

        public void NotifyUserOnRegistration(string usersEmail, string password)
        {
            var emailMessage = CreateEmailMessageForUser(usersEmail, password);
            _emailService.SendEmail(emailMessage, "support");
        }

        //...

As I've tested and integrated it to application, everything were just fine. Till the time I reset database and re-run tests. The problem, that INotificationService itself depends on IEmailService that uses ICredentialsRepository to extract email server credentials (account, password, settings) from database. After database is reset, Credentials table is just empty and IEmailService throws exception that there are no credentials, so send email is impossible. I could not add credentials as SQL to database script, since it depend on configuration and exposes private password. Do it manually after each reset of database is boring task. Furthermore, I don't want my application to send any emails as I just do some development testing.

The obvious design workaround is - define INotificationServiceFactory that responsible for NotificationService instantiation. Factory decides, if application run in debug mode, just stub of NotificationService is used, otherwise real implementation is used.

namespace Trackyt.Core.Services
{
    public class NotificationServiceFactory : INotificationServiceFactory
    {
        public INotificationService GetService()
        {
            if (HttpContext.Current.IsDebuggingEnabled)
            {
                // just stub..
                return new NotificationServiceForDebug();
            }

            // here I need to pass EmailService to constructor
            return new NotificationService ( // ??? );
        }

        // ...

But it is not so easy as it seems to.. Here the problem: NotificationService have to accept EmailService, that have to be created created by DI framework (I could not create it by new since I loose all benefits of inversion of control). So, in factory I need to have a IKernel object - Ninject core object, for instantiating of objects from Inversion of Control container. It should be extended with constructor taking IKernel as argument.

Issues:

  • Circular dependency - factory is defined in Core assembly, kernel is defined in Web application.. Web application references Core, to make it work now Core need to reference Web (it is actually possible, but very ugly.. I try to avoid such things).
  • Additional references - now Core also need to reference Ninject, to make it compliable.
  • Violation of Dependency inversion principle - one of the SOLID principles of object oriented systems. Model must not depend on infrastructure.

Fortunately Ninject provides functionality to avoid issues mentioned above! Instead of binding to exact type, like


    Bind<INotificationServiceFactory>().To<NotificationServiceFactory>();

I can bind creation of type to Provider:


    Bind<INotificationService>().ToProvider<TrackyNotificationServiceProvider>();

Provider is class that implement IProvider interface, which is actually just one method CreateInstance. CreateInstance, receives IContext object as parameter that contains IKernel. TrackyNotificationServiceProvider is placed on same level as the rest of Ninject infrastructure code is placed. Model remains clear and exact and do not mess up with infrastructure code.

namespace Web.Infrastructure
{
    public class TrackyNotificationServiceProvider : Provider<INotificationService> 
    {
        protected override INotificationService CreateInstance(IContext context)
        {
            if (HttpContext.Current.IsDebuggingEnabled)
            {
                return new NotificationServiceForDebug();
            }

            return new NotificationService(context.Kernel.Get<IEMailService>());
        }
    }
}

Now, in case of INotificationService object need to be instantiated (in my case it is injected to RegistrationController as constructor parameter), CreateInstance is called. If web.config contains <compilation debug="true" targetFramework="4.0"> the stub of service is created. On production, where <compilation debug="false" targetFramework="4.0">, real instance of NotificationService is put to work.

Extension methods and clean code

Extension methods is one of my favorite features of C# language. It appeared from version 3.0 and became very popular.

The main goal of Extension Methods is to provide ability of extension of any class, without creating any derived classes, modifying original type or do "whatever" hacks. It is allowed to extend any type with any functionality in a very seamless fashion. What also great about Extension Methods is they allow to beautifully emulate behavior usually called pipelining (in F# or Bash) and implement Chain of responsibility pattern.

But the most important as for me - Extension Methods help to keep my code clean. Clean code criteria is something I concerned a lot, nowadays.

I recently started to practice with code katas, that I found essential for any developers who cares about keeping their saw sharp. So, after several iterations I came up with extension methods implementation that I pretty happy about. I'm using Roy Osherove's StringCalculator kata. It is about the implementation of simple method Add that:

  • Takes numbers separated by delimiter, as string
  • Determines if custom delimiter is set
  • Split up original string to array of number tokens
  • Validates the input (no negatives allowed) and returns the sum of numbers, ignoring numbers greater than 1000

I would like to show to you both implementation and try to evaluate them from "clean code" point of view.

Original one (this is of cause a little "unwinded" version, I had a different structure with smaller methods.. But idea still the same).

public int Add(string numbers)
{
    var delimiters = new[] { ",", "\n" };

    if (IsCustomDelimeterProvided(numbers))
    {
        delimiters = GetDelimitersFromNumbers(numbers);
    }

    var processed = numbers;
    if (IsCustomDelimeterProvided(numbers))
    {
        processed = processed.Substring(processed.IndexOf('\n') + 1);
    }

    if (IsContainDelimeters(processed, delimiters))
    {
        var splittedNumbers = numbers.Split(delimiters, StringSplitOptions.None);
        var validation = new NumbersValidation();

        foreach (var number in splittedNumbers)
        {
            validation.Check(number);
        }

        validation.Validate();

        return splittedNumbers.Sum(p => GetIntegerWithCondition(p, IgnoreNumbersMoreThatThousand()));
    }

    return Convert.ToInt32(processed);
}

Do you think is this code clean? I don't think so.. Of cause, it might be not so difficult to understand it, but:

  • Method is just too long
  • A lot of if statements make it difficult to see instruction flow
  • It messes up "infrastructure" code (splits, validation) with primary functionality (sum of numbers)

Let's try to read it: I got the numbers and I check if custom delimiter is set on the beginning of numbers string, if so I try to extract the custom delimiters from original string. After I pre-process the string to remove custom delimiter prefix, so do not break the rest of function. If numbers string contains the delimiters, I split it up, perform the validation by helper object (which will throw exception is something wrong). Run Sum algorithm that would: covert string to integer and ignore one if it is greater that 1000.. Otherwise, it just tries to convert to integer and return.

A lot of words, a lot of ifs isn't it? Thats not good.

Now, my last implementation with using of Extension Methods:

public int Add(string numbers)
{
    var defaultDelimiters = new string[] { ",", "\n" };
    var delimiters = numbers.CustomDelimiters().Concat(defaultDelimiters).ToArray();

    return numbers.Replace(" ", "").Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
        .RemoveSpecialSymbols().ToIntegersArray().ValidateIntegersArray().IgnoreIntegersGreatThanThousand().Sum();
}

Do you feel the power? I definitely do!

I believe that this code is very clean. It basically does not require any comments, because it looks like "plain English" explanation of what's the functionality is all about! Anyway, let's try to read: I extract custom delimiters from numbers string and concatenate them with default delimiters. I replace all space with empty symbol (note: this step is not in original requirement, but I put it to keep code robust), then I split them with delimiters ignoring empty lines. After I remove all special symbols in numbers string and convert the result to array of integers. I validate this array (no negatives) and ignore any numbers great than thousand. At the end I sum up everything and return the result.

What is good about this code:

  • Method is very short
  • All details are hidden
  • Control flow is very straightforward
  • All dependent methods has meaningful names
  • Method does exactly what it is suppose to do

Conclusion

Well, don't get me wrong here. I'm not saying that now only Extension Methods is a way of solving the issues. Of cause not. But if you feel the smell of pipeline of chain of responsibility patters, extension methods are right choice. As always you should consider to do not "overplay" with some particular feature of language/framework.

You can use links I gave above to read about technical details in MSDN. Check out full implementation and tests as my example of usage.

How to export SQL data script for SQL Express 2008 R2

Before deployment of new version of my application I wanted to make sure that everything is alright, by doing development test on my machine. I backed up production database and copied it my local environment. Task was easy, restore database from backup and run all unit/integration tests, run the smoke test of application manually. But as I started to restore database I got such error from my SQL Express Management Studio:


TITLE: Microsoft SQL Server Management Studio
------------------------------

Restore failed for Server 'LOCAL\SQLEXPRESS'.  (Microsoft.SqlServer.SmoExtended)

------------------------------
ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: The database was backed up on a server running version 10.50.1600. That version is incompatible with this server, which is running version 10.00.2531. Either restore the database on a server that supports the backup, or use a backup that is compatible with this server. (Microsoft.SqlServer.Smo)

Basically it meant that my production and local environment are different. On production I have SQL Express 2008 R2, locally I have SQL Express 2008. It was a surprise to me, cause my WebPI shows me that I'm upgraded up to R2.

Anyway, I had no time to upgrade my local environment and I did very simple workaround that might work for you as you don't have very big database to handle.

There is a feature of SQL Express (and Server) that allows you to export your database as SQL script and you can run this script on local SQL instance and got exactly same version.

It is easy taks, but by doing that initially I successfully exported schema only, but not data itself. So, script generated didn't contain and INSERT statement. As it turns out you have to change some default options, to export both schema and data. Follow the instructions:

  1. Expand your database list and right click on target database.
  2. Select "Tasks" -> "Generate Scripts" context menu item. Generate scripts wizard will open.
  3. Press "Next" on welcome screen and select your database from databases list.
  4. Make sure you checked option "Script all object in selected database" if you want to script all db. In case you need only some particular table you might consider to select it later. Click "Next".
  5. On Script option step, make sure to select "Script Data" option (this is exactly what I missed and didn't understand why data is not present in final script).
  6. Proceed to the end of wizard to complete it.

At the end you will got SQL script with schema and data that you can run on SQL Express 2008 and got exactly the same database as on R2.

This helped me quickly to workaround "version incompatibility" issue, hope it might help you as well.

Val Gardena (Dolomites) trip 2011

It is over. It was one of my best vacations ever. We had a chance to see a lot of beautiful spots, especially in Venice and Gratz and had great snowboarding times on Val Gardena area slopes.

As I said in previous post, this time we did plan our trip more carefully. Without long night driving and staying in hotels for night to have a rest. We went out of the Kiev early morning (about 3.00) and went to west Ukraine border to small town - Astey where we crossed the border to Hungary. This time we are 2 cars team. Connected with radio stations, we feel like a professional rally riders for a long test drive trip :).

Dmytro (the manager of our trip) booked very nice hotel All-4 U in center Budapest. Living in center has pros and cons, of cause.. It is good that you could walk to main city POI's, but it was very (very!) hard to find hotel and find a parking place for car. Center of Budapest is in heavy maintenance now, so our GPS were guide us through streets that are closed for traffic now. We finally found hotel but it was located in very small street, with no free parking places so we did several circles, to finally hit the entrance and underground parking.

So, at the morning we had a quick breakfast and went to Venice, Italy. Nothing more as so good as driving by Euro highways. It is easy and safe and fast. Our path to Italy were made through Slovenia. Slovenia is very beautiful country and we very much enjoyed the ride. Near the 20.00 we came to hotel Alteri near Venice. We had a quick shower and preparation, got a bus tickets and went to city. Since we were really hungry, first place to visit was some restaurant to get some food. The owner of hotel recommended us some place and we went there. It was a quite small place. Food and vine were just perfect, very tasty. I was a little nervous about the price, but as I glanced to menu I was happy to see that prices are not overhigh. It is even lower that some expensive restaurants in center of Kiev.. but could you compare Kiev and Venice, with number of tourists, attractions? No way..

Venice is town on water. No transport, no cars, nothing. Only walking and using gondolas to go by chanells. Since we came on night, not a lot of tourists were in town that time. Some times it really created illusion that we are alone there! So quite, so small streets with small bridges.. so magical! If you are not familiar much with Venice you really think it is like maze. We lost several times but it was really fun. Andrey, the guy who held the map and was showing directions, was doing a great job to save us, but is was like that: "Now, let's turn right, pass the bridge.. turn left and right again and bla-bla", but after 10 minutes we were on same place we started with :). Fanstastic.

Venice streets

Main channel

Beautiful bridge

Next morning we had just a several hours to have a walk, so we were hurry to Venice again. At morning it looks really different. You can see much more details of cause (like, how all those building are really old.. or color of water in channels), but now it is overcrowded with tourists and souvenirs dealers. So the magic just gone :). But still a lot of shops and churches are opened, so you might have a chance to visit those.

Sashka near one of the channels

Together on San Marko

Gondolas

The weather were fine, but wind were quite cold. Late January is probably not the best time to visit Venice, but anyway I had a lot of pleasure to be in this legend place.

We packed our bags and went to target point of our journey, St. Christina. We were driving by highway, with a very sunny weather behind the car glass, seeing a lot of vineyards. Outside view was so warm that it was to difficult to imagine that somewhere is cold and snow covered peaks of mountains.

We came to St. Christina at evening, it was -4C and we climb to 1650m over sea level. It was dark already so we could not see mountains, but the air was so fresh and so nice that it could be only in Alps. We were exited about next 6 days! Val Gardena is huge and you might have everyday snowboarding in different places. So, it was a good idea to take good rest before exploring the mountains.

Val Gardena meet our expectations for sure! I've never seen so much exceptional view as from Seceda or Marmolada tops! Really-really beautiful landscapes. The killer feature of Val Gardena area is Sellaronda. Sellaronda is a circuit around Sella mountains massif.. Big number of slopes and lifts that makes it possible to feel all beauty of Dolomites. You can do the circuit in 2 directions, green one and orange one. They are mostly equal.. orange just contains a bit more red and black (more complex) slopes. Green one can be used by everyone, even if you are not so confident in skies or snowboard. It took about 3-4 hours to complete the circle.

Sella

Great sunny day

Sashka

Me going down the slope

The biggest disadvantage of Val Gardena - it is overcroweded. Despite of huge area, you typically will be in long waiting lines for lifts on a popular slopes (especially ones that are on green or orange route). Besides of that just before our period of stay it was a quite warm weather there, without out big snowfalls, made slopes very hard and icy.

Marmolada is highest point of resort. According to wikipedia it is even seen from Venice on clear day. We dedicated one day for trip to Marmolada. It took almost 6 hours to me and Sasha to make possible to get on top and back to St. Christina. Even it took a lot of time to get where and spent a time in long waiting lines, as soon as you take a view from top you immediately forget about all bad things!

Exceptional view

Europenean Rocky Mountains :)

And I really-really much enjoyed the run from Marmolada back to valley. That was fantastic.

We've spend one evening in Ortizei looking for a fun public places, but have found nothing.. except one small bar where ski-instructors were getting drunk after hard work days :). Despite of Ischgl Apre-ski is not so popular in Italy, so after skiing we usually went home, preparing food and did our small parties.

6 days of snowboarding went very fast. Originally I planned to read some books and small coding stuff, but in evenings I was so tired that after a good dinner, usually with grappa or other alcohol, all I could do is only crawl into bedroom direction :). Our snowboarding times getting over, but way back-home with visits of Gratz and Lviv was waiting for us. Moreover, I've lost my camera in Budapest hotel, so we had to be there to take it back :).

Gratz is quite big city in Austia. Since we had not a lot of time, we visited only two Gratz's spots, as Grazer Schloßberg and Kunsthaus. Schloßberg is a castle on mountain, you can get there either by foot or take a lift. From the mountain you might have very nice Gratz views.

Way to Schloßberg

View from mountain

Kusthaus

Kusthaus is a museum of the modern art. Unfortunately, main space of museum were closed the time we visited it.. and the stuff I saw didn't impressed me much. We paid for tickets, entered the hall see several small rooms with devices pretended to be robots and after museum worker said: "That's basically it, goodbye". Not fair.

We've spend some time to find a place to eat.. Some restaurants were closed already that time, some was so luxury with man's wearing smoking and lady's in long evening dresses, that we could not conform to their companies :). I started to lose hope and recalling do we still have those crackers in hotel, but finally we found something. Austrian dishes differs from Italian ones. I liked Italian more, but anyway it was good and tasty.

So, next morning we were moving directly back to Ukraine, with one small stop at Budapest to get camera back :). We did a route fast and easy and soon was on Ukrainian customs. Faces of custom workers immediately return you to "Ukrainian Reality". Fortunately they were to lazy to check our car, because we a little violate the law of amount of alcohol you allowed to bring in. After the customs you are completely back to earth with the roads you have to drive. Leaving Ukraine is easy stuff, but getting back is very depressing :). Roads are awful, full of wholes and without any road markings and lightings makes it really hard to drive. Situation is complicated with a big number of trucks moving from a border of Ukraine, with a low speed.. so you all the time have to practice in overtaking. In night, with limited far view it is difficult, scary and dangerous. First car crew was helping us a lot by moving forward and giving a directions and recommendations of safe overtaking.

I hardly could imagine how people from Europe will be driving to Ukraine to see Euro 2012.

In spite of everything we came to Lviv, one of the most beautiful places in Ukraine. Similar to Budapest, the center of Lviv is not very car-friendly. Small streets, block pavement, trams makes the problems. But now we are home, feeling that most problems are in past :). While we approached Lviv, we've booked appartments to live and table in one of the best places in Lviv called Kumpel'. They produce great beer (I like dark especially) and very nice dishes. After ~600km of road having a big glass of cold and tasty beer is great fun, believe me :).

Walking Lviv streets

Chimera on house

Ukrainian delicious "Salo" with dark bread and garlic - great taste

We got to Kiev, mostly with no serious at 15.00 next day. I was mostly sleep all day with a little driving before Kiev.

"East or west the home is best", as saying goes.. We finally entered own city. Had a good bye by radio station with guys, saying "see you next year", we landed near my house to unpack the bags and snowboards.

That was a great trip for sure! We did 3,908 kilometers in total. We had no injuries, no car damages. Visited greatest places and had snowboarding that I'll be seeing in my night dreams in summer. You can find some more picture here. Now, it is time to work again.. to learn new things, to blog and self-improve. Thanks a lot if you read till this point :).