Latest Posts

<< >>

Getting started with node.js

What is node.js? node.js is a development platform based on Javascript created by Ryan Dahl and currently maintained by the cloud provider Joyent. The interesting thing about node.js is that it runs in a single thread, and attacks concurrency by trying to block as little as possible (if at all). In it’s most simplistic form, [...]

Unit Testing and Test Driven Development (Lessons Learned)

I started a discussions with my colleagues at Tellago about Unit Testing and Test Driven Development, and a lot of interesting things came out of that discussion. Here are my thoughts. Unit Testing Unit testing is an automated way of testing a piece of the system in isolation (unit). This practice seems to be useful [...]

Unit Testing with Knockout.js

Knockout is an MVVM framework for JavaScript. When using an MVVM framework, you have to deal with your model, the views and the “view model”. A view model is a class/object that handles the logic of the view. So if something has to be visible given a certain condition, that’s handled by the view model. [...]

Why Knockout.js is awesome

Some very good javascript and web developers that I know, don’t buy the whole MVVM with knockout.js idea. The only valid complains I have heard so far are: people not liking MVVM on one side, and that data bindings in the markup are “obtrusive” on the other. As for the first, there’s not a lot [...]

Getting started with node.js

What is node.js?

node.js is a development platform based on Javascript created by Ryan Dahl and currently maintained by the cloud provider Joyent. The interesting thing about node.js is that it runs in a single thread, and attacks concurrency by trying to block as little as possible (if at all). In it’s most simplistic form, node.js provides a REPL interface for the command line:

repl

node.js happens to be very good at running web servers, apart from being very simple to do so, the non-blocking philosophy makes it a very good allied of concurrency, since it’s not limited to the amount of threads that your process can run. Here’s how a hello world web server looks like:

 1: var http = require('http');
 2: 
 3: http.createServer(function (request, response) {
 4:     response.writeHead(200, { 'Content-Type': 'text/plain' });
 5:     response.end('Hello World\n');
 6: }).listen(8000);
 7: 
 8: console.log('Server running at http://127.0.0.1:8000/');

And you could could run this very easily if you save it to a file like this:

node index.js

Another very interesting thing about writing web applications in node, is that you keep the client side and server side languages consistent. If you add a json-document based NoSQL database like mongo to the mix, you have yourself a complete javascript/json environment for developing websites.

Getting started in windows

If you want to get started with windows, you can download the installer from the node.js website. At the moment of writing this post, the version 0.6.18 was only 3MB. After you install, you will find the nodejs installation under you ‘program files(86)’ folder. You can open your cmd or powershell command line, and you will already have the node and npm command at your disposal.

There are a number of cloud services that will host your node.js applications out there like:

Getting up and running in Azure turns out to be pretty simple with the latest SDK they released. You can get the SDK using the Web Platform Installer searching for node:

wpi

And you will get a set of powershell commandlets for creating node webroles, and even deploying to azure from the command line.

And last but not least, if you want to host your node.js apps in IIS, you can install IISNode for IIS. From the IISNode, here are the benefits:

  • Process management
  • Side by side with other content types
  • Scalability on multi-core servers
  • Integrated debugging
  • Auto-update
  • Access to logs over HTTP
  • Minimal changes to node.js application code
  • Integrated management experience
  • Other IIS benefits. Port sharing, security, URL rewriting, compression, caching, logging

Getting started in linux

You can also go to the node.js website and download the installer, but there’s another cool way of getting node in your linux environment called “nvm”. Nvm is a sh script that will download, build and manage the different versions of node that you might want to use in your environment. For getting nvm, all you have to do is go to the nvm github website, and copy the script into some file in you computer (for example ~/nvm/nvm.sh), and then either execute or add this to your bash profile file: . ~/nvm/nvm.sh

Once you have nvm, you can do the following things:

Install a specific version:
nvm install v0.6.18

Start using a specific version:
nvm use v0.6.18

…and you are ready to node!

Writing javascript for node is no different than writing javascript for any other platform (including browsers), so you can really any text editor that supports the javascript syntax. Lately, I have been using Sublime Text 2 thanks to my friend Jose Romaniello and it’s awesome and I can use it in both Windows and Linux!

As for resources for starting to use node these seem to be the best out there:

Unit Testing and Test Driven Development (Lessons Learned)

I started a discussions with my colleagues at Tellago about Unit Testing and Test Driven Development, and a lot of interesting things came out of that discussion. Here are my thoughts.

Unit Testing

Unit testing is an automated way of testing a piece of the system in isolation (unit). This practice seems to be useful in the following scenarios:

  • When doing TDD/Test first (more on this later)
  • After a feature is complete for automatic testing of the integration of different components.
  • When documenting how to consume an API.
  • When fixing a bug, to prove that a bug exists, use the test to fix it, and prevent the bug from emerging again.
  • After coding, to avoid manual testing (something along the lines of integration testing).
  • Exploring the behavior of somebody else’s API.

Regardless of the use we give to unit testing, seems like it’s not an optional practice anymore. It’s a must-have skill that every developer should work on mastering. Here are some of the advantages:

  • You get written specifications of how the software should behave.
  • You get client code of the API under test.
  • You get instant feedback of the impact of refactorings/changes.
  • Saves a lot of time! For every time you run 1 unit test, you are saving probably 1 or more minutes of manual testing.
  • Gives you confidence for committing code.
  • Gives you confidence for touching code written by somebody else.
  • Gives you confidence for more aggressive refactorings.

There is (I believe) a downside of inefficient unit testing, and it’s that when testing the wrong things, you might end up with fragile tests, that make maintenance even harder (and more painful).

TDD/Test First

Some of us try to practice TDD or Test First as much as possible, and we strongly believe that it makes us write better and faster code by getting very early feedback of what we are doing. Here’s how ideally we would practice TDD:

  1. Define test
  2. Write test
  3. Verify the test fails.
  4. Write minimum code to make the test pass (with a minimum share of common sense).
  5. Refactor code to make it cleaner/better.

The benefits of doing test first are many, here are a few:

  • Early feedback of your code’s design. You see how your API will be consumed even before you actually coded it.
  • In order to make your test simple, the code under test should have few (or en better one!) responsibilities. This helps design your classes following the single responsibility principle.
  • Confines your brain to the smallest possible piece of your entire solution. You concentrate on doing a small part at a time, but doing it right! The good ol’ “Divide & Conquer” they taught us in the first Algorithms class.

This doesn’t seem to be that much harder than unit testing after something is coded, it actually sounds easier… WHY ISN’T EVERYBODY DOING TEST FIRST THEN???

I remember when I first read about TDD, and it felt totally unnatural (it still does sometimes). I had been coding in the entirely opposite way for so long, that it was awkward, slow, and tests weren’t as good. So here’s the catch, unfortunately, IT TAKES TIME! Not hours, or days, it may take months to start feeling comfortable with writing tests first.

If somebody says that unit testing first makes them slower, to me, that sounds like they haven’t tried it enough, and they are not used to doing it. I have not known a person that has done hardcore TDD for a long time, and then came back to Non-TDD coding because they were not fast enough.

PS: Thanks for the guys at Tellago for the great discussion!!!

Unit Testing with Knockout.js

Knockout is an MVVM framework for JavaScript. When using an MVVM framework, you have to deal with your model, the views and the “view model”. A view model is a class/object that handles the logic of the view. So if something has to be visible given a certain condition, that’s handled by the view model. Knockout handles the binding of the view model to an HTML view.

Note: I am not going to get into the whole obtrusive/unobtrusive discussion, but I have to say that I didn’t quite like what I’ve seen in some of the samples around. So I decided to put up a knockout sample with what I think to be a better approach (a TDD, logic-free-binding approach).

Localtodo

For the sake of learning knockout using TDD and at the same time building something to compare with backbone.js (and also because it’s cool), I asked Jérôme Gravel-Niquet permission to take his localtodos sample built in backbone.js, and port it to see how it would look in knockout. Here’s how the sample looks:

image

Live demo: http://localtodos.herokuapp.com
Live Test: http://localtodos.herokuapp.com/tests.html
Source code: https://github.com/machadogj/localtodos-ko

Testing with Knockout

One of the huge advantages of using an MVVM pattern, is that you can test the logic of how a view/form is supposed to behave, without actually going through all the trouble of actually testing the view itself. In my opinion, if you are not going to do unit testing on the view model, you are not going to get the most out of knockout.

Contrary to what I thought, unit testing JavaScript is dead simple; I used qunit and it just simply works. Here is an example of a test that asserts that new tasks are not completed:

  1. test(“when creating a task, it is not completed.”, function () {
  2.     var t = new knocklist.Task();
  3.     //assert
  4.     ok(!t.completed());
  5. });

One of the reasons why these tests are so easy, is that when working with Knockout you don’t have to handle HTML.

When you run the tests (browsing the tests.html file) you’ll see something like this:

image

Classes

I liked how it felt to do my view model with “classes”. I thought of the different parts of the screen as different classes, and then had them combined in a bigger view model. This way the code under test is a much smaller. Here is a class for the portion of the view that is a form for adding tasks:

  1. var NewTaskModel = function (backlog) {
  2.     this.backlog = backlog;
  3.     this.name = ko.observable();
  4.     this.toTask = function () {
  5.         returnnew todos.Task(this.name(), false, this.backlog);
  6.     };
  7.     this.clear = function () {
  8.         this.name(“”);
  9.     }
  10.     this.save = function () {
  11.         var task = this.toTask();
  12.         this.clear();
  13.         return task;
  14.     };
  15.     this.hasName = ko.dependentObservable(function () {
  16.         returnthis.name() && this.name().length > 0;
  17.     }, this);
  18. };

I liked how it felt to use “this” to reference the objects properties. There’s one catch though. When using dependentObservables, you have to pass the context as the second parameter for “this” to make sense. Something like:

  1. this.hasName = ko.dependentObservable(function () {
  2.     returnthis.name() && this.name().length > 0;
  3. }, this);

Data-bindings

Avoid adding logic to your data-bindings. This is the one thing that people that usually don’t like knockout will argue, and it’s wrong anyway. Putting logic into your data bindings maybe a quick dirty trick to get going fast, but it’s not a good practice. And what’s even worse, it’s not (easily) testable. To show a quick sample of what not to do:

  1. <buttondata-bind=“click: registerClick, enable: !hasClickedTooManyTimes()”>Click me</button>

Wouldn’t “canClick” be better for a UI binding than “!hasClickedTooManyTimes()” ?

Avoid doing bindings that reference a method on a property, for example:

  1. <buttondata-bind=“click: loginForm.signIn”>Sign in</button>

Knockout will pass the attached View Model as the context to that method. Basically it means that the meaning of “this” inside of “signIn” method will not be “loginForm” but the object that has the loginForm property. This will usually not make your unit tests to fail, so don’t do that; but when you move to the HTML you will notice that it’s not working properly.

I found the “with” data bind in the knockout 1.3 beta to be extremely useful for avoiding the previous problem.

Multiple View Models per Page

When working on knockout, many people is used to create one View Model per page. In my opinion this is fine if the page is very simple, however if the page is a little bit complicated, or has multiple different forms in it, I think it’s very advisable to split that big view model into multiple different view models. Knockout has different ways in which you can do this. The most simple case would be to attach one of the smaller view models to a specific HTML dom element. You can do this with the applyBinding method:

  1. <scripttype=“text/javascript”>
  2.     var currentBacklog = new Backlog();
  3.     ko.applyBindings(currentBacklog.newTask, document.getElementById(“newCurrentTask”));
  4. </script>

When doing this, you can test the “newTask” class without having to worry about Backlog or the rest of the classes.

Pub/Sub Pattern

Multiple views in one page looks good, but there’s one catch though, what if you need to reference a list of tasks in Backlog class, from within the NewTask class? Pay attention to the “save” function:

  1. <scripttype=“text/javascript”>
  2.     var Backlog = function () {
  3.         this.newTask = new NewTask(this);
  4.         this.tasks = [];
  5.     };
  6.     var NewTask = function (backlog) {
  7.         this.backlog = backlog;
  8.         this.name = ko.observable();
  9.         this.save = function () {
  10.             this.backlog.tasks.push(this.name());
  11.             this.name();
  12.         };
  13.     };
  14. </script>

While this is possible, and 100% testable, it is making your NewTask and Backlog quite coupled. For simple straight forward scenarios this might be ok, but when making a more complex or composite apps, this can get pretty complex and fragile pretty fast.

One thing that I found extremely useful for tackling this problem is the pub/sub pattern. Where basically you expose events, you subscribe to these events, and then you publish events. So suppose that the NewTask class instead of accesing directly the backlog, it exposes an event called “taskAdded”; so that everytime that the save function is invoked, a “taskAdded” event is published with the name as the data. At that point, Backlog class could subscribe to this event, and be the one in charge of adding the task to the list. There are many implementations of pub/sub in javascript, you can use whichever you want.

Notice how by using an event aggregator for pub/sub NewTask does not depend on Backlog anymore:

  1. <scripttype=“text/javascript”>
  2.     var Backlog = function () {
  3.         this.newTask = new NewTask();
  4.         this.tasks = [];
  5.         var that = this;
  6.         eventAggregator.Subscribe(“taskAdded”, function (name) {
  7.             that.tasks.push(name);
  8.         });
  9.     };
  10.     var NewTask = function () {
  11.         this.name = ko.observable();
  12.         this.save = function () {
  13.             eventAggregator.Publish(“taskAdded”, name);
  14.             this.name();
  15.         };
  16.     };
  17. </script>

 

Tests

Naming my tests properly has helped me a great deal when refactoring and/or porting code from one project to another. I found out that it’s better to name your tests in a way in which specifies the behavior of the view and not the implementation of your view model. Here’s what I think to be a very useful test for me:

backlog: when cleaning a completed task, backlog’s uncompleted task is not deleted.

This other test on the other hand is not so useful:

newTaskModel: clear sets the name to empty string.

If you go to the UI you will see that there’s no “Clear” button for creating tasks. This was meant to test a method that is used when creating tasks. Even though these tests can be very helpful for us to exercise our code, when it comes to reading the specifications it can be confusing. So as I was writing this blog, I realized that I would rather have a test that says:

newTaskModel: after a task is saved, the name field should be cleared.

Conclusion

I consider Unit Testing to be a good practice regardless of the language. When writing Unit Tests you have to do code that’s well decoupled and well interfaced for your tests to be easy. When developing your applications with Unit Tests in mind, It’s important to pick the right patterns. The MVVM pattern turns out to be an excellent pattern for decoupling your view logic from the view representation; thus taking the unit tests as close of the UI as possible without testing the UI directly. In my opinion Knockout is a pretty cool MVVM implementation, so it’s a perfect fit for unit testing.

Why Knockout.js is awesome

Some very good javascript and web developers that I know, don’t buy the whole MVVM with knockout.js idea. The only valid complains I have heard so far are: people not liking MVVM on one side, and that data bindings in the markup are “obtrusive” on the other. As for the first, there’s not a lot we can do, all I know is that people that have worked with MVVM usually likes it very much (obviously any pattern has it’s drawbacks). The second one though, while I do not agree at all, I can see where that is coming from.

Bad reputation

Of course you are not going to like something that couples your views to your logic. Something that has logic in your views. So I can see why people looking at samples like this…

  1. <buttondata-bind=“click: function() { numberOfClicks(0) }”>Reset clicks</button>

…think that knockout is “obtrusive”. This has been taken from the second live sample of the knockout site here. People see this, and get’s literally scared, and run away without giving knockout a chance. I think that the author tried to illustrate that if you NEED to, you could define bindings like in this way, but I wouldn’t consider this a best practice at all. Here is how easily you can modify this sample to remove the function from the binding:

First

I haven’t come across a case where I would NEED to do something like this, without any other alternatives. I usually create my view models in a way in which by binding to a particular DOM will not require this functions declared inside of the data-bind attribute.

Second

People who find knockout “obtrusive”, usually think that using jquery templates is a more acceptable approach. However just as easily as you can put functions in the data-bind attribute with knockout, you can also put logic into jquery templates. It’s actually not uncommon at all to see this type of templates:

  1. <scriptid=“movieTemplate”type=“text/x-jquery-tmpl”>
  2. <li>        
  3.     Title: ${Name}.        
  4.     {{if Languages.length}}         
  5.     (Alternative languages: ${$item.getLanguages(” – “)}).        
  6.     {{/if}}
  7. </li>
  8. </script>

(This is actually taken from the jquery templates documentation here.)

Third

While I don’t necessarily recommend it, you should know that there are ways to define the bindings outsite of the markup; like using jquery with selectors to set the data-bind attribute manually before calling the applyBindings. As a more “advanced” alternative to this, knockout 1.3 beta comes with a conventions prototype to apply bindings based on css selectors. Here is an working sample taken from Steve Sanderson blog (notice the lack of “data-bind” attributes in the markup):

A very common misconception…

Knockout is usually compared to other frameworks like backbone.js. While both of them are totally cool, they do things that are very different. Knockout is an MVVM framework. MVVM framework stands for Model-View-ViewModel. The cool part is the ViewModel part; which means that you get to model how the view reacts to different states programmatically, without actually holding a reference to the view itself. If you have a rule that says “when there’s no text in the name field, disable button X” you have several different ways to solve this. Here is a more traditional approach:

  1. $(“#name”).keyup(function(e) {
  2.     var name = $(this).val();
  3.     if (name.length === 0) {
  4.         $(“#buttonX”).attr(“disabled”, true);
  5.     }
  6.     else {
  7.         $(“#buttonX”).attr(“disabled”, false);
  8.     }
  9. });

This is far from ideal, apart from the fact that if your DOM changes you are screwed, this is very hard to test thanks to all the DOM you have to create and validate against.

Let’s now explore at how we would do this in Knockout

This is not only easy to test, but also the logic attached to it doesn’t depend on ids or css classes, you can literally change the input for a textarea, or add an id to it and everything will continue to work as long as you don’t mess with the data-bind.

Conclusion

While I think knockout is not the only alternative out there for doing highly dynamic interfaces, I consider knockout to be an excellent alternative which does an awesome job at decoupling the html from the javascript. Having said that, I also think that another big advantage of using knockout is that you can test your view models very easily.

Database Version Control – Incremental Scripts

Back in this post, I explained the three different methods for versioning databases that I have worked with: backups, incremental scripts and Visual Studio Database Project. I never had a chance to blog about incremental scripts method and I thought I’d blog about it now.

Setting things up

DbVersion table

First, you need to add a table to keep track of all the incremental scripts that were executed against your database. Something like this will do:

  1. CREATETABLE [dbo].[DbVersion](
  2.     [Id] [int] IDENTITY(1,1)NOTNULL,
  3.     [FileName] [varchar](250)NOTNULL,
  4.     [Description] [varchar](4000)NOTNULL,
  5.     [Executed] [date] NOTNULL,
  6. CONSTRAINT [PK_lalala] PRIMARYKEYCLUSTERED
  7. (
  8.     [Id] ASC
  9.   )WITH (PAD_INDEX  =OFF,STATISTICS_NORECOMPUTE  =OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS  =ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
  10. )ON [PRIMARY]

So now you can query this table to see the current version, and what’s more, if the sequence in which the scripts were executed is correct.

Baseline

The baseline is a script which creates the entire database to a given point in time. So the first script that creates the database from scratch is one of many baselines that we might have. For creating the baseline in SQL Server, you can use the generate script option:

image

This will open a wizard that will guide through the steps to script your database. In order to have a proper baseline, you can clean the database, but leave all the data in the enumeration tables (like categories, and built in data), and use the “Script data and schema” option:

image

Versioning Scheme

You should pick a versioning scheme that suites your development process. The minimum setup that I would use is the following: [project name].[major].[minor]. In this scenario the major would be the current baseline, and the minor the incremental script relative to the baseline. All the versions with minor “0” are the baselines themselves. Now that we chose our scheme, let’s save the baseline with the following filename: demo.1.0.sql.

Workflow

Scenario 1 – Clean setup

By clean setup, I mean that you don’t have a database in your local environment. At this point you should do the following:

1.- Pick the biggest baseline (ie: demo.2.0.sql, etc) and execute it.
2.- Run all the incremental scripts of that baseline in ascending order (ie: demo.2.1.sql, demo.2.2.sql, etc).

Scenario 2 – Making a change

When making a change to our database, we will create a new incremental script, thus increasing the version in our database. Suppose that you update your SVN (or whichever version control tool) database folder, and you see that the latest script is demo.2.3.sql. At that point you’ll create a new file called demo.2.4.sql for your change.

The script itself can be made by a tool like Red Gate’s SQL Compare and SQL Data Compare, or even manually. Whichever method you choose for your scripts, it is usually a good practice to enclose the changes inside of a transaction. When the script is run, and after the changes are made, the script should insert a record in the DbVersion table mentioned before. By doing this, we ensure that the DbVersion is always up to date. Here is a sample script generated with SQL Compare to which I manually removed the GOs and added the insert to the DbVersion table:

 

  1. /*
  2. Run this script on:
  3.         (local)\sqlexpress.RestBucks2    -  This database will be modified
  4. to synchronize it with:
  5.         (local)\sqlexpress.Store
  6. You are recommended to back up your database before running this script
  7. Script created by SQL Compare version 9.1.0 from Red Gate Software Ltd at 10/6/2011 7:41:17 PM
  8. */
  9. SETNUMERIC_ROUNDABORTOFF
  10. SETANSI_PADDING,ANSI_WARNINGS,CONCAT_NULL_YIELDS_NULL,ARITHABORT,QUOTED_IDENTIFIER,ANSI_NULLSON
  11. IFEXISTS(SELECT*FROM tempdb..sysobjectsWHERE id=OBJECT_ID(‘tempdb..#tmpErrors’))DROPTABLE #tmpErrors
  12. CREATETABLE #tmpErrors(Error int)
  13. SETXACT_ABORTON
  14. SETTRANSACTIONISOLATIONLEVELSERIALIZABLE
  15. BEGINTRANSACTION
  16. PRINTN’Altering [dbo].[Product]‘
  17. ALTERTABLE [dbo].[Product] DROP
  18. COLUMN [Version]
  19. IF@@ERROR<>0AND@@TRANCOUNT>0ROLLBACKTRANSACTION
  20. IF@@TRANCOUNT=0BEGININSERTINTO #tmpErrors(Error)SELECT1BEGINTRANSACTIONEND
  21. IFEXISTS(SELECT*FROM #tmpErrors)ROLLBACKTRANSACTION
  22. IF@@TRANCOUNT>0BEGIN
  23. INSERTINTO [dbo].[DbVersion]
  24.            ([FileName]
  25.            ,[Description]
  26.            ,[Executed])
  27.      VALUES
  28.            (‘demo.2.4.sql’
  29.            ,‘Removing Version column from Product table.’
  30.            ,GETDATE())
  31. PRINT‘The database update succeeded’
  32. COMMITTRANSACTION
  33. END
  34. ELSEPRINT‘The database update failed’
  35. DROPTABLE #tmpErrors

Creating a Baseline

After several changes are made to a database, more and more scripts are required to be executed in order to have a clean set up. In order to avoid having too many incremental scripts, you can create a baseline as a way to shortcut a bunch of those incremental scripts. Sometimes it is a good idea to create a baseline when a production deployment is done, sometimes it is a good idea to create one when you have more scripts than you would like. In order to create a baseline, the only thing you need to do is, pick the previous baseline, run all the incremental scripts in that baseline, and then script the entire database like we did before.

Updating Your Local Database

The flow for updating an existing database would be the following:

1.- Query the DbVersion table in your database to find the current version.
2.- Query your database scripts repository looking for scripts that are newer than yours.
3.- Execute the scripts, except for the baselines (minor equals “0”).
4.- Query the DbVersion table to make sure that all the scripts ran successfully and in order.

Usually this step can be easily automated. Here’s the PowerShell script for updating your database (it’s only a little bit over 30 lines).

  1. $SqlServer=‘.\sqlexpress’
  2. $DB=‘RestBucks2′
  3. $conn_options=(“Data Source=$SqlServer; Initial Catalog=$DB;” +
  4. “Integrated Security=SSPI”)
  5. $conn= New-ObjectSystem.Data.SqlClient.SqlConnection($conn_options)
  6. $conn.Open()
  7. $cmd=$conn.CreateCommand()
  8. $cmd.CommandText =‘Select top 1 FileName from dbVersion order by FileName desc’
  9. $reader=$cmd.ExecuteReader()
  10. if ($reader.Read())
  11. {
  12.     $columns= New-Objectobject[] 1
  13.     $reader.GetValues($columns)>$null
  14.     $current=$columns[0]
  15.     $conn.close()
  16. }
  17. else
  18. {
  19.     $current= “”
  20. }
  21. $files=get-childitem |Where {$_.Name -like “$DB.*.*.sql”}
  22. $tokens=$files|Select-Object @{Name=“FileName”;Expression={$_}}, @{Name=“Tokens”;Expression={$_.Name.Split(‘.’)}}
  23. $scripts=$tokens|Select-Object @{Name=“FileName”;Expression={$_.FileName.Name}}, @{Name=“IsBaseline”;Expression={$_.Tokens[2] -eq 0}}
  24. $updates=$scripts|where {$_.IsBaseline -eq $false-and$_.FileName.CompareTo($current)-gt 0}
  25. foreach($scriptin$updates)
  26. {
  27.     $conn= New-ObjectSystem.Data.SqlClient.SqlConnection($conn_options)
  28.     $conn.Open()
  29.     $cmd=$conn.CreateCommand()
  30.     $cmd.CommandText =get-content $script.FileName
  31.     $cmd.ExecuteNonQuery()
  32.     $conn.close()
  33. }

Modifying an update

If you made a mistake in a script, and you need to correct it, don’t! Always try to create a new version rather than altering an update that’s already in the svn, because those changes are hard to push to the rest of your team. However, if you made a mistake that may result in the loss of data, then fix it, commit it to SVN, and let everyone know! :)

Stored Procedures

Stored procedures and view in SQL Server are a little special. Suppose that you change a table, in order to remove a column that a Stored Procedure or a view is using. At that point, SQL Server will perform the update and break the SP or the view silently. So as part of the update process of a database, it’s not a bad a idea to drop all the stored procedures and all the views, and recreate them. For doing that you have to keep the SPs and Views in different scripts, probably in a different folders and one file per SP or View.

So sacrifice a little bit of development time, to make your life much easier multiple times when migrating databases in every environment, including the most critical one: PRODUCTION!

Pros

  • It’s blazing fast.
  • You never lose your data as part of a change in any of your environments. So no need for updating testing scripts, etc.
  • Deployments are dead simple. By the time you get to the production deployment, the scripts were already executed in every developer’s machine, dev, qa, staging environments, etc.
  • Easy to automate deployments.
  • No need for complex heavy tools like Visual Studio Database Projects.
  • The updates history resides in the database itself (see DbVersion table).

Cons

  • May require SQL knowledge to craft migration scripts.
  • It’s hard to test the incremental scripts.
  • Takes up a little bit more of developer’s time in some cases.

So even though I am sure this method of versioning the database may not work on every project, I consider it a perfectly valid way to keep your database under version control.

Tellago Studios Launches Moesion!

 I am very excited to be writing this post, since we have been working very hard on getting this new product out. Moesion was the most challenging, innovative and cool projects that I have ever participated in.

So what is Moesion?

moesion mobile apps Moesion is a cloud based platform that brings mobility to the IT world. With Moesion you can do all kinds of stuff to manage your servers from your phone, tablet or desktop. Instead of a “remote desktop” solution that never fits well in mobile devices, we managed to create a touch-first interface with a great user experience as the main goal.

How did we do it?

It merges cool new technologies like HTML 5, PubNub and of course Azure, this project has “cool” written all over it! With HTML 5 we were able to provide excellent user experience in the mobile ecosystems like smart phones and tablets, matching the native apps capabilities like touch, rotate and even swipe!

How can you get it?

Subscribe now for a beta access in www.moesion.com!

Connected System MVP award 2011

The first of July while I was on the phone with Jesus Rodriguez and Pablo Cibraro, I received a very important email from the Microsoft MVP program; I was granted the Connected System MVP Award. It was funny that I read that email out loud in that call, since Jesus and Pablo where the guys who pushed me and mentored me in achieving this award. One part of the story they didn’t know is that at the same time, my wife Veronica was reading the email, and she was jumping off her chair of happiness, the reason being that getting the MVP was a very ambitious goal I had and for which I worked very hard throughout the year. So I want to take this opportunity to thank Jesus, Pablo and Veronica for being there for me all this time.

So what is the MVP?

MVP_Horizontal_FullColor

From the MVP program website, they describe it like this:

We seek to recognize the best and brightest from technology communities around the world with the Microsoft® Most Valuable Professional (MVP) Award.

These exceptional community leaders come from a wide range of backgrounds. They are teachers, artists, doctors, engineers, as well as technologists, who actively share their high-quality, real-world technical expertise with the community and with Microsoft.

With the MVP Award, we thank these inspiring individuals for representing the voice of thousands in the community through the powerful and independent feedback they give us, and for helping our customers maximize the potential of their software.

What is Connected System?

In the last few years, I’ve come to learn and master the WCF stack, and SOA practices, and had a hell of a time while doing it. So it has become my main area of expertise to explore ways to connect systems. The latest being through the use of REST services with the new WCF Web API.

Why did I want to become an MVP?

Before I joined Tellago, I knew little about the MVP program, but when Jesus and Pablo told me more about it I just loved the idea. To be awarded and recognized for your efforts in the tech community, makes contributing even more exciting. During this trip, I have known extremely cool people, excellent professionals, I had countless interesting debates, and it couldn’t have been a better experience.

Since the beginning, it was Tellago’s vision to serve to their employees as a platform for growing as professionals, and the fact that I was able to become an MVP is just one of the many proofs that Tellago stays true to that vision, and it’s, in my opinion, what makes Tellago the best company I’ve ever worked for.

Introducing Hermes – Open Source Pub/Sub

We are very excited to announce that Tellago DevLabs just released a new open source project, Hermes. Hermes is a publish/subscribe messaging engine based on HTTP and MongoDB. The project is open source, and it’s hosted in GitHub. The code can be downloaded from here, and Hermes documentation can be reached here.

There are several things that makes Hermes a very attractive alternative for doing pub/sub:

  1. it provides a fully documented RESTful API making the engine as interoperable as it gets.
  2. it is a very light weight .NET alternative.
  3. it is open source.
  4. it will run either on premise or in the cloud.

So don’t hesitate to give it a try, we are looking forward to your feedback :)

Tellago Studios launched Telesharp!

I am very happy to announce a new product release by Tellago Studios. Telesharp is what we call an application repository, and it will make the configuration management much easier and better by centralizing the applications assets, the configuration settings and logging of all the applications in your company.

Having worked as a Configuration Manager in some projects, and being in charge of deployments, I know how painful it is to keep the configuration files up to date. Half of the deployment problems are basically somebody forgetting to add some settings in a configuration file. Not to mention the fact that developers usually don’t have access to production credentials, etc.

So in my opinion, Telesharp is a must have application in every company with a formal configuration management process (which should be every company :) ).

Visit the product page at Telesharp for an amazing overview of all the features in the product. And if you want to see it in action, check out the videos here.

Attending TechEd NorthAmerica 2011

This year, I had the chance to visit US for the first time, and go to the TechEd NorthAmerica 2011 thanks to Tellago, the company I work for. I can’t be more thankful for working in such a cool company that will go through all the trouble of taking me from Buenos Aires to Atlanta for the TechEd. Apart from having a great time at the TechEd I also knew 4 of my co-workers: Elizabeth Redding, Jesus Rodriguez, Suresh Girirajan and Chris Love; which was totally awesome. I’ve also met some very cool guys from Microsoft that even said they loved the stuff we were doing with the SO-Aware Test Workbench!

In the sessions I have attended, I have learnt so many cool stuff, here’s just a few I can think of:

  1. Windows Azure: Web, Worker and VM roles.
  2. SQL Azure
  3. Azure tables
  4. Azure blobs
  5. Azure Windows Connect
  6. Azure AppFabric: Service Bus. Development Tools. Application Manager
  7. Private Cloud (I’ve actually seen one in action right there running all the hands on labs)
  8. Entity Framework 4.1: Database initializer. Entity framework migrations (for updating existing database). Enums support!!! (for those who were there :P )
  9. SQL Server (code name ‘Denali’): text search and spatial improvements.
  10. WCF 4.0: routing, discovery, dependency ping, web service governance.
  11. WF: real world scenarios (Jesus Rodriguez), and State Machine (Ron Jacobs).
  12. WIF: extensibility points.
  13. Windows Phone 7: Microsoft Push Notification Service(http://watoolkitwp7.codeplex.com)

And all this fun stuff in one week! It was certainly a remarkable experience, and I hope to be able to do it again soon.

Performance Optimization WordPress Plugins by W3 EDGE