Creating a Webservice Part 1 of 2

Source: Internet
Author: User
Tags date config soap sql server connection string resource tostring web services wsdl
Web with some help from the great guys from Secure Webs, I decided to expose my site, http://www.123aspx.com, as a web SE Rvice. I wanted to-start with something simple and so I decided to expose the "What ' New" asp.net. The "What ' s New" section contains the latest additions to my site. This is a quick tutorial around writing that webservice.
WebServices in asp.net are built around the SOAP (simple Object Access Protocol) and WSDL (Web Services Description Langua GE). We ' re not going to get into the standards (WSDL, and SOAP), but instead, focus on creating a webservice and consuming it .


Planning
I decided to return a DataSet object as my collection the new resources. I chose a dataset because most ASP.net developers are already with familiar, and datasets can they as easily to data Grids. The dataset consists of 4 columns:
Name-the name or title of the resource.
Url-the URL to the resource
Domain-the Domain Name The resource can is found at.
Dateupdated-the date the resource was updated

Layout
We start programming a webservice by declaring it to the. NET engine and importing the following:
<%@ WebService language= "VB" class= "Aspx123websvc"%>
Option Strict on
Option Explicit on
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports system.web
Imports System.Web.Services
Imports Microsoft.VisualBasic
We also need to tell the compiler this class "Aspx123websvc" would be WebService enabled. We are inheriting the WebService namespace in the class declaration.
Public Class aspx123websvc:inherits WebService
Now so we have our classes defined, I went ahead and declared the main function.

Getting to It
Because we are declaring a method here, we need to mark it as a WebService method using <webmethod () >
Public Function getnewresources () as DataSet
I decided to add a friendly description to this method and to tell the consumer what this method does. When we view the default WSDL, supplied natively by asp.net, our description'll show is available to the consuming Progr Amer. Once we have our functions and classes declared, writing a webservice are just like writing no other codebehind file.

Accessing the Database
Now this I have my WebService framework in place, let's go ahead and get we our data. In this example, I need to massage the data a little bit, specifically the domain name of the asp.net resource. So what I decided to do, is to return a DataReader, strip off only the domain name of the resource (instead of returning The complete URL), and then builds the dataset that we'll eventually be returning. To access the database I use 2 utility functions. One function is called Getdatareader () and the other function is called sqlconnstring (). . Getdatareader () returns a SqlDataReader, it also takes advantage of System.Data.CommandBehavior.CloseConnection. System.Data.CommandBehavior.CloseConnection is a parameter that tells the framework to close the DataReader as soon as I ' m Done reading from it. Sqlconnstring () is used to read Me SQL Server connection string from the Web.config file. I ' ve included a snippet from me Web.config file to display how I ' m adding a appsettings section to WEB.Config.  
Getdatareader ()
Private Function Getdatareader (SQLText as String) as SqlDataReader
Dim Dr as SqlDataReader
Dim Sqlconn As SqlConnection = New SqlConnection (Sqlconnstring ())
Dim SQLCMD as SqlCommand = new SqlCommand (SQLText, sqlconn)

SqlCmd.Connection.Open ()
Dr = Sqlcmd.executereader (System.Data.CommandBehavior.CloseConnection)

Return Dr
End Function

Sqlconnstring ()
Private Function sqlconnstring () as String
Return System.Configuration.ConfigurationSettings.AppSettings ("websvcdb")
End Function

Web.config
<appSettings>
<add key= "websvcdb" value= "password=; User id=sa;initial catalog=pubs;data source=127.0.0.1; "/>
</appSettings>

Getting the Data
I have a stored procedure called "s_res_whats_new".  I execute the stored procedure to return the DataReader. I also create my dataset, that I'll be passing the webservice.
REM--Get the data from the database
Dim SQLText as String = "Exec s_res_whats_new"
Dim DBRead as SqlDataReader = Getdatareader (sqltext)

REM-Create the DataTable
Dim ds as DataSet = New DataSet ("Newresources")
Dim dt as DataTable = ds. Tables.add ("Resourcelist")
Dim Dr as DataRow




Assembling the DataSet
Once I had a DataReader back from my database, full of new resources, I Loop through the DataReader to create a dataset. The reason I didn ' t bring back the dataset directly, are because I needed to modify some of the data, before I sent it out As the webservice, mainly the Date and Domain name. I modify the date, to have a short date format, and I modify the URL to only return the domain name part of the URL. For example, if I am referencing the resource http://www.aspfree.com/authors/Default.asp, I only want to return WWW.ASPFR ee.com. Once I have the parameters URL, dateupdated, Domain, and Resource Name, I add them to a DataRow and add the Dataro W to a DataTable, which are part of the dataset. This is the code I with to loop through the DataReader and compile the dataset.
REM--Get the data from the database
Dim SQLText as String = "Exec s_res_whats_new"
Dim DBRead as SqlDataReader = Getdatareader (sqltext)

REM-Create the DataTable
Dim ds as DataSet = New DataSet ("Newresources")
Dim dt as DataTable = ds. Tables.add ("Resourcelist")
Dim Dr as DataRow

While Dbread.read ()
dateupdated = DateTime.Parse (Dbread.item ("res_dateupdated"). ToString ())
ResourceName = Dbread.item ("Res_name"). ToString ()
ResourceUrl = Dbread.item ("Res_url"). ToString ()
RESOURCEPK = Dbread.item ("RES_PK"). ToString ()

Resourcedomain = ""
If Len (resourceurl) >prot_prfx_len Then
REM-Strip off ' http://' and remove everything after. com,. NET, or. org, or less than characters
Urlwhatsnew = ResourceUrl & "/"
Resourcedomain = LCASE (left (urlwhatsnew, Prot_prfx_len, Instr (prot_prfx_len,urlwhatsnew, "/")-prot_prfx_len), Max_domain_len))
End If
Resourcedate = dateupdated.toshortdatestring ()
ResourceUrl = "http://www.123aspx.com/resdetail.asp?rid=" & RESOURCEPK

REM--Add to DataSet DS
Dr = dt. NewRow ()
Dr ("URL") = ResourceUrl
Dr ("dateupdated") = Resourcedate
Dr ("Domain") = Resourcedomain
Dr ("Name") = ResourceName

Dt. Rows.Add (DR)
End While


Here I am manipulated the "res_dateupdated" field by the-a-date of the-a-converting. Because SQL Server is storing the date as a long date (mm/dd/yy with seconds), I needed to parse the date  Mm/dd/yy. Creating a short date can do by the following line:
Res_date = date_dateupdated. ToShortDateString ()
I added each local variable to a column in a DataRow, and then added the "Row to the" DataSet. After the DataReader had finished looping, I returned the Dataset.

Testing
Test123aspxws.jpg
Now it is time to test my webservice.  asp.net provides a default page for testing webservices. If you look closely, you'll be description: "Returns the latest New and Updated resources at HTTP://WWW.123ASPX.C Om "So we used to describe we are Getnewresources.here is a screenshot.

asp.net returns a WebService in the form of the industry Strandard, WSDL protocol. The WSDL is an XML document that'll tell the consumer what methods are available to be called, and can considered a type of the API.  We can now test my WebService by clicking the Invoke button. This is a screen shot of the the ' the ' of the ' a ' of ' 3 ' and ' would be ' sent to the consumer.
Wsresults.jpg
Conclusion
ASP.net makes it extremely easy for the US to build webservices. Once we have a basic understanding of how asp.net works, it isn ' t so hard to extend our knowledge to WebServices


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.