Reviewed Book “Object-Oriented Thought Process – by Matt Weisfeld”
Being an MVB (Most Valuable Blogger) at DZone, I have gotten an opportunity to review a book named “Object-Oriented Thought Process – Fourth Edition”, written by Matt Weisfeld.
Following is a review I made for this book,
“A great book to learn the Object oriented principles and start thinking in object terms. Matt has provided the real life examples which help reader to understand the concept of object oriented principles easily. He started from the basic concepts and ended up with more advanced concepts like Object persistence and design patterns that helps reader to gain knowledge on the vital areas as well when designing or else working on any project. Although there are many code snippets provided to discourse any topic but there is no single programming language used to express code, this is a valuable effort to provide code snippets in different languages but the convention is not consistent. It can be improved by providing code extracts for other languages as well while addressing any topic with some special formatting that helps reader to understand code in preferred language.”
Enabling Lazy Loading in Entity Framework Code First Model
In Entity Framework you can configure several attributes for your Database Context class. In this article I will tell you what Is Lazy Loading and how you can leverage this feature in Code First Model.
Lazy Loading is a feature through which the Code First engine loads the navigation objects that belongs to the parent entity. For e.g. If there is a Person Entity and Person belongs to particular Department. Now when you load the Person retrieve the person object it will load the Department object values as well through which you can easily navigate to its properties and display those on forms or anywhere.
In order to enable Lazy Loading you can enable the properties values under your context constructor as follows.
public DemoContext()
{
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ProxyCreationEnabled = true;
}
One important point, lazy loading will only work if the ProxyCreationEnabled is enabled and the Navigation property of entity is virtual.
public
class
Person
{
public
Int32 Id { set; get; }
public
String Name { set; get; }
public
virtual
Department Department { get; set; }
public
Int32 DepartmentId { set; get; }
public
string Gender { set; get; }
}
public
class
Department
{
public
Int32 Id { set; get; }
public
String DepartmentName { set; get; }
public
virtual
ICollection<Person> Persons { set; get; }
}
Now, let suppose person table and department table have few records stored. When you read the Person using context.ToList () or any other linq function it will automatically load the department objects as well.
Develop a function that returns the list.
public
Person GetPerson(int id)
{
DemoContext context = new
DemoContext();
{
var items = context.Persons.Where(i => i.Id == 1);
return items;
}
}
Now, by adding a watch on Items you can see that you will get corresponding Department values i.e. DepartmentName and Id as well.

Therefore, Lazy loading helps developer to retrieve the child objects rather making joins in Linq query and automatically do the join part.
Happy Coding!
Enabling Transactions in WCF
Transaction plays an important role in any business application that involved CRUD operations. To implement transactions, we utilize TransactionScope class that automatically manages transactions and detect the scope of the transaction. You can apply TransactionScope on a block of code and regardless of how many WCF services instances you have opened or operation contracts you are calling will be carried on the scope of that transaction. For example, if you are calling three services methods and third one fails to complete the operation, transaction will be rolled back unless it’s outside the boundary of a TransactionScope.
WCF supports transaction on following bindings.
- WSHttpBinding
- NetTcpBinding
- NetNamedPipeBinding
- WSDualHttpBinding
- WSFederationHttpBinding
While developing a Service Contract you have to specify the TransactionFlow attribute on each Operation Contracts that requires a Transaction to be handled. In the below code snippet there are two methods one which submit employee master information and the other that submits employee details. As both require transaction so I have specified TransactionFlow attribute on both of them.
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void CreateEmployee(Common.DataContracts.Employee employee);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
void SubmitEmployeeDetails(EmployeeDetails employeeDetails);
There are following flow options in the TransactionFlow attribute.
TransactionFlowOption. Allowed : Transaction can be flowed.
TransactionFlowOption.Mandatory : Transaction must be flowed.
TransactionFlowOption.NotAllowed : Transaction should not be flowed. This is default.
Next, implement the service and specify OperationBehavior attribute on each method. You can specify the TransactionScopeRequired property as true or false.
[OperationBehavior(TransactionScopeRequired= true)]
public void CreateEmployee(Common.DataContracts.Employee employee){
}
Now enable the Transaction on the binding itself. Open your web.config file and specify the transactionflow = true as follows
<wsHttpBinding>
<binding
name=“TransactionalBind“
transactionFlow=“true“/> </wsHttpBinding>
Now add service reference and consume the service. While calling CreateEmployee and SubmitEmployeeDetails method you have to put them in the TransactionScope block and if any of the method fails, the transaction will be rollback.
using (TransactionScope scope = new
TransactionScope())
{
try
{
Services.EmployeeService.EmployeeServiceClient()
clientobj = new Services.EmployeeService.EmployeeServiceClient();
clientobj.CreateEmployee(employeeObj);
clientobj.SubmitEmployeeDetails(employeeObjDetails);
scope.Complete();
}
catch (Exception ex)
{
scope.Dispose();
}
}
Happy programming!
Basic Introduction about T4 Templates & How to customize them for ASP.NET MVC Project
In ASP.Net MVC 3 you can easily generate views from predefined scaffolding templates provided for Create, Edit, List, Delete and Details views out of the box which seems quite riveting. Actually, there are some *.tt template files (known as T4 templates) stored at following path C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web that contains the basic structure and page layout for these views and based on those templates it generates the Create, Edit, Delete, List, Details and Empty .cshtml or .aspx files depends on which project language you have chosen for ASP.Net MVC project.
In this post I will discuss about T4 templates and how we can customize by taking a simple example.
What is T4
T4 stands for Text Template Transformation Toolkit. T4 generates text based on Text based template files, Template is a combination of text and control logic that you can define using C# or VB.net. Transformation actually executes the code written in template and brings out a final output whereas the Toolkit contains some assemblies leverage to produce the desire output file.
Now, let’s quickly open the sample Create.tt file to see what it looks like and how we can customize. When you open the file you can see directives
<#@ template language=”C#” HostSpecific=”True” #>
<#@ output extension=”.cshtml” #>
language specifies which language we are using either C# or VB.net and HostSpecific =”True” used only with custom hosts. If you set the value of parameter to true, you can access a property called Host in your text template. The property is a reference to the object that hosts the engine. At last, the output extension tells the extension in which the new file this will be generated.
T4 contains 4 types of blocks
-
Expression block
Used as <#= expression #>, we can write C# or VB.net code but don’t use semi-colon at the end of statement
-
Statement block
Used as <# code…. #>, define any C# or VB.net code and initialize variables, define loops etc. Here we have to specify semi-colon at the end of the code statement just like as we program in a class file.
-
Class feature block
Used as <#+ code… #>, define methods, classes, properties and constants and can we called from anywhere within the template file. For example, we can create a function that perform some calculation based on the parameters passed and return a Boolean through which we can handle the UI designing.
Below is the actual page content that dynamically generates the page based on the model attached to it.
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend><#= mvcHost.ViewDataType.Name #></legend>
<#
foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {
if (!property.IsPrimaryKey && !property.IsReadOnly && property.Scaffold) {
#>
<div class=”editor-label”>
<#
if (property.IsForeignKey) {
#>
@Html.LabelFor(model => model.<#= property.Name #>, “<#= property.AssociationName #>”)
<#
} else {
#>
@Html.LabelFor(model => model.<#= property.Name #>)
<#
}
#>
</div>
<div class=”editor-field”>
<#
if (property.IsForeignKey) {
#>
@Html.DropDownList(“<#= property.Name #>”, String.Empty)
<#
} else {
#>
@Html.EditorFor(model => model.<#= property.Name #>)
<#
}
#>
@Html.ValidationMessageFor(model => model.<#= property.Name #>)
</div>
<#
}
}
#>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}
<div>
@Html.ActionLink(“Back to List of Main Page”, “Index”)
</div>
In the above mentioned code there is if statement that checks whether the property is a foreign key or not and based on that it generates a drop down code otherwise an input control.
Let’s create a sample application in ASP.Net MVC 3 and check it out by customizing a Create T4 template.
- Create a sample project in ASP.Net MVC3 in Visual Studio.
-
Create a model class for Person and Designation. Person record contains some basic information and Designation holds the list of designations. Below is the Code First model Approach using Entity Framework ver. 4.3.1.
public
class
Person
{
public
long PersonId { set; get; }
public
String FirstName { set; get; }
public
String LastName { set; get; }
public
String EmailAddress { set; get; }
public
String Phone { set; get; }
public
long DesignationId { set; get; }
public
virtual
Designation Designation { set; get; }
}
public
class
Designation
{
public
long DesignationId { set; get; }
public
String DesignationName { set; get; }
public
virtual
ICollection<Person> Persons { get; set; }
}
-
Create a DBContext class and define DBSet for these entities.
public
class
DBContext : System.Data.Entity.DbContext, IDisposable
{
public
DbSet<Person> Persons { get; set; }
public
DbSet<Designation> Designations { set; get; }
}
-
Now create a Person controller selecting Controller with read/write actions and select Person as a Model class and DB Context as you Database Context class.

-
Now if you open the Create.cshtml file you will see a drop down list for designation. As in the template file there was a foreign key check. If you run the application form will be shown as below.

-
Now let’s change a drop down to list box in the Create.tt file.
<div class=”editor-field”>
<#
if (property.IsForeignKey) {
#>
@Html.ListBox(“<#= property.Name #>”)
<#
} else {
#>
Is not a foreign key baba: <#= property.IsForeignKey #> : @Html.EditorFor(model => model.<#= property.Name #>)
<#
}
#>
@Html.ValidationMessageFor(model => model.<#= property.Name #>)
</div>
- Delete the previous controller and generate it again. It will generate a ListBox as specified in a tt file.

This was the simple example showing how developers can modify existing templates based on their needs and reduce development time. Hope this helps!
Using Enterprise Library Validation Application Block in WCF
Validation plays an important role in any messaging communication between distributed systems and especially when you are designing a SOA where the service is consumed by many third party consumers.
In this post I will show how to leverage the Enterprise Library Validation Application Block to apply validation on WCF Service contracts that really makes the task very easy for the developers to apply validations.
Develop Service
I will create a simple project that shows how one can apply validation on Service contracts in WCF.
- First of all create a Simple WCF Service Application Project in Visual Studio
-
Add a reference to Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF assembly.

- Open the Service Interface (by default it generated IService) and apply the class level attribute “ValidationBehavior” on service’s interface. ValidationBehavior is Validation Application Block Service Behavior and is responsible to validate requests. Now you need to apply the FaultContract and specify the type of data that holds the information about the error.
FaultContract is used to communicate error from service to client.
[ServiceContract]
[ValidationBehavior]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(ValidationFault))]
string Execute(Name value);
}
In the above code you can see there is a Name class object passed as a parameter in Execute function.
4. Now implement the Service Contract interface in HelloWorldService class.
public class HelloWorldService :IService1{
public string Execute(Name name){
return string.Format(“your name is {0} {1}”, name.FirstName, name.LastName);
}
}
5. This Name class is the Service’s DataContract. Below is the code snippet for Name class
[DataContract]
public class Name {
[StringLength(25, MinimumLength=1, ErrorMessage="First Name length is not correct")]
[DataMember]
public String FirstName{ set; get; }
[StringLength(25, MinimumLength = 1, ErrorMessage = "Last Name length is not correct")]
[DataMember]
public string LastName { set; get; }
}
In the above code, I have specified two properties of String type and applied Data Annotations attribute for String length validation. You can apply as many validations as you want.
Consume Service
6. Create a sample console project in Visual Studio to test.
7. Add a service reference by clicking on the Service References in Visual Studio.
8. Initialize service instance
9. Call Execute function and pass invalid string values.
static void Main(string[] args) {
var name = new Name { FirstName = “”, LastName = “” };
var client = new ConsoleApplication1.Services.Service1.Service1Client();
try{ Console.WriteLine(client.SayHello(name)); }
catch (FaultException<ValidationFault> fault)
{
foreach (var detail in fault.Detail.Details){
Console.WriteLine(“{0}:{1}”, detail.Key, detail.Message); }
}
client.Close();
Console.ReadLine();
}
10. In the above code I have passed Name object with empty string values to test whether the service is validating or not and here is the result.

Develop and Consume OData Web Services in WCF
What is OData?
OData is an Open Data Protocol used to access data from various sources like Relational databases, file systems, etc. and exposes it to the consumers that can query or update data. OData is based upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from variety of data sources. Consumers can query the data using HTTP protocol and get the results in AtomPub and JSON formats. These are the formats through which the service can deliver the requested resources or collection of entities.
OData is released under the Open Specification Promise http://www.microsoft.com/openspecifications/en/us/programs/osp/default.aspx and anyone can freely interoperate with OData implementations.
Developing WCF Service using OData Protocol
Microsoft has first introduced OData support in Visual Studio 2008 SP1 in terms of ADO.Net Data Services (subsequently known as WCF Data Services). Developers can create services on the fly and exposes data using Entity Framework or LINQ 2 SQL ORM tools.
Let’s create a simple WCF Data Service and expose data using Entity Framework.
- Start Visual Studio 2010 and create a new WCF Service Application project.

-
Right click the WCF Service Application project and click on the “Add New Item”, then select WCF Data Service.

-
If you open the WCF Data Service class file you can see the Class will be derived from the generic DataService class. This is the main entry point for developing WCF Data services. We have to specify the data source class name. In order to proceed further I will add entity framework model which creates the entities model on the fly.
-
Right click on the Service Project and Add “ADO.Net Entity Data Model” from the dialog.

When you add ADO.Net Entity Model it will ask you to select the data source, go through the wizard by selecting the data source and finish a dialog.
-
Now open the .edmx file click on properties.

Here’s the entity container named as “DDMSEntities”. Just specify the name DDMSEntities in your WCF Data Service base class like below
public class WcfDataService1 : DataService<DDMSEntities>
-
You can now add the SetEntitySetAccessRule for each entity you want to expose. Default configuration is to deny access to resources. When a service is initialized the access rights must be enabled.
Sample code snippet below
public static void InitializeService(DataServiceConfiguration config){
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
config.SetEntitySetAccessRule (“Levels”, EntitySetRights.AllRead);
config.SetEntitySetAccessRule (“NodeTypes”, EntitySetRights.All);
}
In Above code, I have added two tables i.e. Levels and NodeTypes and given permissions as AllRead. There are many permission levels you can set as follows. Below are the enums of EntitySetRights with their description
- All – Authorize to create, read, update and delete data.
- AllRead- Authorize to read data.
- AllWrite- Authorize to write data.
- None- Denies all rights to access data.
- ReadMultiple – Authorize to read sets of data.
- ReadSingle – Authorize to read single data of items.
- WriteAppend- Authorize to create new data items in the data sets.
- WriteDelete –Authorize to delete data items from the data sets.
- WriteMerge – Authorize to merge data.
-
WriteReplace – Authorize to replace data.
-
Now let’s build a service and test it. Once you hit the web service in a browser, you will see the page as below

The above feed representing the data as per Atom Syndication format. There are two entity collections namely “Levels” and “NodeTypes”.
-
You can query levels by navigating to
- Also, apply filter using filter property as follows
http://localhost:32555/WcfDataService1.svc/Levels?filter= LevelTree gt
”gt” is used for greater than where as “lt” is used for less than.
Consuming WCF Data Service in Web Application
-
Create a new Web Application project in Visual Studio
-
Add a service reference by right clicking on Add Service Reference and select the newly service created.

-
Add a button to call the service on its click event.
-
On the click event you can consume the service like below
Services.DMSEntities.DDMSEntities entities = new Services.DMSEntities.DDMSEntities(new
Uri(“http://localhost:32555/WcfDataService1.svc”));
var lst = entities.Levels.FirstOrDefault();
This will return the first item in the collection. You can execute all CRUD operations depending on the rule set in the Service for that entity.
Hope this helps, happy coding!
Problem loading ASP.Net project after installing VS 2010 SP1
Sometimes developer faces this problem on loading existing web projects that were hosted on local IIS server and using the same port number that has been used by the IIS Express for particular websites. IIS Express installed by default when you apply the SP1 for Visual Studio 2010.
In my case, I installed VS 2010 SP1 to install Silverlight 5 Tools for VS 2010 and when opened my existing web project which was earlier hosted on my Local IIS server using the same port no i.e. 8080, came across this error.

In order to rectify, the simplest way is to change the port no in the applicationhost.config file placed under [Win_Drive]:\Users\[User]\Documents\IISExpress\config folder. When open the applicationhost.config file you will find the <bindings> tag under <site> tag followed with the port no.
Change the port no and don’t forget to save the file. Now try reloading the project and it opens without any issue.
