HTML Tutorials |
|
XML Tutorials |
|
Browser Scripting |
|
Server Scripting |
|
.NET (dotnet) |
|
Multimedia |
|
Web Building |
|
Java Tutorials |
|
Programming Langauges |
|
Soft Skills |
|
Database Tutorials |
|
Operating System |
|
Software Testing |
|
SAP Module |
|
Networking Programming |
|
Microsoft Office |
|
Accounting |
|
|
Serviços da correia fotorreceptora de XML |
Serviço 1 da amostra
|
Nesta seção nós criaremos um serviço simples da correia fotorreceptora. Ao trabalhar com correia fotorreceptora presta serviços de manutenção os namespaces que são requeridos estão sumariados como segue:
|
System.Web.Services:
|
O namespace consiste um jogo mínimo e completo dos tipos necessitados construir um serviço da correia fotorreceptora
|
System.Web.Services.Description:
|
Isto permite que nós interajam com o WSDL programmatically
|
System.Web.Services.Discovery:
|
Estes tipos permitem que um consumidor descubra os serviços da correia fotorreceptora instalados em uma máquina dada
|
System.Web.Services.Protocols:
|
Este namespace define um número de tipos que representa protocolos do invocation (HTTP-GET, HTTP-POST e o SABÃO)
|
O namespace de System.Web.Services
|
O namespace de System.Web.Services é o namespace que nós usamos normalmente em a maioria dos projetos enquanto os tipos que nós necessitamos são definidos já neste namespace. Seguir é os membros do namespace de System.Web.Services:
|
WebMethodAttribute: Adicionando um <WebMethod () > o atributo a um método em um serviço da correia fotorreceptora faz o método acessível de um cliente remoto através do HTTP. Este atributo expõe a funcionalidade do método a que é aplicada ao mundo exterior.
|
WebService: Isto define a classe baixa opcional para serviços da correia fotorreceptora.
|
WebServiceAttribute: O atributo de WebService pode ser usado adicionar a informação a um serviço da correia fotorreceptora que possa a descrever seja funcionalidade.
|
WebServiceBindingAttribute: Declara um protocolo que obrigatório um método dado do serviço da correia fotorreceptora está executando.
|
Codificando um serviço da amostra |
Nós criaremos agora um serviço da amostra. Isto um serviço simples que convirta uma distância dada dos quilômetros às milhas e ao versa vice. Começar o estúdio visual .NET e abrir um projeto novo do projeto de File->New->. No tipo projetos básicos visuais seletos dos projetos da placa e nos moldes selecionar o serviço da correia fotorreceptora do ASP .NET, nomear este serviço como ConvertUnits e APROVAÇÃO do clique. O diálogo novo do projeto olha como a imagem abaixo
|
Pelo defeito, os projetos do serviço da correia fotorreceptora críam automaticamente um diretório virtual novo sob IIS e armazenarão nossas limas lá. Comutar à vista do código do serviço da correia fotorreceptora para fazer exame de você ao código atrás da lima que é uma lima com extensão de .asmx.vb. Se você observar a janela do explorador da solução você encontrará quatro limas que são os Global.asax, Service1.asmx, ConvertUnits.vsdisco e a lima de Web.config. A lima de Global.asax permite nós respondam aos eventos do global-nível, a lima de Web.config permite que nós configurem declaratively nosso serviço novo da correia fotorreceptora, a lima de .asmx é uma lima do serviço da correia fotorreceptora que definem os métodos do serviço e a lima de .vsdisco é uma lima da descoberta que contenha uma descrição de XML dos serviços da correia fotorreceptora em um URL dado.
|
Pelo defeito o código atrás da lima olha como este quando você a abre:
|
Imports
System.Web.Services
<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service2
Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
' WEB SERVICE EXAMPLE
' The HelloWorld() example service returns the string Hello World.
' To build, uncomment the following lines then save and build the project.
' To test this web service, ensure that the .asmx file is the start page
' and press F5.
''<WebMethod()> Public Function HelloWorld() As String
' HelloWorld = "Hello World"
' End Function
End Class
|
|
Nós construiremos no código acima mencionado atrás da lima. Nós executaremos alguma funcionalidade simples que adiciona nossos próprios métodos. O serviço que nós construiremos converterá a distância expressada nos quilômetros às milhas e ao versa vice. O código para aquele olha como este:
|
Imports
System
Imports System.Web.Services
<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service1 Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
#End Region
<WebMethod()> Public Function ConvertUnits(ByVal EnterUnit As Decimal, _
ByVal FromUnits As String, ByVal ToUnits As String)
'ConvertUnits function with three arguments
Select Case FromUnits.ToUpper.Chars(0)
'making a selection with Select Case
Case "K"
'for converting distance from kilometers to miles
Select Case ToUnits.ToUpper.Chars(0)
Case "K"
Return EnterUnit
'if both FromUnits and ToUnits are same, returns the entered distance
Case "M"
Return EnterUnit / 1.4
'converts distance from kilometers to miles, assuming 1 mile=1.4 kilometer
Case Else
'to throw exception
End Select
Case "M"
'for converting distance from miles to kilometers
Select Case ToUnits.ToUpper.Chars(0)
Case "M"
Return EnterUnit
Case "K"
Return EnterUnit * 1.4
'converts distance from miles to kilometers
Case Else
'to throw exception
End Select
End Select
End Function
End Class
|
|
Após terminar com o código funcioná-lo selecionando Debug->Start do menu principal ou pressionando F5 no teclado. Pelo defeito nosso browser funciona como um cliente temporário e mostra uma vista do HTML do mercado dos métodos com o <WebMethod () > atributo. Estalar aqui para ver a página que o primeiro carrega quando você funciona este serviço. Estalar sobre a ligação ConvertUnits. Estalar na ligação faz exame de você a uma página que forneça os tipos do Textbox que permitem que nós incorporem alguns valores a eles. Incorporar algum valor ao campo de EnterUnit e ao campo de FromUnits incorporar ou M ou K e no ToUnits arquivado incorpora K ou M. Se você desejar converter 1000 quilômetros em milhas então você necessita incorporar 1000 ao campo de EnterUnit, a K no FromUnits e a M no ToUnits. Uma vez que você é feito com ele, o clique invoca. Isto invocará o método que nós escrevemos no código e o resultado será retornado através de um atributo de XML. Estalar aqui para funcionar agora o serviço. Aquele é tudo que faz exame para criar um serviço simples da correia fotorreceptora.
|
Serviço 2 da amostra
|
Nesta seção nós criaremos um serviço da correia fotorreceptora da calculadora que os trabalhos similares a uma calculadora e executem operações como adicionar, subtraiam, multipliquem, se dividam e nós consumamos este serviço da correia fotorreceptora com uma aplicação básica visual de Windows. Para começar, para abrir um projeto novo e uma correia fotorreceptora seleta do ASP .NET prestar serviços de manutenção ou adicionar a um serviço novo da correia fotorreceptora ao projeto existente do serviço da correia fotorreceptora do ASP .NET direito-estalando o nome do projeto no explorador da solução e selecionando o serviço da correia fotorreceptora de Add->Add. Nomear este projeto como a calculadora, abrir o código atrás da lima e começá-lo escrever o seguinte código.
|
Sample Service 2
|
In this section we will create a Calculator Web service that works similar
to a Calculator and performs operations like Add, Subtract, Multiply,
Divide and we will consume this Web service with a Visual Basic Windows Application.
To start, open a new project and select ASP .NET Web service or add a new Web service
to the existing ASP .NET Web service project by right-clicking the project name in
Solution Explorer and selecting Add->Add Web service. Name this project as Calculator,
open the code behind file and start writing the following code.
|
Imports System
Imports System.Web.Services
<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service1
Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
#End Region
<WebMethod(Description:="Click to Add numbers")> Public Function
Add_
(ByVal x As Integer, ByVal y As Integer) As Integer
'this method adds two numbers by accepting the input from the user
'Description property allows to document the functionality of the Web method.
Return x + y
End Function
<WebMethod(Description:="Click to Subtract numbers")> Public
Function Subtract_
(ByVal x As Integer,ByVal y As Integer) As Integer
'this method subtracts by accepting the input from the user
Return x - y
End Function
<WebMethod(Description:="Click to Multiply numbers")> Public
Function Multiply_
(ByVal x As Integer,ByVal y As Integer) As Integer
'this method multiplies two numbers by accepting the input from the user
Return x * y
End Function
<WebMethod(Description:="Click to Divide numbers")> Public
Function Divide_
(ByVal x As Integer,ByVal y As Integer) As Integer
'this method divides two numbers by accepting the input from the user
If (y = 0) Then
Throw New Exception("Can't divide by zero")
'if number entered is 0 throws an exception
End If
Return x / y
End Function
End Class
|
|
Once when you finish with the code run the service by selecting Debug->Start from
the main menu or by pressing F5 on the keyboard. The Service that loads can be
viewed by
clicking here. You can view all the methods we created in code along with the
method description on that page. Also you can enter some values in the Textboxes
and test the service. We will consume this service in a Windows Form.
|
Consuming this Web service
|
Open a new Visual Basic Project and select Windows Application from the template.
From the toolbox add a Button to the form. Our intention here is to consume
the Web service which we created with this Windows Application.
When we click the Button it will call the method which
we specify in it's click event and will return the calculated result in a MessageBox.
|
Adding Web Service Reference to the Windows Application
|
We can add a reference to the Web service in two ways,
with Solution Explorer and using WSDL tool. In the Solution Explorer right click on
references and select Add Web Reference.
That opens up a template similar to the image below.
|
In the address bar type the URL of the Calculator service which we created.
Since it's in the root directory of IIS you need to type
the following address: http://localhost/Calculator/Service1.asmx.
It should look like the image below.
|
After the Calculator service is loaded, click Add Reference.
That adds a reference to the Calculator service.
|
To use WSDL tool to add a reference to this Web service,
open Visual Studio .NET command prompt, change the folder
in the command prompt to the location where you created Calculator and type the following:
|
WSDL "http://localhost/Calculator/Service1.asmx" /l:VB.
After you finish typing the command, in Solution Explorer, right-click Calculator,
select Add and then click Add Existing Item.
Locate Service1.vb, and then click to select it. Click Open.
|
Calling the Service from Windows Form
|
Open Form1 and place the following code.
Recall that we are calling a method when the Button in this application is clicked.
We need to create an instance of the proxy class localhost.Service1
and call the function, passing a string argument.
The code for that looks like this:
|
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
Dim myService As localhost.Service1 = New localhost.Service1()
'creating an instance
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
MessageBox.Show("Sum is " & myService.Add(10, 20))
'calling the Add method in the Web Service returning the result in a messagebox
End Sub
End Class
|
|
Once you finish with the application, run the form and click on the Button.
The sum of two numbers will be displayed in a MessageBox.
We not only created a Web service but also consumed the service in other application.
|
Sample Service 3
|
In this section we will build a more interesting Web service that returns a ADO .NET DataSet,
containing the full set of records from a table.
We will create our own database table and access the data from the table with this Web service.
To Start, open Microsoft Access and create a new Database named Currency.
Create a new table Table1 and add three columns named, Country Code, Country Name and Currency.
Enter some values in the table and close it.
Open Visual Studio .NET and select ASP .NET Web service from the projects type template.
Drag a OleDb connection from the Data tab in the toolbox and using the properties window build
a connection string that connects to the Currency database which we created.
Switch to the code view and start writing the following code.
|
Imports System
Imports System.Web.Services
Imports System.Data.OleDb
'import this namespace as we are working with an OleDb source
<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service1 Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
#End Region
<WebMethod()> Public Function GetData() As DataSet
'WebMethod name is GetData,generate data set
Dim da as OleDbDataAdapter=new OleDbDataAdapter("Select * From
Table1",_
OleDbConnection1)
'dataadapter
Dim ds As DataSet=new DataSet()
'declaring a new DataSet
da.Fill(ds, "Table1")
'filling dataadapter
Return ds
'returning dataset
End Function
End Class
|
|
Consuming the Service
|
Once you finish with coding the Web service we need to consume this service.
To do that, open a new Windows Application and from the toolbox drag a DataGrid and a Button.
Our intention here is to load the data from Table1 in the Currency database into the DataGrid
when we click the Button. Now, add a Web reference to the Web service
by selecting Reference->Add WebReference in the Solution Explorer Window.
Enter the URL of the service in the address bar and click "Add Reference".
That adds a reference to the Web Service.
Now double-click on the Button and write the following code.
|
Public Class Form1 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs)Handles Button1.Click
Dim myService As New localhost.Service1()
'an instance of the Web service
Dim ds1 As DataSet = myService.GetData
DataGrid1.DataSource = ds1.Tables("Table1")
'filling the datagrid with table
End Sub
End Class
|
|
Once you finish with the code, run the Windows Application and click on the Button.
The data you entered in Table1 of the Currency database will be displayed in the datagrid.
The difference, we are accessing the data with a Web service. The image below displays that.
|
 |
 |
Keywords:xml encryption, xml web services wsdl, xml specifications, xml signature
|
|
HTML Quizes |
|
XML Quizes |
|
Browser Scripting Quizes |
|
Server Scripting Quizes |
|
.NET (dotnet) Quizes |
|
Multimedia Quizes |
|
Web Building Quizes |
|
Java Quizes |
|
Programming Langauges Quizes |
|
Soft Skills Quizes |
|
Database Quizes |
|
Operating System Quizes |
|
Software Testing Quizes |
|
SAP Module Quizes |
|
Networking Programming Quizes |
|
Microsoft Office Quizes |
|
Accounting Quizes |
|
|