October 2009 - Posts
Entity Framework Free Tools List
In my last session at Microsoft
I mentioned some EF free
tools that you can use which can
help you to be more productive.
Since I got a comment about
sharing my list, this is the free tool list and
the places you can find them and download them:
- eSqlBlast – a suite of tools that target editing and executing
eSQL statements. - LINQPad – lets you query data sources in a modern language – LINQ.
Supports not only EF and also: LINQ to Objects, LINQ to SQL,
LINQ to XML and more. - Entity Framework Mapping Helper - lets you create sample
mapping files for the set of scenarios you are interested in. - ADO.NET Entity Framework Extensions - includes utilities that make
querying stored procedures, creating typed results from DB data
readers and state tracking external data much easier in the Entity
Framework. - EdmGen2 – a command-line tool for Entity Framework.
- Tracing and Caching Provider Wrappers for Entity Framework - a sample
which demonstrates how to implement wrapping providers which add
interesting functionality to an EF application. - Entity Framework Contrib – community contributions for the Entity
Framework.
This list only hold freeware tools! There are a lot of products in the EF area which
I didn’t mentioned in the list and can also help you when you use EF. I will
update the list occasionally with other tools which I’ll find or get notice about.
Enjoy!
Building a Custom Site Map Provider
In the last ASP.NET
course I delivered I
was asked how to
build a custom
site map provider.
This post holds the answer.
You can download the full example from here.
Building a Custom Site Map Provider
There are times that our requirements demand that our site
navigation will not be based on the default site map provider.
Such times are for example when we want to use a database table
to hold our site navigation. In these times we can create a
custom site map provider. What we need to do is to inherit from the
StaticSiteMapProvider class and then to implement our business
functionality. There are two methods that we need to override which
are BuildSiteMap and GetRootNodeCore. The first is building the
site map and the second return the root node of the built site map.
The following code demonstrate how I to create a simple site map
provider:
using System.Web;
namespace WebApplication1
{
public class CustomSiteMapProvider : StaticSiteMapProvider
{
#region Members
private readonly object _siteMapLock = new object();
private SiteMapNode _siteMapRoot;
#endregion
#region Methods
public override SiteMapNode BuildSiteMap()
{
// Use a lock to provide thread safety
lock (_siteMapLock)
{
if (_siteMapRoot != null)
{
return _siteMapRoot;
}
base.Clear();
CreateSiteMapRoot();
CreateSiteMapNodes();
return _siteMapRoot;
}
}
protected override SiteMapNode GetRootNodeCore()
{
return BuildSiteMap();
}
private void CreateSiteMapRoot()
{
_siteMapRoot = new SiteMapNode(this, "Root", "~/Default.aspx", "Root");
AddNode(_siteMapRoot);
}
private void CreateSiteMapNodes()
{
SiteMapNode node = null;
for (int i = 1; i <= 3; i++)
{
node = new SiteMapNode(this,
string.Format("Child{0}", i),
string.Format("~/WebForm{0}.aspx", i),
string.Format("Child{0}", i));
AddNode(node, _siteMapRoot);
}
}
#endregion
}
}
The site map that I generate is very simple and only show the guidelines
of how to create your own provider. You can use instead a database call,
web service or any other data source to create your own functionality.
Deploying the Custom Site Map Provider
After we have our custom site map provider we need to register it in the
web.config file. We need to use the siteMap element of system.web
element. This example shows how to do so with the previous custom
site map provider:
<system.web>
<siteMap defaultProvider="CustomSiteMapProvider" enabled="true">
<providers>
<clear/>
<add name="CustomSiteMapProvider" type="WebApplication1.CustomSiteMapProvider"/>
</providers>
</siteMap>
</system.web>
As you can see first I clear the default provider and then I register my
own.
Using the Custom Site Map Provider
I created the following web application structure in order to
demonstrate how to use the new provider:
In the Site1.Master file I dropped a TreeView control and a
SiteMapDataSource. All the other web forms use the master file
and provide no functionality.
The code of the master page file:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication1.Site1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" ImageSet="Simple"
NodeIndent="10">
<ParentNodeStyle Font-Bold="False" />
<HoverNodeStyle Font-Underline="True" ForeColor="#DD5555" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#DD5555" HorizontalPadding="0px"
VerticalPadding="0px" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px"
NodeSpacing="0px" VerticalPadding="0px" />
</asp:TreeView>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
The result of using this application is:
Summary
Lets sum up, in the post I demonstrated how to create your own
site map provider. This is very helpful when we don’t want to use the
default provider which uses a Web.sitemap xml file. After we create our
provider we need to register it in the site’s configuration file and then
we can use it inside our web application.
ADO.NET Entity Framework Session Slide Deck
Two days ago I had a half
day session at Microsoft
about Entity Framework.
The agenda was as follows:
- Entity Framework Introduction
- Exploring the Entity Data Model
- Querying and Manipulating Entity Data Models
- Customizing Entity Data Models Examples
- EF4
As I promised the slide deck and demos can be downloaded from here.
I want to thank the attendees of the session and I hope you had great
time like I did.
Also, I’m sorry for the late publishing but it was caused by technical problems
to upload the files into the blog’s server. Instead I put it in my Skydrive.
P.S – in order to use the demos you need to restore the added database
backup and replace all the connection strings in the demos to point to
the database you restored.
Calling User-Defined Functions (UDFs) in Entity Framework
Yesterday I answered
a question in Entity
Framework forum in
regard of how to use
User-Defined Functions
(UDFs) in Entity Framework.
This post holds the answer.
The Problem
I have a UDF in my database that I want to use with Entity Framework.
When you use the Entity Data Model Wizard you can surface the function
in the SSDL. When you will try map the created function element to a
FunctionImport you’ll get the following exception:
”Error 2054: A FunctionImport is mapped to a storage function
'MyModel.Store.FunctionName that can be composed. Only stored
procedure functions may be mapped.”
So how can we use the UDF?
Calling User-Defined Functions (UDFs) in Entity Framework
The only way to call the function is using Entity SQL. Since the function mapping
sits in the SSDL then it can be used by Entity SQL in order to get back the needed
results. So if we have the following UDF:
CREATE FUNCTION dbo.GetPersonType(@PersonID int)
RETURNS tinyint
As
BEGIN
DECLARE @personType tinyint
SELECT @personType = PersonType from Person where PersonID = @PersonID
RETURN @personType
END
We will be able to use it after mapping it into the EDM using the EDM Wizard.
The following code show how to use the imported function:
using (var context = new SchoolEntities())
{
var sql = "SELECT VALUE SchoolModel.Store.GetPersonType(p.PersonID) FROM SchoolEntities.People AS p";
var query = context.CreateQuery<byte>(sql);
foreach (var type in query)
{
Console.WriteLine(type);
}
}
Console.ReadLine();
Summary
Lets sum up, there is no way to use UDF as FunctionImport in Entity Framework
currently. The work around is to use the imported functions with Entity SQL.
The post demonstrated how to do such a thing.
Another solution to use UDF in your model is by using DefiningQuery elements
which you can read about this element here.
Table Splitting in Entity Framework
Entity Framework include
a lot of ways to customize
the Entity Data Model. One
such way is Table Splitting
which enables to map multiple
entity types to a single table.
This post will show how we can achieve this ability.
Why Using Table Splitting?
Sometimes we want to delay the loading of properties which the columns
that they map to hold very large amount of data. This can be a big Xml
column, images or big binary data (blob). In such cases that we want to use
lazy loading to some columns, you will want to use the table splitting
feature of Entity Framework. Another reason which is less important is
to organize and arrange the columns you have in a single table into more
then one object. For this reason I prefer to use complex types which
aren’t managed as EntityObjects.
Table Splitting Preparation for the Example
In the example I’m going to use the following table:
CREATE TABLE [dbo].[Course](
[CourseID] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[Days] [nvarchar](50) NOT NULL,
[Time] [datetime] NOT NULL,
[Location] [nvarchar](100) NULL,
[Credits] [int] NOT NULL,
[DepartmentID] [int] NOT NULL,
CONSTRAINT [PK_School.Course] PRIMARY KEY CLUSTERED
(
[CourseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Pay attention that there is no reason to use table splitting in this
table. I use this table only to show the concept.
After generating the model from the database the result model will
look like:
Table Splitting
Now that we have our model lets split the table. I’m going to split
the table into a course and a course details entities.
Step 1
Copy and paste the Course entity to the model.
The model should look like:
Step 2
Rename Course1 to CourseDetails and remove the irrelevant properties in
every entity. In CourseDetails remove Title, and DepartmentID. In Course
remove all the properties of CourseDetails (not including! the CourseID).
The model should look like:
Step 3
Create a 1 to 1 association between Course and CourseDetails.
After pressing OK the resulting model will look like:
Step 4
Map the model to the relevant parts. Map CourseDetails to Course table
and map the association to Course table. The CourseDetails mapping will
look like:
and the association mapping will look like:
Step 5
In EF1 save the model and open it in Xml editor to edit the CSDL.
In the CSDL we need to add referential constraint to inform the model that
there is a parent child relationship between Course and CourseDetails:
<Association Name="CourseCourseDetails">
<End Type="SchoolModel.Course" Role="Course" Multiplicity="1" />
<End Type="SchoolModel.CourseDetails" Role="CourseDetails" Multiplicity="1" />
<ReferentialConstraint>
<Principal Role="Course">
<PropertyRef Name="CourseID"/>
</Principal>
<Dependent Role="CourseDetails">
<PropertyRef Name="CourseID"/>
</Dependent>
</ReferentialConstraint>
</Association>
In EF4 the referential constraint is automatically created. If it isn’t created
you can use the designer to generate it for you with the
Referential Constraint designer.
Step 6
Test the result.
using (var context = new SchoolEntities())
{
// get all courses
foreach (var c in context.Courses)
{
if (!c.CourseDetailsReference.IsLoaded)
{
c.CourseDetailsReference.Load();
}
}
// create a new course with details
var course = Course.CreateCourse(30, "New Course", 1);
context.AddToCourses(course);
var courseDetails = CourseDetails.CreateCourseDetails(30, "M", DateTime.Now, 3);
course.CourseDetails = courseDetails;
context.SaveChanges();
}
Summary
Lets sum up, in the post I showed another way to customize your
entity data model which is table splitting. Table splitting is very appropriate
for loading large data properties on demand and not in every query to
the database.
Back to Basics – Exposing UserControl Events
This morning I saw
Shlomo’s post
(in Hebrew) that
explain how to
expose events in a
UserControl in order
to enable the page to register to that event. This post will show
a different solution to do the same thing and also explain my opinion
in regard of whether to expose events through UserControl or not.
Should We Expose UserControl Events?
One of the things that I always explain when I’m being asked my opinion
about exposing UserControls events is that UserControls are like islands of
separation. I see them as a dumb controls which need to be striped from
business logic (including validation which in my opinion are a part of the
business logic) . What I mean in saying that is that UserControl are reusable
components that gather some visualization that is being repeated inside a
web application. After saying that probably you understand my opinion on
exposing events. I encourage to expose events from UserControls since I
prefer that the page will hold the implementation (through business logic
components) for the events and therefore making the UserControl more
reusable. When we implement the events inside the control we don’t
gain that flexibility.
Exposing UserControl Event Example
Our UserControl is going to look like:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs"
Inherits="AutoCompleteExtenderTriggerButton.WebUserControl" %>
<div>
<div>
<asp:Label ID="lblUserName" runat="server" Text="User Name: "></asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</div>
<div>
<asp:Label ID="lblPassword" runat="server" Text="Password: "></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</div>
<div>
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
</div>
</div>
A simple login control.
The first thing to do is to create a delegate for the event we
are going to expose:
public delegate void LoginHandler(string userName, string password);
After we have the delegate we can expose the event from the
UserControl. The following example use the delegate that I showed
earlier and expose the event through the event of the login button:
public delegate void LoginHandler(string userName, string password);
public partial class WebUserControl : UserControl
{
public event LoginHandler Login;
protected void btnLogin_Click(object sender, EventArgs e)
{
if (Login != null)
{
Login.Invoke(txtUserName.Text, txtPassword.Text);
}
}
}
That is it. Now we can wire up the event in the page that the UserControl
is being hosted in.
Summary
Lets sum up, I explained a little about my opinion in regard of exposing
UserControl events. I also showed another way to expose UserControl
events. The way that Shlomo showed in his post is also applicable for
event exposing but I prefer the traditional way of creating a delegate
that inform the user of the control your intentions.
I hope that this post will help you.
Create Your First Dynamic Data Entities Web Application
Two weeks ago I was
asked if there is a way
to build a web back office
quickly. One thing that
popped into my mind was
the new ASP.NET Dynamic Data
framework that was shipped with
Visual Studio 2008 SP1. This post is the same introduction that I
made to the team members that asked me the question. Since
there weren’t any customizations needed in the back office they
needed the result was a standing back office in 5 minutes. That is
very productive.
Creating the Dynamic Data Application
The first thing to do is to create the Dynamic Data application.
This is a very easy job since we can pick one of Dynamic Data templates
which will generate the site. In Visual Studio choose File menu
and New –> Project or New –> Web Site and then choose one of
Dynamic Data templates on the Web templates. The options are
Dynamic Data Web Application which will generate a general Dynamic
Data application or Dynamic Data Entities Web Application which is
more appropriate to use with Entity Framework or LINQ to SQL.
I chose the second:
After pushing the OK button Visual Studio generates the Dynamic Data
application and we are clear to go. The result will look like:

Adding ADO.NET Entity Framework to the Application
When we have the application at hand now we need to create the Entity
Framework model. This is very straight forward. You can choose to create a
different class library and put the model there (the preferred way) or you
can just put the model in the created project. For the simplicity of this demo
I chose the second option and the result is the model I’m using in all my demos:
Since this is only a demo for Dynamic Data and not for Entity Framework
I’m not showing how to create the model. If you seek information about how
to create an Entity Framework EDM I encourage you to read my
ADO.NET Entity Framework Tutorials series and in particularly the post
Entity Data Model (EDM) In Entity Framework.
Integrating the Context to the Dynamic Data Application
Now that we have the application and the Entity Framework model
it is time to combine them both. We do so by opening the Global.asax
file and in the RegisterRoutes we register the context using the model
object’s RegisterContext method. Pay attention that I set the
ScaffoldAllTables to true in order to show all the entities in my context.
If you want to show only part of them set the ScaffoldAllTables to false
and for every entity you want to show create a partial class and add there
the [Scaffold(true)] attribute.
After I register the context the RegisterRoutes will look like:
public static void RegisterRoutes(RouteCollection routes)
{
MetaModel model = new MetaModel();
model.RegisterContext(typeof(SchoolEntities), new ContextConfiguration() { ScaffoldAllTables = true });
routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
{
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
Model = model
});
}
That is all. Now we can run the Dynamic Data application and use it as
a web back office for our application.
My application looks like:

Summary
Lets sum up, I showed in this post how in 5 minutes of work you
can create a working web back office application. The Dynamic
Data framework can be very useful in lots of scenarios such as creating
web back office for example.I suggest to give it a try and to find out
were it can fit your requirements.
Replacing ASP.NET Session with Velocity Session Provider
One nice feature of
Microsoft
Distributed
Cache aka Velocity is
a custom session
provider that can
replace the ASP.NET
default session provider.
In this post I’ll explain how to replace ASP.NET session with the
Velocity session provider that is being provided with Velocity.
Why Replacing the ASP.NET Session with Velocity Session?
Sometimes we want to share a session across servers in a server farm.
The ways to do so are to use a State Server or a database. When Velocity
came out it was released (currently in CTP) with a custom session provider.
The use of Velocity cluster as a session provider can have impact of
performance as opposed to the other methods since we are talking about
a distributed cache. Another reason to use Velocity as session provider is
the availability feature it gives us compared to State Server or database
which can fail and we will need a recovery plan for them.
Doing the Trick
First of all we need to reference the Velocity dlls from the ASP.NET
web site or web application. You should reference the CacheBaseLibrary
and ClientLibrary dlls. After we have the reference you should add the
following data in the web.config file -
In the configSections element add the following element:
<section name="dataCacheClient" type="Microsoft.Data.Caching.DataCacheClientSection, CacheBaseLibrary"
allowLocation="true" allowDefinition="Everywhere"/>
Add the dataCacheClient element with your relevant configurations.
This can be for example:
<dataCacheClient deployment="simple">
<localCache isEnabled="true" sync="TTLBased" ttlValue="300" />
<hosts>
<host name="localhost" cachePort="22233" cacheHostName="DistributedCacheService"/>
</hosts>
</dataCacheClient>
The last thing to do is in the system.web element to add the sessionState
element that will be custom and point to the Velocity session provider:
<sessionState mode="Custom" customProvider="Velocity">
<providers>
<add name="Velocity" type="Microsoft.Data.Caching.DataCacheSessionStoreProvider, ClientLibrary" />
</providers>
</sessionState>
That is it. After doing so you can run the Velocity cluster and use the
ASP.NET session as you used it before. The only difference will be that
the data will be saved inside Velocity.
A full example could look like:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
</sectionGroup>
</sectionGroup>
</sectionGroup>
<section name="dataCacheClient" type="Microsoft.Data.Caching.DataCacheClientSection, CacheBaseLibrary" allowLocation="true" allowDefinition="Everywhere"/>
</configSections>
<dataCacheClient deployment="simple">
<localCache isEnabled="true" sync="TTLBased" ttlValue="300" />
<hosts>
<host name="localhost" cachePort="22233" cacheHostName="DistributedCacheService"/>
</hosts>
</dataCacheClient>
<appSettings/>
<connectionStrings/>
<system.web>
<sessionState mode="Custom" customProvider="Velocity">
<providers>
<add name="Velocity" type="Microsoft.Data.Caching.DataCacheSessionStoreProvider, ClientLibrary" />
</providers>
</sessionState>
</system.web>
</configuration>
Summary
Lets sum up, I explained why you should consider using Velocity as a
session provider. The main reasons for that are performance and availability.
Also, I showed how to configure your ASP.NET application to use the
Velocity session provider.
CodeProject
Data Types For Caching
One of the big problems I see
when I talk with people about
caching is not recognizing the
different cached data types.
Understanding the different types
of data can help us to define
what sort of caching do we need and also how to use caching systems
to achieve the appropriate cache scenario we are going to use.
This post will describe how to define data types for caching.
Reference Data
Reference data is data that doesn’t change frequently. This kind of
data is usually a result of data storage/storages query or aggregate query.
Since it doesn’t change frequently it is very ideal for caching. Instead of
hitting the data source when we need this kind of data, in the first hit
we will store it in cache and then retrieve it from cache when it is needed.
Reference data can also change so we need to refresh it periodically.
A very good example of reference data can be catalogs or lookup tables
(for example countries lookup table) that don’t change frequently.
Activity-Oriented Data
Activity-oriented data as it’s name indicate is data that belong to some
business activity or transaction. The data is created inside a business
activity and then at the end of the activity is persisted into the data
storage for historical or log information. Such data type is a data per
open session. A good example for an activity data is shopping cart in
a web store like Amazon. Other examples can be a user session state
or purchase order. As you can understand this kind of data has exclusive
access and therefore it is very recommended to cache it.
Resource-Oriented Data
Resource-oriented data is shared, concurrently read and write into, and is
accessed by many users/transactions. This kind of data is very hard to keep
inside a cache since there can be race conditions between transactions and
many transactions can manipulate the data at the same time.If this kind of
data is used inside cache it should be handled with caution and you should
use concurrency mechanisms in order to minimize problems. Examples for
such data can be auction items and flight inventory.
Summary
Let sum up, it is very important to understand the kinds of data that you
are going to use with cache. Every data kind has it’s appropriate caching
scenarios and have different considerations. These data type include
reference data, activity-oriented data and resource-oriented data.
ADO.NET Entity Framework Session at Microsoft
A few months ago I wrote
about a session I’m supposed
to do on ADO.NET Entity
Framework at Microsoft Israel.
This is a reminder for that
session which will take place
on October 19 at Microsoft Ra’anana.
In the session I’ll introduce Entity Framework and talk about how
to use it. I’m also going to dedicate the end of the session for EF4 and show
some of the features it include like POCO, Model-Defined Functions and more.
If you are interested to hear about Entity Framework this is the place to be.
You can sign in to it from here.
I hope to see you there.
Microsoft MVP Award
Today I’ve started a new journey.
I have the honor to be awarded Microsoft MVP.
My old journey started over two years
ago when my former manager in SRL Group,
Maor David, convinced me to open a Blog in
the Microsoft Israeli blogs system. Opening the blog was the first step
toward this day which I got the mail indicating that I was awarded
Microsoft MVP.
I want to thank the following people that helped me on the way to this
achievement:
First of all to Maor my mentor – if you didn’t pushed me I would have never
written this post.
Guy Burstein – Your help on the way was something which deserve a
great thanks.
To other friends like Yaron Shkop, Ran Wahle and Leon Langleyben which being
surrounded by them helped me to gain knowledge and better understanding in the
art of programming. And to all the other people that have been there on the way.
I also want to thank Microsoft for the award which encourage me to keep on
sharing my knowledge and keep on doing the things I do.
And last and not least I want to thank Sela Group, my company.