February 2009 - Posts
Web Data Services with ADO.NET Data Services Article
As a promo to the session I’m going
to deliver next week a new article that I wrote,
Web Data Services with ADO.NET Data Services,
was published on the Hebrew MSDN site.
The article describe the problems that were
targeted by ADO.NET data services, what is a data
service? a little about REST and data service architecture and a data service example.
You can read the article here.
You can read more Hebrew MSDN articles here.
Entity Framework Learning Guide
After I published yesterday
the Entity Framework Supported
Mapping Scenarios White Paper
post, I got an e-mail today
from Zeeshan Hirani regarding
an e-book that he published
in his blog which is a free 514 pages guide for Entity Framework. I’ve
only scanned the e-book and from what I saw it’s worth reading (which is
what I’m going to do in the near future).
You can download the e-book from here.
Thanks for sharing Zeeshan Hirani.
Entity Framework Supported Mapping Scenarios White Paper
While preparing to the
session I’m going to
present on
Sunday, March 1, 2009, I
got back to one of the most
important issues to be familiar
when using Entity Framework – mapping scenarios.
If you want to get to know with almost all the mapping scenarios that
Entity Framework support, I suggest reading Asad Khan’s white paper.
You can read the white paper from here.
Enum-Based Dictionaries and the Boxing Issue
While reading today one
of Ayende Rahien
(Oren Eini) posts -
Dictionary<Enum,T> Puzzler –
I have learned a new issue
regarding enum-based dictionaries.
Apparently, the use of enums as the keys for a dictionary makes us pay
in performance. The reason for that is that enums don’t implement IEquatable<T>.
Because of that when we use enum-based dictionaries the comparing of keys will
be performed by the ObjectComparer and we will have a boxing issue.
Ayende suggest to read a very good article by Omer Mor - Accelerating Enum-Based
Dictionaries with Generic EnumComparer. I really enjoyed reading that article.
On Sunday I’m going to check the enum-based dictionaries that I use in some of
my solutions and probably use Omer’s solution.
Thanks for sharing Omer.
Disabling Change Tracking in Entity Framework
Entity Framework came along
with a very helpful change
tracking system. But with
great power comes great
responsibility. The responsibility
of the developers is to make
sure that the change tracking option will not be responsible to bad performance.
How to Disable the Change Tracking Option
In Entity Framework, change tracking is being done by the ObjectStateManager.
The ObjectStateManager maintains object state and identity management
for entity type instances and relationship instances. When you retrieve data
that is read only or in ASP.NET applications you should consider disabling the
change tracking option. Doing so will increase the performance of your system
in some situations. In order to disable change tracking you use the
MergeOption.NoTracking option of the MergeOption enumeration. Using that
option will retrieve entities in a detached state.
One place to disable the change tracking is when we retrieve data with the
ObjectQuery object. One of the overloaded constructors of the ObjectQuery
gets as a parameter the MergeOption enumeration. The following example
shows how to do it:
using (SchoolEntities context = new SchoolEntities())
{
var query = new ObjectQuery<Course>(
"SELECT VALUE c FROM SchoolEntities.Course AS c",
context,
MergeOption.NoTracking);
foreach (var course in query)
{
// the courses we enumerate are detached state
Console.WriteLine("{0} {1}", course.CourseID, course.Title);
}
}
Another way to disable the change tracking is by setting the
MergeOption for the relevant EntitySet. The following example
shows how to do it:
using (SchoolEntities context = new SchoolEntities())
{
context.Course.MergeOption = MergeOption.NoTracking;
foreach (var course in context.Course)
{
// the courses we enumerate are detached state
Console.WriteLine("{0} {1}", course.CourseID, course.Title);
}
}
Summary
Lets sum up, sometimes it’s very helpful to disable the change tracking
option of Entity Framework. These occasions are when we use read
only entities or in ASP.NET applications that don’t need the change
tracking option. The disabling of the change tracking can help to increase
the performance of the system because the application will not use the
ObjectStateManager.
Web Developers Community (WDC): Start Thinking with ADO.NET 3.5 Session
I will be presenting introduction
to ADO.NET 3.5 in the
Israeli WDC (Web Developers
Community) on Sunday, March 1, 2009
at Microsoft office in Ra’anana.
The talk will introduce the following topics:
- Entity Framework
- ADO.NET Data Services
- Datasets Enhancements
You can register the event here.
I hope to see you there.
Back to Basics – Master Pages and Content Page Events
The post is going to
explain the concept
of master page events
during the page life
cycle.
The Problem
Sometimes I get asked by colleagues when events occur during
the page life cycle. This question is a very basic but very important
thing to know. The problem starts when master pages are involved.
Which event happens before which event? In what order events occur?
This is going to be answered in the next section.
Master Pages and Content Page Events
The sequence in which events occur when a master page is
merged with a specific content page:
- Master page controls Init event.
- Content controls Init event.
- Master page Init event.
- Content page Init event.
- Content page Load event.
- Master page Load event.
- Content controls Load event.
- Content page PreRender event.
- Master page PreRender event.
- Master page controls PreRender event.
- Content controls PreRender event.
(This sequence is taken from the MCTS Self-Paced Training Kit
(Exam 70-528))
Summary
Lets sum up, in the post I showed the events sequence occurrence
when using master pages. This is a must know sequence in order to
know when things happen and to use this knowledge when you
program ASP.NET pages code.
How To Use Unity Container In ASP.NET MVC Framework
In the past I wrote the
post How To Use Unity
Container In ASP.NET.
In this post I’m going to
explain how we can
use Unity IoC container
in ASP.NET MVC Framework.
Building The Container
As in the previous post the first thing to do is to build the
container itself. I’ll use the same method I used in the previous post
in order to persist the Unity container’s state during the application
execution. The right place to put the Unity container is as part of the
Global.asax file as a property of the current running application.
I’m going to use the same interface as before:
public interface IContainerAccessor
{ IUnityContainer Container { get; }}
After the building of the interface implement it in the Global
class in the Global.asax file:
public class MvcApplication : HttpApplication, IContainerAccessor
{ #region Members
private static IUnityContainer _container;
#endregion
#region Properties
/// <summary>
/// The Unity container for the current application
/// </summary>
public static IUnityContainer Container
{ get
{ return _container;
}
}
#endregion
#region IContainerAccessor Members
/// <summary>
/// Returns the Unity container of the application
/// </summary>
IUnityContainer IContainerAccessor.Container
{ get { return Container; } }
#endregion
#region Application Events
protected void Application_Start()
{ RegisterRoutes(RouteTable.Routes);
InitContainer();
ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));
}
protected void Application_End(object sender, EventArgs e)
{ CleanUp();
}
#endregion
#region Methods
public static void RegisterRoutes(RouteCollection routes)
{ routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults );
}
private static void InitContainer()
{ if (_container == null)
{ _container = new UnityContainer();
}
// Register the relevant types for the
// container here through classes or configuration
_container.RegisterType<IMessageService, MessageService>();
}
private static void CleanUp()
{ if (Container != null)
{ Container.Dispose();
}
}
#endregion
}
The Unity Controller Factory
The real and important change with this new implementation of
Global.asax is the setting of the controller factory which I wrote.
The code for the UnityControllerFactory:
public class UnityControllerFactory : IControllerFactory
{ #region IControllerFactory Members
public IController CreateController(RequestContext requestContext, string controllerName)
{ IContainerAccessor containerAccessor =
requestContext.HttpContext.ApplicationInstance as IContainerAccessor;
Assembly currentAssembly = Assembly.GetExecutingAssembly();
var controllerTypes = from t in currentAssembly.GetTypes()
where t.Name.Contains(controllerName + "Controller")
select t;
if (controllerTypes.Count() > 0)
{ return containerAccessor.Container.Resolve(controllerTypes.First()) as IController;
}
else
{ return null;
}
}
public void ReleaseController(IController controller)
{ controller = null;
}
#endregion
}
The main thing to do is to implement the CreateController method of
the IControllerFactory interface. I use the request context parameter to
retrieve the current application instance and from it I get the Unity container
through the interface of IContainerAccessor. I also need to instantiate the
relevant controller class which is being done by the Unity container for me.
The container will inject the dependencies in the controller by the Resolve
method and we will get the dependency injection functionality that we
wanted.
The Class to be Injected
I also wrote a MessageService which is a simple class that returns a
message and inherit from the IMessageService which declare the
GetMessage method:
public interface IMessageService
{ string GetMessage();
}
public class MessageService : IMessageService
{ #region IMessageService Members
public string GetMessage()
{ return "Hello Controller!";
}
#endregion
}
The Controller
The last piece of this puzzle is the controller class.
I implemented the HomeCotroller class with the following code:
[HandleError]
public class HomeController : Controller
{ #region Members
[Dependency]
public IMessageService MessageService { get; set; }
#endregion
#region Actions
public ActionResult Index()
{ ViewData["Message"] = MessageService.GetMessage();
return View();
}
public ActionResult About()
{ return View();
}
#endregion
}
The UnityControllerFactory will inject the dependency of the MessageService
property with the relevant class and that’s it simple as that.
Summary
Lets sum up, I showed an example of how to use Unity container in ASP.NET
MVC Framework application. This is a very simple example that will help you
to get started with Unity in your MVC web applications
CodeProject
ToTraceString Method in Entity Framework
In this post I’m going
to introduce the ToTraceString
method which enables us to
view the generated T-SQL
statement of a specific query
we execute in Entity Framework.
The ToTraceString Method
The ToTraceString method is a method that outputs the generated
T-SQL statement that is going to be submitted to the database by a
specific query in Entity Framework. The method is part of
EntityCommand object (which is part of the System.Data.EntityClient
namespace) and is a part of the ObjectQuery object (which is part of the
System.Data.Objects namespace). The method can help us when we
don’t what to use a profiler (like SQL profiler) in order to see the
T-SQL statement that is going to be executed. One important thing about
the use of ToTraceString is that it doesn’t execute the query,
it’s only output the statement to be executed. Another important thing
when using the ToTraceString method is that it needs to have an open
connection to the database in order to work. If there is no connection
to the database an exception will be thrown.
How to use ToTraceString Method?
It is very simple to use the ToTraceString method. The next example
shows the use of the method with ObjectQuery object:
using (SchoolEntities context = new SchoolEntities())
{
var sql = "SELECT VALUE department FROM SchoolEntities.Department AS department";
var query = context.CreateQuery<Department>(sql);
if (context.Connection.State != ConnectionState.Open)
{
context.Connection.Open();
}
Console.WriteLine(query.ToTraceString());
Console.ReadLine();
}
The next example shows how to use the ToTraceString method with the
EntityCommand object:
using (SchoolEntities context = new SchoolEntities())
{
EntityConnection conn = new EntityConnection(context.Connection.ConnectionString);
var sql = "SELECT VALUE department FROM SchoolEntities.Department AS department";
EntityCommand cmd = new EntityCommand(sql, conn);
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
Console.WriteLine(cmd.ToTraceString());
Console.ReadLine();
}
The output of executing these code sample is the same:
Summary
Lets sum up, when you want to get an output of the queries statements you send
to the database using the Entity Framework, you can use the ToTraceString
method. The ToTraceString method is a way to see the generated T-SQL statement
of a specific query without the use of a profiler. I showed two examples of how to use
the method.
My Blog is One Year Old
A year has past since
I have started blogging
and a lot has happened since
then. Few of these things
were:
Few Stats About my Blog
- Subscribed readers by Feedburner: ~115.
- Total blog posts: 113.
- Total comments: 216.
- Total trackbacks and pingbacks: 81.
- Google Analytics summary of last year:
- Page Views: 57,539.
- Unique Pageviews: 49,714.
- Average time on site: 02:42.
Top Ten Posts Ordered by Number of Views
Tell me how can I Improve!
I’d like to hear from you, the readers of my blog, how can I improve it,
feel free to leave comments such as which topics would you like me to
write about? which things add value to you when you read my blog? or every
comment that you want to share with me in regard to my blog.
I want to thank Maor David for the encouragement to open the blog in the
first place.
As a last statement, I want to thank every one of my blog readers. You are the
reason I keep on writing and sharing my knowledge. Thank you all!
Back to Basics – Zip in .NET
In today’s post I’m
going to share a
problem I solved this
week. The solution was
to use the framework’s
System.IO.Compression namespace and the GZipStream object.
The Problem
In my current project we save Xml data in our database. The field to
save the data was of type varchar(6000). This way of saving the data raised
a problem of big Xml data (over 8000 kb for every Xml data)
which were saved in the database and for the long run could raise
space and performance problems.
The Solution
Use the compression abilities of .NET framework, compress the
Xml data and save the data in a binary form. We needed to change the
field type in the database to binary type and compress the Xml data
before inserting it to the database. After the binary data was retrieved
from the database a reverse process of decompress returns the
original Xml string.
The Code
I first built a console application to write the code and test it.
Then, I wired the zip and unzip methods I wrote to the part that needed
the compression. The following code is the console application’s
zip and unzip methods I used to compress the Xml data.
static void Main(string[] args)
{
string data = "<Root><Child></Child>data1<Child>data2</Child><Child>data3</Child><Child>data4</Child><Child>data5</Child></Root>";
Console.WriteLine(data);
byte[] zipped = ZipDocumentData(data);
Console.WriteLine(Encoding.UTF8.GetString(zipped));
data = UnZipDocumentData(zipped);
Console.WriteLine(data);
Console.Read();
}
private static byte[] ZipDocumentData(string documentData)
{
byte[] byteArray = Encoding.UTF8.GetBytes(documentData);
string result = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream stream = new GZipStream(ms, CompressionMode.Compress))
{
//Compress
stream.Write(byteArray, 0, byteArray.Length);
}
return ms.ToArray();
}
}
private static string UnZipDocumentData(byte[] zippedDocumentData)
{
string result = string.Empty;
//Prepare for decompress
using (MemoryStream ms = new MemoryStream(zippedDocumentData))
{
using (GZipStream stream = new GZipStream(ms, CompressionMode.Decompress))
{
//Reset variable to collect uncompressed result
byte[] byteArray = new byte[4096];
//Decompress
int rByte = stream.Read(byteArray, 0, byteArray.Length);
result = Encoding.UTF8.GetString(byteArray);
}
}
return result;
}
Some things that should be concerned if you are going to use this code:
- The encoding of the strings I use are in UTF8 format. If you use other
formats you should change the Encoding.UTF8 code to the format you
use.
- In the decompress process I use a fixed array of 4096 bytes. This is only
for the testing application in the real method I save the original size of
the array.
Summary
Lets sum up, I used a compression method to compress Xml data in the
database. I showed the code to do that using the GZipStream object which
is part of System.IO.Compression namespace. I hope the code will help you
when you’ll ever need to compress data.