Wednesday, August 29, 2012

How Helicopters Work


The Blade Are Spinning and the Engine Is Running

Sikorsky and a few of his contemporaries brought a technical rigor to the field that finally made vertical flight safe, practical and reliable. As the flight-crazy Russian continued to refine his helicopter designs, he worked out the fundamental requirements that any such machine needed to have to be successful, including:
  • a suitable engine with a high power-to-weight ratio
  • a mechanism to counteract rotor torque action
  • proper controls so the aircraft could be steered confidently and without catastrophic failures
  • a lightweight structural frame
  • a means to reduce vibrations
Many of the basic parts seen on a modern helicopter grew out of the need to address one or more of these basic requirements. Let's look at these components in greater detail:


Main rotor blade -- The main rotor blade performs the same function as an airplane's wings, providing lift as the blades rotate -- lift being one of the critical aerodynamic forces that keeps aircraft aloft. A pilot can affect lift by changing the rotor's revolutions per minute (rpm) or its angle of attack, which refers to the angle of the rotary wing in relation to the oncoming wind.
Stabilizer -- The stabilizer bar sits above and across the main rotor blade. Its weight and rotation dampen unwanted vibrations in the main rotor, helping to stabilize the craft in all flight conditions. Arthur Young, the gent who designed the Bell 47 helicopter, is credited with inventing the stabilizer bar.
Rotor mast -- Also known as the rotor shaft, the mast connects the transmission to the rotor assembly. The mast rotates the upper swash plate and the blades.
Transmission -- Just as it does in a motor vehicle, a helicopter's transmission transmits power from the engine to the main and tail rotors. The transmission's main gearbox steps down the speed of the main rotor so it doesn't rotate as rapidly as the engine shaft. A second gearbox does the same for the tail rotor, although the tail rotor, being much smaller, can rotate faster than the main rotor.
Engine -- The engine generates power for the aircraft. Early helicopters relied on reciprocating gasoline engines, but modern helicopters use gas turbine engines like those found in commercial airliners.

 Working the Controls




Fuselage -- The main body of the helicopter is known as the fuselage. In many models, a frameless plastic canopy surrounds the pilot and connects in the rear to a flush-riveted aluminum frame. Aluminum wasn't widely used in aeronautical applications until the early 1920s, but its appearance helped engineers make their helicopters lighter and, as a result, easier to fly.

Cyclic-pitch lever -- A helicopter pilot controls the pitch, or angle, of the rotor blades with two inputs: the cyclic- and collective-pitch levers, often just shortened to the cyclic and the collective. The cyclic, or "stick," comes out of the floor of the cockpit and sits between the pilot's legs, enabling a person to tilt the craft to either side or forward and backward.

Collective-pitch lever -- The collective-pitch lever is responsible for up-and-down movements. For example, during takeoff, the pilot uses the collective-pitch lever to increase the pitch of all the rotor blades by the same amount.

Foot pedals -- A pair of foot pedals controls the tail rotor. Working the pedals affects which way the helicopter points, so pushing the right pedal deflects the tail of the helicopter to the left and the nose to the right; the left pedal turns the nose to the right.

Tail boom -- The tail boom extends out from the rear of the fuselage and holds the tail rotor assemblies. In some models, the tail boom is nothing more than an aluminum frame. In others, it's a hollow carbon-fiber or aluminum tube.

Anti-torque tail rotor -- Without a tail rotor, the main rotor of a helicopter simply spins the fuselage in the opposite direction. It's enough to make your stomach heave just thinking about all that endless circling. Thankfully, Igor Sikorsky had the idea to install a tail rotor to counter this torque reaction and provide directional control. In twin-rotor helicopters, the torque produced by the rotation of the front rotor is offset by the torque produced by a counterrotating rear rotor.

Landing skids -- Some helicopters have wheels, but most have skids, which are hollow tubes with no wheels or brakes. A few models have skids with two ground-handling wheels.
The main rotor, of course, is the most important part of a helicopter. It's also one of the most complex in terms of its construction and operation. In the next section, we'll peer at the rotor assembly of a typical helicopter.

The Heart of the Helicopter: The Rotor Assembly

 


A helicopter's main rotor is the most important part of the vehicle. It provides the lift that allows the helicopter to fly, as well as the control that allows the helicopter to move laterally, make turns and change altitude. To handle all of these tasks, the rotor must first be incredibly strong. It must also be able to adjust the angle of the rotor blades with each revolution they make. The pilot communicates these adjustments through a device known as the swash plate assembly.

The swash plate assembly consists of two parts -- the upper and lower swash plates. The upper swash plate connects to the mast, or rotor shaft, through special linkages. As the engine turns the rotor shaft, it also turns the upper swash plate and the rotor blade system. This system includes blade grips, which connect the blades to a hub. Each hub contains a rubbery bearing sandwiched between metal plates that allow its blade to flap up or down. Control rods from the upper swash plate have a connection point on the hubs, making it possible to transfer movements of the upper swash plate to the blades. And the hubs themselves mount to the mast via the Jesus nut, so named because its failure is said to bring a pilot face-to-face with Jesus.

The lower swash plate is fixed and doesn't rotate. Ball bearings lie between the upper and lower swash plates, allowing the upper plate to spin freely on top of the lower plate. Control rods attached to the lower swash plate connect to the cyclic- and collective-pitch levers. When the pilot operates either of those two levers, his or her inputs are transmitted, via the control rods, to the lower swash plate and then, ultimately, to the upper swash plate.

Using this rotor design, a pilot can manipulate the swash plate assembly and control the helicopter's motion. With the cyclic, the swash plate assembly can change the angle of the blades individually as they revolve. This allows the helicopter to move in any direction around a 360-degree circle, including forward, backward, left and right. The collective allows the swash plate assembly to change the angle of all blades simultaneously. Doing this increases or decreases the lift that the main rotor supplies to the vehicle, allowing the helicopter to gain or lose altitude.
Now it's time to see how all these parts work together to get the helicopter airborne

How Helicopters Fly




Imagine that we would like to create a machine that can simply fly straight upward. Let's not even worry about getting back down for the moment -- up is all that matters. If you are going to provide the upward force with a wing, then the wing has to be in motion in order to create lift. Wings create lift by deflecting air downward and benefiting from the equal and opposite reaction that results (see How Airplanes Work for details -- the article contains a complete explanation of how wings produce lift).

A rotary motion is the easiest way to keep a wing continuously moving. You can mount two or more wings on a central shaft and spin the shaft, much like the blades on a ceiling fan. The rotating wings of a helicopter are shaped just like the airfoils of an airplane wing, but generally the wings on a helicopter's rotor are narrow and thin because they must spin so quickly. The helicopter's rotating wing assembly is normally called the main rotor. If you give the main rotor wings a slight angle of attack on the shaft and spin the shaft, the wings start to develop lift.

In order to spin the shaft with enough force to lift a human being and the vehicle, you need an engine, typically a gas turbine engine these days. The engine's driveshaft can connect through a transmission to the main rotor shaft. This arrangement works really well until the moment the vehicle leaves the ground. At that moment, there is nothing to keep the engine (and therefore the body of the vehicle) from spinning just as the main rotor does. In the absence of anything to stop it, the body of the helicopter will spin in an opposite direction to the main rotor. To keep the body from spinning, you need to apply a force to it.
Enter the tail rotor. The tail rotor produces thrust like an airplane's propeller does. By producing thrust in a sideways direction, this critical part counteracts the engine's desire to spin the body. Normally, the tail rotor is driven by a long driveshaft that runs from the main rotor's transmission back through the tail boom to a small transmission at the tail rotor.

In order to actually control the machine and, say, guide it into a canyon to complete the ultimate rescue, both the main rotor and the tail rotor need to be adjustable. The next three sections explain how pilots guide the helicopter into taking off, hovering or buzzing off in a particular direction.

Flying a Helicopter: Taking Off
The ability of helicopters to move laterally in any direction or rotate 360 degrees makes them exciting to fly, but piloting one of these machines requires great skill and dexterity. To control a helicopter, the pilot grips the cyclic in one hand, the collective in the other. At the same time, his feet must operate the foot pedals that control the tail rotor, which allows the helicopter to rotate in either direction on its horizontal axis. It takes both hands and both feet to fly a helicopter
During takeoff, the pilot works the collective and the foot pedals simultaneously. Before we discuss how to take off, you should know that the collective typically looks like a handbrake whose grip functions as the throttle. Twisting the grip controls the power output of the engine, increasing or decreasing the speed of the main rotor. With that in mind, we're ready to begin a typical helicopter takeoff:
  1. First, the pilot opens the throttle completely to increase the speed of the rotor.
  2. Next, he or she pulls up slowly on the collective. The collective control raises the entire swash plate assembly as a unit. This has the effect of changing the pitch of all rotor blades by the same amount simultaneously.
  3. As the pilot increases collective pitch, he or she depresses the left foot pedal to counteract the torque produced by the main rotor.
  4. The pilot keeps pulling up slowly on the collective while depressing the left foot pedal.
  5. When the amount of lift being produced by the rotor exceeds the weight of the helicopter, the aircraft will get light on its skids and slowly leave the ground.

Flying a Helicopter: Directional Flight






In addition to moving up and down, helicopters can fly forward, backward and sideways. This kind of directional flight is achieved by tilting the swash plate assembly with the cyclic, which alters the pitch of each blade as it rotates. As a result, every blade produces maximum lift at a particular point. The rotor still generates lift, but it also creates thrust in the direction that the swash plate assembly is tilted. This causes the helicopter to lean -- and fly -- in a certain direction. The pilot can impart additional directional control by depressing or easing up on the foot pedals, which increases or decreases the counteracting thrust of the tail rotor.
Let's assume for a moment that the helicopter we discussed in the last section needs to fly forward. This is the pilot's procedure:
  1. First, he or she nudges the cyclic lever forward.
  2. That input is transmitted to the lower swash plate and then to the upper swash plate.
  3. The swash plates tilt forward at an amount equal to the input.
  4. The rotor blades are pitched lower in the front of the rotor assembly than behind it.
  5. This increases the angle of attack -- and creates lift -- at the back of the helicopter.
  6. The unbalanced lift causes the helicopter to tip forward and move in that direction.
When the aircraft reaches about 15 to 20 knots of forward airspeed, it begins to transition from hovering flight to full forward flight. At this point, known as effective translational lift, or ETL, the pilot eases up on the left foot pedal and moves closer to a neutral setting. He or she also feels a shudder in the rotor system as the helicopter begins to fly out of rotor wash (the turbulence created by a helicopter's rotor) and into clean air. In response, the rotor will try to lift up and slow the aircraft automatically. To compensate, the pilot will continue to push the cyclic forward to keep the helicopter flying in that direction with increasing airspeed.
A helicopter that is flying forward can stop in mid-air and begin hovering very quickly.


Flying a Helicopter: Hovering


The defining characteristic of a helicopter is its ability to hover at any point during a flight. To achieve hovering, a pilot must maintain the aircraft in nearly motionless flight over a reference point at a constant altitude and on a heading (the direction that the front of the helicopter is pointing). This may sound easy, but it requires tremendous experience and skill. 
Before we tackle the technique of hovering, let's take a moment to discuss nap-of-the-earth (NOE) flight, another unique characteristic of helicopters. NOE flight describes a helicopter located just above the ground or any obstacles on the ground. Military pilots perfected the technique during Vietnam as a means to become more elusive to ground-based weapons. In fact, film footage from the era often shows helicopters rapidly skimming the Earth's surface, machine-gunners firing from open rear doors or hovering with their skids just a few feet off the ground as troops disembark at a target location.
Of course, any helicopter taking off or landing must undertake NOE flight, if only for a few moments. It's a particularly critical time for a helicopter because a wild attitude adjustment could tip the craft too far and bring the rotor blades in contact with an obstacle. Attitude, for our purposes, refers to the helicopter's orientation in relation to the helicopter's direction of motion. You'll also hear flight-minded folks talk about attitude in reference to an axis, such as the horizon.
With that said, here's the basic technique to bring a helicopter into a hovering position:
  1. First, the pilot must cease any directional flying. For example, if flying the helicopter forward, the pilot must ease back on the cyclic until the helicopter's forward motion stops and the aircraft remains motionless over a point on the ground.
  2. Next, it's important that the pilot can detect small changes in the aircraft's altitude or attitude. He or she accomplishes this by locating a fixed point outside the cockpit and tracking how the helicopter moves relative to that point.
  3. Finally, the pilot adjusts the collective to maintain a fixed altitude and adjusts the foot pedals to maintain the direction that the helicopter is pointing.
To maintain a stabilized hover, the pilot must make small, smooth, coordinated corrections on all of the controls. In fact, one of the most common errors of novice pilots is to overcompensate while trying to hover. For example, if the helicopter begins to move rearward, the pilot must be careful not to apply too much forward pressure on the cyclic because the aircraft will not just come to a stop but will start drifting forward.
Over the years, innovations in helicopter design have made the machines safer, more reliable and easier to control. The next page presents a few of these innovations to provide a glimpse of how far helicopters have come and where they might go in the future.

Helicopter Innovations
The modern helicopter, like any complex machine, is an accumulation of innovations from numerous inventors and engineers. Some of these modifications improve performance significantly without changing the overall appearance of the aircraft. For example, Arthur Young's stabilizer bar looks small and insignificant when compared to the gross anatomy of a chopper, but it revolutionized vertical-lift flight. Other innovations are less subtle and seem to give the helicopter a complete makeover. Let's check out a few changes.
One significant advancement in the last decade has been the no-tail rotor, or NOTAR, helicopter. As you now know, vertical-lift flight is impossible without a tail rotor to counteract the torque produced by the main rotor. Unfortunately, the much-smaller tail rotor makes a lot of noise and is often easily damaged. The NOTAR helicopter solves both of these problems. Here's how it works: A large fan at the rear of the fuselage blows spent air from the main rotor down the tail boom. Slots along the side of the tail boom and at the end of the boom allow this air to escape. This creates a sideways force that counteracts the main rotor's torque. Varying the amount of air expelled from the rear slot provides additional directional control.
Some helicopters started receiving a second engine, which can operate the main rotor if the main engine fails. For example, the UH-60 Black Hawk helicopter, the workhorse of the U.S. Army, features this design improvement. Either engine can keep the aircraft aloft on its own, enabling the pilot to land safely in the event of an emergency.
Scientists have also fiddled with the main rotor assembly in an attempt to simplify one of the most complex parts of a helicopter. In the late 1990s, researchers developed a solid-state adaptive rotor system incorporating piezoelectric sheets. A piezoelectric material is one in which its molecules bend and twist in response to an electric field. In a rotor assembly, piezoelectric sheets -- not mechanical linkages -- twist sections of the blade root, thereby changing the pitch of the blades as they rotate. This eliminates parts in the rotor hub and decreases the chance of a mechanical failure.
Finally, it's worth mentioning those strange machines, known as tiltrotors, that bring together the best features of helicopters and airplanes. A tiltrotor aircraft takes off like a helicopter, with its two main rotors upright. But when it's airborne, the pilot can tip the rotors forward 90 degrees, enabling the machine to fly like conventional turboprop airplane. The V-22 Osprey, which completed a successful test flight in 1989, operates in this fashion.
None of these innovations has made helicopters less absurd-looking. Some, like the tiltrotor, only increase the aircraft's awkward visual appearance. All of which brings us back to Harry Reasoner's 1971 commentary about helicopters:
Mark Twain once noted that he lost belief in conventional pictures of angels of his boyhood when a scientist calculated for a 150-pound men to fly like a bird, he would have to have a breast bone 15 feet wide supporting wings in proportion. Well, that's sort of the way a helicopter looks.
Mr. Reasoner may be right, but a helicopter's peculiar design and configuration haven't diminished its impact. It's become one of the most versatile and widely used aircraft in the world today.

Helicopter Parts & Functions

A helicopter flies using the same basic principles of lift and thrust to overcome drag and gravity as an airplane. But the application of those principles is different and allow the helicopter to routinely maneuver in ways that most airplanes cannot. Features such as the rotor system, tail rotor and the transmission make the helicopter unique machines.

Turbine Engine

·         The turbine engine in a helicopter operates nearly identically to its counterpart in an airplane. The engine's compressor heats and compresses intake air, directing it into a burner where a mixture of the air and fuel is burned. The heat and energy from combustion is directed across two sets of turbines. The first drives the compressor and the second turns a main driveshaft. Unlike the engine in an airplane, most of the energy produced by a helicopter engine is directed through a power turbine shaft to a transmission rather along the axis of the engine as thrust.

Transmission

·         A typical helicopter transmission is mounted forward of the engine and directly below the main rotor. The transmission reduces the high-speed revolutions from the main drive shaft and drives the mast that turns the main rotor as well as a second drive shaft to the tail rotor.

Main Rotor

·         There are multiple designs for a helicopter's main rotor system. Some helicopters have two blades such as the Army's UH 1 (Huey). Other larger helicopters have as many as eight rotor blades. In flight, a fuel control governor maintains the rotor speed at constant revolutions per minute. When rotating at the proper RPM, the individual rotor blades act as a single disk. The pilot's inputs of pitch using the collective and the cyclic flight controls control the helicopter's altitude, direction and speed.

Tail Rotor and Pedals

·         The helicopter's tail rotor is driven from the transmission through a tail rotor driveshaft and is designed to counter the torque produced by the rotation of the main rotor blades. Torque causes the aircraft's fuselage to spin in the opposite direction to the main rotor. As the pitch is increased to the main rotor blades, the pilot counteracts the torque by increasing the pitch to the tail rotor blades with the pedals in the cockpit. By changing the tail rotor's pitch, the pilot can also turn the aircraft to the right and left.

Collective

·         The collective flight control is used for climbing and descending. Located to the left of the pilot's seat, it is placed at approximately a 35-degree angle to the floor. By pulling up on the collective, the pilot can uniformly increase pitch to all of the blades of the main rotor system. This increased pitch creates additional lift, and also increases the power demanded from the engine.

The Cyclic

·         The cyclic control system (sometimes called the stick) is used for direction and speed. It is attached to the floor in front of the pilot's seat and aft of the pedals. The cyclic increases pitch to the main rotors unevenly; thus causing the disc formed by the main rotors to tilt in one direction or another. The aircraft travels in the direction the pilot moves the cyclic. It is this control that allows the helicopter to fly backward, forward and sideways.

Tuesday, August 28, 2012

SOA


Architecture of SOA

 Figure ‘Architecture of SOA’ shows a complete view of a SOA. Please note this architecture diagram is not tied up with implementation of Microsoft, IBM etc. It’s a general architecture. Any vendor who implements SOA needs to fulfill the below SOA components. How they do it is completely their own technological implementation.

Figure: - Architecture of SOA

The main goal of SOA is to connect disparate systems. In order that these disparate system work they should messages to each other. ESB (Enterprise service bus) acts like a reliable post office which guarantees delivery of messages between systems in a loosely coupled manner. ESB is a special layer which delivers messages between applications. In the figure we have shown a huge plump pipe. It’s not hardware or some wire etc. It’s a group of components/software which helps you to send and receive messages between the disparate applications. Do not try to code your own ESB, you can think of buying one from Microsoft, IBM, Oracle, progress etc.

SOA registry is like a reference database of services. It describes what each services do, where are they located and how can they communicate. It’s a central reference of meta-data for services.

SOA workflow allows us to define work flow using the services in SOA registry. We will read more about BPM in the further questions.

Service broker reads the work flow and takes services from the SOA registry and ties them together. Service brokers are normally middleware like EAI (Enterprise application Integration) products. You can get a list of decent EAI from Sun, Microsoft, and IBM etc.

Process manager is nothing but the collection of SOA registry, SOA workflow and service broker.

SOA supervisor is traffic cop ensuring that services do not have issues. It deals mainly with performance issues of the system so that appropriate service levels are met. If any of the services have performance problems it sends messages to the proper infrastructure to fix the issue.

Key Components of SOA 
The first step in learning something new is to understand its vocabulary. In the context of SOA, we have the terms service, message, dynamic discovery, and web services. Each of these plays an essential role in SOA. 

Service
A service in SOA is an exposed piece of functionality with three properties:
  1. The interface contract to the service is platform-independent.
  2. The service can be dynamically located and invoked.
  3. The service is self-contained. That is, the service maintains its own state.
A platform-independent interface contract implies that a client from anywhere, on any OS, and in any language, can consume the service. Dynamic discovery hints that a discovery service (e.g., a directory service) is available. The directory service enables a look-up mechanism where consumers can go to find a service based on some criteria. For example, if I was looking for a credit-card authorization service, I might query the directory service to find a list of service providers that could authorize a credit card for a fee. Based on the fee, I would select a service (see Figure 1.1). The last property of a service is that the service be self-contained.

Figure 1.1. Directory service
Message
Service providers and consumers communicate via messages. Services expose an interface contract. This contract defines the behavior of the service and the messages they accept and return. Because the interface contract is platform- and language-independent, the technology used to define messages must also be agnostic to any specific platform/language. Therefore, messages are typically constructed using XML documents that conform to XML schema. XML provides all of the functionality, granularity, and scalability required by messages. That is, for consumers and providers to effectively communicate, they need a non-restrictive type of system to clearly define messages; XML provides this. Because consumers and providers communicate via messages, the structure and design of messages should not be taken lightly. Messages need to be implemented using a technology that supports the scalability requirements of services. Having to redesign messages will break the interface to providers, which can prove to be costly. 

Dynamic Discovery
Dynamic discovery is an important piece of SOA. At a high level, SOA is composed of three core pieces: service providers, service consumers, and the directory service. The role of providers and consumers are apparent, but the role of the directory service needs some explanation. The directory service is an intermediary between providers and consumers. Providers register with the directory service and consumers query the directory service to find service providers. Most directory services typically organize services based on criteria and categorize them. Consumers can then use the directory services' search capabilities to find providers. Embedding a directory service within SOA accomplishes the following:
  1. Scalability of services; you can add services incrementally.
  2. Decouples consumers from providers.
  3. Allows for hot updates of services.
  4. Provides a look-up service for consumers.
  5. Allows consumers to choose between providers at runtime rather than hard-coding a single provider.
Web Service
Although the concepts behind SOA were established long before web services came along, web services play a major role in a SOA. This is because web services are built on top of well-known and platform-independent protocols. These protocols include HTTP, XML, UDDI, WSDL, and SOAP. It is the combination of these protocols that make web services so attractive. Moreover, it is these protocols that fulfill the key requirements of a SOA. That is, a SOA requires that a service be dynamically discoverable and invokeable. This requirement is fulfilled by UDDI, WSDL, and SOAP. SOA requires that a service have a platform-independent interface contract. This requirement is fulfilled by XML. SOA stresses interoperability. This requirement is fulfilled by HTTP. This is why web services lie at the heart of SOA. 

Endpoint Architecture
Contract, Address and Bindings on which SOA service stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-

• Contract (What)
Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.
• Address (Where)
An Address indicates where we can find this service. Address is a URL, which points to the location of the service.
• Binding (How)
Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.

Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.


Figure: - Endpoint Architecture

Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract.

Monday, August 27, 2012

mojoPortal Introduction

Presentation Layer

The whole web site is the presentation layer and therefore should only have code related to presentation logic. That is one of my goals in designing this framework. This web site was built using ASP.NET. It consists of:
  •     .aspx pages
  •     .ascx user controls
  •     a Global.asax file
  •     a Web.config file
  •     a Culture.config file
  •     mojoPortal.Web.dll, which contains all the presentation logic for the core framework
mojoPortal.Web.dll talks to mojoPortal.Business.dll and presents its interfaces to the user as web pages. The Web Site can run under Windows/IIS or under mono/Apache with most GNU/Linux distributions or Mac OS X.

When working in the web site I try to make sure that all of my code is presentation logic, providing a mapping between business object properties and methods to visual controls for intuitive user interaction.

Business Layer

All business logic for the core framework modules is handled by mojoPortal.Business.dll or other business layer dlls for various features

When developing in the business layer I try to think of the most natural way to represent or abstract business entities as objects in a way that can be easily consumed by the UI.

Data Access Layer

All data access logic for mojoPortal.Business.dll is handled by mojoPortal.Data.dll. There are different versions of mojoPortal.Data.dll for each of the supported databases, MS SQL, MySQL, PostgreSQL, Firebird Sql, and SQLite. You can put any version in the bin folder of the web along with mojoPortal.Business.dll, and the site is happy as long as a valid database exists for the provided connection strings.

When developing in the data layer I try to think like the database and optimise operations according to its capabilities.

Sunday, August 26, 2012

MVC Introduction

MVC stands for Model - View - Controller and these three are the building blocks that make up the MVC pattern. A website which uses MVC will be mainly based on the communication that happens between these three components.

What is a Controller?
Controllers will be the receivers and dispatchers. When a user sends a request by clicking a link or button then the request is handed over to the controller (There can be many controllers in the website and the correct controller to handle a particular request will be identified by the URL pattern) the controller will have a set of methods(show, index, etc...) defined and one of these methods will do the necessary tasks to generate a response. Basically, Controller will be the intermediary who will communicate with the Modal and generate an appropriate View and send that to the client.

What is a Model?
Model handles the database interactions for the application. The Model will return the data which is requested by the Controller.

What is a View?
View is the HTML output that a user sees when he makes a page request. This view will be rendered based on the Controllers' request and by the data that is passed in by the Model.

As explained earlier the MVC architecture defines a clear isolation between the Presentation layer and the Data access layer. The presentation will be in the View and the Data will be in the Model. These two never interact directly with each other. Just look at the steps below to get an idea of how a request/response cycle works in MVC, the numbers indicate the order of execution.

1.0. User request arrives
1.1. Controller receives the request
1.2. Pass it to the correct controller method
1.3. Fetch data from the database by initiating the appropriate Model
1.4. Pass the data from 1.3 to the View and generate the HTML View.
1.5. Send the generated HTML as the response.

Wednesday, August 15, 2012

ASP.NET application and page life cycle


ASP.NET request processing is a 2 step process as shown below.
User sends a request to the IIS:-
• ASP.NET creates an environment which can process the request. In other words it creates the application object, request, response and context objects to process the request.
• Once the environment is created the request is processed through series of events which is processed by using modules, handlers and page objects. To keep it short lets name this step as MHPM (Module, handler, page and Module event), we will come to details later.
 

In the coming sections we will understand both these main steps in more details.
 

Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is issue in one app domain it does not affect the other app domain.

Step 3:- The newly created application domain creates hosting environment i.e. the ‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system then object of the ‘global.asax’ file will be created. Please note ‘global.asax’ file inherits from ‘HttpApplication’ class.
Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’ instances might be reused for multiple requests.

Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to process the page.

Step 6:- ‘HttpApplication’ then starts processing the request by http module events , handlers and page events. It fires the MHPM event for request processing.







 

Below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which has creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects. 





Once ‘HttpApplication’ is created it starts processing request it goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections it invokes different events which the developer can extend and add customize logic to the same.
Before we move ahead lets understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:-
• If you want to inject logic based in file extensions like ‘.ASPX’ , ‘.HTML’ then you use ‘HttpHandler’. In other words ‘HttpHandler’ is an extension based processor.


 



















• If you want to inject logic in the events of ASP.NET pipleline then you use ‘HttpModule’. ASP.NET . In other word ‘HttpModule’ is an event based processor.


Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below :-

Step 1(M ? HttpModule):- Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET ‘HttpModule’ emits events which can be used to inject customized logic. There are 6 important events which you can utilize before your page object is created ‘BeginRequest’,’AuthenticateRequest’,’AuthorizeRequest’,’ResolveRequestCache’,’AcquireRequestState’ and ‘PreRequestHandlerExecute’.

Step 2 (H ? ‘HttpHandler’ ) :- Once the above 6 events are fired , ASP.NET engine will invoke ‘ProcessRequest’ event if you have implemented ‘HttpHandler’ in your project.

Step 3 (P – ASP.NET page):- Once the ‘HttpHandler’ logic executes the ASP.NET page object is created. While the ASP.NET page object is created many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages ‘Init’ , ‘Load’ , ‘validate’ , ‘event’ , ‘render’ and ‘unload’. You can remember the word ‘SILVER’ to remember the events S – Start ( does not signify anything as such just forms the word ) , I – (Init) , L ( Load) , V ( Validate) , E ( Event) and R ( Render).

Step4 (M ? HttpModule):- Once the page object is executed and unloaded from memory ‘HttpModule’ provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events ‘PostRequestHandlerExecute’, ‘ReleaserequestState’, ‘UpdateRequestCache’ and ‘EndRequest’.
Below figure shows the same in a pictorial format.









 

The million dollar question is in which events we should do what? . Below is the table which shows in which event what kind of logic or code can go.
 
Section
Event
Description
HttpModule
BeginRequest
This event signals a new request; it is guaranteed to be raised on each request.
HttpModule
AuthenticateRequest
This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.
HttpModule
AuthorizeRequest
This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.
HttpModule
ResolveRequestCache
In ASP.NET we normally use outputcache directive to do caching.  In this event ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch.  Any caching specific activity can be injected here.
HttpModule
AcquireRequestState
This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.
HttpModule
PreRequestHandlerExecute
This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.
HttpHandler
ProcessRequest
Httphandler logic is executed. In this section we will write logic which needs to be executed as per page extensions.
Page
Init
This event happens in the ASP.NET page and can be used for :-
·      Creating controls dynamically, in case you have controls to be created on runtime.
·      Any setting initialization.
·       Master pages and them settings.
In this section we do not have access to viewstate , postedvalues and neither the controls are initialized.

Page
Load
In this section the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.
Page
Validate
If you have valuators on your page, you would like to check the same here.

Render
It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser you can enter your HTML logic here.
Page
Unload
Page object is unloaded from the memory.
HttpModule
PostRequestHandlerExecute
Any logic you would like to inject after the handlers are executed.
HttpModule
ReleaserequestState
If you would like to save update some state variables like session variables.
HttpModule
UpdateRequestCache
Before you end if you want to update your cache.
HttpModule
EndRequest
This is the last stage before your output is sent to the client browser.

With this article we have attached a sample code which shows how the events actually fire. In this code we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events , below is how the output looks like.
Below is the class for ‘HttpModule’ which tracks all event s and adds it to a global collection.
 
public class clsHttpModule : IHttpModule
{
......
void OnUpdateRequestCache(object sender, EventArgs a)

{
objArrayList.Add("httpModule:OnUpdateRequestCache");
}
void OnReleaseRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnReleaseRequestState");
}
void OnPostRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPostRequestHandlerExecute");
}
void OnPreRequestHandlerExecute(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnPreRequestHandlerExecute");
}
void OnAcquireRequestState(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAcquireRequestState");
}
void OnResolveRequestCache(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnResolveRequestCache");
}
void OnAuthorization(object sender, EventArgs a)
{
objArrayList.Add("httpModule:OnAuthorization");
}
void OnAuthentication(object sender, EventArgs a)
{

objArrayList.Add("httpModule:AuthenticateRequest");
}
void OnBeginrequest(object sender, EventArgs a)
{

objArrayList.Add("httpModule:BeginRequest");
}
void OnEndRequest(object sender, EventArgs a)
{
objArrayList.Add("httpModule:EndRequest");
objArrayList.Add("<hr>");
foreach (string str in objArrayList)
{
httpApp.Context.Response.Write(str + "<br>") ;
}
}
}                      
              

Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event.
 
 public class clsHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)

{
clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");
context.Response.Redirect("Default.aspx");
}
}          
              

We are also tracking all the events from the ASP.NET page.
 
public partial class _Default : System.Web.UI.Page
{
protected void Page_init(object sender, EventArgs e)
{

clsHttpModule.objArrayList.Add("Page:Init");
}
protected void Page_Load(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Load");
}
public override void Validate()
{
clsHttpModule.objArrayList.Add("Page:Validate");
}
protected void Button1_Click(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:Event");
}
protected override void Render(HtmlTextWriter output)
{
clsHttpModule.objArrayList.Add("Page:Render");
base.Render(output);
}
protected void Page_Unload(object sender, EventArgs e)
{
clsHttpModule.objArrayList.Add("Page:UnLoad");
}}

                       
              

Below is how the display looks like with all events as per the sequence discussed in the previous section.


 


Any ASP.NET page has 2 parts one is the page which is displayed on the browser which has HTML tags , hidden values in form of viewstate and data on the HTML inputs. When the page is posted these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code you can execute and write your own login on the same and render the page back to the browser.





 

Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform we need to put these logics appropriately in those events.
Note: - Most of the developers directly use the ‘page_load’ method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes etc everything happens on the page load. So if we can put logic in proper events as per the nature of the logic that would really make your code clean.


 
Seq
Events
Controls Initialized
View state
Available
Form data
Available
What Logic can be written here?
1
Init
No
No
No
Note: - You can access form data etc by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings.In this section we do not have access to viewstate , posted values and neither the controls are initialized.
2
Load view state
Not guaranteed
Yes
Not guaranteed
You can access view state and any synch logic where you want viewstate to  be pushed to behind code variables can be done here.
3
PostBackdata
Not guaranteed
Yes
Yes
You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.
4
Load
Yes
Yes
Yes
This is the place where you will put any logic you want to operate on the controls. Like flourishing a combox box from the database , sorting data on a grid etc. In this event we get access to all controls , viewstate and their posted values.
5
Validate
Yes
Yes
Yes
If your page has validators or you want execute validation for your page this is the right place to the same.
6
Event
Yes
Yes
Yes
If this is a post back by a button click or a dropdown change then the relative events will be fired. Any kind of logic which  is related to that event can be executed here.
7
Pre-render
Yes
Yes
Yes
If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.
8
Save view state
Yes
Yes
Yes
Once all changes to server controls are done this event can be an opportunity to save control data in to view state.
9
Render
Yes
Yes
Yes
If you want to add some custom HTML to the output this is the place you can.
10
Unload
Yes
Yes
Yes
Any kind of clean up you would like to do here. 


Mixed Content: The page at xxx was loaded over HTTPS, but requested an insecure

 Mixed Content: The page at ' https ://www.test.com/signup.aspx' was loaded over HTTPS, but requested an insecure script ' http ...