Buy Electronics

Wednesday, March 24, 2010

Design Patterns for ASP.NET Developers

Basic Design Patterns and Groups

Design patterns fall into several groups based on the type and aims of the pattern. For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses. The following list shows some of the most common design patterns within these groups:

  • Presentation Logic
    • Model-View-Controller (MVC)
    • Model-View-Presenter (MVP)
    • Use Case Controller
  • Host or Behavioral
    • Command
    • Publish-Subscribe / Observer
    • Plug-in / Module / Intercepting Filter
  • Structural
    • Service Agent / Proxy / Broker
    • Provider / Adapter
  • Creational
    • Factory / Builder / Injection
    • Singleton
  • Persistence

o Repository




Model-View-Controller and Model-View-Presenter PatternsFigure 1. The Model-View-Controller and Model-View-Presenter Patterns: These patterns separate the data held by the Model from the View, linking them via a Controller or Presenter.

The Model-View-Controller (MVC) and Model-View-Presenter (MVP) patterns improve code re-usability by separating the three components required to generate and manage a specific user interface (such as a single web page). The Model contains the data that the View (the web page) will display and allow the user to manipulate. The Controller or Presenter links the Model and the View, and manages all interaction and processing of the data in the Model (see Figure 1).

In the MVC pattern, user interaction with the View raises events in the Controller, which updates the Model. The Model then raises events to update the View. However, this introduces a dependency between the Model and the View. To avoid this, the MVP pattern uses a Presenter that both updates the Model and receives update events from it, using these updates to update the View. The MVP pattern improves testability, as all the logic and processing occurs within the Presenter, but it does add some complexity to the implementation because updates must pass from the Presenter to the View.

Provider and Adapter Patterns

Figure 2. The Provider and Adapter Patterns: These patterns provide ways for otherwise incompatible components to interact.

The Provider and Adapter patterns allow otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the other. In more practical terms, these patterns provide separation between components that allows behavioral changes to occur without prior knowledge of requirements. The application and any data sources it uses, outputs it generates, or classes it must interact with, can be created independently yet still work together (see Figure 2).

The Provider pattern separates source data from data processing objects and the application. It allows application code to be independent of the data source type and data format. A Provider component or service exposes standard methods that the application can call to read and write data. Internally, it converts these calls to the equivalents that match the data source, letting the application work with any source data type (such as any kind of database, XML document, disk file, or data repository) for which a suitable provider is available.

The Adapter pattern has the same advantages, and works in a similar way. Often, the target of an Adapter is some kind of output. For example, a printer driver is an example of an Adapter. ASP.NET itself, and other frameworks such as Enterprise Library, make widespread use of the Provider and Adapter patterns.











Thursday, March 11, 2010

Creating a .NET Web Service

Introduction

Microsoft .NET marketing has created a huge hype about its Web Services. Here we will create a .NET Web Service using C#. We will look closely at the Discovery protocol, UDDI, and the future of the Web Services.

Why do we need Web Services?

After buying something over the Internet, you may have wondered about the delivery status. Calling the delivery company consumes your time, and it's also not a value-added activity for the delivery company. To eliminate this scenario the delivery company needs to expose the delivery information without compromising its security. Enterprise security architecture can be very sophisticated. What if we can just use port 80 (the Web server port) and expose the information through the Web server? Still, we have to build a whole new Web application to extract data from the core business applications. This will cost the delivery company money. All the company wants is to expose the delivery status and concentrate on its core business. This is where Web Services come in.

What is a Web Service?

Web Services are a very general model for building applications and can be implemented for any operation system that supports communication over the Internet. Web Services use the best of component-based development and the Web. Component-base object models like Distributed Component Object Model (DCOM), Remote Method Invocation (RMI), and Internet Inter-Orb Protocol (IIOP) have been around for some time. Unfortunately all these models depend on an object-model-specific protocol. Web Services extend these models a bit further to communicate with the Simple Object Access Protocol (SOAP) and Extensible Markup Language (XML) to eradicate the object-model-specific protocol barrier (see Figure 1).

Web Services basically uses Hypertext Transfer Protocol (HTTP) and SOAP to make business data available on the Web. It exposes the business objects (COM objects, Java Beans, etc.) to SOAP calls over HTTP and executes remote function calls. The Web Service consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web.

Figure 1. SOAP calls are remote function calls that invoke method executions on Web Service components at Location B. The output is rendered as XML and passed back to the user at Location A.

How is the user at Location A aware of the semantics of the Web Service at Location B? This question is answered by conforming to a common standard. Service Description Language (SDL), SOAP Contract Language (SCL) and Network Accessible Specification Language (NASSL) are some XML-like languages built for this purpose. However, IBM and Microsoft recently agreed on the Web Service Description Language (WSDL) as the Web Service standard.

The structure of the Web Service components is exposed using this Web Service Description Language. WSDL 1.1 is a XML document describing the attributes and interfaces of the Web Service. The new specification is available at msdn.microsoft.com/xml/general/wsdl.asp.

The task ahead

The best way to learn about Web Services is to create one. We all are familiar with stock quote services. The NASDAQ, Dow Jones, and Australian Stock Exchange are famous examples. All of them provide an interface to enter a company code and receive the latest stock price. We will try to replicate the same functionality.

The input parameters for our securities Web service will be a company code. The Web service will extract the price feed by executing middle-tier business logic functions. The business logic functions are kept to a bare minimum to concentrate on the Web service features.

To create a Web Service we should familiar with the following concepts:

  • Basic knowledge of .NET platform
  • Basic knowledge of C#
  • Basic knowledge of object-oriented concepts

Creating a Web Service

We are going to use C# to create a Web Service called "SecurityWebService." A Web Service file will have an .ASMX file extension. (as opposed to an .ASPX file extension of a ASP.NET file). The first line of the file will look like

<%@ WebService Language="C#" class="SecurityWebService" %>

This line will instruct the compiler to run on Web Service mode and the name of the C# class. We also need to access the Web Service namespace. It is also a good practice to add a reference to the System namespace.


using System;
using System.Web.Services;

The SecurityWebService class should inherit the functionality of the Web Services class. Therefore, we put the following line of code:


public class SecurityWebService : WebService


Now we can use our object-oriented programming skills to build a class. C# classes are very similar to C++ or Java classes. It will be a walk in the park to create a C# class for anyone with either language-coding skills.

Dot-net Web Services are intelligent enough to cast basic data types. Therefore, if we return "int," "float," or "string" data types, it can convert them to standard XML output. Unfortunately, in most cases we need get a collection of data regarding a single entity. Let's take an example.

Our SecurityWebService stock quotes service requires the user to enter a company code, and it will deliver the full company name and the current stock price. Therefore, we have three pieces of information for a single company:

  1. Company code (data type - string)
  2. Company name (data type - string)
  3. Price (data type - Double)

We need to extract all this data when we are referring to a single stock quote. There are several ways of doing this. The best way could be to bundle them in an enumerated data type. We can use "structs" in C# to do this, which is very similar to C++ structs.

public struct SecurityInfo
        {
               public string Code;
               public string CompanyName;
               public double Price;
        }

Now we have all the building blocks to create our Web Service.

Therefore, our code will look like.

<%@ WebService Language="C#" class="SecurityWebService" %>
 
using System;
using System.Web.Services;
 
public struct SecurityInfo
{
        public string Code;
        public string CompanyName;
        public double Price;
}
 
public class SecurityWebService : WebService
{
        private SecurityInfo Security;
        
        public SecurityWebService()
        {
               Security.Code = "";
               Security.CompanyName = "";
               Security.Price = 0;
        }
 
        private void AssignValues(string Code)
        {
            // This is where you use your business components. 
            // Method calls on Business components are used to populate

// the data.
            // For demonstration purposes, I will add a string to the Code
            // use a random number generator to create the price feed.
                                      
              Security.Code = Code;
              Security.CompanyName = Code + " Pty Ltd";
              Random RandomNumber = new System.Random();
Security.Price = double.Parse(new System.Random(RandomNumber.Next(1,10)).NextDouble().ToString("##.##"));
        }
 
 
[WebMethod(Description="This method call will get the company name and the price for a given security code.",EnableSession=false)]
        public SecurityInfo GetSecurityInfo(string Code)
        {
               AssignValues(Code);
               SecurityInfo SecurityDetails = new SecurityInfo();
               SecurityDetails.Code = Security.Code;
               SecurityDetails.CompanyName = Security.CompanyName;
               SecurityDetails.Price = Security.Price;
               return  SecurityDetails;
        }
 
}
 

Remember, this Web Service can be accessed through HTTP for any use. We may be referring to sensitive business data in the code and wouldn't want it to fall into the wrong hands. The solution is to protect the business logic function and only have access to the presentation functions. This is achieved by using the keyword "[Web Method]" in C#.


Let's look at the function headers of our code.

[WebMethod(Description="This......",EnableSession=false)]
public SecurityInfo GetSecurityInfo(string Code)

This function is exposed to the public. The "description" tag can be used to describe the Web Service functionality. Since we will not be storing any session data, we will disable the session state.

private void AssignValues(string Code)

This is a business logic function that should not be publicly available. We do not want our sensitive business information publicly available on the Web. (Note:- Even if you change the "private" keyword to "public," it will still not be publicly available. You guessed it, the keyword "[Web Method]" is not used.)

We can use the business logic in this function to get the newest stock price quote. For the purpose of this article I have added some text to the company code to create the company name. The price value is generated using a random number generator.

We may save this file as "SampleService.asmx" under an Internet Information Service (IIS)-controlled directory. I have saved it under a virtual directory called "/work/aspx." I'll bring it up on a Web browser.

This is a Web page rendered by the .NET Framework. We did not create this page. (The page is generated automatically by the system. I did not write any code to render it on the browser. This graphic is a by-product of the previous code.) This ready-to-use functionality is quite adequate for a simple Web Service. The presentation of this page can be changed very easily by using ASP.NET pagelets and config.web files.

Notice a link to "SDL Contract." (Even if we are using WSDL, .NET Beta still refers to SDL.). This is the description of the Web Service to create a proxy object. This basically gives an overview of the Web Service and it's public interface. If you look closely, you will only see the "Web-only" methods being illustrated. All the private functions and attributes are not described in the SDL contract.

How do we use a Web Service?

Now we can use this Web Service. Let's enter some values to get a bogus price feed.

By clicking the Invoke button a new window will appear with the following XML document

This is how the Web Service releases information. We need to write clients to extract the information from the XML document. Theses clients could be

  1. A Web page
  2. A console / Windows application
  3. A Wireless Markup Language (WML) / WMLScript to interact with mobile phones
  4. A Palm / Win CE application to use on Personal Digital Assistants (PDAs).


You can also call the Web Service directly using the HTTP GET method. In this case we will not be going through the above Web page and clicking the Invoke button. The syntax for directly calling the Web Service using HTTP GET is

http://server/webServiceName.asmx/functionName?parameter=parameterValue

Therefore, the call for our Web Service will be

http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo?Code=IBM

This will produce the same result as clicking the Invoke button.

Now we know how to create a Web Service and use it. But the work is half done. How will our clients find our Web Service? Is there any way to search for our Web Service on the Internet? Is there a Web crawler or a Yahoo search engine for Web Services? In order to answer these questions we need to create a "discovery" file for our Web Service.

The future of the Web Services

The future looks bright for the Web Service technology. Microsoft is not alone in the race for Web Service technology. Sun and IBM are very interested. There are SOAP toolkits available for Apache and Java Web servers. I believe Web Services needs a bit of work, especially the Web Service discovery process. It is still very primitive.

On a positive note, Web Services have the potential to introduce new concepts to the Web. One I refer to as "pay per view" architecture. Similar to pay-TV, we can build Web sites that can generate revenue for each request a user sends (as opposed to a flat, monthly subscription). In order to get some data, we can sometimes pay a small fee. Commercially this could be handy for a lot of people.

Examples

  • Online newspaper sites can publish a 10-year-old article with a $2 "pay per view" structure.
  • Stock market portals can itemize every user portfolio for every single stock quote and build pricing and discount structures.

And the list goes on ...

On a very optimistic note, Web Services can be described as the "plug and play" building blocks of enterprise Business to Business (B2B) Web solutions.


Monday, March 8, 2010

India 1835

Just read what INDIA was as per LORD MACAULAY on his statement on 2nd February 1835, in the last snap. That would really shock us Old Photographs from Indian History. Please Read the last Article Carefully……


The daughter of an Indian maharajah seated on a panther she shot, sometime during 1920s.

A British man gets a pedicure from an Indian servant.

The Grand Trunk Road , built by Sher Shah Suri, was the main trade route from Calcutta to Kabul .

A group of Dancing or notch girls began performing with their elaborate costumes and jewellery.

A rare view of the President's palace and the Parliament building in New Delhi .

Women gather at a party in Mumbai ( Bombay ) in 1910.


A group from Vaishnava, a sect founded by a Hindu mystic. His followers are called Gosvami-maharajahs


An aerial view of Jama Masjid mosque in Delhi , built between 1650 and 1658.

The Imperial Airways 'Hanno' Hadley Page passenger airplane carries the England to India air mail, stopping in Sharjah to refuel.

See what the India was at 1835.......


Mobiles