Tuesday, 16 April 2013

Why to use Entity Framework in .NET? Advantages of Entity Framework

Why to use Entity Framework in .NET? Advantages of Entity Framework
 
Entity Framework is an Object Relational Mapping (ORM) Framework for the .NET Framework. Entity Framework  returns the data in your database as an object.
 
Entity Framework is actually written on top of ADO.NET, meaning under this framework, we are still using ADO.NET. So we cannot say that Entity Framework is a replacement of ADO.NET.
 
Entity Framework basically generates business objects and entities according to the database tables.
 
Advantages of Entity Framework: There are lot of reason why should you use entity framework over LinqToSql and ADO.NET.
 
1. Database performance is improved. Updating your EDM based on your DB changes would take less time rather than the conventional methods. Database operations like select, insert, update, delete will work faster as you don't have to hit database again and again as you would be working with objects not with database tables.
 
2. Entity Framework performing basic CRUD (Create, Read, Update, Delete) operations. So most of the time you don't have to write any SQL yourself. When you make any changes to the object, the ORM will usually detect this, and mark the object as 'modified'. When you save all the changes in your ORM to the database, the ORM will automatically generate insert/update/delete statements, based on what you did with the objects.
 
3. Entity Framework works on databases other than Microsoft SQL Server, like Oracle, MySQL etc. While Linq is limited to MS SQL Server. It is easy to add support for another database (like Oracle) as we are programming against a model.
 
4. Easily managing "1 to 1", "1 to many", and "many to many" relationships.
 
5. Ability to have inheritance relationships between entities.

Monday, 15 April 2013

What is the use of persistence layer in any application architecture?

What is the use of persistence layer in any application architecture?
 
Recently, I fell in a .NET project whose architecture was prepared by one of our senior .NET person who is architect here in .NET. I was confused with pesistence layer he had created in the application architecture. I searched it on google but found on consolidated answers from anywhere. At last I came to get help from Stackoverflow .NET experts. I asked following question on stackoverflow and got valuable responses.
 
My question on persistence layer architecture:
 
I have to create an application in which I am asked to create an persistence layer in the application. The application is in .net. I have created business layer and presentation layer but I don't know how and why to create persistence layer.
 
I googled and came to know that persistence layer is used for storing and retrieving data usually from a database.
 
Can anybody explain in detail?
 
Responses I got:
 
Davide Piras Response which I accepted later on:
 
The reason for you to build a DAL ( Data Access Layer ) or any other kind of intermediate layer between database engine and Business / Application logic, is that by adding this layer in the between you isolate the rest / upper layers of your application from the specific database engine / technology you are using right now.
 
This has several advantages, like easier migration to other storage engines, better encapsulation of database logic in a single layer ( easier to replace or modify later depending on how well you have designed your cross-layer interfaces etc...)
 
See my most rated answer here, it is an example about ASP.NET MVC and EF but the structuring of solution and projects is actually technology independent: MVC3 and Entity Framework
 
Also read some articles to better understand this matter, for example: http://www.developerfusion.com/article/84492/net-and-data-persistence/
 
Renan's Response
 
If you're not saving your data somewhere, it won't be there again when your app is opened again. You can save it to a database as you said (SQL, Oracle, PostGRE etc.), or directly to disk (serializing in binary format, or plain text etc.).
 
Using a layer to do that is a good practice. It reduces coupling (i.e. spaghetti code), and makes maintenance much easier.
 
I suggest you read about Hibernate and it's .NET cousin, NHibe
 
Kenneth Garza's Response:
 
Persistance layer otherwise known as a Data Access Layer or other terminology.
 
It seperates the guts of getting and saving the data from the business layer. The reason you do this is so your business logic (the part of the application that does the heavy lifting for your data manipulation) is not tied to a specific type of data source.
 
The data layer will need to be written to be database specific. So if you're using MySQL to access all your data then you will write the dataLayer for that use.
 
If at some point you decide to move to MongoDB, then instead of rewriting your entire application. You can rewrite just the data access parts to get the data from MongoDB. Since the business logic doesnt care how you get the data, only that you do, it and the Presenation layer can remain intact.
 
Hope this helps.
 
Belogix Response:
 
In very simple terms a persistence layer is a way to SAVE and RETRIEVE items that your application uses.
 
A simple example is you have a class that represents a person (name, age and gender). While your application is running this is held in memory. But, say you want that information available if you close and open your application again. Well, you need some way to SAVE that person and then later on RETRIEVE it again. This is where a persistence layer comes in and will write your person somewhere "permanent".
 
That could be a database, a flat file, registry depending on the life-time and requirements etc.
 
In your persistence layers you will perform CRUD (Create, Read, Update, Delete) operations. Often against a database so you would Create a new person (Fred Bloggs). Say they change their name another user of your system might Read the record and change to Fred Miggins and Update the database. That customer then leaves the country so you Delete them.
 
Please refer to stackoverflow page for details.

What is the difference between Webservice and WCF in .NET?

What is the difference between Webservice and WCF in .NET?
 
If you are going for .NET technical interview and have mentioned WCF in your CV/Resume, I am 100% sure that you will be asked the question "What is the difference between webservice and WCF"? So be ready with this technical interview question.
 
WCF is a .NET 3.5 technology introduced by Microsoft. It unifies all communication options available in earlier versions of .NET framework. You can make a WCF application that would act exactly the same as a WebService, but it will be easier to implement and manage.
 
Here is the list of differences between Webservice and WCF
 
1. WCF has been designed by Microsoft from the scratch to comply with SOA (Service Oriented Architecutre). while Webservices do not comply with the Service Oriented Architecutre.
 
2. Webservice can only be hosted on IIS while WCF can be hosted on any server like WAS (Windows Activation Service), Self-hosting, Managed Windows Service.
 
3. WCF can be accessed via various protocols like SOAP over HTTP, Binary over TCP, Named Pipes, P2P, MSMQ etc. while webservices can only be accessed via HTTP. 
 
4. [WebService] attribute has to be added to the class and [WebMethod] attribute to be added to the method exposed to client in case of webservice while [ServiceContraact] attribute is added to the class and [OperationContract] attribute is added to the method exposed to client in case of WCF. 
 
5. System.Xml.Serialization namespace is used for serialization in webservice while System.Runtime.Serialization namespace is used for serialization in case of WCF.
 
6. WCF can be multithreaded via ServiceBehavior class while webservices cannot be multithreaded.

Saturday, 13 April 2013

How to get Property Name of a Class as a String at runtime in C#?

How to get Property Name of a Class as a String at runtime in C#?

Getting property names of class at runtime is the rare situation but it has very simple solution. In this article, I will try to give very basic example of getting property names of class in C# at runtime and storing that property name as a string. Suppose I have a public class say ClassName and this class has property say IntProperty which returns integer type.

public class ClassName
{
  public static int IntProperty { get { return 0; } }
}

Lets say I have to fetch the name of each property as a string at runtime, then I will have to use PropertyInfo and typeof keywords to get the name of properties at runtime. Below is the code c# snippet for this.

foreach (PropertyInfo p in typeof(ClassName).GetProperties())
{
    string propertyName = p.Name;
    //....
}

In this case I have taken the example of class which has only one property for making the article simple. But by using foreach loop which I have used you can assign names of properties to list of string at runtime as per your requirement.

Friday, 12 April 2013

Difference between OUT and REF Reference Types in C#

Difference between OUT and REF Reference Types in C#

Out is often preferred to ref. It ensures that you can avoid assigning the variable before passing it as an argument.

The out and the ref parameters are used to return values in the same variables that you pass as an argument of a method. These parameters are very useful when your method needs to return more than one value.

The C# language has strict rules regarding the passing of parameters by value and by reference. The default is to pass all parameters by value, even if those parameters are themselves references.

out and ref are pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialised, and the method using the out parameter has to set it to something. out is often preferred to ref. It ensures that you can avoid assigning the variable before passing it as an argument.

int x;
Foo(out x); // OK

int y;
Foo(ref y); // Error


C# Example to show the usage of out and ref

using System;
class Program
{
    static void Main()
    {
      int val = 0;

      Example1(val);
      Console.WriteLine(val); // Still 0!

      Example2(ref val);
      Console.WriteLine(val); // Now 2!

      Example3(out val);
      Console.WriteLine(val); // Now 3!
    }

    static void Example1(int value)
    {
      value = 1;
    }

    static void Example2(ref int value)
    {
      value = 2;
    }

    static void Example3(out int value)
    {
      value = 3;
    }
}


Output
0
2
3

Generic Types in C#: Syntax and Example

Generic Types in C#: Syntax and Example

Generic classes have type parameters. Separate classes, each with a different field type in them, can be replaced with a single generic class. The generic class introduces a type parameter. This becomes part of the class definition itself.

These types themselves contain type parameters, which influence the compilation of the code to use any type you specify.

Common examples of generics are Dictionary and List.

Program that describes generic class C#

using System;
class Test<T>
{
    T _value;
    public Test(T t)
    {
       // The field has the same type as the parameter.
       this._value = t;
    }
    public void Write()
    {
      Console.WriteLine(this._value);
    }
}

class Program
{
    static void Main()
    {
      // Use the generic type Test with an int type parameter.
      Test<int> test1 = new Test<int>(5);
      // Call the Write method.
      test1.Write();
      // Use the generic type Test with a string type parameter.
      Test<string> test2 = new Test<string>("cat");
      test2.Write();
    }
}

Output
5
cat

C# Nullable Types: Why and why not to use Nullable Types in C#?

C# Nullable Types: Why and why not to use Nullable Types in C#?

Nullable types in the C# language can be constructed by specifying the question mark after a value type in a declarator statement. The nullable int can be specified with the syntax "int?"

Nullable types are described in the C# language specification as being value types that are wrapped inside the nullable type, and they can then be unwrapped dynamically and implicitly.

Following program demonstrates a use of the nullable integer type, which can be specified with the int? syntax. You can use a question mark at the end of a value type to transform the type into a nullable type. The program demonstrates a null int type, the HasValue and Value properties, and using the nullable type to acquire the value of the instance.

Program that uses nullable int type C#

using System;
class Program
{
    static void Main()
    {
       // Assign null to an integer            
       int? value = null;
       Console.WriteLine(value.HasValue);
       // Assign the nullable integer to a constant integer. The HasValue property is now true.
       value = 1;
       Console.WriteLine(value.HasValue);
       Console.WriteLine(value.Value);
       Console.WriteLine(value);
       if (value == 1)
       {
         Console.WriteLine("True");
       }
    }
}

Output
False
True
1
1
True

Nullable<int> is the same as int?. When you use a type such as int?, you have access to extra properties such as HasValue and Value.

The HasValue instance property on the nullable type returns a Boolean that indicates whether the nullable instance contains a set value. If the type is null, it does not have a value and HasValue is false. If the type is assigned to an integer, the HasValue property is true. Also, if the HasValue property is true, you can access the Value property without an exception.

Let's examine the implementation of the nullable generic struct in the base class library.

When you use a type such as int?, the C# compiler actually uses the Nullable<T> struct, where T is the value type you are using such as int. Structs in the C# language are allocated in continuous memory for performance reasons, and this makes nullable types fairly efficient.

Why to use Nullable Types in C#?

1. Nullable<T> is useful for when you need a possible invalid state for a value type.

2. If the data is being retrieved from a database that may contain a null value for the column.
 
Why not to use Nullabe Types in C#?

1. There is overhead to using nullable types and this translates to reduced performance over raw value types in some cases.

2. If nullable types are used incorrectly, these will unnecessarily increase the complexity of your code.

3. You also have to be careful to avoid null dereferences, so they place additonal burden on programmers working with that code.