LAN Web TCP Delphi

Title: WEB SERVICES
Question: Web services is the latest Microsoft architecture vision and dream. Most of the other big players have already become enthusiastic about it and started diligent preparations for competence in this new direction. Even Borland decided, at the very last moment, not to stay aside. Suddenly they took out Delphi 6 after having kept quiet about it for a long time.
Answer:
POLITICS AND VISION
I havent had the opportunity to see the new Delphi yet, but according to the published information it offers a full support to the very base of the Web services -SOAP - neglecting the Borland MIDAS layer in favor of SOAP.
Why are Web services so enticing to the big software sharks? It is easy to understand their motivation. Web services means no more selling of products, but selling of services instead. No more software piracy. Fully protected copyright: the producer remains the sole owner of the product. The contract with the software user would be long term. And not unlike an addiction, the more the user consumes, the bigger his urge to consume. In terms of large organizations this means much money, great dependency and concentrated power. In the worst scenario Web services would lead to the programming of the consumers' brains to be dependant and thus to total control of the consumers' communications and everyday life - a mixture of a new capitalistic revolution and 'big brother'-nightmare .
One hopes that this is only a hysterical fantasy. Only the future will show the true role of the Web services in society. But there is no doubt they constitute a big change for the industry, not unlike the invention of the PC and Internet. And we, the developers, have to be prepared for it.
Here is a simple example of the software designing volution. The task is to get the result of some arithmetic operation, x+y for instance. (This is a highly abstract example; one can easily apply it to any real-life situation). Some years ago the approach to this task used to be to write some procedure like:
function HaveSum (x: integer; y: integer): integer;
begin
Result:=x+y;
End;
After that, the OOP was invented. The new wave requested from the programmers to create, let's say ThaveSum class with object instance having 2 integer properties and GetSum method. On a design level it seemed both elegant and efficient (this is not the place to start a discussion about the advantages of OOP). The next move was a Microsofts one they implemented COM and the object was not just building material, but rather a living entity. Designing a program became negotiating between all these entities to do you the favor of serving at a certain moment to achieve a certain goal rather than masonry.
It is a different matter that not all of these entities were friendly enough to serve, but the strategy was implemented one can say to perfection in Microsoft Office. Logically COM was educated to receive tasks from a distance, so if there was a office with 20 users who had to know how much exactly x+y was, it was enough only one of these IhaveSum Com to be produced, distributed, purchased and questioned by all these users.
And now, the Web services vision comes: not the product, but the summing service is being distributed. Every time one needs this unique service a call to the distributor has to be executed and a payment has to be processed accordingly. The software user is totally disconnected from the software product and concerned only with the desirable result this product gives (and which was the very reason for buying, or illegally copying, the software in the 'good old times' we are saying good-bye to.)
SIMPLE DELPHI 5 EXAMPLES
Two of the tree todays pillars of the Web services: HTTP and XML are already well known to the Delphi developers. Next I intend to show different ways of implementing a webservice in Delphi 5 and I hope new examples with Delphi 6 will come very soon..
Firstly I will implement only the HTTP protocol. The server here could be a ASP or PHP page, but we are dedicated to Delphi, so the server is a Delphi CGI stand-alone executable. It will take a few minutes and only a line of code to create it (I am explaining for the very beginners):
- Choose File New New Web Server Application;
- The CGI type is sufficient for our purposes and the easiest for debugging, although in real-life situation an ISAPI DLL may be preferable;
- A new WebModule is created. Open its Action Editor and add an action.
- Add the next line of code on OnAction event of this action, which has to be default:
procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
Response.Content :=IntToStr( StrToIntDef(Request.QueryFields.Values['x'],0) +
StrToIntDef(Request.QueryFields.Values['y'],0));
end;
This way the server calculates the sum of the two variables and sends it back to the client..
There are already many different approaches to implement the HTTP protocol in Delphi. It is possible to use the WinInet API functions (you can find a good example of this in Marco Cantus Mastering Delphi 5) or Indy components, which will be included with Delphi 6 and are available to download at http://www.nevrona.com/Indy. But for this example I have chosen the Microsoft Internet Transfer Control 6.0, so you have to import it in Delphi in order to compile the client. The type library is MSINET.OCX and the name of the help file where more information about the control can be found is INET98.CHM. The control is very easy to use and requires again only a line of code in our example:.
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption :=
inet1.OpenURL('http://localhost/scripts/webcalc.exe?x='+Edit1.Text+'&y='
+Edit2.Text);
end;
The control sends the request and receives the answer from the server. OnStateChange event gives opportunity to obtain more information about the process:
procedure TForm1.Inet1StateChanged(Sender: TObject; State: Smallint);
begin
case state of
icResolvingHost: statusbar1.Panels[0].Text :=
('looking up the IP address of the specified host computer);
icHostResolved: statusbar1.Panels[0].Text :=
(' successfully found the IP address of the specified host computer );
icConnecting: statusbar1.Panels[0].Text :=
(' connecting to the host computer);
icConnected: statusbar1.Panels[0].Text :=
(' successfully connected to the host computer);
icRequesting: statusbar1.Panels[0].Text :=
(' sending a request to the host computer);
icRequestSent: statusbar1.Panels[0].Text :=
(' successfully sent the request);
icReceivingResponse: statusbar1.Panels[0].Text :=
(' receiving a response from the host computer );
icResponseReceived: statusbar1.Panels[0].Text :=
(' successfully received a response from the host computer);
icDisconnecting: statusbar1.Panels[0].Text :=
(' disconnecting from the host computer);
icDisconnected: statusbar1.Panels[0].Text :=
('successfully disconnected from the host computer);
icError: statusbar1.Panels[0].Text :=
('An error occurred in communicating with the host computer);
icResponseCompleted: statusbar1.Panels[0].Text :=
('The request has completed and all data has been received);
end;
end;
Figure1: The Client
And the client application is ready. Instead of doing the calculation by itself, it will depend on the Webcalculator Server to do this operation. We have our Web service and can start offering it to everyone
The next example is one step more advanced: it uses XML to send the variables. XML cannot be frustrating even to the beginner, it is just a standardized format for storing and exchanging of data. This time I am using the post method of the TNMHTTP component you can find at Delphi FastNet palette. The command.
Web.Post('http://localhost/scripts/webCalc.exe',' '+strX+''+strY+'');
does all the job and what is different is that it sends a structured XML document. The server needs an instrument to parse it. There are again different technologies available: you can read more about this in the 'XML Parsing in Delphi' by Charlie Calvert. I use the MSXML.DLL library for XML parsing in the server, so you have to import this Microsoft library in Delphi first. Again the code is concentrated in OnAction event:
procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean(;
var
doc : IXMLDOMDocument;
ElemList: IXMLDOMNodeList;
x, y:integer;
begin
Doc:= CreateOleObject('Microsoft.XMLDOM') as IXMLDOMDocument;
Doc.loadXML (Request.ContentFields.Text );
ElemList:= Doc.getElementsByTagName ('varX'):
x:= StrtoIntDef(ElemList.item[0].text,0);
ElemList:= Doc.getElementsByTagName ('varY);
y:= StrtoIntDef(ElemList.item[0].text,0);
Response.content:= #10+#13+InttoStr(x+y) ;
end;
There are many different approaches to access the document using the XMLDOMObject. The object is well documented in Microsoft XML SDK. The server is ready for use again. The XML is what makes a difference when we intend to send many different variables, not just x and y..
DELPHI 5 AND SOAP EXAMPLE
It is not true that we have to wait for Delphi 6 in order to start working with SOAP. SOAP Toolkit 2.0 can be downloaded and Web service created even with Delphi 5. In the last example here, this approach would be used for our Webcalculator..
The first step is to create a COM object, which will give the service. After that, a Web Service Description Language (WSDL) file has to be created for use in Web services. Fortunately, the SOAP Toolkit 2.0 wizard creates these files automatically. The last step is developing a Delphi application, which will consume the services. For this, the SOAP client has to be controlled from Delphi..
Let start it. The first task is to create a simple COM object, following the functionality of the previous examples. It will have only one interface and one method: the GetSum again:.
ISummer = interface(Idispatch)
function GetSum(const x: WideString; const y: WideString): WideString;
safecall;
Figure2: Our COM Webcalculator will offer the Web service.
function TSummer.GetSum(const x, y: WideString): WideString;
begin
Result:= InttoStr(SysUtils.StrtoInt(x)+ SysUtils.StrtoInt(y);
end;
Is it almost the same as in the other examples, isnt it? Create it like Active Server Object. This way a simple ASP will be written by Delphi, so you can test the object using it first. Compile the ActiveX DLL and publish the ASP on your server:.
Set DelphiASPObj = Server.CreateObject("Project1.Summer")
Response.Write ( DelphiASPObj.GetSum(Request.QueryString.Item("x"),
Request.QueryString.Item("y")))
Set DelphiASPObj = Nothing
Response.End
If everything goes well, the calculator has to work. Check by entering something like http://localhost/scripts/webcalculator.asp?x=3&y=8 in your browser and you have to receive back the answer..
Next, the SOAP toolkit has to be installed. Here is the address : Microsoft - msdn-files/027/001/580/msdncompositedoc.xml After that, choose the WSDL generator from the Toolkit menu. Supply the service name, the name of your Active X dll and your web directory, where new WSDL, WSML and asp files would be generated.
The last step is to create the client- in only 3 lines of code:.
procedure TForm1.Button1Click(Sender: Tobject);
var
SoapClient: OleVariant;
SoapClient := CreateOleObject('MSSOAP.SoapClient);
SoapClient.mssoapinit('http://localhost/scripts/sumservice.wsdl','SumService','SummerSoapPort');
showmessage(SoapClient.GetSum(Edit1.Text,Edit2.Text));
end;
That is all. Congratulations! We have our SOAP Webcalculator!
It is so easy to transform this example into some more real-life model: a web service, which stores the address books of all our customers, for instance ( if you dont believe that people are keen on storing personal or even very personal data on a long distance, you are still underestimating the business opportunities Microsoft have already developed).
Web services can be created even with Delphi 5, using HTTP and XML. Importing the Microsoft Simple Object Access Protocol (SOAP) Toolkit 2.0 makes it possible SOAP to be used too, but the next generation Delphi promises to be a 100% SOAP compatible and to implement these new instruments, created especially for the Web services. As we are entering the Web services age we can be sure of only one thing: they will make the life of us, programmers, even more exciting.
-----
The 3 examples from this article are available to download at Borland Code Central:http://ww6.borland.com/codecentral/ccweb.exe/author?authorid=11004