Showing posts with label PrOgramming. Show all posts
Showing posts with label PrOgramming. Show all posts

Monday, February 15, 2010

Building Web Based N-Tier Applications using C#

Building Web Based N-Tier Applications using C#

This article explores the N-tier and Distributed Application Architecture. Over the last decade, the way applications are designed has evolved and come a long way. We have stand-alone applications, server based applications, client server applications, web based applications, n-tier applications, distributed applications, Peer-to-peer apps, service-oriented Architectures, component based Development and the list goes on. This article discusses the advantages, disadvantages of n-tier applications and methods to implement web based n-tier Applications using C#, .NET


Why N-Tier Applications?
N-Tier Applications can easily implement the concepts of Distributed Application Design and Architecture. The N-Tier Applications provide strategic benefits to Enterprise Solutions.
While 2-tier, client-server can help us create quick and easy solutions and may be used for Rapid Prototyping, they can easily become a maintenance and security night mare.

The N-tier Applications provide specific advantages that are vital to the business continuity of the enterprise. Typical features of a real life n-tier may include the following:


1) Security: Application has Appropriate Authentication, logging and monitoring mechanisms


2) Availability and Scalability: Application should be reliable and should have sufficient fail-over mechanisms ( redundancy) such as fail-over clusters


3) Manageability: Application should be designed to have the capability to Deploy, Monitor and troubleshoot. Methodology to handle Errors, log Errors and provide useful information for problem resolution


4) Easy Maintenance: This is generally achieved by adopting coding standards, deployment standards, modular application design, ‘data abstraction’ and application frameworks.


5) Data Abstraction: Easily make changes to the functionality, business rules with the least amount of impact to the entire applications


The above mentioned points are some of the Key design goals of a successful n-tier application that intends to provide a good Business Solution.


What does it take to build the n-tier Application?
The single most important factor that decides the success of the n-tier application is a through business or domain knowledge.


The second most important access is the technical and design know how. N-tier applications require us to put in a sufficient amount of thought to successfully distribute the overall functionality of the application in the appropriate ‘tiers’.



When n-tier Applications should not be used?
Building and implementing a successful n-tier application requires a lot of Effort, Skill, experience, commitment and Organizational Maturity.

It also implies cost.

Hence a favorable Cost-Benefit Ratio is necessary before you decide to go ahead with the n-tier Application.



What is a n-tier Application?
Simply stated, an n-tier application helps us distribute the overall functionality into various tiers or layers.



For example in a typical implementation you can have one or more of the following layers
1) Presentation Layer
2) Business Rules Layer
3) Data Access Layer
4) Database/Data store



In certain scenarios some of the layers mentioned above may be split further into one or more sub layers.



Each Layer can be developed independently of the other provided that it adheres to the standards and communicates with the other layers as per the specifications.



This is one of the biggest advantages of the n-tier application.
Each layer can potentially treat the other layers as ‘black-box’



In other words, each layer does not care how the other layer processes the data as long as it sends the right data in a correct format.



Building them with C#, .NET:
C#.NET provides us an excellent, robust feature rich platform.
C# being Object Oriented Programming Language it helps in practically laying down the standards. For instance you could create a base class with standard functions and require that all new classes should be derived from this base class. Please see the article on “Inheritance” in this series.

.NET provides type safety, automatic Garbage Collection which is very important in implementing good n-tier apps.



The Logical Building Blocks




The above diagram describes the logical building blocks of the Application.



1) The Presentation Layer: Also called as the client layer comprises of components that are dedicated to presenting the data to the user. For example: Windows/Web Forms and buttons, edit boxes, Text boxes, labels, grids, etc.



2) The Business Rules Layer: This layer encapsulates the Business rules or the business logic of the encapsulations. To have a separate layer for business logic is of a great advantage. This is because any changes in Business Rules can be easily handled in this layer. As long as the interface between the layers remains the same, any changes to the functionality/processing logic in this layer can be made without impacting the others. A lot of client-server apps failed to implement successfully as changing the business logic was a painful process.



3) The Data Access Layer: This layer comprises of components that help in accessing the Database. If used in the right way, this layer provides a level of abstraction for the database structures. Simply put changes made to the database, tables, etc do not effect the rest of the application because of the Data Access layer. The different application layers send the data requests to this layer and receive the response from this layer.



The database is not accessed directly from any other layer/component. Hence the table names, field names are not hard coded anywhere else. This layer may also access any other services that may provide it with data, for instance Active Directory, Services etc. Having this layer also provides an additional layer of security for the database. As the other layers do not need to know the database credentials, connect strings and so on.



4) The Database Layer: This layer comprises of the Database Components such as DB Files, Tables, Views, etc. The Actual database could be created using SQL Server, Oracle, Flat files, etc.
In an n-tier application, the entire application can be implemented in such a way that it is independent of the actual Database. For instance, you could change the Database Location with minimal changes to Data Access Layer. The rest of the Application should remain unaffected.



Many packaged n-tier Applications are created so that they can work the same with SQL Server, Oracle, UDB and so on. In the above pages we have seen the background and the logical design of the n-tier application. Large enterprise apps are typically designed as n-tier applications and large portion of them are web based applications. Therefore they can be viewed in a secure manner, from any PC with a browser. This is a good combination of ease of use and security.



How do the Layers communicate with each other?
Each Layer comprises of one or more components. Each component being a part of the app may communicate with one or more component. The component may “speak” to the other components using one of the many protocols, HTTP, FTP, TCP/IP and mechanisms such as XML/RPC, SOAP, REMOTING etc. The data as such may be “passed” across in many formats such as binary, string , XML. For the purpose of this article we will use XML format for passing data between the components.



Communication Techniques in n-tier ‘.NET’ Apps :
The different layers of the n-tier applications can be located on physically different machines.
Various techniques can be used to communicate between the various layers and components. The most common include



XML Web Services
.NET Remoting




A Web Based N-Tier Application




In the diagram above we observe that the Presentation Layer is made of Web Pages, Web Components and Web Server such as IIS. The end user sees the web pages on a Browser such as IE.



To create a web based n-tier Application using C#, .NET the following steps need to be followed:



1) Define what the Application should do. In other words the functionality of the application.



2) Segregate the application logic. The logic related to the User Interface or presentation layer will be part of the presentation layer, The logic related to the Business Rules goes to the Business Layer and so on.



3) Design the Database Structures, such as Tables, Views and so on. The Database design is a very crucial step and it effects the overall application performance, reliability and usability



4) After this you can design the Data Access Layer. This Layer comprises of code to access the database. The Data Access Layer components may typically be called by the Business Layer Components. The Design also defines how this call should be made. This includes the interface definition, Inputs, Outputs, Data Structure Definition and so on.



5) Similarly Business Application Layer design will define the Components that are part of this layer. Specifications for each component should include the Interface Definition, Inputs, outputs and Data structures (example XML DTD).



6) The Presentation Layer is designed keeping in mind the ease of Use. The User Interface should be intuitive and pleasant. The Presentation Layer may comprise of Web Pages such as .aspx,HTML, and compiled components.


Each of the layers can typically be located on physically separate machines for various reasons such as reliability, security and scalability.



To understand the actual coding aspects for building an n-tier application or a distributed application architecture refer to our articles on Creating Components in C#.



Summary:
In the above article we discussed the evolution of various architectures and specifically n-tier applications and distributed application Architecure.

Thursday, June 18, 2009

24 JavaScript Best Practices for Beginners

Click here to find out the 24 Best Javascript Coding Practices for Beginners.. Enjoy..

Friday, May 8, 2009

Saturday, April 25, 2009

Aspect Oriented Programming using .NET

What is AOP

Aspect Oriented Programming or AOP is an interesting concept that can be applied to many of the programming problems we solve everyday. In our Visual Studio team system code we have a lot of web-services and remoting code that essentially does the following

public void MyMethod(int parameter)

{

Trace.EnteredMethod("MyMethod", parameter);

SecurityCheck();

// Bunch of processing

Trace.ExitMethod("MyMethod");

}

This is not just peculiar to our domain but is seen across different domains. In OO programming classes and methods are designed for performing specific operations and common/duplicate functionality are factored out into common classes. However, there are cross-cutting concerns that span accross all classes and methods, like logging and security checks. OOP only partially solves this problem by requiring users to define separate classes for logging and security checks and requiring each class/methods needing these services to call them. AOP targets and solves this problem elegantly.

AOP divides code into base-code (code for your functionality) and a new construct called aspect. Aspect encapsulates these cross-cutting concerns using the following concepts

  • join-points: The points in the structure of base-code where the cross-cutting functionality needs to execute. This is typically when specific methods are entered or exited or properties are accessed.
  • point-cut: A logical description of join-points using some specific syntax
  • advice: additional code like logging and security check that each of these methods need to perform

The most mature AOP language is probably AspectJ which adds AOP extensions to Java. However, for this blog, I'd stick to .NET languages like AspectDNGAspect# and C#.

Language support for AOP

AOP support has to be built in to the language and/or framework because it is based on method call interception. Whenever a methods is called the framework needs to provide a stub to call some other piece of code. Though .NET CLR has this capability, but it is intrusive as you need an object to extend fromMarshalByRefObject  or ContextBoundObject to allow method-interception. This is a serious limitation because each class needs to be written so that it supports AOP. Many AOP languages or language-extensions get around this limitation by using various techniques. The techniques generally fall into two broad categories runtime or dynamic weaving, compile-time or static weaving.

Aspect# is AOP language which uses static compile time weaving. It uses its own proxy (and not CLR's proxy) called DynamicProxy. DynamicProxy is generated compile time and works differently while proxying interfaces (generates dynamic class and delegates method calls to the target of invocation) and proxying classes (generates stub class that inherits from the target).

Aspect# provides syntax to define point-cut and call method-interceptors or advice for them. It's done as follows 

import YourCompany.CMS.ContentProviders in YourCompanyAssembly
import YourCompany.CMS.Aop.Interceptors
aspect SecurityAspect for RSSContentProvider
     include Mixins.SecurityResourceImpl in MyMixinsAssembly

pointcut method(* MyMethod(*))
           advice(TracingInterceptor)
     end



end
public class
TracingInterceptor : IMethodInterceptor { public object Invoke(IMethodInvocation invocation) { // Trace using information from IMethodInvocation
// like Method, MethodInvocationTarget
return invocation.Proceed(); } }

The important bits are marked in bold. The first block is the point-cut in a Ruby like syntax which specifies all methods with the name MyMethod to be included in the join-points.  The second block is the interceptor (advice) TracingInterceptor. The TracingInterceptor is a class that has to implement theIMethodInterceptor. It can call invocation.Proceed to continue with the method invocation once it's done with the tracing. So whenever the MyMethod is called TracingInterceptor.Invoke gets called.

Other languages like AspectDNG (.NET based AOP language-extension) accomplishes this using something called IL weaving. In this the target or base-code is coded in any language that can be compiled into MSIL like C#, VB.NET, J#. So the target code can look like

using System;

 

public class MyClass {

public int ProcessString(String s, out string outStr) {

// ...  

}

}

There is no special code or any type of modification needed on the base-code as evident from above which is plain-vanilla C# code. The aspect code is written as follows which can also be C# code and needs some additional assembly reference and attribute decoration for AspectDNG to pick them up

using DotNetGuru.AspectDNG.MetaAspects;

using DotNetGuru.AspectDNG.Joinpoints;

using System;

public class AspectsSample{

[AroundCall("* MyClass::ProcessString(*)")]

public static object YourMethodCallInterceptor(JoinPoint jp) {

Console.WriteLine("Code before calls to '.. MyClass.ProcessString(..)'");

object result = jp.Proceed();

Console.WriteLine("Code after calls to '.. MyClass.ProcessString(..)'");

return result;

}
}

Here point-cut is specified using attributes like AroundCallAroundBody. Both the base-code and the aspect code are separately compiled into different assemblies using respective compilers like csc into Target.exe and aspect.dll. Then the aspectdng.exe tool can be used which uses reflection to reach to the attribute in the aspect code to weave call to them so that a new assembly called Target-weaved.exe is created. In target-weaved.exe AspectDNG directly puts in calls to the aspects around the target code by inserting/replacing IL code wherever required.

There are some AOP languages like Encase which apply the aspects at run time. These languages use AOP frameworks which reads in configuration files for point-cuts and at runtime generate proxy classes that intercept calls, allows advice of the aspect to execute first and then invokes the actual target. The benefit is that there is not edit-compile cycle but it faces performance issues.

AOP in C#

Till now we were talking about non-mainstream languages to get AOP done. However, by doing a bit extra work we can get the same functionality in C# as well. The limitation with CLR is that it allows method interception only when the classes containing the methods inherit from MarshalByRefObject  orContextBoundObject. When a class inheriting from ContextBoundObject is activated, the .NET interceptor comes into play. It creates a trasparent-proxy and a real-proxy. The transparent-proxy gets called for all invocation of the target. The transparent proxy serializes the call stack and passes that on to the real-proxy. The real-proxy calls the first message sink which is an object implementing theIMessageSink interface. Its the duty of this first message sink to call the next until the final sink goes and calls the actual target. In this sink chaining we can insert objects which can execute our aspect advice.

Another limitation with C# is that there is no way in C# syntax to specify join-points. We will circumvent these two limitations by inheriting the target classes from ContextBoundObject. We'll use attributes on specific classes so that all methods and field-setters in them become included into the join-points.

using System;

// Include the aspect framework

using Abhinaba.Aspect.Security;


[
Security()]

public class MyClass : ContextBoundObject {

public int ProcessString(String s, out string outStr) {

Console.WriteLine("Inside ProcessString");

outStr = s.ToUpper();

return outStr.Length;

}
}

Here Security is an attribute defined in our Abhinaba,Aspect.Security namespace which pulls in our support for AOP and includes the current class and all its methods in the join-points. The whole AOP framework looks as follows. All the important parts are marked in bold.

using System;

using System.Diagnostics;

using System.Runtime.Remoting.Messaging;

using System.Runtime.Remoting.Contexts;

using System.Runtime.Remoting.Activation;

namespace Abhinaba.Aspect.Security

{

internal class SecurityAspect : IMessageSink {

internal SecurityAspect(IMessageSink next)

{

m_next = next;

}

 

private IMessageSink m_next;

#region IMessageSink implementation

public IMessageSink NextSink

{

get{return m_next;}
}

public IMessage SyncProcessMessage(IMessage msg)

{

Preprocess(msg);

IMessage returnMethod =
m_next.SyncProcessMessage(msg);

return returnMethod;

}

public IMessageCtrl AsyncProcessMessage(IMessage msg,
IMessageSink replySink)

{

throw new InvalidOperationException();

}

#endregion //IMessageSink implementation


#region
Helper methods

private void Preprocess(IMessage msg)

{

// We only want to process method calls

if (!(msg is IMethodMessage)) return;

IMethodMessage call = msg as IMethodMessage;

Type type = Type.GetType(call.TypeName);

string callStr = type.Name + "." + call.MethodName;

Console.WriteLine("Security validating : {0} for {1}",
callStr,
Environment.UserName);

}

#endregion Helpers

}

public class SecurityProperty : IContextProperty,
IContributeObjectSink

{

#region IContributeObjectSink implementation

public IMessageSink GetObjectSink(MarshalByRefObject o,
IMessageSink next)

{

return new SecurityAspect(next);

}

#endregion // IContributeObjectSink implementation

#region IContextProperty implementation

// Implement Name, Freeze, IsNewContextOK

#endregion //IContextProperty implementation

}

[AttributeUsage(AttributeTargets.Class)]

public class SecurityAttribute : ContextAttribute

{

public SecurityAttribute() : base("Security") { }

public override void GetPropertiesForNewContext(
IConstructionCallMessage ccm)

{

ccm.ContextProperties.Add(new SecurityProperty());

}

}
}

 

SecurityAttribute derives from ContextAttribute and MyClass derives from ContextBoundObject, due to this even before the ctor of the class is called the framework instantiates SecurityAttribute and calls the GetPropertiesForNewContext passing it a reference to IConstructionCallMessage.SecurityAttribute creates an instance of SecurityProperty and adds it to the context. This addition makes the framework call the various IContextProperty methods that SecurityProperty implements and then calls the ctor of MyClass.

After this the first time any MyClass method or variable is referenced it calls GetObjectSink method ofSecurityProperty through its IContributeObjectSink interface. This method returns a newly created instance of SecurityAspect. Till this you can consider everything as initialization code andSecurityAspect implements our main functionality for AOP advice.

When the instance of SecurityAspect is created its constructor is passed a reference to next message sink so that all the sinks can be chained and called one after the other. After this SyncProcessMessage is called which is our main method interceptor and where all processing is done. After doing all processing like security verification the code calls the target method. Then it can refer to the return value and do post-processing. With this we have AOP implementation albeit some intrusive code as the target codes needs to be modified for AOP support.

Possibilities

AOP is a very generic programming method and can be used in a variety of situation. Some of them are as follows

Sample code

The sample solution (VS2005) including all sources are available here. It contains sources for two different aspects, one for security and one for tracing both applied on the same class. I have applied conditional compilation attribute to the tracing aspect so that on release build tracing gets disabled.

True object oriented language

Today I was spreading the goodness of Ruby and why I love it so much (and you can expect multiple posts on it). SmallTalk programmers can sneer at me, but hey I wasn't even born when SmallTalk came into being and hence I can be pardoned for pretending that Ruby invented this :)

Languages like Ruby are "truly" object oriented. So even a number like 2 is an instance of the FixNum class. So the following is valid Ruby code which returns the absolute value of the number.

-12345.abs

Taking this to an extreme is the iteration syntax. In C# to write something in a loop "n" time I'd be needed to get into for/foreach syntax, however in Ruby I can do the following

5.times { puts "Hello"} 

Which prints Hello 5 times.

However, I actually lied about having to use for/foreach statement in C#. With the new extension-method/lambda goodness we can very well achieve something close in C#.

For that first we create the following extension method

public static class Extensions

{

    public static void times(this int n, Action a)

    {

        for (int i = 0; i <>

        {

            a();

        }

    }

}

Then we can call "times" on an int as easily (well almost as I still need some lambda ugliness).

5.times(() => Console.WriteLine("Hello"));

// Or 

6.times(delegate { Console.WriteLine("Hello"); });