ASP.NET Code
  Home arrow ASP.NET Code arrow Creating a Webservice Part 1 of 2
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 CODE

Creating a Webservice Part 1 of 2
By: Dave - 123aspx.com
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2003-01-01

    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

    With some help from the great guys from 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.Here is a screenshot.

    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 Code Articles
    More By Dave - 123aspx.com

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Best practices for software analysis: An introduction to the IBM Rational Software Analyzer application

    This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Build Web services with transport-level security using Rational Application Developer V7, Part 1: Build Web services and Web services clients

    Build secure Web services with transport-level security using IBM Rational Application Developer V7 and IBM WebSphere Application Server V6.1. Follow this three-part series for step-by-step instructions about how to develop Web services and clients, configure HTTP basic authentication, and configure HTTP over SSL (HTTPS). This first part of the series walks you through building a Web service for a simple calculator application. You generate and test two different types of Web services clients: a Java Platform, Enterprise Edition (Java EE) client and a stand-alone Java client. You also handle user-defined exceptions in Web services.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    FREE! Go There Now!


    NEW! Rational Build Forge Express eKit

    Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast.
    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! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Using IBM Rational Developer for System z and IBM Rational ClearCase together to manage application development

    Whether you are creating new applications or modifying existing ones, managing integration of new components with traditional z/OS elements is a critical part of building and deploying modern applications. Listen to this webcast to see how IBM can help you optimize your development process using an IDE like Rational Developer for System z that integrates with management tools, such as ClearCase to manage your application development on mainframes.
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control





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