Monday, November 29, 2010

Smelly code

Original, smelly code
public bool isLocked(string s)
{
    if (!File.Exists(s)) return false;
    try { FileStream f = File.Open(s, FileMode.Open, FileAccess.ReadWrite); f.Close(); }
    catch { return true; }
    return false;
}

Objections and Comments
The code abve has in my eyes several problems:

  1. Method name starts with lower case
  2. The name of the input parameter is meaningless
  3. Logical code blocks are not separated by a new line
  4. You need some time to understand what this 4 lines of code do
  5. Multiple instructions on the same line
  6. The "return false;" statement should be inside the try block because it is logically associated to it
  7. Missing Method documentation


Proposed Refactoring
/// <summary>
/// Checks if a file is in use or not.
/// </summary>
/// <param name="filePath">The path to the file that should be checked.</param>
/// <returns>True if the file is locked; false otherwise</returns>
public bool IsLocked(string filePath)
{
    if (!File.Exists(filePath))
    {
        return false;
    }

    try
    {
        FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);
        fileStream.Close();
        return false;
    }
    catch
    {
        return true;
    }
}

Monday, July 19, 2010

Strange undestroyable folders

A friend of mine had a very very strange problem. Suddenly on his external hard disk there appeared a bunch of very strangely named folders like "%/sl94..." and other symbols which windows was not able to display. They occupied 300GB and clearly my friend wanted to delete them; unfortunately windows was not able to delete them. It gave always an error like "Path not found" or "Invalid path symbols".
I tried then to delete them with different data shredders but none of them was able to successfully delete them.
I have then run also different virus and spy-ware scanners over them but none of them found something.
I was stuck and at the end with my knowledge.

Then I found on the Internet the good old command line instruction:

del foldername

With that I was finally able to delete them all.

Direct SQL vs. View vs. Stored Procedure

I was wondering for a very very long time what all these "battels" around direct sql, views and stored procedures are about. I read several articles on the Internet where people were claiming that nowadays there is almost no difference anymore between these three database "constructs". I saw many discussions and blogs where people tested the performance of these three with different results and that made me even more confused.

So as I am curious and the fact that I need to know this as a software developer I decided to try this out by myself. At work I had the chance to test this against a very large amount of real data (I needed to optimize this query anyway);
Sometimes the sample databases which are used for theses kinds of tests are either very small or very simple or even both which makes not really sense in my eyes.

So the query consisted of joins of multiple tables with a case in the select statement. I run the query 300 times with every "construct" and then I took the average value for all three of them in order to reduce network and SQL Server workload "noise".

The result of my test (in Ticks):

Direct SQL

23077

View

19363

Stored procedure

3438

So what I found out for myself is that it really does matter what kind of "construct" you use to query your data; especially on a large amount of data.
On large data you should also take into consideration that a big performance impact may also have where you set your indexes and which statistical data you let create by SQL Server.

If you made other experiences on this, please let me know and leave a comment...

Executing SQLQueries on ObjectContext

Recently I worked with the entity framework (3.5) and at some point I had the need to execute a custom SQL command. Fortunately does the object context provide the underlying DBConnection and with that you can simply execute SQLCommands.

I read on the Internet that the new Version (4.0) has already integrated something similar.

This is an extension Method that I wrote which makes it easy to execute these queries:


public static void ExecuteSQL(this ObjectContext context, string sql)
{
var connection = context.Connection;
var command = connection.CreateCommand();
command.CommandText = sql;

try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}

Monday, July 5, 2010

Handy Windows shortcut

Sometimes it happens to me that I have to copy the path of a file to the clipboard and paste the it somewhere (console, visual studio, etc.); but it is not as easy to get the path as it is with folders where you can simply get it from windows explorer.
Windows has a hidden shortcut to get the path; when you press "shift" and click with the right mouse button on a file then in the context menu you get an additional entry which is called
"Als Pfad kopieren" or "Copy as path". Afterwards you can simply paste wherever you need it.
I find this feature extremely useful.

Saturday, November 21, 2009

USB 2.0 vs. Firewire 400 vs. eSATA

To backup my data I bought the external harddisk Western Digital My Book Home Edition with a capacity of 1 Terabyte which provides the following interfaces:
  • 2 x Firewire 400
  • 1 x USB 2.0
  • 1 x eSATA
As I was curious to see how big is the difference between these interfaces I did some performance testing.
This are the results:




I did the perfomance testing under Windows Vista 64bit edition with the tool HDD Speed Test Tool by Marko Oette.
Regarding the eSATA interface I would like to say that the hot plug works (connect/disconnect while windows is running) and that while working with my computer I encountered sometimes some strange problems. The whole computer was blocked especially when I used applications that show an open file dialog or something similar. As soon as I unplugged the external HDD everything worked well. I would say that eSATA does not work 100%. This may be especially frustrating when making a backup of very large files and during the backup the HDD disappears (which happened to me). I don't exactly know if it is a driver, hardware or Windows Vista problem.

Search highlighting in WPF DataGrid

Unfortunately the DataGrid of the WPF-Toolkit does not provide a text highlighting feature out of the box; but sometimes it is very usefull for the users to be able to search for text or numbers in the datagrid to find the interesting information more quickly.
Tomer Shamam did a very good work which highlights a search key in different colors depending on which column they were found.

The only things which I don't like on his solution are:
  1. It works only if the datasource of the datagrid are objects
  2. That you have to define a style for every property you want to be highlighted in the datagrid which may be a big work if you have 15 properties for example
  3. When a row with a match is selected you do not see anymore which cell was highlighted
For my pupose I don't need the feature of the different coloring because I want only to highlight all cells in the datagrid where the search term is present in the same color. To resolve all of the above issues I changed the code of Shamam slightly.
You still need this two helper classes written by Shamam:
public class SearchTermConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var stringValue = values[0] == null ? string.Empty : values[0].ToString();
var searchTerm = values[1] as string;

return !string.IsNullOrEmpty(searchTerm) &&
!string.IsNullOrEmpty(stringValue) &&
stringValue.ToLower().Contains(searchTerm.ToLower());
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}

and
public static class SearchOperations
{
public static string GetSearchTerm(DependencyObject obj)
{
return (string)obj.GetValue(SearchTermProperty);
}

public static void SetSearchTerm(DependencyObject obj, string value)
{
obj.SetValue(SearchTermProperty, value);
}

public static readonly DependencyProperty SearchTermProperty =
DependencyProperty.RegisterAttached(
"SearchTerm",
typeof(string),
typeof(SearchOperations),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.Inherits));

public static bool GetIsMatch(DependencyObject obj)
{
return (bool)obj.GetValue(IsMatchProperty);
}

public static void SetIsMatch(DependencyObject obj, bool value)
{
obj.SetValue(IsMatchProperty, value);
}

/* Using a DependencyProperty as the backing store for IsMatch. This enables animation, styling, binding, etc...*/
public static readonly DependencyProperty IsMatchProperty =
DependencyProperty.RegisterAttached("IsMatch", typeof(bool), typeof(SearchOperations), new UIPropertyMetadata(false));
}

As far as I understood this code defines a new dependancy property on the datagrid where the search term is stored and another dependancy property on each cell which stores wheter it is a match or not. Through the style which is defined in the Resource section of the page the "IsMatch" property is used to format the cell accordingly.
This is my modified XAML code to search the text of the datagrid instead of the property. Here you can also change the different colors if you like.
<Grid.Resources>
<local:SearchTermConverter
x:Key="SearchTermConverter" />

<SolidColorBrush
x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Blue" />

<SolidColorBrush
x:Key="HighlightColor"
Color="Yellow" />

<SolidColorBrush
x:Key="SelectedHighlightedColor"
Color="Red" />

<Style
x:Key="DefaultCell"
TargetType="{x:Type toolkit:DataGridCell}">
<Setter
Property="local:SearchOperations.IsMatch">
<Setter.Value>
<MultiBinding
Converter="{StaticResource SearchTermConverter}">
<Binding
RelativeSource="{RelativeSource Self}"
Path="Content.Text" />
<Binding
RelativeSource="{RelativeSource Self}"
Path="(local:SearchOperations.SearchTerm)" />
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger
Property="local:SearchOperations.IsMatch"
Value="True">
<Setter
Property="Background"
Value="{StaticResource HighlightColor}">
</Setter>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition
Property="IsSelected"
Value="True" />
<Condition
Property="local:SearchOperations.IsMatch"
Value="True" />
</MultiTrigger.Conditions>
<Setter
Property="Background"
Value="{StaticResource SelectedHighlightedColor}"></Setter>
</MultiTrigger>
</Style.Triggers>
</Style>
</Grid.Resources>

Then the style is assigned to the datagrid:
<toolkit:DataGrid
AutoGenerateColumns="True"
Name="dgvDataTable"
CellStyle="{StaticResource DefaultCell}"
Margin="0,256,0,0"
Background="White" />

And finally the textbox connected to the "SearchTerm" property of the datagrid;
either via code in the TextChanged event of the TextBox:
SearchOperations.SetSearchTerm(this.dgvObjects, this.textBox1.Text);


or via XAML:
<Window
x:Class="SearchHighlighting.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="460.138"
Width="502"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:local="clr-namespace:SearchHighlighting">
...
<toolkit:DataGrid
AutoGenerateColumns="True"
Name="dgvDataTable"
CellStyle="{StaticResource DefaultCell}"
Margin="0,256,0,0"
Background="White"
local:SearchOperations.SearchTerm="{Binding ElementName=textBox1, Path=Text}" />


The result looks like this:



You can download the whole project from here.