ASP.NET
  Home arrow ASP.NET arrow Creating an ASP.NET Webservice: Part 1 of ...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET

Creating an ASP.NET Webservice: Part 1 of 2
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    2001-07-14

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Creating a Webservice Part 1 of 2by Dave, webmaster of 123aspx.com   Secure Webs, I decided to expose my site, http://www.123aspx.com , as a web service. I wanted to start with something simple, so I decided to expose the "What's New" ASP.NET resources. The "what's new" section contains the latest 12 additions to my site. Here 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 Language). We're not going to get into these 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 of new resources. I chose a dataset because most ASP.NET developers are already familiar with datasets, and they can easily be bound to datagrids. 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 be 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 namespaces:      <%@ 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 that the class "AspX123WebSvc" will be webservice enabled. We do this by inheriting the WebService namespace in the class declaration. Public Class AspX123WebSvc : Inherits WebService Now that 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, to tell the consumer what this method does. When we view the default WSDL, supplied natively by ASP.NET, our description will show be available to the consuming programer. Once we have our functions and classes declared, writing a webservice is just like writing any other codebehind file.
    Accessing the Database Now that I have my webservice framework in place, let's go ahead and get our 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, was to return a datareader, strip off only the domain name of the resource (instead of returning the complete url), and then build the dataset that we will 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 my SQL Server connection string from the web.config file. I've included a snippet from my web.config file to display how I'm adding an 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 will be passing back to 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, is 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 was referencing the resource http://www.aspfree.com/authors/Default.asp, I only want to return www.aspfree.com. Once I have the parameters URL, DateUpdated, Domain, and Resource Name, I add them to a datarow and add the datarow to a datatable, which is part of the dataset. Here is the code I use 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 25 characters
            UrlWhatsNew = ResourceUrl & "/"
            ResourceDomain = LCASE(Left(Mid(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 manipulated the "res_dateupdated" field by first converting it to a date.  Because sql server is storing the date as a long date (mm/dd/yy with seconds),  I needed to parse the date to return only mm/dd/yy.  Creating a short date can be done 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
    Now it was time to test my webservice.  ASP.NET provides a default page for testing webservices.  If you look closely, you will see the description:"Returns the latest 12 New and Updated Resources at http://www.123aspx.com" that we used to describe our method GetNewResources.

    ASP.NET returns a webservice in the form of the industry strandard, WSDL protocol. WSDL is an XML document that will tell the consumer what methods are available to be called, and can be considered a type of API. We can now test our webservice by clicking the Invoke button.  Here is a screen shot of the first 3 rows of data that will be sent to the consumer.

    Conclusion
    ASP.NET makes it extremely easy for us to build webservices. Once we have a basic understanding of how ASP.NET works, it isn't that hard to extend our knowledge to webservices.
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP.NET Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    Be the first to hear about i5/OS V6R1!

    Hold your calendar on January 30, 2008 for this free webcast on the new i5/OS. Rational's Enterprise Modernization products will be discussed at this webcast as they help to drive the application development environment for this new System i OS. <br />And learn how i5/OS will take you to the next step of efficient, resilient business processing. You will hear about the new i5/OS capabilities as it will be the most significant i5/OS release in years. If you cannot join the webcast on 1/30/08 you can still use this link to listen to the replay.<br />
    FREE! Go There Now!


    NEW! Download DB2 9.5 for Linux, Unix, and Windows

    Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Software Analyzer V7.0

    Download a free trial version of IBM Rational Software Analyzer Developer Edition V7.0 to identify bug defects earlier in the software development cycle. Rational Software Analyzer is an extensible software development solution that reduces the expense of bug-fixes by enabling static analysis code reviews and bug identification very early in the development cycle.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! IBM Rational ClearCase Innovator's Series

    Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Rational Testing eKits

    Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET ARTICLES

    - Develop Your First ASP.NET Website with Visu...
    - Run ASP.NET in Windows XP Home with Cassini ...
    - How to Test a Web Application
    - How to Add Code and Validation Controls to a...
    - Working in Source and Split Views to Build a...
    - How to Build a Web Form for a One-Page Web A...
    - How to Develop a One-Page Web Application
    - An ASP.NET Web Application in Action
    - Developing ASP.NET Web Applications
    - An Introduction to ASP.NET Web Programming
    - Introduction to the ADO.NET Entity Framework...
    - Completing an In-Text Advertising System und...
    - Programming an In-Text Advertising System un...
    - Building an In-Text Advertising System Under...
    - Developing a Mini ASP.NET AJAX Server Centri...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT