Skip to main content

Professional ASP .Net page 7

· SQL Injection Problem

A user can enter a user-name and password in a pattern (such as ['b or '1'='1]) that when you concatenate them in the query to check the credential, the query will always be succeeded. To protect from this, you should either parse the strings they enter and remove all single quotes, or use the technique of retrieving the password from the database and comparing it with the value that the user entered or use a stored procedure.

· CLR has the ability to short-circuit expression testing.

· According to performance testing done by Microsoft, the runtime (CLR) can allocate nearly 10 million objects per second on a moderately fast machine.

· The Option Explicit On statement forces the declaration of all variables before they are used and will generate a compiler error if a variable is used before it is declared. The Option Strict On greatly limits the implicit data type conversions. This also disallows any late binding.

· In C#, properties and methods are non-virtual by default, which means that they cannot be overridden in any derived classes. To make a method overridable you have to prefix it with keyword virtual, unless you will get a compilation error.

· If you imported a name-space in a base class, you have to re-import that name-space in the derived class as well. Because the name-spaces are not inherited by the derived classes.

· A serviced component is a .Net component, but it is hosted inside of a COM+ application, and therefore can access the services offered by COM+.

· The manifest can either be embedded within a single DLL, as in the single file assembly, or can be in a separate file, as in the case with multi-file assembly.

· To store an assembly into the global assembly cache:

1) Create a strong name for the assembly using the SN.EXE tool. This tool will generate a file that contains the necessary public and private keys to define a strong name.

2) Pass the contents of that file to the Assembly Generation Tool (AL.EXE) to create an assembly with a strong name associated with it.

3) Use the Global Assembly Cache Tool (GACUTIL.EXE) to install the assembly into the global assembly cache.

· In checking version, the CLR first check the major and minor versions. These must match in order for the assembly to be compatible. If these two numbers match but the build number is different, then as long as the build number of the assembly is greater than the build required by the application, it can be assumed to be backwards compatible with the version expected by the application.

· SOAP is a W3C submitted note that used HTTP and XML to encode and transmit application data.

· ASP .Net Web service files are simply source file with a .asmx file extension.

· Building A Web Service

Define a normal class with properties, methods and all. Expose the application logic as you do in normal applications. To transform this normal class into a web service, just prefix <WebMethod> attribute to the methods or properties. Save your file with a .asmx extension. When you request this file through browser a help page is displayed, containing the information about your web service. The template page that generates this help page is DefaulWsdlHelpGenerator.aspx. You have to add a mandatory directive at the top of .asmx file:

<%@ WebService Class="Fibonacci" %>

You have to import the name-space System.Web.Services. You can gain access to the ASP .Net intrinsic objects, such as Application or Session, by inheriting your own web service class from the base class WebService. ASP .Net page has access to the same application state memory that ASP .Net web service do. Classes do not need to be inherited from the WebService base class in order to be a functional web service. You can still access the intrinsic objects using HTTPContext. For example to use Application object:

StrName = HTTPContext.Current.Application("Name")

· Protocols define how communication between systems takes place. ASP .Net supports three default protocols – HTTP-GET, HTTP-POST, and SOAP – but can be extended to support others.

· The web service we build locally and test used HTTP-GET as a default protocol to communicate to end-point. The parameters are passed on the query string in the form Fibonacci.asmx/GetSeqNumber?FibIndex=6 in case of HTTP-GET. The output from HTTP-POST is similar to HTTP-GET. The difference is HTTP-POST passed parameters or data as name/value pairs within the body of the HTTP request rather than in query string. You can enable a HTTP-POST protocol in the web service by setting showPage flag to true in the DefaultWsdlHelpPage.aspx.

· A SOAP protocol message contains four parts:

1) Envelop

2) Encoding Rules

3) RPC representation

4) Protocol bindings

· The WebMethod Attribute's Properties

1) Description: It used to provide a brief description of the Web-callable method. The value of the Description property is added to the WSDL and to the web service Help page.

<WebMethod (Description:="Returns the value of index")>

2) Enabling Session State: The default is disabled.

<WebMethod (EnableSession:="true")>

3) Aliasing Web Method Names: The most common use of the MessageName property is to uniquely identify polymorphic methods within a class that is to be marked as web-callable.

<WebMethod (MessageName="Add2")>

4) Caching Web Service: Like ASP .Net pages, ASP .Net services support output caching, because on the first request web service has be compiled. The use of caching for web services is configured on a method-by-method basis through the use of the WebMethod attribute's CacheDuration property. Caching variation based on the parameters supplied to the method is supported by default.

<WebMethod (CacheDuration:=30)>

5) Buffering The Server Response: The default is true.

<WebMethod (BufferResponse:="true")>

· The WebService Attribute

The WebService attribute is used to configure properties for the class – rather than the method or property. But it does not, however, mark the methods within the class as Web-callable.

1) Description:

<WebService (Description:="String")> Public Class WSer

2) Namespace: XML uses the namespaces to uniquely identify sections of an XML document. Namespaces are Universal Resource Indicators (URI) such as http://microsoft.com and allow the markup language used to be unique within a given namespace. Even though a URI might take the shape of an http://address, this does not imply that some value or meaning exists at this end-point, it is simply a unique string. The default namespace that ASP .Net assigns to a Web service in http://tempuri.org. You can change it for your web service as:

<WebService (Namespace:="String")> Public Class MyWService

3) Name: You can change the name of your class that is going to be instantiated by the proxies as:

<WebService (Name="MyClassName")>

· Synchronous Versus Asynchronous

A synchronous design allows the ASP .Net thread of execution to run until it's complete. If an action within the code has the potential to block, this can stall the ASP .Net worker thread. This all translates to an impact on the performance and scalability of the system.

An asynchronous design, on the other hand, allows the ASP .Net thread of execution to start up another thread, which can call back onto an ASP .Net thread when the work is complete.

· The best place to find a web service is www.uddi.org.

· WSDL is an XML document that describes:

1) How a web service is used.

2) The location of a web service.

3) The nature of the message exchange.

· Using Web Services

To use a web service in your local code, you have to do it through a proxy class/object. A proxy works on the behalf of others. To do this, you have to create a proxy class in your local code. This proxy class exposes the same methods and properties (even the name will be same) that the actual remote web service class has. The proxy does not implement any method or property inside it, it just calls the actual web service methods on the behalf of its user. For example a method named GetSeqNumber is exposes by the actual web service. You can call this method via your proxy class's method as:

Public Class Fibonacci

Inherits SoapHttpClientProtocol

Public Sub New()

MyBase.New

Me.Url = "http://[Server]//Fibonacci_vb.asmx"

End Sub

Public Function GetSeqNumber(ByVal FibIndex As Integer) As

Integer

Dim Result() As Object = Me.Invoke ("GetSeqNumber",

New Object() {FibIndex})

Return CType(results(0), Integer)

End Function

End Class

· There are four ways to create proxies for web services:

1) Use Visual Studio .Net and add a Web Reference you're your projects.

2) Use the wsdl.exe command-line utility

3) Use the Microsoft SOAP toolkit.

4) Implement your own custom procedure.

· Using Visual Studio .Net For Proxy Classes

Including a reference allows you to early-bind to the object, instead of late-binding. Use Project | Add Web Reference option or use References in the Solution Explorer to add a web service into your project. Visual Studio .Net will do all the work required to connect to the web service, parse the WSDL, and will generate a proxy class that you can use. For example you can use it in your code as:

Dim ObjFibonacci As New Server.Fibonacci()

Result = ObjFibonacci.GetSeqNumber(3)

Here is what happens when you execute the code:

1) ASP .Net creates an instance of the proxy and calls it.

2) The proxy calls the Fibonacci Web service via SOAP, which computes the results and sends it back to the proxy via SOAP.

3) The proxy then de-serializes the SOAP message, (converts the values within the SOAP message to .Net types) and returns an Integer value.

· Using WSDL.EXE For Proxy Classes

First specify the location of the WSDL document for the web service as:

WSDL.Exe http://server/. . /Fibonacci_cs.asmx?wsdl

It will generate a source file and this source file will be compiled again into a .Net assembly. To compile this source file you can use any language compiler (but should be same as used into generate the source file) to generate an assembly.

· Controlling Timeout

Using the Timeout property of the proxy ensures that the application won't wait for a slow web service. The default is 20 seconds but for example you can make it 5 seconds:

Dim ObjProxyClass As New ProxyClass()

ObjProxyClass.Timeout = 5000

· Setting The URL

You can also set the end-point URL of the proxy where the web service is located.

ObjProxyClass.Url = http://. . .

· Maintaining State

If you intend to maintain state through the use of ASP .Net session state within the web service, you need to re-present the HTTP cookie on each subsequent use of the proxy by your application. The cookie that the proxy receives is only valid for the life of the proxy. When the proxy instance goes out of scope or is destroyed, the cookie is lost and on subsequent requests you no longer have access to the Session. To overcome this problem, create an instance of a CookieContainer class and assign that instance to the proxy's CookieContainer property. For example consider the following example. The web service class is as follows:

Import System.Web.Services

Public Class SessionExample

Inherits WebService

<WebMethod (EnableSession:=true> Public Function

SetSesion (Key As String, Item As String)

Session(Key) = Item

End Function

<WebMethod (EnableSession:=true> Public Function

GetSesion (Key As String) As String

Return Session(Key)

End Function

End Class

Now you can create a proxy for this and using that proxy you can store and retrieve the values in the Session at web service:

Import System.Net

Dim ObjProxyClass As New ProxyClass()

Dim ObjCookieContainer As New CookieContainer()

ObjProxyClass.CookieContainer = ObjCookieContainer

ObjProxyClass.SetSession("Name","Rod")

StrResult = ObjProxyClass.GetSession("Name")

· SOAP Exceptions

In case of any error a web service is throws an exception of type SoapException. You can use this exception in your code when calling a web service. You have to import the System.Web.Services.Protocols namespace in your code for using that type of exception.

· Web Services Security

Because ASP .Net web services are simply part of an ASP .Net application, we can take advantage of all the security features provided by ASP .Net.

When web services uses the windows authentication and anonymous access is not enabled, you have to send user credential along with your request. To do this, import System.Net namespace in your code. Create a NetworkCredential object and assign the username, password and other required properties to it. Next set this object as a Credential property of the proxy. Now when you call the web service, you will be authenticated against the credentials you sent with your request.

Those web service users, who come from the non-windows application, can use the Clear-Text/Basic Authentication.

When we use the forms-based authentication with the web services, we have to authenticate the user and generate an authentication cookie our self.

FormsAuthentication.SetAuthCookie("User-Name","Password")

Apart from all the inbuilt authentication and authorization mechanisms provided by the ASP .Net, we can develop our own custom mechanism using SOAP headers.

· Interoperability

Interoperability is a term used to define working of two architecturally different components one upon. In case of .Net interoperability represents using COM components in .Net or using .Net components in COM. To accomplish this, a wrapper is designed between two types of components. This wrapper is responsible for the communication across the boundaries.

Data type marshalling or mapping is performed by the wrapper automatically. There are two kinds of types as far as marshalling goes:

1) Blittable Types: These are the same on both sides of the boundary, and therefore don't need any conversion.

2) Non-Blittable Types: These are different on either side of the boundary, and therefore require conversion. For non-blittable types, you can specify how they are marshaled across the boundary.

· Using COM Objects From .Net

Using COM component from .Net is extremely simple, as there is a tool that takes a COM component or type library and creates a managed assembly (a callable wrapper) to manage the boundary transition for you. From the programming perspective all you have to do is call methods and access properties as you would with the COM component. The difference is that you will be calling the wrapper class, which will take the .Net type, convert them to COM types, and call the COM interface methods. There are several ways in which you can generate the wrapper class:

1) Adding a COM reference in Visual Studio .Net.

2) Using the type library import tool (tlmimp.exe)

3) Using the type library convert class

The System.Runtime.InteropServices namespace contains a class called TypeLibConverter, which provides method to convert COM class and interfaces into assembly metadata.

4) Creating a custom wrapper

Using the wrapper assembly is very easy. First you have to import that assembly into your code. Now you can access its methods and properties as a normal managed assembly.

· Using .Net Components From COM

It is just a reverse process of what is described above. The difference is that you have to explicitly decide which interface and methods you want exposed to COM. This is crucial point, because for .Net components to be available in COM they have to have an interface. You can do this either manually or automatically.

Manually creating interfaces means you use the language features to explicitly declare the interfaces.

Automatically creating interfaces means you use the Interop Services attributes to have an interface automatically created from the class.

Once the .Net assembly has been created, you need to create a COM type library so that COM clients can set reference to the classes. Use tldexp.exe tool to do this. Once the type library is created, the class needs to be registered in the Registry as regasm AssemblyName.

· Registering The DLL For Global Use

If you wish the .Net assembly to be used in multiple applications, then it must be registered in the Global Assembly Cache (GAC). This applies not only to .Net components used from .Net, but also to .Net components used from COM. To register an assembly into GAC you have to follow the steps:

1) Generate the strong name: sn –k Person.snk (This generates a key pair and stores it in the file Person.snk)

2) Add a link attribute in the assembly:

<assembly:AssemblyKeyFile("Person.snk")>

3) Installing in GAC:

Gacutil.exe /i Person.Dll

· API Calls

.Net provides a way to access DLLs that aren't COM based, using the Platform Invoke Services (P/Invoke). You can call the APIs in a manner similar to the way Visual Basic 6 does it. First declare the API to call as:

Declare Auto Function GetSystemMetrics Lib "User32.Dll"

(nIndex As Integer) As Integer

Now you can call it as:

Dim mt As New Metrics

Dim val As Integer = mt.GetSystemMetrics(SM_CXSCREEN)

Comments

Popular posts from this blog

Top Open Source Web-Based Project Management Software

This is an user contributed article. Project management software is not just for managing software based project. It can be used for variety of other tasks too. The web-based software must provide tools for planning, organizing and managing resources to achieve project goals and objectives. A web-based project management software can be accessed through an intranet or WAN / LAN using a web browser. You don't have to install any other software on the system. The software can be easy of use with access control features (multi-user). I use project management software for all of our projects (for e.g. building a new cluster farm) for issue / bug-tracking, calender, gantt charts, email notification and much more. Obviously I'm not the only user, the following open source software is used by some of the biggest research organizations and companies world wild. For example, NASA's Jet Propulsion Laboratory uses track software or open source project such as lighttpd / phpbb use re...

Google products for your Nokia phone

Stay connected with Gmail, Search, Maps and other Google products. Check products are available for your Nokia phone Featured Free Products Search - Find the information you need quickly and easily Maps - Locate nearby businesses and get driving directions Gmail - Stay connected with Gmail on the go YouTube - Watch videos from anywhere Sync - Synchronize your contacts with Google

DotNetNuke Overview

DotNetNuke is the leading Web Content Management Platform for Microsoft .NET. DotNetNuke can be used as a web content management system (CMS) for simple websites or as a powerful application development framework which enables businesses to quickly build and deploy feature-rich, interactive websites and applications in Microsoft .NET. An intuitive, menu-driven interface allows non-technical users to easily create new sites or extend the functionality and features of their existing web site when used as a web CMS. An open API and the availability of over 6,000 third-party add-on modules available through Snowcovered.com allow web development professionals to create complex web sites for demanding applications. Installing new modules or skins is quick and easy, allowing users to deploy new functionality on their web sites in just minutes. DotNetNuke is the world’s most widely adopted framework for building web solutions on Microsoft Windows Server. DotNetNuke powers o...