Skip to content

Gil Fink on .Net
Syndicate content
Fink about IT
Updated: 47 min 3 sec ago

ASP.NET Output Cache Provider

Sun, 07/18/2010 - 12:17
ASP.NET Output Cache Provider

One of the newASP.NET Output Cache Provider
features that were
shipped with
ASP.NET 4
was new providers
for caching purpose.
In this post I’ll explain
one of them – the OutputCacheProvider.

OutputCacheProvider

Up until ASP.NET 4 the output cache mechanism was implemented as
in-memory caching and we couldn’t do nothing to change its behavior.
If we desired to use a distributed cache like AppFabric caching or our own
implementation we couldn’t achieve it. From ASP.NET 4 the caching is now
following the ASP.NET provider model which means that we can create
our own provider in order to use caching. If we wish to use our own output
cache all we need to do is to inherit the OutputCacheProvider class which
exists in the System.Web.Caching namespace. After we implement the relevant
interface that include the Add, Get, Remove and Set methods we can
plug our provider inside the web.config file in order to use it.

OutputCacheProvider Example

As I wrote all we need to do is to inherit the OutputCacheProvider class.
The following code sample is a naive in-memory implementation for
OutputCacheProvider:

public class InMemoryOutputCacheProvider : OutputCacheProvider
{
  #region Members
 
  private Dictionary<string, InMemoryOutputCacheItem> _cache = new Dictionary<string, InMemoryOutputCacheItem>();
  private readonly static object _syncLock = new object();
 
  #endregion
 
  #region Methods
 
  public override object Add(string key, object entry, DateTime utcExpiry)
  {
    Set(key, entry, utcExpiry);
    return entry;
  }
 
  public override object Get(string key)
  {
    InMemoryOutputCacheItem item = null;
    if (_cache.TryGetValue(key, out item))
    {
      if (item.UtcExpiry < DateTime.UtcNow)
      {
        Remove(key);
        return null;
      }
      return item.Value;
    }
    return null;
  }
 
  public override void Remove(string key)
  {
    InMemoryOutputCacheItem item = null;
    if (_cache.TryGetValue(key, out item))
    {
      _cache.Remove(key);
    }
  }
 
  public override void Set(string key, object entry, DateTime utcExpiry)
  {
    var item = new InMemoryOutputCacheItem(entry, utcExpiry);
    lock (_syncLock)
    {
      if (_cache.ContainsKey(key))
      {
        _cache[key] = item;
      }
      else
      {
        _cache.Add(key, item);
      }
    }
  }
 
  #endregion
}

In the code I implement the cache as a in-memory dictionary.
The implementation is very simple and it is based on a item
class which looks like:

public class InMemoryOutputCacheItem
{
  #region Members
 
  public DateTime UtcExpiry { get; set; }
  public object Value { get; set; }
 
  #endregion
 
  #region Ctor
 
  public InMemoryOutputCacheItem(object value, DateTime utcExpiry)
  {
    Value = value;
    UtcExpiry = utcExpiry;
  }
 
  #endregion
}

Configuring the OutputCacheProvider

In order to use the previous output cache implementation we need
to plug it into the web.config file of the application. Under
system.web element we need to add the caching element. Inside the
caching element we add an outputCache element and add the provider
that we have created. The following example show you how to do that:

<?xml version="1.0"?>
<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <compilation debug="true" targetFramework="4.0">
        </compilation>
    <caching>
      <outputCache defaultProvider="InMemory">
        <providers>
          <add name="InMemory" type="InMemoryOutputCacheProvider"/>
        </providers>
      </outputCache>
    </caching>
        <authentication mode="Windows"/>
        <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
</configuration>
Checking the Implementation

Now we are ready to go and test the implementation.
The following web page contains a label control which shows the
current date and time (which is inserted in the code behind).
As you can see I added the OutputCache page directive to the page
in order to test the provider:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="HttpModuleTestWeb.WebForm1" %>
<%@ OutputCache Duration="15" VaryByParam="*" %>
<!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:Label ID="lblTime" runat="server" />
    </div>
    </form>
</body>
</html>

The page code behind:

public partial class WebForm1 : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    lblTime.Text = DateTime.Now.ToString();
  }
}
Summery

In ASP.NET 4 the caching is now provider based. That means that
we can plug our implementation to the cache including the
output cache. In the post I showed a simple example of how to
replace the output cache with a naive in-memory implementation.

kick it on DotNetKicks.com Shout it


Categories: Blogs

Too Much Abstractions? Follow up

Sat, 07/17/2010 - 08:39
Too Much Abstractions? Follow up

I asked a question about how to know when you have too much
abstractions in your code? and do more abstractions implies better
design?
I promised to do a follow up post and give my humble opinion.
So here it goes.

As architect I’m using abstractions a lot. It allows me to hide the
implementation details and create API’s for my consumers. Also, it
lets me the ability to change the implementation at a later stage of
the project if I need to and of course it makes the code more testable. 
One other thing about abstractions is that they decouple the code
we are writing which is a good thing to do. But as always with every
good there can be bad and we can abuse the use of abstractions.

One sentence that I used when I was consulting about
architecture at a customer was “too much abstractions will kill you”.
What I meant was that since we can abstract everything we need to
get the “feeling” when it is appropriate to use this method.
In the customer code there were abstractions on top of other
abstractions which provided less details or identical interface to what
they tried to abstract. So in this situation I preferred to follow the KISS
principle and remove some of the abstractions away. Now the solution is
clearer and more readable with less unneeded abstractions.

The customer’s example shows that even though abstractions are a good
practice you should understand were to apply them. For example to
abstract your infrastructure is a very good practice. Take a look at the
Enterprise Library or Spring.NET code to see how you can leverage
abstractions. On the other hand to create an interface to a Data Transfer
Object which abstract its properties is something that I’ll prefer to avoid.
The reason is that DTOs are meant to be data holders that have no
behavior. If I abstract the properties I gain nothing since in most cases
the implementation will be a getter and a setter and nothing more.
These two examples show exactly what I meant when I wrote that you
should understand were to apply abstractions.  

In conclusion, there are times that we use too much abstractions in
our code. If an abstraction doesn't add any value you shouldn’t create it
because it will complicate your code. There is no such thing as abstractions
compass which can tell you when the abstraction is needed or not (or when
you have created too much abstractions). This is why I start with a simple
implementation and then refactor my code and create the needed
abstractions. As a last statement more abstractions don’t imply better
design.

kick it on DotNetKicks.com Shout it


Categories: Blogs

Too Much Abstractions?

Thu, 07/15/2010 - 11:01
Too Much Abstractions?

Yesterday I had an architecture consulting session at a major customer.
One of the questions that were raised was how to know when you
have too much abstractions in your code?
or to make it even more interesting – do more abstractions implies
better design? 
I want to make it an open discussion and to hear what is your opinion
about this subject before I’ll post my own.


Categories: Blogs

OData Session is Coming

Wed, 07/14/2010 - 16:11
OData Session is Coming

At last my ODataOData Session is Coming
session details were
published today.
The OData ecosystem
is a growing community
of data producers and
consumers using the
Open Data Protocol to
exchange data.
The Open Data Protocol
breaks down data silos and increases the shared value of data and its
associated business logic through the Web by enabling the exposure
of any data source as a Web-friendly data feed. The easiest way to
become an OData producer in the .Net world is by using
WCF Data Services. In the session I’ll talk about things like what is OData,
how to use WCF Data Services to expose OData feeds and how to consume
OData feeds.
If you find this subject interesting you can register the event here.

See you there.


Categories: Blogs

Adding a Javascript Block Into a Form Hosted by WebBrowser Control

Tue, 07/13/2010 - 14:23
Adding a Javascript Block Into a Form Hosted by WebBrowser Control

Today I found myselfInjecting Javascript Into WebBrowser Control
with a need to
add a javascript
block into a WebBrowser
control in order to do some
work. This post will show you
the steps to do exactly that.

The Problem

In a project I’m consulting for there was a need to dynamically add a
javascript block into a web form that is hosted inside a WebBrowser
control. So what can we do?

The Solution

We can use the Microsoft HTML Object Library to achieve the task. 
The Microsoft HTML Object Library is a COM library that you can reference
in order to create HTML elements to use in the WebBrowser control.
You first need to reference it so go to the COM tab in Add Reference view,
search it and reference it. Now you can use the following code in order to
add your script to the head section of the HTML:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement domElement = (IHTMLScriptElement)script.DomElement;
domElement.text = // put your script here;
head.AppendChild(script);

 

Pay attention to replace the comment with your script implementation.

Summary

Using Microsoft HTML Object Library with the WebBrowser can help
you to achieve the insertion of javascript to a web form which is
hosted inside the control.
It also enables the creating and appending other HTML elements and can
be useful for other tasks.


Categories: Blogs

OData Explorer

Tue, 07/06/2010 - 09:46
OData Explorer

One nice tool to use with OData is theOData Explorer
OData Explorer. The OData Explorer
is a tool that helps to explore OData feeds
in a visual way and not by exploring the
Atom/JSON responses. You can download
the tool from here. Another way to use the
tool is by going to the following link:
http://Silverlight.net/ODataExplorer.

OData Explorer Requirements

The tool is a Silverlight 4 project.
In order to use it you’ll have to answer these requirements:

  • Visual Studio 2010
  • Silverlight 4 Developer runtime
  • Silverlight 4 SDK
  • Silverlight 4 tools for Visual Studio
  • Latest Silverlight Toolkit release for Silverlight 4

or of course use it on-line in the link I provided previously.

Using the Tool

When the tool start you’ll get to the Add New OData Workspace view:
OData explorer New OData Workshop

Here you can address your feed or address public OData feeds.
After choosing the workspace you’ll get into the tool:
Data Explorer 

Now you can go over the collections (entity sets) and get their information
in grid representation (which can be edited if the service is updatable):
Grid View

or in row data (Atom/JSON):
Atom JSON View

You can type your own queries in the upper text box or you can
use the Build Query view to create a query:
OData Query Builder

Summary

The OData Explorer is very useful tool when you want to
understand and look at OData feeds without understanding the
protocol. It comes with very nice features and can be very handy
in presenting your feeds.


Categories: Blogs

Repository and Unit of Work T4 Template for Entity Framework

Mon, 07/05/2010 - 12:19
Repository and Unit of Work T4 Template for Entity Framework

Two weeks ago IRepository and Unit of Work T4 Template for Entity Framework
wrote the
Revisiting the Repository
and Unit of Work Patterns
with Entity Framework

post. One thing that I
thought would be nice
was to have an automatic
code generation that will help me to build these patterns without sweating.
So I sat down and created a T4 Template to auto generate the same patterns
that I showed in the post.

The Code

One thing to understand is that the provided T4 Template isn’t bullet
proof and errors can occur (you can change the implementation as you
like). In order to use it copy and paste the code to a .tt file that needs
to be located in the library of your Entity Data Model file
(the T4 seeks edmx files in the current directory to auto generate the
classes). Another option is to download the T4 Template from here
So here it is:

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ import namespace="System.IO" #>
<#@ output extension=".cs" #>
<#         
if(Errors.HasErrors)
{
    return String.Empty;
}
 
CodeGenerationTools code = new CodeGenerationTools(this){FullyQualifySystemTypes = true, CamelCaseFields = false};
MetadataLoader loader = new MetadataLoader(this);
 
string open = "<";
string close = ">";
string SourceCsdlPath = FindEDMXFileName();
ReferenceCsdlPaths = new string[] {};
string namespaceName = code.VsNamespaceSuggestion();
ItemCollection = loader.CreateEdmItemCollection(SourceCsdlPath, ReferenceCsdlPaths.ToArray());
EntityContainer container = ItemCollection.GetItems<EntityContainer>().FirstOrDefault();
#>
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
 
namespace <#=namespaceName#>
{
    public interface IRepository<T> where T : class
    {    
        #region    Methods
    
        T GetById(int id);
        IEnumerable<T> GetAll();
        IEnumerable<T> Query(Expression<Func<T, bool>> filter);        
        void Add(T entity);
        void Remove(T entity);   
        
        #endregion
    }
    
    public abstract class Repository<T> : IRepository<T>
                                  where T : class
    {
        #region Members
 
        protected IObjectSet<T> _objectSet;
 
        #endregion
 
        #region Ctor
 
        public Repository(ObjectContext context)
        {
              _objectSet = context.CreateObjectSet<T>();
        }
 
        #endregion
 
        #region IRepository<T> Members
 
        public IEnumerable<T> GetAll()
        {
              return _objectSet;
        }
 
        public abstract T GetById(int id);
 
        public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
        {
              return _objectSet.Where(filter);
        }
 
        public void Add(T entity)
        {
              _objectSet.AddObject(entity);
        }
 
        public void Remove(T entity)
        {
              _objectSet.DeleteObject(entity);
        }
 
        #endregion
      }
 
<#
    foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
    {        
#>
    
    public partial class <#= entity.Name #>Repository : Repository<#=open#><#=entity.Name#><#=close#>
    {
        #region Ctor
 
        public <#= entity.Name #>Repository(ObjectContext context)
               : base(context)
        {
        }
 
        #endregion
 
        #region Methods
 
        public override <#= entity.Name #> GetById(int id)   
        {
            return _objectSet.SingleOrDefault(e => e.<#= entity.KeyMembers.First().Name #> == id);
        }
 
        #endregion        
    }
<# 
    }        
#>
        
  public interface IUnitOfWork
  {
      #region    Methods
    
    <#
        foreach (EntitySet set in container.BaseEntitySets.OfType<EntitySet>())
        {    
    #>
        IRepository<#= open #><#= set.ElementType.Name #><#= close #> <#= set.Name #> { get; }   
    <# 
        }
    #>
    void Commit();
    
    #endregion
  }
 
  public partial class UnitOfWork : IUnitOfWork
  {
    #region Members
 
    private readonly ObjectContext _context;
    <#
        foreach (EntitySet set in container.BaseEntitySets.OfType<EntitySet>())
        {    
    #>
    private <#= set.ElementType.Name #>Repository _<#= set.Name.ToLower() #>;
    <# 
        }
    #>    
    #endregion
 
    #region Ctor
 
    public UnitOfWork(ObjectContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context wasn't supplied");
      }
 
      _context = context;
    }
 
    #endregion
 
    #region IUnitOfWork Members
 
    <#
        foreach (EntitySet set in container.BaseEntitySets.OfType<EntitySet>())
        {    
    #>
    public IRepository<#= open #><#= set.ElementType.Name #><#= close #> <#= set.Name #>
    {
        get
        {
            if (_<#= set.Name.ToLower() #> == null)
            {
                _<#= set.Name.ToLower() #> = new <#= set.ElementType.Name #>Repository(_context);
            }
            return _<#= set.Name.ToLower() #>;
        }
    }
    <# 
        }
    #>    
    
    public void Commit()
    {
      _context.SaveChanges();
    }
 
    #endregion
  }
}
<#+
public string SourceCsdlPath{ get; set; }
public EdmItemCollection ItemCollection{ get; set; }
public IEnumerable<string> ReferenceCsdlPaths{ get; set; }
 
string FindEDMXFileName()
{            
    string[] entityFrameworkFiles = Directory.GetFiles(Host.ResolvePath(string.Empty), "*.edmx");
    if(entityFrameworkFiles.Length > 0)
    {
        return entityFrameworkFiles[0];
    }
    
    return string.Empty;
}
#>

 

and this is the generated code that I get after running the T4 Template
on my testing edmx file:

 
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
 
namespace ConsoleApplication1
{
    public interface IRepository<T> where T : class
    {    
        #region    Methods
    
        T GetById(int id);
        IEnumerable<T> GetAll();
        IEnumerable<T> Query(Expression<Func<T, bool>> filter);        
        void Add(T entity);
        void Remove(T entity);   
        
        #endregion
    }
    
    public abstract class Repository<T> : IRepository<T>
                                  where T : class
    {
        #region Members
 
        protected IObjectSet<T> _objectSet;
 
        #endregion
 
        #region Ctor
 
        public Repository(ObjectContext context)
        {
              _objectSet = context.CreateObjectSet<T>();
        }
 
        #endregion
 
        #region IRepository<T> Members
 
        public IEnumerable<T> GetAll()
        {
              return _objectSet;
        }
 
        public abstract T GetById(int id);
 
        public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
        {
              return _objectSet.Where(filter);
        }
 
        public void Add(T entity)
        {
              _objectSet.AddObject(entity);
        }
 
        public void Remove(T entity)
        {
              _objectSet.DeleteObject(entity);
        }
 
        #endregion
      }
 
    
    public partial class CourseRepository : Repository<Course>
    {
        #region Ctor
 
        public CourseRepository(ObjectContext context)
               : base(context)
        {
        }
 
        #endregion
 
        #region Methods
 
        public override Course GetById(int id)   
        {
            return _objectSet.SingleOrDefault(e => e.CourseID == id);
        }
 
        #endregion        
    }
    
    public partial class DepartmentRepository : Repository<Department>
    {
        #region Ctor
 
        public DepartmentRepository(ObjectContext context)
               : base(context)
        {
        }
 
        #endregion
 
        #region Methods
 
        public override Department GetById(int id)   
        {
            return _objectSet.SingleOrDefault(e => e.DepartmentID == id);
        }
 
        #endregion        
    }
    
    public partial class EnrollmentRepository : Repository<Enrollment>
    {
        #region Ctor
 
        public EnrollmentRepository(ObjectContext context)
               : base(context)
        {
        }
 
        #endregion
 
        #region Methods
 
        public override Enrollment GetById(int id)   
        {
            return _objectSet.SingleOrDefault(e => e.EnrollmentID == id);
        }
 
        #endregion        
    }
    
    public partial class PersonRepository : Repository<Person>
    {
        #region Ctor
 
        public PersonRepository(ObjectContext context)
               : base(context)
        {
        }
 
        #endregion
 
        #region Methods
 
        public override Person GetById(int id)   
        {
            return _objectSet.SingleOrDefault(e => e.PersonID == id);
        }
 
        #endregion        
    }
        
  public interface IUnitOfWork
  {
      #region    Methods
    
            IRepository<Course> Courses { get; }   
            IRepository<Department> Departments { get; }   
            IRepository<Enrollment> Enrollments { get; }   
            IRepository<Person> People { get; }   
        void Commit();
    
    #endregion
  }
 
  public partial class UnitOfWork
  {
    #region Members
 
    private readonly ObjectContext _context;
        private CourseRepository _courses;
        private DepartmentRepository _departments;
        private EnrollmentRepository _enrollments;
        private PersonRepository _people;
        
    #endregion
 
    #region Ctor
 
    public UnitOfWork(ObjectContext context)
    {
      if (context == null)
      {
        throw new ArgumentNullException("context wasn't supplied");
      }
 
      _context = context;
    }
 
    #endregion
 
    #region IUnitOfWork Members
 
        public IRepository<Course> Courses
    {
        get
        {
            if (_courses == null)
            {
                _courses = new CourseRepository(_context);
            }
            return _courses;
        }
    }
        public IRepository<Department> Departments
    {
        get
        {
            if (_departments == null)
            {
                _departments = new DepartmentRepository(_context);
            }
            return _departments;
        }
    }
        public IRepository<Enrollment> Enrollments
    {
        get
        {
            if (_enrollments == null)
            {
                _enrollments = new EnrollmentRepository(_context);
            }
            return _enrollments;
        }
    }
        public IRepository<Person> People
    {
        get
        {
            if (_people == null)
            {
                _people = new PersonRepository(_context);
            }
            return _people;
        }
    }
        
    
    public void Commit()
    {
      _context.SaveChanges();
    }
 
    #endregion
  }
}

Enjoy!


Categories: Blogs

Loading WCF Data Services Ajax Script Library

Mon, 07/05/2010 - 06:05
Loading WCF Data Services Ajax Script Library

Since I’ve given sessions Loading WCF Data Services Scripts without Sys.require
about WCF Data Services in 
the past (when they were
called ADO.NET Data Services)
I wanted to reuse some of the Ajax
examples I showed for my coming OData 
session. One of the things that have
been changed lately were the scripts to use
when you want to make Ajax calls to your Data Service.
So I downloaded the new scripts and saw that the names
of the objects to use have been changed a little but their functionality
remained the same. Moreover we have a new feature which helps
to figure what to load and how. In this post I’ll explain how to load
the WCF Data Services scripts automatically or manually.

The New Sheriff – Script Loader

One thing to understand about the new Ajax script libraries is
that the libraries ware split into many files in order to enable the
loading of the relevant libraries that you need whenever you need them.
Also, there is a new Script Loader object which help you to load the scripts
and their dependencies automatically. So I went to the documentation
to understand how to use the new OpenDataServiceProxy object (in the past
it was called DataServiceProxy). In order to use it you need to reference the
start.debug.js (or start.js in production):

<script type="text/javascript" src="/Content/Scripts/start.debug.js"></script> 

(where /Content/Scripts is the location of all the Ajax script library files)

Also, you need to use the following statement in order to load the
relevant scripts from your server:

Sys.require([Sys.components.dataContext, Sys.components.openDataContext]);

The Sys.require statement is used to configure the Script Loader to load
the libraries of the data context and the open data context which
include all the functionality to consume WCF Data Services from Javascript.
The Script Loader will check if the libraries exists in the server in the same
directory that start.debug.js exists and then load all the components for us.
It can cause some problems if when you use relative paths so pay attention
to that. Also, using the ScriptManager we can enable a search in Microsoft
Content Delivery Network (CDN) instead of loading the files from our server.
A master page that include an OpenDataServiceProxy object can look like:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="AjaxClient.master.cs"
    Inherits="DataServiceAjaxClient.Master.AjaxClient" %>
 
<!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 src="/Content/Scripts/Start.debug.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <script type="text/javascript">
            var proxy;
            Sys.require([Sys.components.dataContext, Sys.components.openDataContext]);
            Sys.onReady(function () {
                proxy = new Sys.Data.OpenDataServiceProxy("/Services/SchoolService.svc");
            });
        </script>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

Pay attention to the Sys.onReady function which will be called after all the
scripts were loaded.

How to Load the Scripts Manually

In order to manually load the relevant Javascript files we first have to
figure the script files dependencies. The dependencies of files are shown
here:
Microsoft Ajax Library Relationships 
So you can use the ScriptManager to load the scripts like in the
following example (the order of the ScriptReferences is very important!):

<asp:ScriptManager ID="ScriptManager1" runat="server" AjaxFrameworkMode="Explicit">
    <Scripts>
        <asp:ScriptReference Path="~/Content/Scripts/Start.debug.js" />
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxCore.debug.js" />
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxComponentModel.debug.js" />
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxSerialization.debug.js" />            
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxNetwork.debug.js" />
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxWebServices.debug.js" />                        
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxDataContext.debug.js" />
        <asp:ScriptReference Path="~/Content/Scripts/MicrosoftAjaxOpenData.debug.js" />
    </Scripts>
</asp:ScriptManager>

 

Pay attention for the AjaxFrameworkMode attribute that is set to Explicit.
With this attribute you control which are the relevant scripts to load and the
ScriptManager only load the MicrosoftAjax.js file.

Summary

In order to use the new Ajax library you have the new Script Loader to
help you with loading the relevant scripts. If you don’t want to use the
Script Loader you should understand the dependencies of the script
libraries files and to load them according to these dependencies.


Categories: Blogs

Calling a WCF Data Service From jQuery

Sun, 07/04/2010 - 06:15
Calling a WCF Data Service From jQuery

I’m working on a lecture Calling a WCF Data Service from jQuery
about OData which I’ll
will present next month
(stay tuned for more
details in the near future).
One of the things that
I want to show is how easy
and simple it is to consume a WCF Data Service (OData feed)
with the jQuery library. In the post I’ll show you exactly how
to do that.

jQuery’s getJSON Method

When you want to load JSON data from the server using a GET HTTP
request in jQuery you will probably use the getJSON method. That
method gets as input the server URL, a map of key-value pairs which
holds parameters to the server and a callback function to use when
the response arrives back to the client and returns the server response
in JSON format.
This method is the best candidate for consuming WCF Data Services
endpoints. If I want to use the getJSON method I’ll do something
like the example provided in the getJSON documentation:

$.getJSON('ajax/test.json', function(data) {
  $('.result').html('<p>' + data.foo + '</p>'
    + '<p>' + data.baz[1] + '</p>');
});
How to Consume WCF Data Service with jQuery getJSON Method

When we understand that WCF Data Service is just an HTTP
endpoint which returns JSON answer if addressed with
JSON request the road is very clear. If I want to consume the
service all I need to do is to create the relevant URI with the
WCF Data Service URI conventions and that is it.
The following code is an example for that:

$.getJSON("/Services/SchoolService.svc/Courses", null,
    function (data) {
        var sb = new Sys.StringBuilder();
        sb.append("<div>");                                
        $.each(data.d, function (i, item) {
            CreateDivForOneCourse(sb, item)
        });
        sb.append("</div>");
        $('#divResults').html(sb.toString());
    });

What this code is doing is going to a WCF Data Service endpoint 
that is called SchoolService.svc and retrieve the courses entity set
it holds. I don’t pass any parameters to the request so the key-value
pair is null. In the callback function I create a StringBuilder object and
append to it the response by iterating the data and creating a div
for every course. In the end I put the result as html in a div which has
an id of divResults.

The All Example Page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ConsumeDataServicejQuery.aspx.cs"
    Inherits="DataServiceAjaxClient.ConsumeDataService.ConsumeDataServicejQuery" %>
 
<!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 src="../Content/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="../Content/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">                
        var ajaxRequest;
 
        $(document).ready(function () {                        
            $('#btnShowCourses').click(function () {
                GetCoursesData();
            });
        });
 
        function GetCoursesData() {
            if (ajaxRequest != null) {
                ajaxRequest.abort();
            }
            ajaxRequest = $.getJSON("/Services/SchoolService.svc/Courses", null,
            function (data) {
                var sb = new Sys.StringBuilder();
                sb.append("<div>");                                
                $.each(data.d, function (i, item) {
                    CreateDivForOneCourse(sb, item)
                });
                sb.append("</div>");
                $('#divResults').html(sb.toString());
            });
        }
 
        function CreateDivForOneCourse(stringBuilder, item) {
            stringBuilder.append("<div><span>");
            stringBuilder.append(item.CourseID);
            stringBuilder.append("</span>&nbsp;<span>");
            stringBuilder.append(item.Title);
            stringBuilder.append("</span></div>");
        }              
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <input type="button" id="btnShowCourses" value="Show Courses" /><br />
        <div id="divResults" />
    </div>
    </form>
</body>
</html>

After running this example the result looks like:
getJSON result

Summary

Consuming WCF Data Services with jQuery is very easy task.
By using the getJSON method we create the HTTP GET request
to the service and get the returning data in JSON format to
our disposal. 


Categories: Blogs

SQL For .Net Developers – Entity Framework 4 Second Cycle Slide Deck

Mon, 06/28/2010 - 06:14
SQL For .Net Developers – Entity Framework 4 Second Cycle Slide Deck

SQL For .Net Developers – Entity Framework 4 Second Cycle Slide Deck

Yesterday’s evening I delivered a session at Microsoft Raanana about
Entity Framework 4 as a part of Microsoft’s
SQL For .Net Developers series of sessions. I want to thank all the
attendees who came to the session. I really enjoyed to talk about
Entity Framework and the audience was very cooperative with a lot
of really good questions.

As I promised, I uploaded the session slide deck and demos to my
Skydrive and you can download it from here. Pay attention that in the
demos main directory there is a backup file for the demo database.

Enjoy!


Categories: Blogs

Eager Loading with Repository Pattern and Entity Framework

Tue, 06/22/2010 - 07:11
Eager Loading with Repository Pattern and Entity Framework

One question that I Eager Loading with Repository Pattern and Entity Framework
received yesterday
after I published the
Revisiting the Repository 
and Unit of Work Patterns

with Entity Framework
post was
how to include the eager loading
ability of Entity Framework.
This post is offering a solution.

Revisiting Eager Loading and Lazy Loading

Lazy loading is a design pattern that is commonly used to defer
initialization of an object up until it is needed by the program.
The gains of using the pattern include efficiency (if it’s used right)
and sometime performance. Eager loading is the opposite pattern of
lazy loading
. In this pattern we initialize the object before hand and
don’t wait to the second we really need it.
In Entity Framework we can use the Include method in order to
eager load an entity graph.

Eager Loading with Repository Pattern

In the interface of the Repository I will add a new method which
will be called QueryObjectGraph. That method will receive a string
which indicate the children to load. Now the interface will look like:

public interface IRepository<T> where T : class
{        
    T GetById(int id);
    IEnumerable<T> GetAll();
    IEnumerable<T> Query(Expression<Func<T, bool>> filter);
    IEnumerable<T> QueryObjectGraph(Expression<Func<T, bool>> filter, string children);
    void Add(T entity);
    void Remove(T entity);   
}

and the implementation of the abstract Repository will change to

public abstract class Repository<T> : IRepository<T>
                                  where T : class
{
  #region Members
 
  protected ObjectSet<T> _objectSet;
 
  #endregion
 
  #region Ctor
 
  public Repository(ObjectContext context)
  {
    _objectSet = context.CreateObjectSet<T>();
  }
 
  #endregion
 
  #region IRepository<T> Members
 
  public IEnumerable<T> GetAll()
  {
    return _objectSet;
  }
 
  public abstract T GetById(int id);
 
  public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
  {
    return _objectSet.Where(filter);
  }
 
  public IEnumerable<T> QueryObjectGraph(Expression<Func<T, bool>> filter, string children)
  {
    return _objectSet.Include(children).Where(filter);
  }
 
  public void Add(T entity)
  {
    _objectSet.AddObject(entity);
  }
 
  public void Remove(T entity)
  {
    _objectSet.DeleteObject(entity);
  }
 
  #endregion
}

Pay attention that I replaced the IObjectSet<T> into it’s
Entity Framework implementation of ObjectSet<T>. The reason
is that the IObjectSet<T> interface doesn’t include the Include method.
Now I can continue using the same Unit of Work implementation and
also use the eager loading ability like in the following example:

using (SchoolEntities context = new SchoolEntities())
{
  UnitOfWork uow = new UnitOfWork(context);
  foreach (var department in uow.Departments.GetAll())
  {
    Console.WriteLine(department.Name);
  }
 
  foreach (var department in uow.Departments.Query(d => d.Budget > 150000))
  {
    Console.WriteLine("department with above 150000 budget: {0}",
        department.Name);
  }
 
  foreach (var department in uow.Departments.QueryObjectGraph(d => d.Budget > 150000, "Courses"))       
  {
    Console.WriteLine("department with above 150000 budget: {0}, {1}",
        department.Name, department.Courses.First().Title);
  }
}
Summary

In the previous post I only showed the way to implement your
repositories. As you can see in this post I can take the offered
solution and make it specific to my needs.


Categories: Blogs

Revisiting the Repository and Unit of Work Patterns with Entity Framework

Mon, 06/21/2010 - 05:51
Revisiting the Repository and Unit of Work Patterns with Entity Framework

In the past I wrote twoRevisiting the Repository and Unit of Work Patterns with Entity Framework
posts about the
Repository and the
Unit of Work patterns
(here and here). Today
I want to show a better
and less naive solution
for imposing the Unit of Work and the Repository patterns with
Entity Framework.

Revisiting The Repositoy Implementation

In the Repository pattern, I added to the interface two new
methods for adding and removing an entity:

public interface IRepository<T>
                where T : class
{
  T GetById(int id);
  IEnumerable<T> GetAll();
  IEnumerable<T> Query(Expression<Func<T, bool>> filter);    
  void Add(T entity);
  void Remove(T entity);
}

Also I’ve changed the return type of the Query from IQueryable
to IEnumerable in order not to enable additional composition
on that query that will hit the database.
The implementation of the Repository itself will change as follows:

public abstract class Repository<T> : IRepository<T>
                                  where T : class
{
  #region Members
 
  protected IObjectSet<T> _objectSet;
 
  #endregion
 
  #region Ctor
 
  public Repository(ObjectContext context)
  {
    _objectSet = context.CreateObjectSet<T>();
  }
 
  #endregion
 
  #region IRepository<T> Members
 
  public IEnumerable<T> GetAll()
  {
    return _objectSet;
  }
 
  public abstract T GetById(int id);
 
  public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
  {
    return _objectSet.Where(filter);
  }
 
  public void Add(T entity)
  {
    _objectSet.AddObject(entity);
  }
 
  public void Remove(T entity)
  {
    _objectSet.DeleteObject(entity);
  }
 
  #endregion

One of the things to notice is that I hold an IObjectSet as my data 
member of the Repository itself instead of holding the context like
in my previous post. The IObjectSet is a new interface in EF4
which helps to abstract the use of the created entity sets.
Now the Repository is better implemented and looks like an
in-memory collection as it was suppose to be. If I need more specific
methods I can inherit from this Repository implementation and add the
desired functionality. As you can see I don’t implement the GetById
method and enforce my concretes to implement it.
The DepartmentRepository from the previous post will look like:

public class DepartmentRepository : Repository<Department>
{
   #region Ctor
 
   public DepartmentRepository(ObjectContext context)
     : base(context)
   {
   }
 
   #endregion
 
   #region Methods
 
   public override Department GetById(int id)
   {
     return _objectSet.SingleOrDefault(e => e.DepartmentID == id);
   }
 
   #endregion
}
Revisiting The Unit of Work Implementation

After we have our Repository we would like to create a
Unit of Work to hold the application repositories and to
orchestrate the persisting of data for some business transactions.
The new interface for the Unit of Work will look like:

public interface IUnitOfWork
{
  IRepository<Department> Departments { get; }    
  void Commit();
}

By of course if you have more repositories in your application you
will add them to the IUnitOfWork (in the example I only have the
departments repository). Now the implementation of the Unit of Work
won’t be a part of the repository (like in the old post) and will look like:

public class UnitOfWork : IUnitOfWork
{
  #region Members
 
  private readonly ObjectContext _context;
  private DepartmentRepository _departments;
 
  #endregion
 
  #region Ctor
 
  public UnitOfWork(ObjectContext context)
  {
    if (context == null)
    {
      throw new ArgumentNullException("context wasn't supplied");
    }
 
    _context = context;
  }
 
  #endregion
 
  #region IUnitOfWork Members
 
  public IRepository<Department> Departments
  {
    get
    {
      if (_departments == null)
      {
        _departments = new DepartmentRepository(_context);
      }
      return _departments;
 
    }
  }
 
  public void Commit()
  {
    _context.SaveChanges();
  }
 
  #endregion
}

As can be seen the Unit of Work holds the ObjectContext but
you could use an IContext interface instead if you like to be more
abstract and with no dependency on Entity Framework at all. This can be
achieved by using the T4 templates that were provided in EF4 which you
will use to add the IContext interface implementation. The
Unit of Work has a constructor that can be injected using an IoC container.
The testing program will change into:

using (SchoolEntities context = new SchoolEntities())
{
  UnitOfWork uow = new UnitOfWork(context);
  foreach (var department in uow.Departments.GetAll())
  {
    Console.WriteLine(department.Name);
  }
 
  foreach (var department in uow.Departments.Query(d => d.Budget > 150000))
  {
    Console.WriteLine("department with above 150000 budget: {0}",
        department.Name);
  }
}

Some thing to notice here is that I create the context during
the running of the program. As I wrote earlier, this can be changed
to using an IoC container instead which will inject the constructor
dependency.

Summary

Lets sum up, this offered solution is much better then the naive
example I gave in the previous posts. It is much more testable and
abstract and as I wrote you could go further and use an IoC container
to inject the use of Entity Framework in the Unit of Work
implementation.


Categories: Blogs

Consuming OData Feed using Microsoft PowerPivot

Sun, 06/20/2010 - 06:41
Consuming OData Feed using Microsoft PowerPivot

PowerPivot is a data analysis
add-inConsuming OData Feed Using Microsoft PowerPivot for excel that brings to
it computational power.
It also helps “to create compelling
self-service BI solutions, facilitates
sharing and collaboration
on user-generated BI solutions”
(taken from the PowerPivot site).
This post will help you to understand how to consume OData feed
from PowerPivot in order to use the data the OData exposes.

The OData Feed

OData exposed feeds can be found in the http://www.odata.org/ site.
Under the Producers tab you will find OData producers which expose
their data using the OData protocol. In my example I’ll use the
Netflix’s feed that can be found here: http://odata.netflix.com/Catalog/.

Consuming Netflix OData Feed using PowerPivot

In order to use PowerPivot for excel you first need to download it.
There are some prerequisites for doing that including having Office
2010 installed on your machine. After installing PowerPivot open your
excel and go to the PowerPivot tab and open PowerPivot window.
One of the options in the PowerPivot window is to get data from
data feeds (you will see the OData protocol logo beside it):
PowerPivot Window

Use the From Data Feeds menu item in order to open the Table
Import Wizard
:
Table Import Wizard 

In the Data Feed Url textbox insert the relevant OData feed (in my
case the Netflix’s feed Url). Press Next to import the data definition
and then you will see the entity sets the feed exposes as tables:
Data Feed Tables

Choose the tables you want to import and press Finish to end the
process and import the tables. This can take some time depending
on the size of the exposed data set.
I chose the Genres set and this is the result:
Imported Results
Now I can use the PowerPivot’s features to build my relevant report
or to manipulate the data I’ve received.

Summary

Let sum up, I showed how to consume OData feed using Microsoft’s
PowerPivot. The OData ecosystem is growing very fast and as you
could see from this example it consumers can also be BI tools like
PowerPivot and many more. This is one of the reasons to start
learning this protocol now.


Categories: Blogs

Using Paging in WCF Data Services

Sat, 06/19/2010 - 13:56
Using Paging in WCF Data Services

One of the mechanismsUsing Paging in WCF Data Services
which were provided
in WCF Data Services
from the start was
client side paging.
In the new release of
WCF Data Services we also
get a server side paging and this will be addressed in this post.

WCF Data Services Client Side Paging

From the early days of WCF Data Services we could achieve paging
on the client side using the $top and $skip query parameters.
For example the following URI for a data service will bring the 11-20
courses which were requested:

http://localhost:8322/SchoolDataService.svc/Courses?$skip=10&top=10

The problem starts when you expose resources with a lot of items.
Lets say that we have 10000 courses in our course library. The following
URI will bring to the client all of them:

http://localhost:8322/SchoolDataService.svc/Courses
Running this request will decrease the amount of clients for the service
since it will take ages for the query to return. So what can we do?
use server side paging instead.
WCF Data Services Server Side Paging

So how can we limit our returning result set to the client? we can
use a new feature of WCF Data Services. In order to create a
server side paging behavior all we need to do is to configure the
service to return some portion of data. We will use the new method
of the DataServiceConfiguration class which is called
SetEntitySetPageSize for each entity set or for all of them at once
(using * ). The following code create server side paging for all the
entity sets exposed by the data service to return only 10 items
at once:

public class SchoolDataService : DataService<SchoolEntities>
{    
  public static void InitializeService(DataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    config.SetEntitySetPageSize("*", 10);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  }
}

When I use the service now with a URI to retrieve all the courses I will
get only the first ten courses. Also as you can see in the figure we
get a link at the bottom that leads us the next ten results:
Server Side Paging

and the link itself is written as:

http://localhost:8322/SchoolDataService.svc/Courses?$skiptoken=4041
Summary

In the new release of WCF Data Services we get a new paging
feature which enable server side paging. Using this method
or combining it with client side paging extend the capabilities
of WCF Data Services. The use of the server side paging is very
easy – just configure the service. In the post I showed an example
of how you can achieve that behavior.


Categories: Blogs

FeedBurner Counter Hiccups

Tue, 06/15/2010 - 14:50
FeedBurner Counter Hiccups

I’m using the FeedBurner Feedburner Counter Hiccups
counter in my blog from
day one in order to see
how many readers I have
in my blog. Using the service
I could see that during time the amount of readers in my
blog started to grow. In the last couple of weeks I could see
some counter hiccups. One day I had above 400 readers and
in the next day all the readers that are registered with
Google Feedfetcher suddenly disappeared and the counter dropped
to 200 readers. This behavior was written in the FeedBurner Status Blog
Today suddenly my counter exploded with 1261 readers. Since
yesterday it was 381 readers, I went to my FeedBurner account and
checked it. I could see that suddenly I have 885 readers which use
Netvibes.
Even though it is flattering to have such an amount of readers, I guess
that this number isn’t true.
Since I remembered that in the past there were hacks that tempered
the counter using Netvibes, I write this post in order not to damage my
credibility. To be honest I wish this amount is true but I currently don’t
know if it is and I couldn’t find a way to contact FeedBurner in order
to check it out.


Categories: Blogs

Using Conditional Mapping in Entity Framework

Tue, 06/15/2010 - 11:10
Using Conditional Mapping in Entity Framework

There are timesUsing Conditional Mapping in Entity Framework
that we want to
retrieve only
a portion of data
from a table in
the database
permanently by some
filter. For that purpose
we can use the conditional mapping in Entity Framework.

What is Conditional Mapping?

Conditional mapping is a fixed condition that helps use to
filter the result set that is being returned from the database
for a specific entity. Also it enforces that an entity is mapped
to data in the database under only certain conditions which are
supplied inside the conditional mapping.
In order to use conditional mapping we need to open the
Mapping Details View. In the view we can add for each entity
a conditional mapping using the <Add a Condition>:
Conditional Mapping
When we create a condition, that condition will be added to each
query that we will make to the database.

Available Conditional Mappings

There are some possible conditional mapping in Entity Framework
which are provided by two kind of operators – the equality operator
and the Is operator.
The equality operator (=) can have values of strings or integers.
The Is operator check whether a column is Null or Not Null.
When we have more then one condition it will construct an And
operation between all the conditions.

Conditional Mapping Example

A very common example for using a conditional mapping is having
a table field that indicate a logical delete (for example an IsDeleted
field). Since we want to present only undeleted rows/entities
then a conditional mapping can be a valid solution.

In the example I’m using the following table that represent a course data:
Course Table
The IsDeleted has a default value of 0 to indicate that a row’s logical
state is not deleted. If the row is deleted I change the value to 1.

This is the entity in the generated model before I make any
changes:
Course Entity
Now I want to impose the conditional mapping on the course entity.
The first thing to do is to delete the IsDeleted property since it
will be used by the conditional mapping. Then I create a conditional
mapping
that retrieve only entities with IsDeleted equals to 0 in
the following way:
The Conditional Mapping

That is it.
Now whenever I query for courses, the generated query will be
created with a where clause that check whether IsDeleted equals 0.
For example if I query for all courses the following query will be sent to
the database:

SELECT 
[Extent1].[CourseID] AS [CourseID], 
[Extent1].[Title] AS [Title], 
[Extent1].[Days] AS [Days], 
[Extent1].[Time] AS [Time], 
[Extent1].[Location] AS [Location], 
[Extent1].[Credits] AS [Credits], 
[Extent1].[DepartmentID] AS [DepartmentID]
FROM [dbo].[Course] AS [Extent1]
WHERE [Extent1].[IsDeleted] =  CAST( '0' AS tinyint)

Since I use tinyint as data type in the database then there is a
casting in the query.

Summary

A conditional mapping in Entity Framework helps to filter returning
results. If you have a fixed behavior such as logical delete then
conditional mapping can help you achieve the relevant behavior.


Categories: Blogs

Cache Retrieval Pattern

Sun, 06/13/2010 - 06:32
Cache Retrieval Pattern

In my previous post I wrote about cache layer and its position
in every application. In this post I’m going to explain what is
the cache retrieval pattern and show an example of how to
implement it.

Cache Retrieval Pattern

When we implement a cache layer we need a strategy in order to
retrieve cached items. The cache retrieval pattern is very
simple and can be imposed into any application very fast.
So how does it work?
The business logic component will use the cache API in order to
check whether some data exists in the cache. If the data doesn’t exists
in the cache, the business logic component responsibility will be to
insert the data into the cache. Since cache is volatile you can’t depend
on it to hold the data you need. This is why you always need to check
whether the data exists in the first place. The business logic component
will use a data access component to retrieve the relevant data from a
data storage. After it has the data in hand it will place the data in
the cache and return it to its consumer. The following diagram
shows how this pattern work:
Cache Retrieval Pattern

Cache Retrieval Pattern Example

After we understood the what lets take a look at the how.
The following BL class implement the data retrieval pattern:

public class BLComponent
{
  #region Properties
 
  private ICacheManager CacheManager { get; private set; }    
 
  #endregion
 
  #region Ctor
 
  public BLComponent(ICacheManager cacheManager)
  {
    CacheManager = cacheManager;
  }
 
  #endregion
 
  #region Methods
 
  public Department GetDepartmentById(int departmentId)
  {
    if (!CacheManager.Contains(departmentId.ToString()))
    {
      DALComponent dataAccessor = new DALComponent();
      Department department = dataAccessor.GetDepartmentById(departmentId);
      CacheManager.Insert(departmentId.ToString(), department);
      return department;
    }
    return CacheManager.Get<Department>(departmentId.ToString());
  }
 
  #endregion
}

As you can see I use the ICacheManager interface in order to
create an abstraction against the cache layer. This will enable
me to create a class which uses the cache API of my chosen
cache implementation (in memory, distributed and etc).
The ICacheManager can look like:

public interface ICacheManager
{
  /// <summary>     
  /// Add a new object into the cache     
  /// </summary>     
  /// <param name="key">The key of the object to add</param>     
  /// <param name="value">The value of the object to add</param>     
  void Add(string key, object value);
 
  /// <summary>     
  /// Check whether the key is contained by the cache     
  /// </summary>     
  /// <param name="key">The key to check</param>     
  /// <returns>Returns true if the key is contained by the cache</returns>     
  bool Contains(string key);
 
  /// <summary>     
  /// Returns the number of items in the cache     
  /// </summary>     
  /// <returns></returns>     
  int Count();
 
  /// <summary>     
  /// Insert a new object into the cache      
  /// </summary>     
  /// <param name="key">The key of the object to insert</param>     
  /// <param name="value">The value of the object to insert</param>     
  void Insert(string key, object value);
 
  /// <summary>     
  /// Get the object that its key is given    
  /// </summary>     
  /// <typeparam name="T">The object</typeparam>     
  /// <param name="key">The given key to check</param>     
  /// <returns>returns the object or null if it doesn't exists</returns>     
  T Get<T>(string key);
 
  /// <summary>     
  /// Removes the object that is referenced by the given key     
  /// </summary>     
  /// <param name="key">The given key</param>     
  void Remove(string key);
 
  /// <summary>     
  /// Get/Set the the given key and object     
  /// </summary>     
  /// <param name="key">The given key to the indexer</param>     
  /// <returns>Returns the object that the given key reference</returns>     
  object this[string key]
  {
    get;
    set;
  }
}

The data access component isn’t relevant to our discussion because
underneath it can be implemented by IRepository, some service or
whatever method you pick to retrieve your relevant data. Also,
pay attention that this example isn’t thread safe.

Summary

The cache retrieval pattern is simple to understand and implement
in any application. As I wrote in my previous post using caching in
applications is a must and the pattern for retrieving data will help
you to insure you have the relevant data close to your application.


Categories: Blogs

Cache Layer

Fri, 06/11/2010 - 09:51
Cache Layer

Lately I found myself in some architecture consulting sessions at
some customers. In every one of those customers I found myself
explaining how to implement a cache layer in order to decrease
the amount of round trips to the database and for better scalability.
In this post I’ll try to explain in high level how to build a cache layer.

Deciding to Build a Cache Layer

Every application that performance is important to its developers
and managers must contain some sort of caching. The cache is a very
fast in memory resources container which holds relevant data close to the
application itself. I explained in the past the candidate resource types
for caching in this post. So you have decide to implement caching
in your application, what next?
The answer is simple – create a cache layer.

Cache Layer Position in Application Architecture

The next thing to understand is the location of the cache layer in your
application. The next diagram shows were you should place the cache layer:
Cache Layer
As you can see the cache layer's best place is between the business
logic layer and the data access layer. The business logic responsibility
will be to check whether an entity or some data exists in the cache
and then if not to make a round trip to the database (using the data
access layer of course) and bring the data to application. When the data
exists we first put it in the cache and then we have the data in hand
and also it exists our the cache. This is called the cache retrieval pattern.
There are many ways to create a cache layer for example by using
distributed cache like AppFabric caching services, Enterprise Library
Caching Application Block, ASP.NET caching and many more cache services.
It’s your responsibility to evaluate which cache technology to use in your
application by answering to your application requirements.

Summary

Caching in applications is a very vital way to improve the application
performance and make the application more scalable. It’s our
responsibility to create a cache layer which will exists between
your business logic and data access layer. By using the cache retrieval
pattern
you will be able to use your cache in a very efficient way.


Categories: Blogs

Microsoft Israel Sites were DNS Hijacked Yesterday

Fri, 06/11/2010 - 08:17
Microsoft Israel Sites were DNS Hijacked Yesterday

Yesterday there was a DNS hijacking attack on some of
Microsoft Israel sites including this Microsoft blog community.
The sites were defaced with some offensive content which show
that the people behind the attack are very childish and narrow
minded. 

This blog community is sharing its experience and knowledge with
all the Microsoft community all over the world. Denying its service
only hurts the people who search the data from this source of
knowledge.
You won’t see here political posts or other stuff since there are other
places which you can write your opinions such as Facebook, Twitter,
Talkbacks and many more. The posts here are mainly technical
for the Microsoft community worldwide. Since this is the case, attacking
this site or other sites only because they are Israeli sites only show
how shameless and narrow minded the attackers.

One last thought, changing a DNS register can be caused by inside job in
a domain register company (by of course there are other options and I’m
not accusing anyone). I hope that Microsoft will make sure this won’t
happen again.


Categories: Blogs

Entity Framework 4 Course

Wed, 06/09/2010 - 12:03
Entity Framework 4 Course

In the last couple of months,
I have updated myEntity Framework 4 Course
Entity Framework course
to include the new subjects
and features of EF4. Yesterday I
finished to deliver the first cycle
of this course and got good reactions
about it.


If you want to learn what is Entity Framework, how to use it and
how to integrate it into applications you can take a look at the
following syllabus and to register for the three days instructor lead
course I’ve created.
See you there.


Categories: Blogs