Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, 18 January 2012

ASP.NET Cache dependency example


In this article we will learn how to implement file dependency in caching.


In this method the cache["messageDependency"]  loads the file "DependencyFile.txt" in memory(cache) only when its content is changed in the disk.

public void displayMessage()
{
         String message;
         String Path = "~/DependencyFile.txt";
         if (Cache["messageDependency"] == null)
         {
                  System.IO.StreamReader sReader = new StreamReader(Server.MapPath(Path));
                  message = sReader.ReadToEnd();
                  sReader.Close();

                  System.Web.Caching.CacheDependency msgDependency = new System.Web.Caching.CacheDependency(Server.MapPath(Path));
                  Cache.Insert("messageDependency", message, msgDependency);
         }
         Response.Write(Cache["messageDependency"].ToString());
}

Inside Entity Framework: Lazy Loading, Explicit Loading and Eager Loading


When working with Entity Framework, it is important to understand how to hit the database and get the data especially to avoid the performance issues with the applications. That is exactly what I’m going to explain here that there are several ways to hit the database and load the related entities to retrieve the data. Also it is purely developer’s choice which one to use depending on the context to improve the performance.


Lazy Loading:

With lazy loading enabled, related objects are loaded when they are accessed through a navigation property. The default value of LazyLoadingEnabled is false. However, if we use the EF tools to create a new model and the corresponding generated classes, LazyLoadingEnabled is set to true in the object context's constructor by default. In this type of loading, each navigation property that we access causes a separate query to be executed against the data source. 

Here is the simple example which is based on the assumption that there are three tables OrganizationsTenants and Facilities
The relationship between these tables is : 
Organization has multiple Tenants 
Tenants have multiple Facilities

using (DatabaseEntities context = new DatabaseEntities())
{
context.ContextOptions.LazyLoadingEnabled = true;

var organizations = context.Organizations.Take(100);
var tenant = context.organizations.Where(org => org.TenantId == "T1").FirstOrDefault();

// If lazy loading was not enabled no Facilities would be loaded for the tenant.
foreach(Facilities facility in tenant.Facilities)
{
       Console.WriteLine("FacilityID: {0}", facility.facilityID);
}
}

Explicit Loading:

The following example in this topic show you how to explicitly load related objects by using the LoadProperty method on the ObjectContext. In this the Lazy Loading is set to false and we load the related entities explicitly each time. This example is based on the assumption that there are four tables: organizations, tenants, Facilities and ApplicationInstances. The relationship between these tables is an organization has multiple tenants, the tenants have multiple facilities and the facilities in turn have multiple ApplicationInstances.

using (DatabaseEntities context = new DatabaseEntities())
{
context.ContextOptions.LazyLoadingEnabled = false// Disable Lazy Loading
context.MergeOption = MergeOption.AppendOnly;

var organization = context.Organizations.Where(org => org.OrganizationId == “org1”).FirstOrDefault();
context.LoadProperty(organization, org => org.Tenants);

var tenants = organization.Tenants.Where(tnt => tnt.TenantId == "T1").FirstOrDefault();
context.LoadProperty(tenants, tnt => tnt.Facilities);

var facility = tenants.Facilities.Where(fac => fac.FacilityId == "F1").FirstOrDefault();
context.LoadProperty(facility, fac => fac.ApplicationInstances);

var applicationInstances = facility.ApplicationInstances.Where(appIns => appIns.ApplicationInstanceId == "AI1");

foreach(var item in applicationInstances)
{
    Console.WriteLine("ApplicationInstanceID: {0}", item.applicationInstanceID);
}
}

Eager Loading:

There are circumstances that you may want only one query to hit the database and get the related entities rather than hitting every time. At times it may be a costlier operation to hit the database every time to load the related entities. In this scenario this Eager loading is very handy to do this operation. This example is based on the assumption that there are four tables: organizations, tenants, Facilities and ApplicationInstances. The relationship between these tables is an organization has multiple tenants, the tenants have multiple facilities and the facilities in turn have multiple ApplicationInstances.

DatabaseEntities context = new DatabaseEntities();
context.MergeOption = MergeOption.OverwriteChanges;

var organization = (from org in context.Organizations.Expand(tnt => tnt.Tenants.SubExpand(f => f.Facilities.
                 SubExpand(ai => ai.ApplicationInstances)))
         where org.OrganizationId == "T1"
         select org).First();

foreach (var tnt in organization.Tenants)
{
    foreach (var facility in tnt.Facilities)
    {
        foreach (var item in facility.ApplicationInstances)
        {
            //Do Something
        }
    }
}

Code Contracts - .NET Features


How do you make sure your method guarantees to operate correctly under defined expected input states? Well Code Contracts may help you.


One of the fine features provided by .net 4.0 is Code Contracts. First it’s worth thinking a little about what contract means to you. They indicate the expected input states under which the method guarantees to operate correctly. 

Contracts act as checked documentation of your external and internal APIs to be shipped. The code contracts are used to improve testing via runtime-checking, enable static contract verification. One of the interesting features of Code Contracts is that it includes a MSIL rewriter (ccrewrite.exe) that post-processes an assembly to change the intermediate language instructions emitted by the compiler. Another great feature of Code Contracts is that you can turn static analysis on and off on a per project basis. I believe this will be important to anyone practicing TDD and BDD. 

A code contract follows design principle of Design By Contract (Dbc). This principle has 3 tenets which code contract also takes care of 
a) Pre-condition: 
Refer to the things it expect to do. These are expressed using Contract.Requires() 

b) Post-condition: 
Refer to the things it guarantees to do. These are expressed using Contract.Ensures() 

c) Object Invariant: 
Refer to things it maintains. 

These are expressed using Contract.Invariant() Well, the tenets are fine for Dbc and .Net Code Contract follows each of these properly. 
We will examine each of them in this article.

How? 
The following example illustrates how the three main features of contracts are used.

a) Pre-condition
public Rational(int numerator, int denominator) 

     Contract.Requires(denominator!= 0); 
this.numerator = numerator; 
this.denominator = denominator;
}

The preconditions are generally used to specify valid parameter values. The example provided makes sure or checks that the denominator is not equal to zero. We can throw error if the condition is not satisfied using the overloaded method as below. 
The example provided makes sure or checks that the denominator is not equal to zero. We can throw error if the condition is not satisfied using the overloaded method as below

b) Post-condition
Contract.Ensures(this.Result!= 0);

Basically the postconditions are checked /Executed before exiting the method call. The example provided checks/ Ensures that the result is not equal to zero. We can throw an exception if the condition is not satisfied using an overloaded method.

Contract.EnsuresOnThrow<ArgumentException> (this.Result!=0);

c) Object Invariant
public int EMIPercentage 

      get; private set; 
}

[ContractInvariantMethod] 
void ObjectInvariant() 

       Contract.Invariant(this. EMIPercentage >= 0);
}

The object invariants are conditions that should hold on each instance of your class whenever the object is visible. They express the condition under which the object is in a “good” state. The methods are identified with [ContractInvariantMethod] attribute. The invariants are checked at the end of each public method call. In the example above the denominator will checked at the end of each public method.