November 2009 - Posts
Execute T-SQL Statements in Entity Framework 4
In this post I’m
going to show a
new Entity Framework 4
feature that enable us
to execute T-SQL
from the ObjectContext
directly to the database.
Executing T-SQL Statements from ObjectContext
One of the new improvements in EF4 is the ability to execute
T-SQL store queries and commands. This ability enable the EF
developer to execute T-SQL directly against the database. This ability
should only be used in cases that Entity Framework doesn’t support
something that you need which can be a very complicated query for
example. In order to use this feature the ObjectContext supply two new
methods: ExecuteStoreQuery<T> and ExecuteStoreCommand.
Using ExecuteStoreQuery<T> Method
The ExecuteStoreQuery<T> method should be used to query
data and return it in the shape of the given generic parameter.
The method will only work if T has default constructor and also
there is a one to one match between the returned column names
and the class property names. This imply that you can use any class
that you want which confirm to the restrictions as the T generic
parameter and not only EF generated entities. If the classes are
entities you can provide the EntitySet name and a MergeOption
in order to connect the entity to the ObjectContext.
You use the method like in the following example:
class Program
{
static void Main(string[] args)
{
using (var context = new EntityFrameworkExampleEntities())
{
var query = context.ExecuteStoreQuery<Company>("SELECT * FROM Companies");
foreach (var company in query)
{
Console.WriteLine(company.CompanyName);
}
}
Console.ReadLine();
}
}
This is a very simple query that only show the concept of how to use
the method. In such queries I won’t bother to use ExecuteStoreQuery<T>
since I can use LINQ to Entities instead.
Using ExecuteStoreCommand Method
The
ExecuteStoreCommand method should be used to send a command
to the database such as update, delete or insert. The return value is
the number of rows that were affected by the command you sent.
The following is a very simple delete command:
class Program
{
static void Main(string[] args)
{
using (var context = new EntityFrameworkExampleEntities())
{
var count =
context.ExecuteStoreCommand(@"DELETE FROM Companies
WHERE [CompanyID]=4");
Console.WriteLine(count);
}
Console.ReadLine();
}
}
As in the previous example this is only a simple example.
Summary
Lets sum up, there are times that you hit a wall when you use EF.
It can occur in very complicated commands or queries that you need
in your application but LINQ to Entities can’t help you with them. In
such situations ExecuteStoreQuery<T> and ExecuteStoreCommand
can come to your help.
Applying Strategy Pattern Instead of Using Switch Statements
Once in a while I’m stumbling on switch statements during a
Code Review session. Whenever this is happening my first reaction
is to understand why did the developer use it.
Since using switch statement sometime implies spaghetti code and
also can get very crowded (in case statements of course) in this post
I’m going to show an alternative method that I prefer to use.
Alternative Method for Switch Statements
Whenever you start to use a switch statement you should
ask yourself whether you can use Strategy Pattern instead.
The Strategy Pattern help us to divide an algorithm from a host class
and then move it to another class. By doing so the client can choose
which algorithm will be performed in runtime from a set of algorithms
that were implemented earlier.
The Strategy Pattern can also help us when we want to replace a
switch statement. We can look at every case as a different
algorithm that we want to use which differ only by some condition
or a key. Since this is the case, for every case we can build a class that
do an action (the algorithm) and by that we can prevent the horror of
using an “endless” switch or spaghetti code.
Applying Strategy Pattern Over a Switch Statement
The following code shows how to replace a switch statement with
a Strategy implementation. We start with the first implementation
before we refactor it:
class Program
{ public enum ePassengerTitle
{ Mr,
Mrs,
Doctor,
}
static void Main(string[] args)
{ ePassengerTitle title = ePassengerTitle.Doctor;
switch (title)
{ case ePassengerTitle.Mr:
// do something
break;
case ePassengerTitle.Mrs:
// do something
break;
case ePassengerTitle.Doctor:
// do something
break;
default:
break;
}
}
}
As you can see I have an enum which holds a passenger title.
This title can get crowded for example when we want to add
more titles like Reverend, Miss or more.
Lets see how we can change this implementation to use the
Strategy Pattern:
#region Strategy Interface
public interface IPassengerTitleStrategy
{ void DoAlgorithm();
}
#endregion
#region Concrete Classes
public class MrPassengerTitleStrategy : IPassengerTitleStrategy
{ #region IPassengerTitleStrategy Members
public void DoAlgorithm()
{ throw new NotImplementedException();
}
#endregion
}
public class MrsPassengerTitleStrategy : IPassengerTitleStrategy
{ #region IPassengerTitleStrategy Members
public void DoAlgorithm()
{ throw new NotImplementedException();
}
#endregion
}
public class DoctorPassengerTitleStrategy : IPassengerTitleStrategy
{ #region IPassengerTitleStrategy Members
public void DoAlgorithm()
{ throw new NotImplementedException();
}
#endregion
}
#endregion
#region Context
public class Context
{ #region Members
private static Dictionary<ePassengerTitle, IPassengerTitleStrategy> _strategies =
new Dictionary<ePassengerTitle, IPassengerTitleStrategy>();
#endregion
#region Ctor
public static Context()
{ _strategies.Add(ePassengerTitle.Mr, new MrPassengerTitleStrategy());
_strategies.Add(ePassengerTitle.Mrs, new MrsPassengerTitleStrategy());
_strategies.Add(ePassengerTitle.Doctor, new DoctorPassengerTitleStrategy());
}
#endregion
#region Methods
public static void DoAlgorithm(ePassengerTitle title)
{ _strategies[title].DoAlgorithm();
}
#endregion
}
#endregion
You can see that I register all the algorithms inside a dictionary
which will help us to imply the relevant algorithm whenever we
need it. The registration is done inside the Context class which
then exposes the DoAlgorithm method which gets the relevant
passenger title and implies to it the relevant algorithm.
Lets see how our program change when we use the Strategy
implementation:
public enum ePassengerTitle
{ Mr,
Mrs,
Doctor,
}
class Program
{ static void Main(string[] args)
{ ePassengerTitle title = ePassengerTitle.Doctor;
Context.DoAlgorithm(title);
}
}
This is only one way to implement the
Strategy Pattern. There are other
ways to do the same thing but without dictionaries which you can find in
the internet.
- The code is easier to read. I don’t need to go and read (or
search) an “endless” switch statement to understand each
aspect of the code.
- The code is more maintainable. I only need to go to the
relevant class that implement the algorithm in order to change it
or refactor it when needed.
- It is easier to add more algorithms. I only need to add more classes
to the pile of algorithms and that is it. Doing so helps us to imply
the Open / Closed Principle because in switch statement we are going
to have to change our code (add another case statement) in opposed
to Strategy which we add another algorithm class.
- Strategy Pattern is more testable.
Even so, there are times that switch statement is preferable then
Strategy Pattern but when you find yourself having an “endless” switch
or repeat the same switch all over the place this should alert you that
Strategy Pattern is needed.
Summary
In the post I showed an alternative method for switch statement use. I
always prefer the use of Strategy Pattern instead of switch statements.
This approach is more OOP for developing even though it will force you to
implement more classes. In the end you can choose either the switch
statement or Strategy Pattern but if you have chosen a switch statement
do it in the right place.
CodeProject
Using External Configuration File for Enterprise Library Configuration
One of the things
that I always do when
I’m using Enterprise
Library is to separate
its configurations to
external configuration file.
The reason is very obvious – using Enterprise Library makes
configuration files very crowded. Since this is the case, the
configuration files become unmanageable and then its time to
separate the Enterprise Library’s configurations from other
configurations.
How to Use external Configuration File for Enterprise Library Configuration?
It is very simple to separate the Enterprise Library configurations
to another external file.
Step 1
Create a new configuration file in the solution which is going to
hold the Enterprise Library configurations. In my solution I added
a new EL.config file in the root of the project along side for the
web.config.
Step 2
From Enterprise Library Configuration Tool add a new Configuration
Sources node.
Step 3
In the node add a new File Configuration Source with
the name you want to give the file.
Give it a relevant name such as EntLib Configuration Source.
Step 4
In the properties of the created File Configuration Source add the
path to the file which can be full path or relative path. I prefer the
relative path.

Since my file sits in the root of the project I only have to write
its name and it will be given a relative path. If for example I put it
in a Configuration directory I’ll have to write Configuration/EL.config.
Step 5
Make the new File Configuration Source the selected source and
that is it.
After doing so all the Enterprise Library configurations
will sit in the file configuration source and not in your web.config
enabling the separation of Ent-Lib configurations from the application
configurations. Also when you’ll open the web.config (or app.config) in
Enterprise Library Configuration Tool it’ll show the Enterprise Library
configurations and enable making changes which will be saved in the
other EL.config automatically for you.
Summary
In the post I showed how to separate the Enterprise Library configurations
to external file. This is done to increase manageability of configuration files.
CodeProject
Velocity Cache Notifications
I’ve been asked by a friend how to
use cache notifications in Velocity.
if you don’t know, Velocity,
Microsoft distributed cache, offers a
cache notification mechanism that can
help you to get notified when cache operations occur.
This post will help you to get started with Velocity cache notifications.
Cache Notifications
As written earlier, Velocity has a cache notifications feature. That feature
enables us to get notified when cache operations occur in our cache cluster.
What happens when this feature is enabled is that we get asynchronous
cache notifications for many aspects of the cluster including the cache,
region and cached item operations.
The following are the notifications that we can receive:
- Create/Clear/Remove regions.
- Add/Replace/Remove cached items.
The following notifications can be added:
- Cache level callback – get notified on all the operations that
occur on all the items and regions in a specific cache.
- Region level callback – get notified on all the operation that
occur on all the items and region of a specific region.
- Item level callback – get notified on all the operations that
occur to a specific item.
For more details go to the following MSDN post – Cache Notifications (Velocity).
How to Enable Cache Notifications?
In order to enable server cache notifications (which is disabled by default)
we need to configure the relevant named cache. There are two
PowerShell commands that enables us to do that thing which are
New-Cache and Set-CacheConfig.
They get as parameter NotificationEnabled which enable the cache.
For example –
New-Cache –CacheName cache1 –NotificationsEnabled
will create a new named cache with the name cache1 which has the
cache notifications enabled.
Summary
Lets sum up, Velocity is going to be shipped with cache notification mechanism.
That mechanism can help you to get notified whenever a cache operation
occurs. This mechanism can help to monitor the Velocity cluster or to know
when operation occurs in the cache. In the post I showed how to enable
cache notifications in a specific named cache. In the next post I’ll demonstrate
how to add cache notifications callbacks.
Working with Large Databases in Entity Framework
Yesterday I was asked by
a colleague a very good EF
question. The question was
how to split a model or how
create a model for a large
database.
I pointed that colleague for the next three good resources which deal
with such situations:
I hope it will help you too if you seek for such an answer.
Enjoy!
Back to Basics – How to Invoke Web Methods from a Remote Machine
I’ve been
asked today
how to enable
invocation of
WebMethods of
an asmx web service
from a remote machine
for testing.
The post holds the answer.
How to Invoke Web Methods from a Remote Machine?
Sometimes we want to test our asmx web service not from
localhost but from a remote machine. Trying to open the test form
of the web service from a remote machine will show the following
message: “The test form is only available for requests from the local
machine”. In order to enable the invocation we need
to go the the web service’s configuration file and add to the
system.web element the following configuration:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
The configuration will enable the protocols of Get and Post on the
service and that is it.
Pay attention – you should use this configuration only in develop or
test environments. Also, this ability is only available for simple types.
Trying it with complex types won't work.
Summary
Enabling test invocation from a remote machine is very easy. It include
simple configuration and it will work. Don’t forget to use it only in
develop or test environments.
Enjoy!