January 2011 - Posts
Book Review – Entity Framework 4 In Action
I spent some time lately to read the book “Entity Framework 4 in Action” which was written by several
authors – Stefano Mostarda, Marco De Sanctis and Daniele Bochicchio. This book was sent to me by Manning Publications as part of the Manning Early Access Program (MEAP).
What You are Going to Gain from The Book?
The book is all about Entity Framework 4. The authors don’t assume that you are familiar with the technology and they take you to an Entity Framework tour. At the end of the book you will have a lot of Entity Framework knowledge. The flow of the book is great and there are lots of details and hidden gems that can help you whether you are a junior Entity Framework developer and whether you are a senior Entity Framework developer. The authors take you step by step in the Entity Framework path and late chapters rely on previous ones which help you to build the knowledge gradually.
What is Included in The Book?
The book isn’t small – approximately 550 pages and includes 19 chapters and 2 appendices (LINQ appendix and Tip & Tricks appendix). The book is divided into 4 parts which are
- Redefining your data access strategy
- Working with Entity Framework
- Mastering Entity Framework
- Applied Entity Framework.
Every part relies on the previous parts and therefore you can’t read the parts as standalone if you are a novice in Entity Framework. If you are a senior Entity Framework developer you can read the parts as standalone but you’ll probably miss some details which are included in previous parts.
- Chapter 1: Data access reloaded: Entity Framework
The chapter include a discussion about the ORM world and also about the impedance mismatch which lead to the development of ORMs.
- Chapter 2: Getting started with Entity Framework
In the chapter the authors shows and describe how to build the Entity Framework part of an application that will be used across the book. During the chapter you’ll get to know what is Entity Framework and will learn a lot of basic stuff.
- Chapter 3: Querying the model: the basics
This chapter is all about the basics of querying the Entity Framework model. You will get to know the ways to do that and what is happening under the hood in the query process.
- Chapter 4: Querying with LINQ to Entities
The chapter will explain in details what is LINQ to Entities and how to use it.
- Chapter 5: Domain model mapping
This chapter is all about the EDM. You will hand craft the EDM parts manually and will gain valuable knowledge about its XML.
- Chapter 6: Understanding entity lifecycle
The chapter describes the entity life cycle and the change tracking mechanism. This is a very important chapter since the details in it are very important to the understanding how Entity Framework is working under the hood.
- Chapter 7: Persisting objects into the database
The chapter describe how to perform data manipulations by using Entity Framework.
- Chapter 8: Handling concurrency and transactions
As in the chapter name, you will learn how to handle concurrency and transactions with Entity Framework.
- Chapter 9: An alternative way of querying: Entity SQL
In this chapter you will learn what is Entity SQL and how to apply in order to query the model.
- Chapter 10: Working with stored procedures
This chapter is all about stored procedures and how to use them in Entity Framework environment.
- Chapter 11: Working with functions and views
The chapter will explain how to use model defined functions and defining query elements.
- Chapter 12: Exploring EDM metadata
In this chapter you will gain the understanding how to use the MetadataWorkspace in order to make runtime EDM metadata queries.
- Chapter 13: Customizing code and designer
In the chapter you learn how to customize the code generation by changing the Entity Framework T4 templates. Also you will learn how to extend the Entity Framework designer.
- Chapter 14: Designing the application around Entity Framework
The chapter starts with a Domain Driven Design discussion and shows how Entity Framework can help you to design applications which are more Domain Driven.
- Chapter 15: Entity Framework and ASP.NET
The chapter will guide you how to use Entity Framework with ASP.NET with EntityDataSource.
- Chapter 16: Entity Framework and N-Tier development
The chapter discuss how to include Entity Framework inside N-Tier applications. You will learn about the Self-Tracking entities and how to use DTO design pattern.
- Chapter 17: Entity Framework and Windows applications
The chapter will guide you how to use Entity Framework with WPF and WinForms.
- Chapter 18: Testing ADO.NET Entity Framework
The chapter starts with a discussion about Unit Testing and explains how to test Entity Framework by using Microsoft Testing Framework.
- Chapter 19: Keeping an eye on performance
This chapter is all about performance tuning. I expected more from this chapter but the major things of performance tuning are there.
The Bottom Line
This is a good Entity Framework book and I recommend it especially for junior Entity Framework developers. The book's content is more then enough to get started with Entity Framework and also it is organized well. There are discussions about methodologies like Domain Drive Design and Unit Testing that I really liked which add to the content you are reading and enrich your understanding. The book is doing it job by giving a good deep dive into Entity Framework 4. I give the book 5 stars out of 5.
MIX11 Open Call Voting Has Started Today
MIX conference is the biggest Microsoft web conference which occurs every year in Las Vegas.
As in every year Microsoft asked the developers and designers communities to propose sessions that will be part of a community voting. The sessions that will be chosen will be performed on stage at this year’s conference. Since I’m going to MIX11 as in last year, I proposed two sessions and they were chosen to the open call voting. This is the session descriptions:
- Building Data-Driven MVC Applications with Entity Framework Code First
Entity Framework 4 brings many new opportunities for building complex data driven applications. Code First is a new Entity Framework feature that provides a code-centric experience for interacting with models and databases. In this session we will build a full blown MVC application on top of Entity Framework Code First. - Creating OData Services with WCF Data Services
Data is a first-class element of every application. The Open Data Protocol (OData) applies web technologies such as HTTP, AtomPub and JSON to enable a wide range of data sources to be exposed over HTTP in a simple, secure and interoperable way. This session will cover WCF Data Services best practices so you can use it the right way.
If you find this content interesting I encourage you to go and vote for me and maybe you will hear the session in MIX11. There are other sessions that you can vote to in this link and you can vote up to 10 sessions. The voting will be open up until February 4.
Happy voting!
Building Data Access Layers with Entity Framework Slide Deck
Today I had an Entity Framework session (“Building Data Access Layers with Entity Framework”) session
at Microsoft Ra’anana.
I want to thank all the attendees who came to hear the session.
You were a great audience.
In the session I
- Introduced EF.
- Explained the EDM concept.
- Explained how to query the database using EF.
- Explained how to make data manipulation using EF.
- Talked about EF4 and the major features it brought to the framework.
I published the slide deck and demos in my SkyDrive and you can download it from here.
Enjoy!
Adding Metadata to Entities in The Data Model
Sometimes I’m being asked how to add metadata to a generated entity in Entity Framework.
This metadata can be data annotation or other attributes which can help the developer during runtime. One answer that I give is to edit the T4 template in order to add the attributes. This solution can be combined with the building of an extension to Entity Framework designer which can add more details to the EDM. But it can take some time to develop. Another solution is to create a MetadataType for the entity and use the entity’s partial class behavior to add this type. This post will show you the second solution.
Adding Metadata to a Generated Entity
In the example I’m going to use the following simple entity:

This type is part of a Dynamic Data site and the requirements for it are not to show the TypeID and that the Url needs to be up to 100 characters. Since Dynamic Data work with Data Annotations I want to add this metadata to the entity. But the problem is that the entity is generated by Entity Framework code generation. So how can I add the annotations? using the MetadataType attribute. The MetadataType is an attribute that is part of the System.ComponentModel.DataAnnotations assembly. It indicates that the a data model class has an associated metadata class. The MetadataType attribute gets a type parameter to specify which type is holding the metadata for the class. We can use the fact that the entity is generated as partial class and add the MetadataType attribute to it. Lets look at an example of how to use the MetadataType attribute:
public class CRMTypeMetadata
{
[ScaffoldColumn(false)]
public int TypeID { get; set; }
[StringLength(100)]
public string Url { get; set; }
}
[MetadataType(typeof(CRMTypeMetadata))]
public partial class CRMType
{
}
The first thing to notice in the example is that I’ve created a public class by the name CRMTypeMetadata which hold the properties annotated with the relevant attributes. The Metadata postfix in the class name is a convention that I encourage you to use. After I create the metadata class all I need to do is to create a partial class for the generated entity and annotate it with the MetadataType attribute. The MetadataType attribute will get as a parameter the type of the metadata type which is CRMTypeMetadata in the example. That is all.
Now the expected behavior was achieved.
Summary
One of the solutions to add metadata to entities in the Entity Data Model is by using the MetadataType attribute. It is very simple to use and can help you in frameworks like ASP.NET MVC, Dynamic Data, WCF Ria Services and more.
Finding Good Client Web Developers is Hard
Today I had a meeting at a customer.
One of the things that we talked about was the difficulty in finding good web developers.
To be more accurate, the difficulty in finding good client web developers!
Since I have lots of experience in interviewing candidates, I really understand that guy's problem. He published his company’s job requirements and seek for an experienced client web developer and all the candidates that he interviewed so far didn’t know javascript very well…
Since the customer and I work in ASP.NET environment then the majority of developers in this world are more server side oriented than client side. I hear a lot of sentences like “javascript is hard!”, “why use javascript if you can use server controls?” and more.
Mastering javascript is a must in web development! and being a web developer in .Net environment doesn’t excuse you from learning javascript.
If you are a web developer I expect you to know javascript and also HTML and CSS very well.
These are the building blocks of web development!
Like in other craftsmanship, if you don’t know the basics how do you expect to become a master?
SDP Conference 2011 is Coming
Sela Developer Practice (SDP) conference will occur between 13 to 16 of March. In this annual conference we (Sela Group) are going to share the current and future Microsoft technologies. The conference will give you a chance to see the best lecturers and leading experts, to be exposed to new technologies and to learn about the Microsoft products that have been launched last year. This is of course an opportunity to meet with colleagues from different organizations and to share knowledge.
In the conference I’m going to have a session about Code First in Entity Framework and to attend the MVP Panel which is an ask the experts like session. Also, I’m taking a part in an very interesting Entity Framework seminar along with Ido Flatow and Erez Harari. In the seminar we are going to talk about O/RM as a concept, explore Entity Framework as an O/RM solution and talk about best practices for using Entity Framework in applications. This is going to be fun.
There are other tutorials and sessions that are very recommended so if you want to be a part of the conference you can go to the conference web site – SDP.
See you there.
Book Review – HTML5: Up and Running
In the last two weeks I read the book “HTML5: Up and Running” that was written by Mark Pilgrim.
Since I’m and always was a web guy I always like to read about the things to come and HTML5 is a specification that is heading our way very fast.
What You are Going to Gain from The Book?
The book is about HTML5 which is a specification that is being written in these days and will be the de facto standard in the next years. Since reading all the specifications would probably make you crazy (go to the specification to see how long it is…) then reading a book that summarize the primary features is something that I recommend you to do. I picked this book since I found the book’s site while I was searching for HTML5 information. The book is very easy to read but it doesn’t go deep into details so you get a summarize of things with a few examples and that is all. I think that if the book was more thorough it would have given more added value then in its current version.
What is Included in The Book?
The book is very short – only 224 pages long. It is starting with some history that explain how did we get to HTML5 and how to detect HTML5 features (with or without the Modernizr framework). After the first two chapters the book covers eight main topics in HTML5:
- Chapter 3: What Does It All Mean?
Covers the new semantic elements that HTML5 introduce such as header and footer. - Chapter 4: Let’s Call It a Draw(ing Surface)
Explain in details the new canvas element that is a two-dimensional drawing surface that can be programed using javascript. - Chapter 5: Video on the Web
Explains what are the video and audio elements and also main formats and standards in this area. - Chapter 6: You Are Here (And So Is Everybody Else)
Explains what is Geolocation which enables to share physical locations with web applications. - Chapter 7: The Past, Present, and Future of Local Storage for Web Applications
Explains what is the Web Storage specification and how to use it. - Chapter 8: Let’s Take This Offline
Cover what is offline web applications which work when the user is offline and how to create this behavior. - Chapter 9: A Form of Madness
Covers a lot of the new HTML form elements such as search, email, number and etc. - Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Shows how to “extend” HTML5 markup using the Microdata data model.
The books flow is very good and every chapter can be read as stand alone so you can skip things that you know or go to chapters that you find more interesting. The author’s language is very clear and he spread witty jokes that makes the reading flow of very intensive. I really liked the “Ask Professor Markup” sections that highlight things in the book.
Summary
As a jump start to HTML5 the book “HTML5: Up and Running” is doing its job. It is not recommended to beginners since it depends on previous knowledge in web development. I give this book 4 stars out of 5 only because I expect technical books to be more thorough and with much more examples.
Using Web Storage in Web Applications
Web Storage is a specification that was a part of HTML5 but was moved to its own specification.
Currently, it is only a W3C editor draft but it is implemented in all the major browsers (even in IE from IE8) by the name Local Storage or DOM Storage. In this post I’m going to explain what is Web Storage and how you can use it even today in your web application/site.
Before Web Storage Came to the World
The need to save data and state in web applications/sites is very desirable since they work in a stateless manner. In the early days we could use cookies in order to save our data but this mechanism was very limited. The cookies had lots of limitations and downsides such as being sent in every HTTP request, 4KB of storage, can be disabled by the users and more. A need for a better mechanism was raised and Web Storage specification was born.
What is Web Storage?
Web Storage is a key/value dictionary that is stored in the web browser and persists your data even if you close the browser/browser tab (resembles the cookie mechanism). Unlike cookies Web Storage’s data is local to the web browser and isn’t sent to the server (no downgrade in traffic performance). In the specifications there is no limit to the amount of disk space that Web Storage can have but it is said that the browsers need to limit that amount. Web Storage is divided into two different storage objects:
- sessionStorage – data in this storage is accessible to any page from the same site opened in that window.
- localStorage – data in this storage spans multiple windows and lasts beyond the current session.
Each web application/site has its own dedicated storage.
Web Storage API
The Web Storage API include the following methods:
- length – get the number of key/value pairs in the storage.
- key(n) – returns the n’th key in the storage.
- getItem(key) – returns the value of the provided key. If the item doesn’t’ exists it will return null. Pay attention that the returned item is a string! so if you saved data such as integer or boolean you will have to parse it.
- setItem(key, value) – inserts a new value into the storage with the provided key.
- removeItem(key) – removes the item that is connected to the provided key. If the key doesn’t exists the method do nothing.
- clear – empty the storage from its data.
For example here is how you can get or set an item in the localStorage:
localStorage.setItem("key", "value);
var val = localStorage.getItem("key");
You can also use the storage without the get and set methods. You can do that by using the storage as a class with properties that you can access. The previous example can also be used as follows:
localStorage.key = "value";
var val = localStorage.key;
In some browsers the storage can also be treated as a dictionary (or javascript array) with an indexer such as you can see in this example:
localStorage["key"] = "value";
var val = localStorage["key"];
Currently, the indexer behavior isn’t part of the specification (but maybe it will be added).
Another aspect of the Web Storage is the storage event that is fired when a change occurs in the storage. That event is wired to the window object and is fired whenever setItem, removeItem or clear are being used. You can wire to that event with a function that receive an event parameter:
if (window.addEventListener) {
window.addEventListener("storage", handleStorageEvent, false);
} else {
// for IE versions below IE9
window.attachEvent("onstorage", handleStorageEvent);
};
function handleStorageEvent(eventData) {
// Do something
}
The eventData parameter in the previous example will hold the following members for your own use:
- key – the key that is being changed.
- oldValue – the old value of the key that is being changed.
- newValue – the new value of the key that is being changed.
- url – the address of the document whose key is being changed.
- storageArea – the storage that is being affected by the change.
An Example of Use
In the following example I’m using the localStorage in order to save the number of page load events and to present them to the user:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function pageLoadCounter() {
if (!localStorage.getItem('loadCounter')) {
localStorage.setItem('loadCounter', 0);
}
localStorage.setItem('loadCounter', parseInt(localStorage.getItem('loadCounter')) + 1);
document.getElementById('counter').innerHTML = localStorage.getItem('loadCounter');
}
</script>
</head>
<body onload="pageLoadCounter()">
<form id="form1">
<p>
You have viewed this page <span id="counter"></span> times.
</p>
<p>
<input type="button" onclick="localStorage.clear();" value="Clear Storage" />
</p>
</form>
</body>
</html>
This is a very simple example but it shows the use of the API methods like getItem, setItem and clear. As you can see the data is saved in a string manner so you’ll have to parse it in order to retrieve it. In the example I parse the counter number which is an integer using the parseInt method. When you will close the browser or tab and then open it again you will notice that the storage will persist the last counter.
Summary
Web Storage is a new specification that tries to target the lack of opportunities to store client side data. There are other ways to store data on the client such as cookies or using Google Gears with its embedded database which is based on SQLite. I hope that this introduction will help you to get started with a feature that you can use even today. For further information you can go to Web Storage specification on W3C site.
Detecting HTML5 Features Using Modernizr
In the past I wrote a post about using feature detection instead of browser
detection when writing web applications/sites. There are frameworks like jQuery that do that for you and all you have to do is to use them. There are other frameworks like Modernizr that are specializing in testing the current browser you use in order to detect whether it supports upcoming features such as HTML5 or CSS3.
What is Modernizr?
Taken from Modernizr site: “Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.”
How to use the Modernizr?
Using Modernizr is very easy. First download the library from Modernizr’s site. Then add the javascript file you downloaded to your site and use Moderinzr API. For example, here is how you’ll detect whether HTML5 Canvas is available in the browser:
// In your BLOCKED SCRIPT
if (Modernizr.canvas) {
var c = document.createElement('canvas');
var context = c.getContext('2d');
// Do your work
}
Here is an example of detecting search input type:
<input type="search" name="searchBox" id="searchBox">
<script>
if (!Modernizr.inputtypes.search){
// if no native support, create your own search box
createSearchBox(document.getElementById('searchBox'));
}
</script>
Here is a check for SVG:
if (Modernizr.svg)
{
// SVG is supported by your browser
} else
{
// SVG is not supported
}
As you can see the API is very easy to use and easy to pick up. For further information about the API you can go to Modernizr’s documentation.
Summary
Feature detection can help you to create a more stable web application/site. Modernizr is a javascript library that can help you to detect upcoming features such as HTML5 or CSS3. It is very easy to use and can be downloaded from here.
Revisiting XML Configurations In Unity
In the past I wrote a few tutorials about Unity application block.
One of the things I wrote about was how to configure a Unity container using design time configuration. In this post I’m going to revisit that post and show you how the configurations changed (for the better) and are much more easier to work with in the current version of Unity (version 2).
The Unity Configuration Section
As in my previous post we will first start with a small example of Unity configuration section in order to understand it. Later I’m going to discuss the elements and how to configure them. So here is the configuration file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<connectionStrings>
<add name="ConnectionString" connectionString="something" providerName="System.Data.SqlClient" />
</connectionStrings>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<!-- An interface for logger implementation -->
<alias alias="ILogger" type="UnityExamples.Common.ILogger, UnityExamples.Common" />
<!-- An abstarct class for database classes -->
<alias alias="Database" type="UnityExamples.Common.Database, UnityExamples.Common" />
<container name="MyContainer">
<register type="ILogger" mapTo="UnityExamples.Common.FileLogger, UnityExamples.Common" />
<register type="Database" mapTo="UnityExamples.Common.CustomDatabase, UnityExamples.Common">
<constructor>
<param name="connString" type="System.String">
<value value="connection value..."/>
</param>
<param name="logger" type="ILogger">
<dependency/>
</param>
</constructor>
</register>
</container>
</unity>
</configuration>
As opposed to the configurations we mad ein Unity’s first version this is much shorter. One thing to notice is the use of Xml namespace (http://schemas.microsoft.com/practices/2010/unity) which you will need to use in the Unity configuration section in order to get Intellisense.
Unity Elements Changes
Lets check what was changed.
Aliases – the first thing to notice is the absence of the typeAliases container element. Instead of it you can register your aliases one after another. Also, the element name typeAlias was changed to alias. This is no big deal but it is making the aliases registration a little more shorter.
Containers – like the aliases, the containers element was disposed. You will create a container element for each container with a relevant name. In every container you will register types and instances to be resolved. Instead of the Types element and the Type element you will use the register or instance elements. Inside these elements you will configure things like the constructor injection that I used in the example.
Building the Runtime Example
I’m using the same example which I used in the previous post. Here are the classes:
public interface ILogger
{
#region Methods
void Log(string message);
#endregion
}
public class FileLogger : ILogger
{
#region ILogger Members
public void Log(string message)
{
}
#endregion
}
public abstract class Database
{
}
public class CustomDatabase : Database
{
#region Members
private ILogger _logger;
private string _strConnString;
#endregion
#region Ctor
/// <summary>
/// Construct a new CustomDatabase object
/// </summary>
public CustomDatabase(string connString, ILogger logger)
{
_logger = logger;
_strConnString = connString;
}
#endregion
}
When you want to use the Xml configurations Unity exposes a container method which is called LoadConfiguration which will load the configurations for you. Here is an example of how to use it:
IUnityContainer container = new UnityContainer();
container.LoadConfiguration("MyContainer");
var database = container.Resolve<Database>();
var logger = container.Resolve<ILogger>();
First you create the
Unity container. Then you use the container's
LoadConfiguration method in order to load the configurations you made into the container. In the example I use the container name (MyContainer) from the configuration file. Then you can use
Unity resolve method to get the relevant runtime implementation. Easy as that.
Summary
Even though I prefer to use runtime configuration in order to configure my Unity container, there are times that the specifications don’t change and a design time configuration can be used. In this post I showed you how to use Unity’s current version Xml configuration. If your are using the previous version of Unity you can find details about its configurations in my old post.
Entity Framework 4 Session
Lately I wasn’t blogging or working because of a very annoying virus.
I’m feeling better now so don’t worry I’ll return blogging gradually. I also wanted to tell you about an open house I’m having at Microsoft about Entity Framework 4. The session will take place at Microsoft’s office at Ra’anana in Monday 24 of January. In the session I’m going to introduce Entity Framework and then what’s new in Entity Framework 4. For more details and for registration you can go to the following link.
See you there!