Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Web Development  »  Web Services  »  Create Web Services and Web Forms Programmatically with the .NET Framework SDK. Part 1
Create Web Services and Web Forms Programmatically with the .NET Framework SDK. Part 1
by Matt Frame | Published  03/14/2002 | Web Services | Rating:
Matt Frame

Matt Frame is a Senior Software Engineer with Sorvive Technologies, Inc which provides web application services for B2B. He concentrates on web application development with multiple development tools and is currently evaluating the functionality of .Net and the .Net Framework. Matt continuously looks at emerging technologies to provide customers with the best solutions for their business needs.

 

View all articles by Matt Frame...
Create Web Services and Web Forms Programmatically with the .NET Framework SDK. Part 1

Article source code: websvc_prog.zip

Microsoft's release of Visual Studio .NET and the .NET Framework have been the most anticipated software to be released in recent years. This new architecture and development studio have revolutionized the way we think about developing web applications.

The first thing that happens when a new development tool is released is the flood of samples that promote the ease of use and rapid deployment of applications using wizards. These are fine to get adjusted to the tool but don't really satisfy the developers needs of knowing what is going on and how it works. This has definitely been the case with Visual Studio .NET. Finding out how to programmatically develop in ASP.NET has been difficult as there are plenty of samples utilizing wizards and drag-and-drop but very few in using straight code.

Well, I have poured through the documentation and read different articles and books about ASP.NET and now I want to demonstrate how to programmatically create a web service and a web form from scratch and without Visual Studio.NET.

For creating this sample application you need Windows 2000, SQL Server and the .NET Framework SDK installed. We will be using the pubs database for this tutorial. The .NET Framework SDK can be downloaded for free from http://msdn.microsoft.com/vstudio.

Configuring IIS

The first part of this exercise requires you to create two IIS Application directories. You must begin by creating a virtual root in IIS for your applications to run. This is done automatically by the IDE when creating a web service or web form project. First you need to create the directories under \inetpub\wwwroot. Open Windows Explorer and locate \inetpub\wwwroot. For our web service sample we need to create a directory called webservices and for the web form one called webforms under \inetpub\wwwroot. Then you must start the Internet Services Manager under Start -> Programs -> Administrative Tools and expand the Default Web Site. Locate the webservices directory, right click then select properties. In the Application Settings area click Create to transform your directory into an application. Click Ok and perform the same step for the webforms directory. Exit the Internet Services Manager.

Creating the Web Service

You can use any ASCII editor for entering the code. I used Notepad for this tutorial. Enter or cut-and-paste the following code and save it under \inetpub\wwwroot\webservices as EmployeeSVC.asmx. ASP.NET web services use an extension of .asmx.

<% @WebService Language="vb" Class="EmployeeSVC" %>
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Public Class EmployeeSVC
    Inherits System.Web.Services.WebService
    <WEBMETHOD< font>()>Public Function GetAllEmployees() As DataSet
    Dim dbConn As SqlConnection
    Dim dbDataAdapter As SqlDataAdapter
    Dim dsEmployee As DataSet
        dbConn = New SqlConnection("Data Source=(local);Initial " _
                                 & "Catalog=pubs;user id=usr;password=pwd")
        dbDataAdapter = New SqlDataAdapter("select * from employee"dbConn)    
        dsEmployee = New DataSet()  
        dbDataAdapter.Fill(dsEmployee"Employee")
        Return dsEmployee
    End Function
End Class
Generated using PrettyCode.Encoder

Make sure to change usr and pwd to match your user id and password for your database.

Since the .NET Framework uses the Just-in-Time compiler it will compile this code once it is requested. Open your browser and enter http://localhost/webservices/employeesvc.asmx for the URL. If you are running your web services on a separate machine make sure to substitute localhost with the server running IIS and your web service. If everything is correct then you should receive a screen that looks like Figure 1. If not compiler errors will be displayed in the browser with detail information about the problem.

ASP.NET automatically generates a web service test page. This screen displays all methods available and also recommends adding a local namespace before going productional with this module. We will fix this shortly but for now understand that your web service is now available for use.

Click on the link GetAllEmployees. You should now see a screen similar to Figure 2. This is a dynamically built .NET test page that allows you to work with your web service to verify that it works correctly. It also provides sample methods for calling your Web Service via different protocols.

To execute your web method, press the Invoke button under the test section. If you created a method that required parameters then input boxes would be here as well so you could enter them for your test. You should get a new browser window with the Employee dataset, which is an XML Schema of the Employee table followed by the Employee data. See Figure 3.

The Just-in-Time compiler or JIT compiles only the requested function within a Web Service. So the first call to GetAllEmployees() is longer than subsequent calls. The JIT only compiles methods when they are requested. So if you had more functions in EmployeeSVC.asmx they would not be compiled until requested. If you execute GetAllEmployees again you will see that execution time is faster since it has already been compiled.

Now that you have a working Web Service, lets review what the code is doing:

<% @WebService Language="vb" Class="EmployeeSVC" %>

The <%%>syntax is left over from the old ASP language. The @WebService directive identifies to .NET that this page exposes Web Services. The Language and Class declarations are self defining.

Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient

These statements reference Namespaces which can be thought of as libraries for the page to use the specific functionality of each.

Public Class EmployeeSVC

This statement defines the class for the Web Service. All web methods you write for this Web Service will be contained in this class. Even functions written to support your web methods will be inside this class but will not be made public unless you explicitly do so.

    Inherits System.Web.Services.WebService

This statement causes your web service to inherit all functionality contained in the namespace.

    <WEBMETHOD< font>()>Public Function GetAllEmployees() As DataSet

The <WEBMETHOD()>is an attribute that allows your function to be made available via your Web Service. This attribute can only be applied to Public Functions. The rest of this declaration is definitely familiar to any VB programmer.

    Dim dbConn As SqlConnection
    Dim dbDataAdapter As SqlDataAdapter
    Dim dsEmployee As DataSet
        dbConn = New SqlConnection("Data Source=(local);Initial " _
                                 & "Catalog=pubs;user id=usr;password=pwd")
        dbDataAdapter = New SqlDataAdapter("select * from employee"dbConn)    
        dsEmployee = New DataSet()  
        dbDataAdapter.Fill(dsEmployee"Employee")
        Return dsEmployee

This structure denotes typical Visual Basic logic with the exception of the new database connectivity objects which we will not cover here. One unique change in Visual Basic is that when a function returns data it is no longer returned by setting the function to the value. Instead a specific Return instruction is used. This was done to come inline with Microsoft's other development languages and the way the Common Language Runtime (CLR) was implemented.

    End Function
End Class

Close the function and the class.

Earlier I said we would fix the screen display in Figure 1 to stop reminding of us to use a permanent namespace here is that correction. On the same line as your Public Class statement but prior to the keyword Public insert the following:

<?XML:NAMESPACE PREFIX = WebService(Namespace /><WebService(Namespace:="http: ?) webservices microsoft.com>

The modified statement should read:

<WebService(Namespace:="http: ?) webservices microsoft.com>
Public Class EmployeeSVC

Before making a web service productional you should use your http://yourdomain.com/something/ to uniquely identify your web services.

That's it! Your web service is complete and ready to be consumed by a SOAP request. I know what you are thinking and you're right, this was too simple and that's why I said it's ready to be used by a SOAP request. You will see the steps necessary to utilize this service next in a web form.

In Part 2 we will cover Creating the Web Form...
How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:4 out of 5
 13 people have rated this page
Article Score17011
Article Series
Comments    Submit Comment

Comment #1  (Posted by Dave Clark on 03/15/2002)

Very concise, to the point article. The author doesn't waste any time showing us how to create a web service. I liked the fact that he was able to show us how to do it in Notepad, so we could concentrate on the code and not the tool.
 
Comment #2  (Posted by Lee on 09/02/2002)

Dear Author

I do find your codes very useful and informative. However i face a problem when i run the aspx file and it was due to the fact that the computer could not locate the namespace. I have followed closely to the instructions given but i have yet to solve the bug.

Could you please advise me on this matter.
Thanks a lot,
Lee


 
Comment #3  (Posted by Matt Frame on 09/03/2002)

Lee,

I would appreciate it if you could send me your current source code.

Thanks,

Matt

 
Comment #4  (Posted by Roger TaulĂ© on 01/04/2003)

I have found this article really interesting. Thank you.

The people who have problem in deploying the web service, be careful, there is a miss spelling letter in the html webservice code:

Wrong one:
dbConn = New SqlConnection("Data Source=(local);Initial " & "Catalog=pubs;User D=sa;password=juju")

Correct one:
dbConn = New SqlConnection("Data Source=(local);Initial " & "Catalog=pubs;User ID=sa;password=juju")

Change user and password to fit your system.

Siau!
 
Comment #5  (Posted by Matt Frame on 01/04/2003)

Roger,

Thanks for letting me know about that typo. I am working with the editor of the site to get it corrected. Hope everything else about the article helped you out in some way.

Thanks,

Matt
 
Comment #6  (Posted by Serge Baranovsky on 01/04/2003)

I corrected the user id problem. Thanks, Roger, for reporting this.
 
Comment #7  (Posted by carl culter on 03/09/2005)
Rating

http://localhost/webservices/employeesvc.asmx?op=GetAllEmployees

The test "Invoke" on this page throws a 500 error in a new browser. Looks like a db connection problem but no diagnostics given.

...& "Catalog=pubs;user id=;password=")
I left the user and password fields empty.Also tried:
user id=sa;password=")
user id=Administrator;password=")
I just installed sql 2000 and don't remember being asked for a password combo. Any suggestions.

cc
 
Comment #8  (Posted by Lam Giang on 07/07/2005)
Rating
Take a mention to this command line :

dbConn = New SqlConnection("Data Source=(local);Initial " _
& "Catalog=pubs;user id=usr;password=pwd")

If I want to use database on other server than (local)
I'll get error message :
System.Data.SqlClient.
SqlException: SQL Server does not exist or access denied

Do you have a solution ? Thank you !


 
Comment #9  (Posted by Lam Giang on 07/07/2005)

Sorry, I need make some information
I have written code like this :

Public Function GetCustomers() As DataSet
Dim cn As System.Data.SqlClient.SqlConnection
cn = New System.Data.SqlClient.SqlConnection("server=OtherServer;uid=sa;pwd=sa;database=Northwind")
cn.Open()
Dim da As System.Data.SqlClient.SqlDataAdapter
da = New System.Data.SqlClient.SqlDataAdapter("select * from Customers", cn)
Dim cust = New DataSet
da.Fill(cust, "Customers")
Return cust
End Function

and get the error
But I run these codes in Windows Application, like this :

Dim cn As System.Data.SqlClient.SqlConnection
cn = New System.Data.SqlClient.SqlConnection("server=OtherServer;uid=sa;pwd=sa;database=Northwind")
cn.Open()
Dim da As System.Data.SqlClient.SqlDataAdapter
da = New System.Data.SqlClient.SqlDataAdapter("select * from Customers", cn)
Dim cust = New DataSet
da.Fill(cust, "Customers")
Datagrid1.DataSourse = cust
Datagrid1.Refresh

program runs OK

where is the error ?


 
Comment #10  (Posted by an unknown user on 03/07/2007)
Rating
Its good
 
Comment #11  (Posted by an unknown user on 04/23/2007)
Rating
Excellent explanation.
 
Comment #12  (Posted by an unknown user on 05/31/2007)
Rating
can be understood by all
 
Comment #13  (Posted by John on 06/20/2007)
Rating
I followed the article "Create Web Services", everything worked perfectly, however I have a question about editing the data that was rendered in the webform is there a way edit this data and submitted back to table in the database?

Thank you
 
Comment #14  (Posted by an unknown user on 06/11/2008)
Rating
it gives detailed description
 
Sponsored Links