C# and .NET step by step with interview questions
Showing posts with label application blocks. Show all posts
Showing posts with label application blocks. Show all posts
Tuesday, May 17, 2011
Monday, May 16, 2011
Saturday, September 12, 2009
DI using Unity Application Blocks
Introduction
In the previous article we discussed about the fundamentals of IOC and DI design patterns.In the same article we also discussed about how Windsor can be used to solve this problem. In this article we will take up a simple example and try to implement DI using unity application blocks thus resulting in loosely coupled architecture.
Please feel free to download my free 500 question and answer videos which covers Design Pattern, UML, Function Points, Enterprise Application Blocks,
OOP'S, SDLC, .NET, ASP.NET, SQL Server, WCF, WPF, WWF, SharePoint, LINQ, SilverLight, .NET Best Practices @ these videos http://www.questpond.com/
DI using Unity Application Blocks
- The problem
- Creational patterns
- Dependency Injection
- Solving problem using UNITY block
- Download and installing Unity
- Defining the common interface
- Providing the injection gateway
- Defining the config file
- The client code
- The actual internal working
- Enter the real world of loosely coupling
The problem
Any good architecture always stands on the base that components are loosely coupled… let me stress the point truly loosely coupled. Let’s try to understand this with a scenario and how we normally approach this problem using pure object oriented way.Consider a scenario where we have a customer class which needs to perform insert operation on database. The customer class should be customizable to save in either Sql server or oracle database. In future we should also be able to add new databases with out disturbing the customer class.
Below is what we will do. Define two classes one for SQL server and other for Oracle. Both these classes inherit from some kind of same interface ‘Idatabase’. The customer class points to this interface. So the customer class is theoretically shielded from the concrete implementation of SQL Server or oracle. But because the object creational activity needs to be done by the customer class it still needs to be aware of the concrete classes.

Figure: - General loosely coupled thinking
This is what will happen in actual implementation as shown in figure ‘Concrete classes’. The customer class will be creating objects of either oracle or SQL server depending on condition. That means the customer class is exposed to the concrete classes which defeats the purpose of interface. Any change in the database classes will lead to compiling of the customer class.
Figure :- Concrete classes
Creational patterns
The next thing comes in mind is creation patterns. If we can introduce a factory who takes the creational aspect of the concrete classes thus isolating the concrete classes from the customer class.
Here are the issues with factory which makes us force to think about some other solutions:-
• Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
• Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
• Factories are custom: - They are very much custom to a particular implementation.
• Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.
I will not be explaining factory pattern in case you are not aware of you can read the same in my previous article SoftArchInter1.aspx
Ok, I will show you a magic…Rather than writing those huge line of code for factory…lets go the DI way (Dependency injection).
Dependency Injection
Rather than writing factory pattern, how about injecting the object directly in to the customer class. So let the customer class references the interface and we should be able to inject the concrete type in to the customer class. With this the customer class does not need to use the new keyword and is complete decoupled from the concrete classes.

Figure: - Dependency injection
Injection can be done using containers. So basically you need to put both the classes in to the container and the container will create object and inject the same in to the other class.
Figure: - Containers
Solving problem using UNITY block
Now that we know the benefit of containers we will explore unity application block which helps us to achieve dependency injection.
Download and installing Unity
The first step is to download the unity application block from http://msdn.microsoft.com/en-us/library/cc468366.aspx and install the same. Depending on whether you have 2008 or 2005 the documentation will vary. For this tutorial I will be using VS 2005 because majority professionals are still using 2005.

Figure: - unity block installed
Once you install the block you should be able to see the same in Microsoft patterns and practices.The first thing you need to do is to get the references of at least two components Unity and Unity configuration.

Figure: - Add referenced to Unity components
Once you have got reference to the components import the “Microsoft.Practices.Unity” namespace in to your code as shown in figure ‘Import unity namespace’.
Figure: - Import unity namespace
Defining the common interface
As said previously we should be able to inject SQL Server database object or oracle database object in the customer class. So as a good practice we will inherit the SQL server implementation and oracle implementation from a common interface ‘Idatabase’.

Figure: - Database interfaces
Providing the injection gateway
In the customer class we will reference the interface and expose the public property using [Dependency] attribute. This exposure is essential for the unity container. Unity container needs some kind of gateway by which it can inject the object. So what we have done is we have exposed the interface ‘iDatabase’ publicly. There are lot of other ways by which we can achieve the same you can read my previous article on the different ways of providing injection gateways for containers
<<here>>.

Figure: - Providing injection gateway
Defining the config file
To achieve high customization unity application allows us to specify how the injection will work in the config files ( web.config and app.config ). As this example is a windows command application we will be defining an app.config file.
You can see below a simple template of App.config file from unity perspective. The Configsection is compulsory and keep it as it is. The important section to be noted is the types section which comes under container section. In this we specify which interfaces map to which concrete class. The unity container creates object from this section and inserts in to the customer object through the dependency attribute.

Figure: - App.config file
The client code
The client code is pretty simple. The first step us we create the unity container object. In the second step we read the unity section. In step 3 we configure the container using the unity section data.
In step 4 we tell the container to create the customer object. This is the most important step of all. In this the container using the config data and the dependency attribute injects either the SQL server database object or oracle database object in to the customer class. This object creation depends on what is defined in the app.config file.
Finally in step 5 we call the save method

Figure: - Client code
The actual internal working
So what happens internally in the container is that the unity container creates the object of either oracle or SQL server data objects and injects in to the customer class through the dependency defined attribute.
Enter the real world of loosely coupling
So if you define the ‘clsSqlServer’ class it will create the object of ‘clsSqlServer’ and inject it in to the customer class. If you define the ‘ClsOracle’ class it will inject the ‘clsOracle’ object. You can see in figure ‘The real fun’ how easy it to change implementation by just modifying the config file type sections
Figure: - The real fun
Friday, September 11, 2009
Five step of how to use logging utility in your projects using application blocks
Introduction
It is new world of software reusability. Gone are the days when we need to build things from scratch. One of the most needed functionality is the logging utility. Every software project needs a logging utility. To make your own logging utility is a big project by itself. In this tutorial we will quickly run through how you can use Microsoft logging application blocks to log messages and activities.Please feel free to download my free 500 question and answer videos which covers Design Pattern, UML, Function Points, Enterprise Application Blocks, OOP'S, SDLC, .NET, ASP.NET, SQL Server, WCF, WPF, WWF, SharePoint, LINQ,SilverLight, .NET Best Practices @ these videos http://www.questpond.com
You can log your errors or debug messages to the following sources using logging application blocks:-
• Event log
• Database
• Message queue
• Write to text file
• WMI events
• Custom locations using application block extension points
Five step of how to use logging utility in your projects using application blocks
Step 1Step 2
Step 3
Step 4
Step 5
Step 1
Create a new project with a simple button on the ASPX page. Let’s name this button as btnlogger. What we will do it when any one clicks on this button we will log a error message in the event log.
Figure :- Simple project
Step 2
Download the Enterprise library 4.0 from http://www.microsoft.com/downloads/details.aspx?FamilyId=90DE37E0-7B42-4044-99BE-F8ECFBBC5B65&displaylang=en . Once you install it you should see the same in programs – Microsoft patterns and practices.Click on open and browse to your web.config file and click the open button.
Figure :- Enterprise library installed

Figure :- Enterprise library installed
Figure :- Open the web.config file
Step 3
All your logging facility is stored on the web.config file. Now right click on the tree , click new and click logging application block menu.


Figure: - Add logging application block
Step 4
By default the logging utility logs to event logs. So you will see in the trace listeners a event log trace listeners already added. Click on the event log trace listeners and specify the machine name. Currently my machine name is HP

Figure:- Specify machine name
Step 5
Now that we have defined the necessary configuration using the logging enterprise tool. It’s time to call the same in the code. So we add the Enterprise logging application DLL , add the logging namespace , create object of ‘logentry’ object and finally log the message using the logger DLL.

Figure: - Use the logging application block
Now if you run the program and click the button you should see the message logged in event viewer. To view event viewer click on start , run and type eventvwr


Figure: - Logged in the event viewer
Exception handling using Enterprise application block in 6 Steps
Exception handling using Enterprise application block in 6 Steps
Exception handling is one of the most important tasks in any application. Many applications either do not handle applications or they handle it in an adhoc manner. In this section we will see how we can use the readymade exception handling block so that we do not need to code and build error handling routines from scratch.Please feel free to download my free 500 question and answer videos which covers Design Pattern, UML, Function Points, Enterprise Application Blocks, OOP'S, SDLC, .NET, ASP.NET, SQL Server, WCF, WPF, WWF, SharePoint, LINQ, SilverLight, .NET Best Practices @ these videos http://www.questpond.com/
Problem
A good error handling has the following features:- You would like to log errors in a source like event viewer, file etc for further debugging and inspection.
- You would also like to change these error logging sources on fly without compiling the project. So sometimes you like to see the error logged in event viewer and sometimes you would like to send an email for some critical errors to the administrators.
- You would also like to apply different error policies depending on where the error occurs. For instance if the error occurs on the UI you would like to throw the error on a label and if it happens on the data access layer you would like to log the error. For some errors you would like to replace it with some custom exception.
- Finally you would like to add, update and remove these error policies depending on situations on fly without compiling the code.
The Solution
The answer to the above problem is use the readymade block exception handling block.Step 1:- The first thing we need to do is add the logging application block. In case you have not read about logging application block please read about it atLogging.aspx. As we had mentioned previously one of the important aspects in error handling is that we should be able to log the errors in some source. This capability is provided by logging application blocks.

Step 2:- Now that we have defined where the errors should be logged it’s time to define exception policies. So right click and add exception handling application block and then right on the exception handling block to add exception policies as shown in below figure.
We will give a name to this policy as ‘Policy1’.
Step 3:- Now right click on policy 1 and define a new exception type as shown in below figure.
For the current scenario select the exception type as general .NET exception as shown in below figure. This type specifies that the policy will catch this type of exception.
Step 4 :- In case this exception occurs we would need to direct the exception block what should be done. For policy exception we would like to log the same in the logger. So click on the exception defined in policy 1 and say that this needs to be logged using the logging handler.
Specify the logging source for the logging handler as shown in below figure:

Select the formatter type as shown in below figure:
Step 5:- Let’s make this example more interesting to exploit the real essence of exception handling block. Let’s add one more policy called as policy 2. In policy 2 we will catch the arithmetic exception. This arithmetic exception will be replaced by general exception.
To define general exception right click on arithmetic exception and define the replace exception type as exception.

Below figure shows how we have define the replace exception type as general exception and a new exception message.
So we have defined two policy one policy i.e. policy1 will take the exception and log it in the event viewer and the other policy will take a arithmetic exception and replace it with a general exception and throw it to the caller.Step 6:- Now the final step calling the exception policy in the code. So first import the namespace i.e. exceptionhandling and logging in code.
Finally use the
exceptionpolicy static class to handle the exception. You can see in the below figure we have two button one which uses policy1 and the other policy2.
The output of policy1 will be logged in to event viewer as shown in below figure.
The output of policy2 will be replaced with a general error as shown in below figure.
The best part of exception handling block is you can change policy on fly without compiling the code. You can also change the error logging source from event viewer to file or email. I hope you have enjoyed this article and I am sure if you use this block properly you can have a very stable, efficient and flexible error handling framework. Client side validation using Validation Application blocks
Introduction
By using enterprise validation blocks you can create validation in a dynamic fashion and the validations can be invoked depending on the user logged in. Now let’s understand one of the biggest drawbacks of the validation blocks and let’s see how we can address the same.Please feel free to download my free 500 question and answer videos which covers Design Pattern, UML, Function Points, Enterprise Application Blocks, OOP'S, SDLC, .NET, ASP.NET, SQL Server, WCF, WPF, WWF, SharePoint, LINQ,SilverLight, .NET Best Practices @ these videos http://www.questpond.com
Client side validation using Validation Application blocks
Problem
The biggest drawback with validation application blocks is it does not generate client code. In other way to put is that all validations happen on the server side. From my perspective I think the application block developers have done it right. I mean they have defined a generic server side framework and left the implementation of the client validation to the respective clients like Windows, ASP.NET, etc.Broader Level Solution
So how do we solve the problem? First thing you can Google how much ever you want you will not find an easy way out for this. You need to develop your own adapter. That means you need to develop an adapter which will read the rules from the validation blocks API and create ASP.NET client side validator like required field, not null, etc.If you find a better solution do email me at shiv_koirala@yahoo.com.
The Actual Code
Ok, now we know the problem let’s see how we can solve the same. If you have run through the video given on the top you will understand that all validations are stored in web.config file. So somehow we need to browse through the web.config file to get those validations. Once we get the validation we can then create ASP.NET validators depending on the validations present in web.config file.If you see your web.config which has validators defined using validation application block it would look something as shown below. All validations are enclosed the validation tag. It’s a four step process to browse to get the validation.
- Step 1:- Using the configuration source get the validation settings.
- Step 2:- Using the validation settings get all the ruleset from the validation tag.
- Step 3:- From the rule set get the rule set data collection.
- Step 4:- Browse through the rule set data and generate the corresponding ASP.NET validators.

In the final step we browse through the validator collection and generate the ASP.NET validators. You can use the type name to see which validator type it is. Using the ‘
There are ranges of different validators provided in validation application blocks. Depending on the type you can create the corresponding type of ASP.NET validators at the client side. You can also generate Windows validators accordingly.
RangeValidatorData’ you can get the details of the validator data and you can generate the ASP.NET validators accordingly.
There are ranges of different validators provided in validation application blocks. Depending on the type you can create the corresponding type of ASP.NET validators at the client side. You can also generate Windows validators accordingly.
Subscribe to:
Posts (Atom)
