Creating an Animated Header with Angular 2

In this article I will show you how to create an animated header in Angular 2.

Introduction

This article is based on version release candidate 5 of Angular 2 (version number: 2.0.0-rc.5). I expect this code should also work in earlier versions of Angular 2 but this hasn’t been tested.

To keep this article as simple as possible it continues on top of the website that is created when you complete the Angular 2 “5 Min Quickstart TypeScript” tutorial. If you want to code along with this article I suggest you quickly step out and go through the tutorial to setup the starting point.

The complete source for the application created in this article can be found on GitHub: https://github.com/mvanbeusekom/Angular-2—Animated-Header

Creating a header

During this chapter we will create an simple header which we will animate in in the chapter “Animating the header“. To create the header I will make use of the Twitter Bootstrap Navbar component. I will not go into it deep and just use a little bit (only some styling) of its functionality. If you want to learn more about this component please checkout http://getbootstrap.com/components/#navbar.

So in this chapter I will show you all steps it will take to create a basic fixed header at the top of your Angular 2 application.

Create the HeaderComponent

To create the “HeaderComponent” create a “header” folder (within the “app” folder) and add the following files “header.component.ts”, “header.component.html” and “header.component.css”.

Now add the following code to each file.

header.component.css:

.navbar {
 padding: 30px 20px;
}

header.component.html:

<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#"> My First Angular 2 App </a>
    </div>
  </div>
</nav>

header.component.ts:

import { Component } from '@angular/core';

@Component({
 selector:'my-header',
 templateUrl: 'app/header/header.component.html',
 styleUrls: ['app/header/header.component.css']
})
export class NavComponent{}

Add the HeaderComponent to the application

Now that the “HeaderComponent” is created we can add it to our application. Todo this open the “app.component.ts” file and take the following steps:

  1. Import the new component by adding the following line directly below the other import line:
    import { HeaderComponent } from './header/header.component';
  2. Replace the current HTML template with the new <my-header></my-header> directives:
    @Component({
      selector:'my-app',
      template: '<my-header></my-header>'})
  3. Add the HeaderComponent class to the directives array in the component metadata:
    @Component({
      selector:'my-app',
      template: '<my-header></my-header>',
      directives: [HeaderComponent]})

After these steps the content of the ‘app.component.ts’ file should look somewhat similar to this:

import { Component } from '@angular/core';
import { HeaderComponent } from './header/header.component';

@Component({
  selector: 'my-app',
  template: '<my-header></my-header>',
  directives: [HeaderComponent]
})
export class AppComponent { }

Add support for Twitter Bootstrap

To finish our header we only have to add support for Twitter Bootstrap to our application. When you followed the “5 Min Quickstart” tutorial, the Twitter Bootstrap module is already downloaded and we only have to reference it in our “index.html” file. To do this take the following steps:

  1. Open the ‘index.html’ file
  2. Find the place where the ‘styles.css’ file is referenced
  3. Insert to following line directly above the ‘styles.css’ reference:
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css" />
    

Now your ‘index.html’ file should look like this:

<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

And if you run the application (by running “npm start”) the application should look like this:
Original header

Animating the header

Now that we have added the header to our application we can start animating it. In this chapter I will show you how you can shrink the header we just created when the user starts scrolling down the webpage. This is a very popular design technique in today’s websites (a few good examples are ‘https://www.google.com/doodles‘, ‘https://material.google.com‘ and ‘http://flinder.nu‘).

The animation is all done using CSS styles. The basic concept is to add a CSS class to the ‘<nav>’ element when the user starts scrolling down and remove this class when the user scrolled back to the top of the page. The tricky part (at least that’s how I felt when I first attempted to do this) is letting the ‘HeaderComponent’ know that the user is scrolling in a way that matches Angular’s design principles.

Define the CSS class

Lets start with the easy part and define the CSS class which will shrink the header. Since we want to shrink the header defined by our ‘HeaderComponent’ it would be best to add our new CSS class to the ‘header.component.css’ file. Here we go:

  1. Open the ‘header.component.css’ file
  2. Add the following class to the file:

    .shrink-header {
      padding-top: 5px;
      padding-bottom: 5px;
      opacity: 0.9px;
    }
    
  3. To create the animation effect add the following lines to the ‘navbar’ class:

    .navbar {
      padding: 30px 20px;
      -webkit-transition: all 0.5s;
      transition: all 0.5s;
    }
    

the contents of the ‘header.component.css’ file should now look like this:

.navbar {
  padding: 30px 20px;
  -webkit-transition: all 0.5s;
  transition: all 0.5s;
}

.shrink-header {
  padding-top: 5px;
  padding-bottom: 5px;
  opacity: 0.9px;
}

Our new ‘shrink-header’ class will change the top and bottom padding to 5 pixels instead of the 30 pixels defined by the ‘navbar’ class. This will effectively shrink the header with 50 pixels. The ‘transition’ property, defined in the ‘navbar’ class, will make sure the change in size happens gradually during a time period of 0.5 seconds, creating the animation effect.

Capturing the scroll event

So now we have a nice style, but we still need to apply it to our header. To be more specific, we want to add or remove the ‘shrink-header’ class based on the scroll position when the user starts scrolling up or down. When the scroll position is all the way on the top we want to remove the ‘shrink-header’ class from the ‘<nav>’ element, but when the scroll position is anything but at the top we would like to add the ‘shrink-header’ class to the ‘<nav>’ element.

There are several ways to accomplish this, however the one I like the most is using a custom directive. In this chapter I will describe how to create this custom directive and in the next (and last) chapter I will show you how to tie everything together.

To create the custom directive take the following steps:

  1. First create a new folder ‘directives’ in the ‘app’ folder
  2. Create a new file called ‘trackscroll.directive.ts’ inside the ‘directives’ folder
  3. Add the following code to the ‘trackscroll.directive.ts’ file:

    import { Directive, EventEmitter, Output, HostListener } from '@angular/core';
    
    @Directive({
        selector: '[track-scroll]',
        host: {'(window:scroll)': 'track($event)'},
    })
    export class TrackScrollDirective {
      @Output() scrolled:EventEmitter<any> = new EventEmitter();
    
      track(event:any) {
        this.scrolled.emit(document.body.scrollTop);
      }
    }
    

This directive will listen for the ‘window:scroll’ event on the host (the page hosting the Angular app which is ‘index.html’ in our case). When a scroll event occurs it will execute the ‘track’ function which in turns emits the ‘scrolled’ event. By capturing this logic inside a custom directive we isolate the tight coupling with the host element into a separate class. This will allow us to more easily test our application and will make it easier if the scrolling implementation would change (e.g. when the application context changes).

Tying everything together

So now we have a CSS class which will shrink the header and we have a custom directive which will let us know when the user is scrolling. In this chapter I will show you how to tie these two together and finish up our implementation.

To actually add and remove the ‘shrink-header’ CSS class to the ‘<nav>’ element of our ‘HeaderComponent’ we will leverage the property binding mechanism of Angular. And of course to control it all we make sure the ‘HeaderComponent’ subscribes to the ‘scrolled’ event fired by our custom directive.

Lets first setup the binding, so all the plumbing is out of the way:

  1. Open the ‘header.component.ts’ file
  2. Add a new property to the ‘HeaderComponent’ class, called ‘shrinkCssClass’:

    export class HeaderComponent {
      shrinkCssClass : string = '';
    }
    
  3. Now open the ‘header.component.html’ file
  4. Replace the ‘class’ attribute in the ‘<nav>’ element with the ‘ngClass’ attribute and add the appropriate binding:

    <nav [ngClass]="['navbar', 'navbar-default', 'navbar-fixed-top', shrinkCssClass]">
      ...
    </nav>
    

The binding is now setup correctly and we are now ready to write the final piece of code. This will listen for our custom ‘scrolled’ event and when fired will simply set our ‘shrinkCssClass’ property with the correct CSS class (which will be the value ‘shrink-header’ to add or an empty string to remove the class).

  1. Make sure the ‘header.component.ts’ file is open
  2. Import our custom directive by adding the following line directly underneath the other imports:

    import { TrackScrollDirective } from '../directives/trackscroll.directive';
    
  3. Add the ‘TrackScrollDirective’ to the directives array in the component metadata:

    @Component({
        selector:'my-header',
        templateUrl: 'app/header/header.component.html',
        styleUrls: ['app/header/header.component.css'],
        directives: [TrackScrollDirective]
    })
    
  4. In the ‘HeaderComponent’ class implement the method which should be executed when the ‘scrolled’ event is fired:

    export class HeaderComponent{
        shrinkCssClass : string = '';
    
        onScrolled(yPos : number) {
            this.shrinkCssClass = yPos ? "shrink-header" : "";
        }
    }
    
  5. Open the ‘header.component.html’ file
  6. Add the ‘track-scroll’ directive to the ‘<nav>’ element and use property binding to subscribe to the ‘scrolled’ event:

    <nav [ngClass]="['navbar', 'navbar-default', 'navbar-fixed-top', shrinkCssClass]" track-scroll (scrolled)="onScrolled($event)">
      ...
    </nav>
    

After these changes your files should look like this:

header.component.ts

import { Component } from '@angular/core';
import { TrackScrollDirective } from '../directives/trackscroll.directive';

@Component({
    selector:'my-header',
    templateUrl: 'app/header/header.component.html',
    styleUrls: ['app/header/header.component.css'],
    directives: [TrackScrollDirective]
})
export class HeaderComponent{
    shrinkCssClass : string = '';

    onScrolled(yPos : number) {
        this.shrinkCssClass = yPos ? "shrink-header" : "";
    }
}

header.component.html

<nav [ngClass]="['navbar', 'navbar-default', 'navbar-fixed-top', shrinkCssClass]" track-scroll (scrolled)="onScrolled($event)">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">
        My First Angular 2 App
      </a>
    </div>
  </div>
</nav>

Testing the code

Yeah! Finally we are finished, lets run ‘npm start’ and see the header shrink. Hmmm wait there isn’t anything to scroll, so our header has nothing to respond to. Lets quickly fix this:

  1. Open the ‘app.component.ts’ file
  2. In the component metadata replace the value for the ‘template’ property to match the following code:
    @Component({
      selector: 'my-app',
      template: '<my-header></my-header><div style="height: 2048px; border: solid 1px #000;">Some scrollable content.</div>',
      directives: [HeaderComponent]
    })
    

These steps will simply add a ‘<div>’ container after our header with a height of 2048 pixels. This should be high enough to make the page scroll. Now lets test the application again (if not yet done run the ‘npm start’ command from the command-line). Now the application should look something like this:

Finished header

And sure enough when we start scrolling the header will shrink:

Shrunk header

That’s it for this article. I hope you found this post helpful, if you have any suggestions, questions or comments be sure to leave a message.

Easy extension method to show a wait cursor the proper way

When developing windows application you will probably have to deal with showing a wait cursor when executing a time consuming task. When you implement this correctly your code will look something like this:

private void ExecuteButton_Click(object sender, EventArgs e)
{
  try
  {
    this.UseWaitCursor = true;
 
    // Execute a long running task.
    ...
  }
  finally
  {
    this.UseWaitCursor = false;
  }
}

By encapsulating the structure into a try..finally statement we ensure that the cursor is always reset back to its original value (even when an exception occurs).

To prevent repeating this structure every time I need to show a wait cursor I developed the following extension method:

public static class WinUiExtensions
{
  public static void ShowWaitCursor(this Control control, Action action)
  {
    try
    {
      control.UseWaitCursor = true;
 
      action();
    }
    finally
    {
      control.UseWaitCursor = false;
    }
  }
}

This allows me to rewrite the first example to the following code:

private void ExecuteButton_Click(object sender, EventArgs e)
{
  this.ShowWaitCursor(() => 
  {
    // Execute a long running task.
    ...
  });
}

This ShowWaitCursor is now available for all instances of the Control class and classes that derive from the control class. And the biggest plus is LESS CODE TO WRITE FOR ME :D.

Helper class for testing INotifyPropertyChanged implementation

Download source: TestHelpers – source.zip

When you make use of databinding in your .NET application, changes are that you also had to implement the INotifyPropertyChanged interface in your business domain classes. And of course as a true believer in test-driven development you want to write unit-test to ensure each PropertyChanged event is fired correctly when the value of one of the properties in you domain class is changed. This was exactly the issue I was facing. After trying my luck on the googlematic I found the article “Testing OnPropertyChanged” by Brad Irby. The code that I will use in this post is heavily based on this article, I basically only wrapped it in a helper class which makes it a bit easier to reuse, so all credits go out to Brad Irby.

As I already mentioned I created a helper class to assist in testing if the PropertyChanged event(s) is fired correctly. This helper class is named PropertyChangedTestHelper has the following methods:

  • PropertyChangedTestHelper(INotifyPropertyChanged): This is the constructor of the helper class. The constructors expects an instance of the class under test which implements the INotifyPropertyChanged interface. The constructor will ensure the helper class subscribes to the PropertyChanged event so it is able to keep track if the event is called.
  • RegisterExpectation(string): This method will register a new expectation indicating that the property (which name matches the supplied string) should fire a PropertyChanged event.
  • RegisterExpectation(Expression<Func<TResult>>): This method like the previous method also registers a new expectation indicating that the specified property should fire a PropertyChanged event. However instead of using a magic string it will use lambda and the Expression class to resolve the property name which is expected to fire the PropertyChanged event. This method has my preference since it will generate compiler errors when the original property is renamed. An example on how to use this method could look like this:
    RegisterExpectation(() => target.MyProperty);
  • VerifyExpectations(): This method is used to check if after acting on the target all expectations were met. This method will verify the following conditions:
    1. if for each registered expectation a matching event was fired (matching is done by comparing the property names of the registered expectation with the property name supplied in the PropertyChangedEventArgs when handling the PropertyChanged event).
    2. if the amount of registered expectations matches the amount of PropertyChanged events which were actually fired.

    When one of the conditions is not met the method will throw an AssertFailedException.

To demonstrate the use of the PropertyChangedTestHelper class I create the following Dummy class which implements the INotifyPropertyChanged interface:

public class Dummy : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;
 
   private void OnPropertyChanged(string propertyName)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
   }
 
   private string _firstValue;
   public string FirstValue
   {
      get { return _firstValue; }
      set
      {
         if (_firstValue != value)
         {
            _firstValue = value;
            OnPropertyChanged("FirstValue");
         }
      }
   }
 
   private string _secondValue;
   public string SecondValue
   {
      get { return _secondValue; }
      set
      {
         if (_secondValue != value)
         {
            _secondValue = value;
            OnPropertyChanged("SecondValue");
         }
      }
   }
}

I have designed the PropertyChangedTestHelper class so that it can be used according to the popular Arrange, Act, Assert pattern. The following unit test gives an example on how the PropertyChangedTestHelper class can be used:

[TestMethod]
public void FirstValue_PropertyChangedTest()
{
   Dummy target = new Dummy();
 
   using(PropertyChangedTestHelper helper = new PropertyChangedTestHelper(target))
   {
      // Arrange: Registeer de verwachting dat de TestValue property een PropertyChanged event afvuurt
      helper.RegisterExpectation(() => target.FirstValue);
 
      // Act: Zorg ervoor dat de TestValue een andere waarde krijgt
      target.FirstValue= "Test 123";
 
      // Assert: Controleer of er aan de geregistreerde verwachtingen is voldaan
      helper.VerifyExpectations();
   }
}

And the following example shows an unit test that will throw an assert, because it registered more expectations then PropertyChanged events that actually got fired:

[TestMethod]
public void FirstValue_PropertyChangedTest()
{
   Dummy target = new Dummy();
 
   using(PropertyChangedTestHelper helper = new PropertyChangedTestHelper(target))
   {
      // Arrange: Registeer de verwachting dat de TestValue property een PropertyChanged event afvuurt
      helper.RegisterExpectation(() => target.FirstValue);
      helper.RegisterExpectation(() => target.SecondValue);
 
      // Act: Zorg ervoor dat de TestValue een andere waarde krijgt
      target.FirstValue = "Test 123";
 
      // Assert: Controleer of er aan de geregistreerde verwachtingen is voldaan
      helper.VerifyExpectations();
   }
}

For more detailed examples of the helper class please download the source and check the PropertyChangedTestHelper test project.

Reading an Excel Workbook using C# and OLEDB

Recently I had to read some data from a Microsoft Excel Workbook using C# and OLEDB. Although I have done this several times before, I still had to Google a few times how to get things done. So I decided to create this post as a quick reference for everybody that wants to query an Excel Workbook using C# and OLEDB.

The connection string

First of all we have to connect to the Excel Workbook. Depending of the version of the Excel Workbook you can use one of the following connection strings:

  • Microsoft Excel 2007
    Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myexcelfile.xlsx;Extended Properties="Excel 12.0;HDR=YES;IMEX=1";
  • Microsoft Excel 2003
    Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\myexcelfile.xls;Extended Properties="Excel 8.0;HDR=YES;IMEX=1";

An important part from the connection strings listed above is the attribute ‘Extended Properties’. In this attribute you can include the following options:

  • “HDR=Yes;” this option indicates that the first row from the selection will contain the columnnames and not data. “HDR=No;” obviously indicates the opposite and will return the first row of the selection as data. In this case the OLEDB driver will create columnnames for each column in the selection (F1 to Fn).
  • “IMEX=1;” indicates that the OLEDB driver a column containing values of different types (e.g. numbers, strings and date values) should read these values as text. “IMEX=0;” indicates that the driver should read the values according to the source type of the Excel column.

NOTE: By default the OLEDB driver will only scan the first eight rows to determine if the column contains values of different types when IMEX is set to 1. If the first eight rows don’t contain any intermixed types but lets say only numeric values, the driver will read all values as numbers (and not as text). More information on this topic can be found here ‘http://www.connectionstrings.com/excel‘ and here ‘http://dougbert.com/blog/post/importing-from-excel-imex-and-mixed-data-types.aspx‘.

Querying data from an Excel sheet

Now we know what the connection string looks like, we can start querying the Excel sheet. The code example below shows how to read all data from the first sheet in the Excel sheet:

string connString = "Provider=Microsoft.Jet.OleDb.4.0; data source=c:\\myexcelfile.xls; Extended Properties=\"Excel 8.0;HDR=Yes\";";  
string query = "SELECT * FROM [Sheet1$]";  
using (var connection = new OleDbConnection(connString))  
{  
  using (var da = new OleDbDataAdapter(query, connection))  
  {  
    connection.Open();  
    DataSet ds = new DataSet();  
    da.Fill(ds);  
  }  
}

Sometimes the data you need is located at a specific position within the Excel sheet (for example starting at cell B12 to cell L502). In this case you can extend your query with a specific range, like so:

SELECT * FROM [Sheet1$B12:L502]

It is also possible to query the data defined in Excel as a ‘Named range’ (instructions on how to create a ‘Named range’ can be found here ‘http://www.contextures.com/xlnames01.html‘). To query a ‘Named range’ simple construct your select query like so:

SELECT * FROM MyRange

Querying the sheets in the Excel Workbook

Sometimes you don’t know which sheets are available in a Excel Workbook beforehand. In these cases it can be useful to first query the Excel Workbook for the available sheets before you can query the sheet for the data you need. You can do this by making use of the ‘GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null)’ method of the ‘OleDbConnection’ class. Below is an example on how to use this method:

private string _connString = "Provider=Microsoft.Jet.OleDb.4.0; data source=c:\\myexcelfile.xls; Extended Properties=\"Excel 8.0;HDR=Yes\";";
 
public string[] GetSheetNames()
{
  string[] workSheetNames;
 
  using (var connection = new OleDbConnection(_connString))   
  {
    connection.Open();
 
    DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);   
    workSheetNames = new string[dt.Rows.Count];   
    int i = 0;   
    foreach (DataRow row in dt.Rows)   
    {   
      workSheetNames[i] = row["TABLE_NAME"].ToString().Trim(new[] { '$' });   
      i++;   
    }   
  }   
 
  return workSheetNames;
}

Conclusion

In this post I have shown how to construct a connection string which can be used to connect to an Microsoft Excel Workbook using C# and OLEDB. After that I have shown a few examples on how to query the Excel sheets for data. Last but not least I have shown you how to query the Excel Workbook for the available sheets.

I hope you have found this post helpful and enjoyed reading it. If you have any questions don’t hesitate to leave a comment.

How to mock a static method call in your unit-test

Assume you have the following method in your data access layer and you want to ensure it works as intended by writing an unit-test.

public class EmployeeRepository
{
  public IList<IEmployee> GetEmployees()
  {
    string sql = "SELECT " +
      "FROM " +
      "ORDER BY ASC";
 
    return Db.Read(sql);
  }
}

It should be pretty clear that this method builds a SQL statement to fetch all employees from the database and calls the static ‘Read(string sql)’ method on the ‘Db’ class.

Ideally when I write the unit-test I would like to make sure the code under test is isolated from other methods, classes or tests. This means that for the method above I am only interested in the part which builds the SQL statement and the call to the ‘Read(string sql)’ method. However we are not interested in how the ‘Read(string sql)’ method executes. Normally you would create a mock of the ‘Db’ class and register an expectation on the ‘Read(string sql)’ method. Since we are dealing with a static class it is impossible to create a mock. Assuming we have access to the source code of the ‘Db’ class and there are no other libraries that link to the ‘Db’ class, we could go ahead and refactor the static class to an instance class but this will bring a few disadvantages:

  • We need to refactor the ‘Db’ class to make it an instance class instead of static. This means we also need to apply the Singleton pattern to ensure the class only exists once in memory.
  • All the code that uses the static class needs to be refactored to use the new Singleton class.

When we don’t have the source code of the ‘Db’ class (because it is part of a third party component) or there are other applications or libraries that rely on the static ‘Db’ class it is simply not possible to change the static class. So how do we test the method if we cannot change the ‘Db’ class. It took me a long time until I found the solution, which is actually pretty easy. Here is how I solved it:

public class EmployeeRepository
{
  internal Func<string, IList<IEmployee>> ReadFromDb = 
    (sql) => Db.Read(sql);
 
  public IList<IEmployee> GetEmployees()
  {
    string sql = "SELECT " +
      "FROM " +
      "ORDER BY ASC";
 
    return ReadFromDb(sql);
  }
}

I extracted the call to the ‘Read’ method of the ‘Db’ class by assigning it to the ‘Func‘ delegate using the ‘(sql) => Db.Read(sql);’ lambda expression. Then I replaced the old call to the ‘Read(string)’ method by calling the new ‘ReadFromDb(string)’ delegate instance.

This allows me to replace the default initialization of the ‘ReadFromDb’ delegate in my unit-test with a different lambda expression which gives me access to the actual SQL statement. Such a unit-test could look like this:

[TestMethod]
public void GetEmployeesTest()
{
  string expectedSql = "SELECT " +
      "FROM " +
      "ORDER BY ASC";
  string actualSql = string.Empty;
 
  EmployeeRepository target = new EmployeeRepository();
 
  // Replace the ReadFromDb delegate by a custom lambda 
  // expression to extract the SQL statement from the
  // GetEmployees method
  target.ReadFromDb = (sql) => 
    {
      actualSql = sql;
      return new List<Employee>();
    };
 
  // Call the GetEmployees method to start the test
  target.GetEmployees();
 
  // Check if the expectations are matched
  Assert.AreEqual(expectedSql, actualSql);
}

One more thing that needs to be done is make the internals from the data access layer available for the test project. To do this add the following line in the ‘AssemblyInfo.cs’ of your data access layer project:

[assembly: InternalsVisibleTo("<assemblyname of test project>, PublicKey=<public key>")]

You can get the public key of an assembly using the ‘Sn’ command line tool like this:

Sn.exe -Tp <assemblyname>

Another nice way of getting the public key directly from within Visual Studio is described here: WebPart Tip: How to quickly view the public key for an assembly in the output window.

Tutorial – Building a Windows Service application in C#

In this post I will explain how to build a Windows Service application which (for debug purposes) could also be started as a Windows Console application using the .NET Framework 2.0 or higher (I recently tested this with .NET Framework 4.5.2, the article below is still applicable). The source code of the application can be downloaded here.

During the course of this article we will construct a small application which will leave a message in the Windows Event Log every minute. The application is of course completely useless, however it demonstrates how to construct a Windows Service application which could also be started as a Windows Console application. Leaving messages in the Windows Event Log also makes it easy for us to see if the application is working correctly when running as a Windows Service. Continue reading

Executing a dynamic T-SQL query (using sp_executesql)

Today at work I needed to make a simple stored procedure containing a simple search query with some dynamic ‘WHERE’ conditions. Since I am working with Miscrosoft SQL Server 2005 I could pick between the EXECUTE (or EXEC) command or the ‘sp_executesql’ system stored procedure.  I knew that both options existed and until today I always figured they were just an alias for each other (shame on me). I finally decided to spend some time researching if there are any differences between the two commands. This is where I stumbled upon the following blog post from Pinal Dave: SQL SERVER – 2005 Comparison SP_EXECUTESQL vs EXECUTE/EXEC.

As explained by Pinal Dave you should use sp_executesql over the EXECUTE command because it accepts parameterized statements. Parameterized statements has a few big advantages (for more details please read Pinal Dave’s article):

  1. Using parameterized statements is more secure, since you don’t have to worry about SQL injection (when implemented properly of course).
  2. Parameterized statements give the advantage of a cached query plan, which improves performance.
  3. Parameterized statements also improve the readability of your SQL code.

So far so good everything is clear lets forget about the EXECUTE command and start using the ‘sp_executesql’ stored procedure from now on… Continue reading

Easy way to backup a Linux system

Recently I started experimenting with Linux (Ubuntu and Debian). Coming from a Microsoft background I was always interested in what else was out there. It didn’t take long before I had my first server up and running. This is where the fun begins, I decided to build a mail server. During the configuration process I struggled a lot and decided several times to renew the complete Linux installation (since I was still learning I messed up a lot). As you can imagine  I was ecstatic when I finally got my first e-mail. This is where I figured I needed a way to backup my new mail server since there was much more experimenting to do and probably I will mess up many many more times.

After browsing the net for ways to backup my new Ubuntu server I realized there is a lot of information out there and I just have to put the stuff together. To save you the time and headaches of having to do the same I will explain how I put everything together… Continue reading