Watch that Linq to sql code code generation at run time

February 20, 2012 at 3:30 PMKevin Bosch

Linq to SQL is a very powerful technology. It integrates the data access and the .Net language very nicely allowing seamless development syntax for accessing database from within the .NET code. However it pays to watch and understand what the Linq to SQL generates against the Database as on the odd occasion it can make some bad performance decisions. There are opportunities to restructure the linq to produce performance gains.

Lets take a look at a hypothetical example

More...

Posted in: C#

Tags: , ,

Finding Unused and missing Indexes in a SQL database.

February 13, 2012 at 3:20 PMKevin Bosch

Motoring Indexes on a SQL server database is a continuous task. Index usage on SQL Server can and does change as the software evolves or even as actual usage of the application changes over time. As such indexes in the database should be monitored and maintained on regular basis. Fortunately SQL Server provides a few DMV’s (Dynamic Management Views) which can help with the process of index optimization. This process involves finding and deleting unused indexes, then looking for potential missing indexes which need to be created. Then finally observing the changes over time then repeating the process.

More...

Posted in: SQL development

Tags: ,

The point at which StringBuilder becomes more efficient than string concatenation

February 11, 2012 at 10:32 AMKevin Bosch

I have always wanted to know at what point does the StringBuilder class becomes more efficient that simple string concatenation. There is no doubt that the StringBuilder it is faster using multiple concatenations especially on a large string output such as a web page but at what point. So what I did is come up with a test to indicate where the cross over point was.

Fundamentally the test is testing the following two blocks of code:

String Concatenation
string result = string.Empty;
result += simpleString;
return result; 

StringBuilder
StringBuilder result = new StringBuilder();
result.Append(simpleString);
return result.ToString();
More...

Posted in: C# | Micro Performance

Tags: , ,

What is this fastest method for testing Empty Strings?

February 4, 2012 at 1:01 PMKevin Bosch

Every now and again you come across a process which is CPU bound. That is the process is using 100% of the CPU for an extended period of time. In these cases it becomes important to start optimising every piece of code you can. You come down to the Micro Performance element of code. In general you not going to notice micro performance benefits unless your code is close to 100% CPU bound and the given piece of code is executed millions of times over.

There are often many different ways to implement a given piece of code. Testing if a string is empty is great example. Below are 6 different methods which yield the same result assuming the input string (str) is not null.

Test 1 - You can use the equality comparison with a new string:

    if (str != ""){...}

Test 2 - You can use the equality comparison with a const string.empty

    if (str != string.Empty){...} 

Test 3 - You can use the String. Equal method

    if (str.Equals(string.Empty)){...} 

Test 4 - You can use the String.Length property

    if (str.Length != 0){...} 

Test - 5 You can use the String.IsNullOrEmpty Method

    if (string.IsNullOrEmpty(str)){...} 

Test 6 - You can test null and String.Len property

    if (!(str == null) && str.Length != 0){...} 

 

Given a non-null string the 6 methods above produce exactly the same results. However it should be noted that tests 3 and 4 cannot deal with null values and an exception will be thrown. More...

Posted in: C# | Micro Performance

Tags:

ObjectCopier to Copy Common Properties between objects

August 10, 2011 at 4:11 PMkevinbosch

A useful method to copy properties from one object to another object which has common properties. This is useful is you have a design which uses DTO type objects. Rather than going and writing lines of copy type code you can make a single call to

ObjectCopier.CopyCommonProperties(object1, object2);

public static void CopyCommonProperties(object source, object destination) { var myObjectFields = destination.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var pi in myObjectFields) { if (pi.CanWrite) { var sourcepi = source.GetType().GetProperty(pi.Name); if (sourcepi != null && sourcepi.CanRead) if (pi.PropertyType.FullName == sourcepi.PropertyType.FullName) pi.SetValue(destination, sourcepi.GetValue(source, null), null); } } }
Example Unit Test to show usage More...

Posted in: DataTable

Tags: , ,

Method to generate your own Asp.NET machineKey validationKey and decryptionKey

September 14, 2010 at 6:58 AMkevinbosch

Often when using pre built framework web applications they have hard coded the <machineKey> validationKey and decryptionKey values. The main reason for this is to add support for web farms as the forms authentication, view state and out of process session state all use these settings for security. Whilst most of these frameworks work out of the box, using the defaults out of the box mitigates most of the benefit of the encryption as the keys are public knowledge becuase the source code is published. Take for example dot Net Nuke whcih is a popular framework, their default encryption keys are hard coded as. More...

Posted in:

Tags: ,

Adding Image captcha to BlogEngine.NET

September 11, 2010 at 5:42 AMkevinbosch

One of the things I liked about BlogEngine.NET is that it had a hidden Captcha feature to mitigate the use of Bots posting comments on the site. However over the last couple of weeks I have noticed a vast increase in amount of bots posting comments and it is getting a little tedious deleting those comments. So I have elected to go add an image Catpcha solution on top of the BlogEngine.NET solution.

The Catpcha solution I ended up using was one derived from http://www.brainjar.com/dotNet/CaptchaImage/ however I elected to use encryption rather than session variables as an academic exercise on how to make it more scalable. More...

Posted in: C#

Tags: , ,

A windows command line application to resize images in a directory

August 25, 2010 at 4:16 PMkevinbosch

I came across a need to resize a whole bunch of images. So I decided to write a little console application in .NET to do the work for me. With 100’s of images to resize it was worth the effort in creating a little application to do the job for me. CA.Console.ResizeImage.exe is what I came up with the source code is listed in this post

CA.Console.ResizeImage.exe is a command line windows utility that resizes the following supported images "jpeg,gif,bmp,png" in a given directory to a maximum size keeping the aspect ratio. It is possible to configure the source, destination and maximum size of the images via config file or command line switches it also has some default options for click and go solution. You can download the ziped binary and config file CA.Console.ResizeImage.exe.zip (4.69 kb).

In the simplest case, you can just copy CA.Console.ResizeImage.exe into the directory of your images and double click on it. It will then generate new images with the same name into a folder called ResizedImages without any configuration it will resize all images to 500 x 500 adjust height or width accordingly to keep aspect ratio. More...

Posted in: .NET Development | DataTable

Tags: ,

T4 Text Template Transformation engine

August 14, 2010 at 4:07 PMkevinbosch

I have just found out about the existence of T4 generator today. Is a very simple yet powerful Template based text generation engine. It uses very familiar asp.net syntax <# #> Its simplicity is its strength. There is a good site on the T4 Text Template Transformation Toolkit by Oleg Sych

T4 Text Transformation Engine

If you have not tried it out you should give it a go.

Looking at generation I am wondering why they have stopped at the generation part. MVC pattern is screaming out to be implemented as part of the generation. I know the MVC model is designed to be implement as part of user interface design. However I think there is a good fit here. The Template generation is clearly the rendering of the view. The model will be the domain specific model such as the data schema when implementing the crud model on top of a relational schema. The controller is responsible for populating the model based on the instance required by the view. As such the part which is screaming out to be specialized is the controller.

Consider the power of the following example which from what i can tell is not possible

        <@# template language="C#" Inherits="GeneratedTextTransformation<MyHelloWorld>#> 
        <# Write(Model.HelloWorld); #>

There is still a bit of learning to do, T4 is looking promising

Posted in: DataTable

Tags:

Getting the last inserted value using SCOPE_IDENTITY()

August 14, 2010 at 6:09 AMkevinbosch

In SQL server the are three ways to get the latest value of an Identity Record

  1. SELECT @@IDENTITY
  2. SELECT IDENT_CURRENT(‘tablename’)
  3. SELECT SCOPE_IDENTITY()

SELECT @@IDENTITY

This will always return the last IDENTITY value produced on a given connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. While @@IDENTITY is limited to the current session, it is not limited to the current scope. For example if a trigger is added to a table to do auditing and that audit table has a Identity Column the value of the @@IDENTITY will contain the identity value for the trigger table and not the table within the codes scope. This is because the the trigger insert fired after the table insert.

SELECT IDENT_CURRENT(‘tablename’)

This statement will return the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. This is very seldom used as IDENT_CURRENT is only limited to a specified table and can cause havoc in a multi user environment if relied on. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

SELECT SCOPE_IDENTITY()

It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. like @@IDENTITY it will will return the last identity value created in the current session, however the but the SCOPE_IDENTITY() will also be limit it to your current scope. When inserting into a table it will only return the identity for that table and will not return and other inserts any triggers could have caused. This is typically what is expected when authoring code.

So when considering @@IDENTITY vs SCOPE_IDENTITY() always go with SCOPE_IDENTITY(). Using @@IDENTITY is opening up potential problems when triggers which involve identity columns are subsequently added to tables.  Using SCOPE_IDENTITY() will always return the the expected value in the context of the last insert statement. and will protect your code from any triggers added at a later date.

 

 

Posted in: SQL development

Tags: