Thursday, August 28, 2008

ASP .NET Services

A Web service is an application stored on a machine that can be accessible through another machine over Internet or LAN. Even before introduction of Web services we were able to access applications or business logics across the net. Therefore, before starting with Web Services we must know the need that gave rise to Web services.

To begin with we would discuss the four Ps that are important in doing business using computers.

  • Partners: Every business needs partners and that is how they make enormous amount of profit.

  • Profit: No business can run without making profits. Profit must increase every year to make the business successful.

  • Productivity: Computer as its very nature can be used to improve productivity of a business and hence the profit.

  • Programming should be cheap: If computer is to improve productivity of the business programming and maintenance cost should decrease.

Let us now understand the current business scenario. We would take an example of an airlines company. The customers of the airlines company may access the company through personal computers, PDAs or simple phones. The airlines company may communicate with partners such as a food company or the bank. Partners and clients would still be there but the way they would interact would be different. The airlines company would have a web server to which clients would send requests for ASP or HTML pages. The request would be in form of HTTP request. The Web Server would communicate with the business logic in the application server and use the data bases to store the data. The Web Server would respond by sending HTML back to the clients. The food company and bank organization would have application servers running business logic in the form of components. They would also have data base servers for secured and efficient data storage. If airlines company is to access the business logic exposed by application servers of food company and bank it would do so through Remote Procedure Calls. Also the food company and bank may also be interacting with each other.

Different client organizations would use various software and programming model. Even the Operating Systems installed on the client devices would be different. The client would like to interact with the Web Server using these devices. The Web Server of the Airline company may either have IIS, JWS or Apache server running appropriate sever side scripts. The food company may have COM+ model on their Application servers with business logic implemented as COM components and MS-SQL database. The bank organization may have J2EE model with business logic implemented as EJB components running on their Application Servers and data base in Oracle.

In a distributed computing architecture the clients form the Presentation layer and the DCOM components, EJB components, CORBA components and DCOM components form the Business layer. The clients has to cross the firewalls to access components. Firewalls ensure that communication is done through a specified port and data format. The external applications, databases and legacy system form the Data layer. In our Airline example, the main reason of conflict is that all the three interacting companies (airlines company, food company and bank) have different standards. The airlines company has CORBA components installed. The food company has DCOM components and Bank has EJB components. The problems faced in developing these components are as follows:

  • Language: DCOM components could be written only in VC++ or VB, whereas, EJB components could be written only in Java.

  • Infrastructure: CORBA components need ORB libraries and services. DCOM components need COM libraries and services, and EJB components need J2EE Services.

  • Layout of Objects: Layout of CORBA components differ from DCOM components which in turn differs from EJB components.

  • Description: CORBA components are defined using CORBA Interface Description Language, DCOM components are defined using Microsoft Interface definition languages and EJB components are exposed as interfaces.

  • Discovery Standards: CORBA components are discovered using the CORBA registry, DCOM using the Registry and EJB using the Java Native Directory Interface.

The conflict between these models occur mainly due to the Wire Protocol and Data Standard. This was different for each of the infrastructure. CORBA uses IIOP (Inter Internet Object Protocol), DCOM uses RPC (Remote Procedure Calls) and EJB uses RMI (Remote Method Invocation) / IIOP. All these protocols are non-standard protocols and hence are not followed by all companies.

These existing Distributed Computing solutions suffer from various problems. For example, DCOM is a proprietary protocol. It does not support interoperability and it has firewall problems because DCOM transfers data in binary format and it uses many ports to call remote functions. CORBA uses IIOP protocol, which is non-internet friendly. EJB requires very costly infrastructure. Moreover all these object models require their client to use the same libraries as that used on server. This makes a very tight coupling between client and the component. If component is changed and written using new object model the client will also have to change.

To address these needs, XML Web services came into existence and were introduced as part of ASP.NET, which is part of the .NET Framework. Web services are based on open Industry standards, such as HTTP, XML, and SOAP. Using these open standards, Web services deliver application functionality across the Web to any type of client, on any platform.

XML Web services are based on open Web standards that are broadly supported and are used for communication and data formats. XML Web services provide the ability to expose application logic as URI-addressable resources, available to any client in a platform-independent way. Web services are self-describing. Any clients incorporating open Web standards for communication and data formatting (HTTP and XML) can query dynamically for Web service information and retrieve an XML document describing the location and interfaces supported by a particular XML Web service. These open standards make Web services indifferent to the operating system, object model, and programming language used. Web services are accessible to disparate systems, supporting application interoperability to an unprecedented level thanks to the ubiquity of HTTP and XML.

Instead of communicating in binary formats between applications, Web services use XML-encoded messages. Because XML-based messaging is used for the data interchange, a high level of abstraction exists between a Web service implementation and the client. This frees the client from needing to know anything about a Web service except for its location, method signatures, and return values. Additionally, most Web services are exposed and accessed via HTTP, virtually eliminating firewall issues.

SOAP

The only requirement of Web services is that both the communicating parties should have SOAP (Simple Object Access Protocol) servers. SOAP is built upon HTTP and uses XML. It describes function calls and their parameters using XML. The .NET Web services use this protocol for transfer of data. A Web service is a piece of code that resides on the net server. This code can accept request from the clients using HTTP and XML. Once a Web service is put on the Internet it can be consumed or used by any client across the Internet that uses HTTP and XML. We can use a Web service already available on net in our web site. For example, a book store can have a Web service that takes an ISBN number of book and returns all the details of the book to the user. This Web service can be used by many sites, which provide information related to books. Apart from being generalized, the main advantage of using SOAP protocol is that SOAP can support a rich set of data types including the primitive data types, enums, classes, structs, ADO.NET data sets and arrays of these types.
I must note here that the Web services can be built in any .NET compliant language like VB.NET, C# or Managed C++.
XML Web services are based on open Web standards that are broadly supported and are used for communication and data formats. XML Web services provide the ability to expose application logic as URI-addressable resources, available to any client in a platform-independent way. Web services are self-describing. Any clients incorporating open Web standards for communication and data formatting (HTTP and XML) can query dynamically for Web service information and retrieve an XML document describing the location and interfaces supported by a particular XML Web service. These open standards make Web services indifferent to the operating system, object model, and programming language used. Web services are accessible to disparate systems, supporting application interoperability to an unprecedented level thanks to the ubiquity of HTTP and XML.

Because XML-based messaging is used for the data interchange, a high level of abstraction exists between a Web service implementation and the client. This frees the client from needing to know anything about a Web service except for its location, method signatures, and return values. Additionally, most Web services are exposed and accessed via HTTP, virtually eliminating firewall issues.

UDDI & WSDL

Web services are discovered using the UDDI (Universal Description Discovery and Integration). We would look at UDDI in more detail later in the article. Any client can use a Web service. Hence, when we create Web services we must provide the information programmers need to know. For example, we must provide information about the methods available, types of parameters and return values of methods, ways of calling these methods, how the web service should be used, etc. This information is available through a WSDL file standing for Web service Definition Language. This file contains XML schema that describes the web service.

Benefits of Web Services

One of the benefits of using Web services is that we have a broader reach. No matter what the infrastructure is, if the object is exposed as Web service the communication becomes easier.
Another benefit is that even within enterprise the objects can be exposed as Web services. Web services hence facilitate Business to Business (B2B) communication and Enterprise Application Integration.

How to Use Web Service

Web services are deployed on Web Servers. Once a Web service is put on the Web any client that understands HTTP and XML can use it. Here we have taken an example of the IIS Web Server. The IIS has a built-in Soap Server. IIS listens for client requests on port 80. The WSDL file can also be kept on the same web server.
The client who wants to use the web service adds the link to WSDL file in VS.NET IDE. VS.NET then creates a proxy, which contains the methods with same name as those were exposed by the Web service. These methods contain logic to convert the data passed by the client to SOAP request. The client calls method in the proxy class. The proxy creates a SOAP envelope and sends it to IIS. When IIS detects that it is a SOAP message IIS passes the message to the SOAP server, which in turn invokes methods in the Web service. The return values trace the path back from the server, get converted into SOAP and are sent to the proxy and finally to the client.
Like any other resources on the Internet, it would be virtually impossible to find a particular Web service without some means to search for it. Web service directories provide central locations where Web service providers can publish information about their Web services. Such directories can be accessed directly or programmatically, which provide search results in response to queries from potential Web service clients. The UDDI is such a location that defines a standard way to publish and discover information about Web services. Using the browser we make a request to search for the Web service. The UDDI responds with listing of the services. The list of services contains URIs of either discovery documents or WSDL documents.
If we get this we can get the WSDL file and then the client creates a proxy object based on the details provided by the WSDL. Once we have the proxy object we can call the methods of the Web service.

Creating A Web Service

After understanding the need of web services, how they evolved and how they make communication possible between heterogeneous systems, let us now see how to build and consume a Web service. We would build a simple Web service that exposes two methods. One method would convert temperature in Celsius to Fahrenheit. Another method would convert temperature in Fahrenheit to Celsius. The steps to create the Web Service are given below:

(a) Open Visual Studio.NET IDE. Select 'File | New | Project | Visual C# Projects'. Select 'ASP.NET Web Service' as project template. Provide the project name as 'webservice' and click OK. The location of this project would be 'C:\Inetpub\wwwroot' folder. The 'Inetpub' folder is present on the local drive if IIS is installed.
(b) A form would get displayed. Right click on it and select 'View Code'. You would see a commented HelloWorld( ) method as shown below:

//[WebMethod]
//public string HelloWorld( )
//{
// return "Hello World" ;
//}

Uncomment the code and execute the program by pressing Ctrl + F5. You would see the output in IE as shown in the following screen shot.


Here, HelloWorld is a Web service. The attribute [WebMethod] enables the method from being called by the clients through network.We would add our web methods and create a Winform client next time.

Testing .aspx Script from Console Prompt

Platform: Windows NT 4.0 or Windows 2000

Version : VS.NET Beta 2 only

Requirements : Favorite editor (whether SDI or MDI )

Method : Simply write the following code into a file and save it as MyTest.exe , then try this out, perform the following steps:

  1. Copy The MyTest.cs and Test.aspx files to a local directory.

  2. Compile MyTest.exe by typing csc MyTest.cs /r:System.Web.dll within a command prompt in the directory.

  3. Type MyTest.exe Test.aspx

One interesting use of this functionality is to pre-process dynamic ASP.NET requests saving the output as static .htm files that you then prop onto a server. You can do this with MyTest.exe by pipeing the output automatically to a static file. For example:

      MyTest.exe Test.aspx > Test.htm


----------------------------------------------
MyTest.cs
----------------------------------------------

using System ;
using System.IO ;
using System.Web ;
using System.Web.Hosting ;

public class MyExeHost : MarshalByRefObject
{
public void ProcessRequest ( String page ) 
{
HttpRuntime.ProcessRequest ( new SimpleWorkerRequest ( page, null, Console.Out ) ) ;
}
public static void Main ( String[ ] args ) 
{
MyExeHost host = ( MyExeHost )ApplicationHost.CreateApplicationHost ( typeof ( MyExeHost ),

"/foo", Directory. CurrentDirectory ) ;
foreach ( String page in args ) 
{
host.ProcessRequest ( page ) ;
}
}
}
 
----------------------------------

Test.aspx
----------------------------------

Hi checking it out ! <%=Now%>

Tuesday, August 26, 2008

ASP.NET security

ASP.NET security is mostly concerned with building secured sites that serve up pages only to authorized users. There are certain sites on the net that require login before displaying certain pages. These sites must implement some application level security to identify authorized users. This application-level security is provided using ASP.NET. It works in conjunction with IIS, the .NET platform and the underlying operating system security services.

Whenever a client tries to connect to a website, it has to make a request to the Web Server for a particular page. This request is known as a webrequest. To implement the security at application level, the application needs to take two actions—identify the person who has made the request to the web server and specify who can access which pages.

This action of identifying the caller of web page is known as authentication. Once authentication is done, it is decided which pages the caller can view. This is known as authorization. ASP.NET supports four types of authentication and authorization mechanisms.

- Windows authentication
- Passport authentication
- Forms authentication

Let us discuss them one by one.

Windows Authentication

This type of authorization is best suited for intranet applications. A user will be able to access a requested resource only if he has a valid and active account on Windows. Moreover that account needs to have permissions to access the specific resource. This type of authentication is very secured since it uses hash algorithms to encode and decode client’s credentials. However there are a few problems, this type of authentication does not work through most proxy servers, firewalls, and some routers. Hence this technique is not very suitable for Internet applications.

Setting up Windows authentication is simple. Just make the following settings in the ‘web.config’ file of your project.


These entries ask ASP.NET to use Windows authentication with Identity impersonation for the authentication. Simply doing this will not work if IIS is configured to accept anonymous requests to this website (by default IIS accepts anonymous requests to any Website). To turn off anonymous access to this site, follow the instructions given below.

(a) Start Internet Services Manager from Administrative tools in the Control Panel.
(b) In the IIS, explore the branch with name same as your local machine name.
(c) Explore ‘Default WebSites’.
(d) Locate the Website we want to authenticate using Windows authentication.
(e) Right click on it and select Properties. Property pages would get displayed.
(f) Select the tab named ‘Directory Security’
(g) Click on the edit button inside the group box named Anonymous access and authentication control
(h) In the following dialog, uncheck Anonymous access check box. Make sure Integrated Windows Authentication check box
is checked.
(i) Click OK to dismiss the dialogs.

This process will force IIS to pop up Windows authentication dialog before displaying the web page requested.

This can be done programmatically by modifying the section of the web.config file. Make the following changes to the authentication section

:::


:::

We instruct IIS to not to allow any users without proper authentication. The tag deny users=”?” will stop all unauthenticated users from accessing the website.

Passport Authentication

Passport authentication is a service provided by Microsoft. This service allows us to implement single SignIn for multiple applications or Websites that want to authenticate users. The user is expected to use only one user name and password to access all the sites more over, the user need not re-SignIn whenever he switches from one site to another (provided both sites support Passport authentication). For example, if site1.com and site2.com both support passport authentication, then if a user visits site1.com, sign in the site and then decide to visit site2.com, you will be automatically authenticated on the basis of the credentials you presented at site1.com. This is possible because whenever you sign into a Passport service supporting site, the service creates a secure cookie into our machine. Later when we visit another Passport supporting site, our browser presents this cookie. This cookie indicates that we have already been authenticated and no new authentication is required. To setup Passport authentication, following configuration needs to be added to the ‘web.config’ file.







But Passport service is not free. If we want to support Passport authentication on our website, we will have to subscribe to it.

Forms Authentication

Form based Authentication is best suited where very high degree of security is not required. We can use our own login form, replacing the default login provided by Windows. In almost all situations we will allow anonymous access to our website, since authentication is done by ASP.NET instead of IIS.

ASP.NET first checks whether there is any authentication cookie present in the request header. If cookie is present, we know that the user is already authenticated and his identity is present in the cookie. Otherwise the user is automatically redirected to our custom login page. The user then presents his login credentials. If the user is authenticated, we place a cookie in the request header and pass it on to ASP.NET other wise access is denied.

Form based authentication is configured in the ‘web.config’ file. The <authentication> section carries information regarding cookies, password formats, list of registered users, etc.

Your Title