This is what we want to achieve. Once we type student ID in the textbox and when we click "Get Student" button we want to
1. Invoke StudentWebService from javascript using asp.net AJAX
2. The student web service should return the specific student data from a database table.
3. The returned data should be displayed in the respective textbox controls on the web form.
Step 1: Create tblStudents table
Create Table tblStudents
(
ID int identity primary key,
Name nvarchar(50),
Gender nvarchar(20),
TotalMarks int
)
Insert into tblStudents values('Mark Hastings','Male',900)
Insert into tblStudents values('Pam Nicholas','Female',760)
Insert into tblStudents values('John Stenson','Male',980)
Insert into tblStudents values('Ram Gerald','Male',990)
Insert into tblStudents values('Ron Simpson','Male',440)
Insert into tblStudents values('Able Wicht','Male',320)
Insert into tblStudents values('Steve Thompson','Male',983)
Insert into tblStudents values('James Bynes','Male',720)
Insert into tblStudents values('Mary Ward','Female',870)
Insert into tblStudents values('Nick Niron','Male',680)
Step 2: Create a stored procedure to retrieve student data from tblStudents table by student ID
Create Proc spGetStudentByID
@ID int
as
Begin
Select ID, Name, Gender, TotalMarks
from tblStudents where ID = @ID
End
Step 3: Create a new asp.net empty web application and name it WebServicesDemo
Step 4: Right click on WebServicesDemo project in the solution explorer and add a class file and name it Student.cs. Copy and paste the following code.
namespace WebServicesDemo
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int TotalMarks { get; set; }
}
}
Step 5: Right click on WebServicesDemo project in the solution explorer and add a web service and name it StudentService.asmx.
Step 6: Copy and paste the following code in StudentService.asmx.cs file. Make sure [System.Web.Script.Services.ScriptService] attribute is included. This attribute allows a web service to be called from JavaScript using asp.net ajax.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
namespace WebServicesDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class StudentService : System.Web.Services.WebService
{
[WebMethod]
public Student GetStudentByID(int ID)
{
Student student = new Student(); ;
string cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetStudentByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("@ID", ID);
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
student.ID = Convert.ToInt32(reader["ID"]);
student.Name = reader["Name"].ToString();
student.Gender = reader["Gender"].ToString();
student.TotalMarks = Convert.ToInt32(reader["TotalMarks"]);
}
}
return student;
}
}
}
Step 7: Right click on WebServicesDemo project in the solution explorer and add a web form. This should add WebForm1.aspx.
Step 8: Copy and paste the following HTML between the opening and closing <html></html> tags in WebForm1.aspx
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function GetStudentById()
{
var id = document.getElementById("txtStudentId").value;
WebServicesDemo.StudentService.GetStudentByID(id,
GetStudentByIdSuccessCallback, GetStudentByIdFailedCallback);
}
function GetStudentByIdSuccessCallback(result)
{
document.getElementById("txtName").value = result["Name"];
document.getElementById("txtGender").value = result["Gender"];
document.getElementById("txtTotalMarks").value = result["TotalMarks"];
}
function GetStudentByIdFailedCallback(errors)
{
alert(errors.get_message());
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/StudentService.asmx" />
</Services>
</asp:ScriptManager>
<table style="font-family:Arial; border:1px solid black">
<tr>
<td><b>ID</b></td>
<td>
<asp:TextBox ID="txtStudentId" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="Get Student" onclick="GetStudentById()" />
</td>
</tr>
<tr>
<td><b>Name</b></td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td><b>Gender</b></td>
<td>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td><b>Total Marks</b></td>
<td>
<asp:TextBox ID="txtTotalMarks" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<h1>
The
time below does not change, when we click Get Student button as we are
doing partial page post back and not a full page postback.
</h1>
<asp:Label ID="lblPageTime" runat="server"></asp:Label>
</form>
</body>
Step 9: Copy and paste the following code in Page_Load() event of WebForm1.aspx.cs
lblPageTime.Text = DateTime.Now.ToString();
Step 10: Add Connection string in web.config file
<configuration>
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=Vamsi\SQLEXPRESS;Integrated Security=true;Initial Catalog=Sample" providerName="System.Data.SqlClient" />
</connectionStrings>
Few Questions from youtube subscribers:
Could
you explain how an object-oriented application such as ASP.NET web
application can make use of web services to access a relational database
?
we discussed exactly the same thing. ASP.NET Web application calls the
web service, and the web service has ado.net code to retrieve data from a
relational database.
Just like an asp.net web application, a
web service can work with any type of datastore (Relational databases,
xml file, text file, access, excel etc)
Where does ADO.NET and XML webservices come in architecture?
Most of the real time applications have 3 or more layers. The most common layers in many of the applications are as follows
1. User Interface of Presentation Layer - Contains only the UI logic
2. Business Logic Layer - Contains logic to validate business rules
3. Data Access Layer - Performs the database CRUD operations
With respect to the above architecture
Web services belong to Business Logic Layer
ADO.NET belong to Data Access Layer
How to call a webservice from the web form without reloading the entire web page?
OR
How to call a webservice without full page postback?
Call the web
service using ASP.NET AJAX, which allows partial page postback. With
partial page postback, only specific portion of the page is updated
without reloading the entire page which is better for performance and
avoids screen flickers.
Showing posts with label Web Services. Show all posts
Showing posts with label Web Services. Show all posts
Mar 14, 2014
Mar 13, 2014
Web Services Faqs
1. What are Windows services?
Windows
services, previously known as NT services, are applications that are
installed on the system as system services. In other words, Windows
services are applications that run in the background with the Windows
operating system. The primary use of Windows services is to reduce the
consumption of memory required for performing backend operations. Let's
take an example to understand this easily. Suppose you want to perform a
variety of functions, such as monitor the performance of your computer
or application, check the status of an application, and manage various
devices, such as printers.
In such a case, you can use Windows services to reduce memory consumption. In addition, Windows services can run on your system even if you have not logged on to your computer. In addition, these services do not have any user interface.
In such a case, you can use Windows services to reduce memory consumption. In addition, Windows services can run on your system even if you have not logged on to your computer. In addition, these services do not have any user interface.
2. Can you share a process between Windows services?
Yes, you can share a process between Windows services.
3. In .NET, which is the parent class to create all Windows services?
The ServiceBase class is the parent class to create all Windows services.
4. Which class in .NET is used to install a Windows service?
The ServiceInstaller class, also known as the project installer class, is used to install a Windows service.
Write the file extension for a Web service.
Write the file extension for a Web service.
A Web service file extension is .asm file. For example, service1.asmx is a Web service file.
Which method is used to uninstall the Windows services?
Which method is used to uninstall the Windows services?
The Uninstall() method is used to uninstall the Windows services.
Explain the WSDL.
WSDL is a short form for Web Services Description Language, which is used to describe a Web service in terms of the messages that it creates and accepts. The WSDL document is an XML file that contains the interface schema for the Web service. It identifies the methods that are used during the exchange between a Web service consumer and a Web service provider. The following are the elements contained in the WSDL document:
Explain the WSDL.
WSDL is a short form for Web Services Description Language, which is used to describe a Web service in terms of the messages that it creates and accepts. The WSDL document is an XML file that contains the interface schema for the Web service. It identifies the methods that are used during the exchange between a Web service consumer and a Web service provider. The following are the elements contained in the WSDL document:
- Types - Describe the variations of data types that are used to exchange messages between the user and the provider.
- Message - Describes the actual message or method call.
- portType - Describes the set of operations and each related message.
- binding - Describes the protocol details.
- service - Used to make groups a set of related ports together.
The
UDDI directory has an advantage over a DISCO file, as it provides a
single location where a client can find the Web services offered by
different organizations.
How can you ensure that only authorized users access your Web service?
How can you ensure that only authorized users access your Web service?
You should use the <authorization>
element to ensure that only authorized users access your Web service.
This element allows or denies access to your Web service according to
their role.
Describe the EventLog class.
Describe the EventLog class.
The EventLog class is used to access the Windows event logs from Windows services. Using EventLog,
you can also customize Windows event logs that record information about
important software and hardware events, such as the events of the .NET
controls, keyboard, or other hardware devices.
The EventLog class allows you to read or write to event logs, delete logs, and create as well as delete event sources. You can use the EventLog class to create event logs while creating an event source. An event source can be used to write to only one event log at a particular time. However, it is possible to associate one event log to multiple sources.
How can you prevent your Web services from unauthorized access?
The following are the ways to prevent your Web service from unauthorized access:
The EventLog class allows you to read or write to event logs, delete logs, and create as well as delete event sources. You can use the EventLog class to create event logs while creating an event source. An event source can be used to write to only one event log at a particular time. However, it is possible to associate one event log to multiple sources.
How can you prevent your Web services from unauthorized access?
The following are the ways to prevent your Web service from unauthorized access:
- Using encryption and message-based security.
- Using authentication and access controls for the Web service.
A
Web service may be defined as an independent and self-sustained unit of
a software application that is hosted on the Web and implement specific
functionalities to execute the business logic. A Web service provides
so many functionalities, such as generating pay slips for employees,
computing tax, broadcasting weather report, and providing updated news.
The Web service allows application to share information or exchange data
with other applications across different operating systems and
hardware.
Therefore, the work of a Web service is to unite software by exchanging data irrespective of their operating systems, supported hardware, and programming language used in their development. The Web services transfer data in the XML format and use Simple Object Access Protocol (SOAP) to communicate. It is an XML based protocol. The Web services use Web Services Description Language (WSDL) and Universal Description, Discovery, and Integration (UDDI) to describe itself.
What advantages have Web services over Component Object Model (COM) and Distributed Component Object Model (DCOM)?
The advantages of Web services over COM and DCOM are as follows:
Therefore, the work of a Web service is to unite software by exchanging data irrespective of their operating systems, supported hardware, and programming language used in their development. The Web services transfer data in the XML format and use Simple Object Access Protocol (SOAP) to communicate. It is an XML based protocol. The Web services use Web Services Description Language (WSDL) and Universal Description, Discovery, and Integration (UDDI) to describe itself.
What advantages have Web services over Component Object Model (COM) and Distributed Component Object Model (DCOM)?
The advantages of Web services over COM and DCOM are as follows:
- Web services are simple to use and can be implemented on varied platforms.
- Web services are loosely coupled; as a result, their interfaces and methods can be extended.
- Web services do not carry any state information with them so that multiple requests can be processed simultaneously.
System.Web.Services is the elementary namespace, which must be imported to develop code of a Web service.
What is DISCO?
What is DISCO?
DISCO
is a technology developed by Microsoft to publish and discover Web
services. It discovers URLs of all XML Web services located on a Web
server and creates a list of these Web services in a file called as a
DISCO file.
Which two methods are used to discover the URL of Web services?
Which two methods are used to discover the URL of Web services?
The two methods to discover the URL of Web services are Web service discovery tool (Disco.exe) and UDDI.
Which step is necessary to perform before a Web service can be consumed?
Which step is necessary to perform before a Web service can be consumed?
It is necessary to build a proxy class by using the wsdl.exe utility before a Web service can be consumed.
Which property of the WebMethod attribute allows you to maintain the state of objects across sessions in a Web method?
Which property of the WebMethod attribute allows you to maintain the state of objects across sessions in a Web method?
The WebMethod attribute's EnableSession property enables you to enable session state for a Web method.
What do you understand by SOAP encoding?
What do you understand by SOAP encoding?
The
Serialization of the types, such as integers and strings, inside a SOAP
message is called encoding. The SOAP objects use XML elements and
attributes to serialized data, for example, encodingStyle is an attribute of the Envelop element, which is used to specify the encoding rules for a SOAP object.
What is the use of a .disco file?
What is the use of a .disco file?
A client application uses a .disco
file to locate or discover the documents that contain the description
of a Web service. The .disco file contains links to other resources,
which describe essential features, such as capabilities of a Web
service. The links contained in a .disco file
can refer to other discovery documents or XSD schemas. The description
about the services and capabilities of a Web service is written in Web
services Description Language (WSDL). A .disco file can also contain the information about other XML Web services that reside on the same or a different Web server.
Does a Web service have state?
Does a Web service have state?
The
Web services do not have any technique to maintain state. However, it
can access ASP.NET objects, such as application and session if they
extend from the WebService base class.
| How to make a method of a web service class accessible through the internet? | |||||
[WebMethod()]
public string MethodName()
HTTP GET
HTTP POST
SOAP
Can you give example for SOAP Format?
< soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
< soap:Header>
...
...
< /soap:Header>
< soap:Body>
...
...
< soap:Fault>
...
...
< /soap:Fault>
...
< /soap:Body>
< /soap:Envelope>
what is the difference between Synchronous and ASynchronous web methods?
A synchronous method call waits for the method to complete before continuing with program flow,
whereas an asynchronous method call will return immediately so that the
program can perform other operations while the called method completes
its work
How can we overload a webmethod?
WebMethods can't have the same name, We can achieve this by using MessageName property of the WebMethod.
[WebMethod (MessageName="HelloWorld")]
public string HelloWorld()
{
return "HelloWorld";
}
[WebMethod (MessageName="HelloWorldWithName")]
public string HelloWorld(string name)
{
return "HelloWorld " + name;
}
How do you handle session in webservices?
ASP.NET Web Services allows you to access the underlying state management provided by ASP.NET. To enable ASP.NET session state, set WebMethod.EnableSession = True. On the client you must also set serviceName.CookieContainer to a new instance of System.Net.CookieContainer.
Client-Side Code
//On the client you must add the following code (for session state only): serviceName.CookieContainer = new System.Net.CookieContainer();
Server-Side Code
//Setting EnableSession to true allows state to be persisted per Session
[WebMethod(EnableSession=true)]
public String UpdateSessionHitCounter()
{
//update the session "HitCounter" here
return Session["HitCounter"].ToString(); }
What are WebMethod attribute properties?
WebMethod attribute has the following properties
Description , TransactionOption, CacheDuration, BuffferResponse, EnableSession, MessageName
Example
[WebMethod(Description = "My WebMethod Description comes here")]
[WebMethod(EnableSession ="true")]
[WebMethod(MessageName = "SinInt")]
[WebMethod(TransactionOption = "Supported")]
[WebMethod(CacheDuration = "180")]
[WebMethod(BufferResponse = "true")]
what is One-Way (Fire-and-Forget) Communication in webservice?
Consider using the OneWay attribute if you do not require a response.
Using the OneWay property of SoapDocumentMethod and SoapRpcMethod in the System.Web.Services.
Protocols namespace frees the client immediately instead of forcing it to wait for a response.
[SoapDocumentMethod(OneWay=true)]
[WebMethod(Description="Returns control immediately")]
public void SomeMethod()
{…}
This is useful if the client needs to send a message, but does not expect anything as return values or output parameters.
Methods marked as OneWay cannot have output parameters or return values.
what are the two Activation modes for .NET Remoting?
Singleton
Singlecall
< soap:Fault>
...
...
< /soap:Fault>
...
< /soap:Body>
< /soap:Envelope>
|
Labels:
Web Services,
Web Services Faqs
WebMethod overloading in Asp.net web services
Method overloading allows a class to have multiple methods with the same name, but, with a different signature. So, in C# methods can be overloaded based on the number, type(int, float etc) and the kind(Value, Ref or Out) of parameters.
WebMethods in a web service can also be overloaded. Notice that the Add() functions below are overloaded based on the number of parameters. The first method adds 2 numbers and the second one adds 3 numbers.
[WebMethod]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
[WebMethod]
public int Add(int firstNumber, int secondNumber, int thirdNumber)
{
return firstNumber + secondNumber + thirdNumber;
}
When we build the solution, it builds successfully. But when we run the web service and try to view the service page we get an exception at runtime -
Both Int32 Add(Int32, Int32, Int32) and Int32 Add(Int32, Int32) use the message name 'Add'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.
To fix this use MessageName property of the WebMethod attribute. MessageName property is used to uniquely identify the individual XML Web service methods.
[WebMethod(MessageName="Add3Numbers")]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
When we now try to view the service page we get a different exception -
Service 'WebServicesDemo.CalculatorWebService' does not conform to WS-I Basic Profile v1.1. Please examine each of the normative statement violations below. To turn off conformance check set the ConformanceClaims property on corresponding WebServiceBinding attribute to WsiClaims.None.
R2304: Operation name overloading in a wsdl:portType is disallowed by the Profile. A wsdl:portType in a DESCRIPTION MUST have operations with distinct values for their name attributes. Note that this requirement applies only to the wsdl:operations within a given wsdl:portType. A wsdl:portType may have wsdl:operations with names that are the same as those found in other wsdl:portTypes.
- Operation 'Add' on portType 'CalculatorWebServiceSoap' from namespace 'http://pragimtech.com/webservices'.
To make service conformant please make sure that all web methods belonging to the same binding have unique names.
To fix this error, change WebServiceBinding attribute on the web service class
FROM - [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
TO - [WebServiceBinding(ConformsTo = WsiProfiles.None)]
When we create a new webservice in Visual Studio 2005 or 2008, the IDE automatically adds the WebServiceBinding attribute on the web service class.
Step 2: The next step is to update the proxy class in the client application, that is in the CalculatorWebApplication.
To achieve this, right click on CalculatorService in Service References folder and select Update Service Reference option.
Step 3: Copy and paste the following HTML in WebForm1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="font-family: Arial">
<tr>
<td>
<b>First Number</b>
</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Second Number</b>
</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Third Number</b>
</td>
<td>
<asp:TextBox ID="txtThirdNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Result</b>
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
<td>
<b>Result1</b>
</td>
<td>
<asp:Label ID="lblResult1" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick="btnAdd_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvCalculations" runat="server">
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code:
namespace CalculatorWebApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorWebServicesSoapClient client =
new CalculatorService.CalculatorWebServicesSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString();
int Result2 = client.Add1(Convert.ToInt32(txtFirstNumber.Text), Convert.ToInt32(txtSecondNumber.Text), Convert.ToInt32(txtThirdNumber.Text));
lblResult1.Text = Result2.ToString();
}
}
}
Build the solution and Run the application
o/p:
Possible web services interview question?
Is method overloading possible in web services?
Yes, use MessageName property of WebMethod attribute.
WebMethods in a web service can also be overloaded. Notice that the Add() functions below are overloaded based on the number of parameters. The first method adds 2 numbers and the second one adds 3 numbers.
[WebMethod]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
[WebMethod]
public int Add(int firstNumber, int secondNumber, int thirdNumber)
{
return firstNumber + secondNumber + thirdNumber;
}
When we build the solution, it builds successfully. But when we run the web service and try to view the service page we get an exception at runtime -
Both Int32 Add(Int32, Int32, Int32) and Int32 Add(Int32, Int32) use the message name 'Add'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.
To fix this use MessageName property of the WebMethod attribute. MessageName property is used to uniquely identify the individual XML Web service methods.
[WebMethod(MessageName="Add3Numbers")]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
When we now try to view the service page we get a different exception -
Service 'WebServicesDemo.CalculatorWebService' does not conform to WS-I Basic Profile v1.1. Please examine each of the normative statement violations below. To turn off conformance check set the ConformanceClaims property on corresponding WebServiceBinding attribute to WsiClaims.None.
R2304: Operation name overloading in a wsdl:portType is disallowed by the Profile. A wsdl:portType in a DESCRIPTION MUST have operations with distinct values for their name attributes. Note that this requirement applies only to the wsdl:operations within a given wsdl:portType. A wsdl:portType may have wsdl:operations with names that are the same as those found in other wsdl:portTypes.
- Operation 'Add' on portType 'CalculatorWebServiceSoap' from namespace 'http://pragimtech.com/webservices'.
To make service conformant please make sure that all web methods belonging to the same binding have unique names.
To fix this error, change WebServiceBinding attribute on the web service class
FROM - [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
TO - [WebServiceBinding(ConformsTo = WsiProfiles.None)]
When we create a new webservice in Visual Studio 2005 or 2008, the IDE automatically adds the WebServiceBinding attribute on the web service class.
Step 2: The next step is to update the proxy class in the client application, that is in the CalculatorWebApplication.
To achieve this, right click on CalculatorService in Service References folder and select Update Service Reference option.
Step 3: Copy and paste the following HTML in WebForm1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="font-family: Arial">
<tr>
<td>
<b>First Number</b>
</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Second Number</b>
</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Third Number</b>
</td>
<td>
<asp:TextBox ID="txtThirdNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Result</b>
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
<td>
<b>Result1</b>
</td>
<td>
<asp:Label ID="lblResult1" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick="btnAdd_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvCalculations" runat="server">
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code:
namespace CalculatorWebApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorWebServicesSoapClient client =
new CalculatorService.CalculatorWebServicesSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString();
int Result2 = client.Add1(Convert.ToInt32(txtFirstNumber.Text), Convert.ToInt32(txtSecondNumber.Text), Convert.ToInt32(txtThirdNumber.Text));
lblResult1.Text = Result2.ToString();
}
}
}
Build the solution and Run the application
o/p:
Possible web services interview question?
Is method overloading possible in web services?
Yes, use MessageName property of WebMethod attribute.
Labels:
Web Services
WebMethod attribute properties In Web Services
http://mvkr.blogspot.in/2014/03/how-to-create-aspnet-web-services.html
http://mvkr.blogspot.in/2014/03/how-to-consuming-web-service-in-aspnet.html
http://mvkr.blogspot.in/2014/03/how-to-use-aspnet-session-state-in-web.html
Please go through the link before you proceed for this article
Description -
Use to specify a description for the web service method
[WebMethod(EnableSession=true,Description="add 2 numbers and return their sum",CacheDuration=20)]
BufferResponse -
This is a boolean property. Default is true. When this property is true, the response of the XML Web service method is not returned to the client until either the response is completely serialized or the buffer is full.
On the other hand, when this property is false, the response of the XML Web service method is returned to the client as it is being serialized.
In general, set BufferResponse to false, only when the XML Web service method returns large amounts of data. For smaller amounts of data, web service performance is better when BufferResponse is set to true.
CacheDuration -
Use this property, if you want to cache the results of a web service method. This is an integer property, and specifies the number of seconds that the response should be cached. The response is cached for each unique parameter.
O/P:
Enter the same comibination for adding example 3,3 it will not add another record with in 20 seconds
http://mvkr.blogspot.in/2014/03/how-to-use-aspnet-session-state-in-web.html
Please go through the link before you proceed for this article
Description -
Use to specify a description for the web service method
[WebMethod(EnableSession=true,Description="add 2 numbers and return their sum",CacheDuration=20)]
BufferResponse -
This is a boolean property. Default is true. When this property is true, the response of the XML Web service method is not returned to the client until either the response is completely serialized or the buffer is full.
On the other hand, when this property is false, the response of the XML Web service method is returned to the client as it is being serialized.
In general, set BufferResponse to false, only when the XML Web service method returns large amounts of data. For smaller amounts of data, web service performance is better when BufferResponse is set to true.
CacheDuration -
Use this property, if you want to cache the results of a web service method. This is an integer property, and specifies the number of seconds that the response should be cached. The response is cached for each unique parameter.
O/P:
Enter the same comibination for adding example 3,3 it will not add another record with in 20 seconds
Labels:
Web Services
How to Use ASP.NET Session State in a Web Service
http://mvkr.blogspot.in/2014/03/how-to-create-aspnet-web-services.html
http://mvkr.blogspot.in/2014/03/how-to-consuming-web-service-in-aspnet.html
Please go through the link before you proceed for this article
To use asp.net session object in a web service, the web service class must inherit from System.Web.Services.WebService class and EnableSession property of WebMethod attribute must be set to true.
Let us now use Session object with the Calculator Service that we have built in Part 2.
We want to display all the calculations that a user has performed as shown below. Here are the steps to achieve this.
Step 1: Copy and paste the following code in CalculatorWebServices.asmx file
using System.Web.Services;
using System.Collections.Generic;
namespace WebServicesDemo
{
[WebService(Namespace = "http://pragimtech.com/webservices")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class CalculatorWebServices : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public int Add(int firstNumber, int secondNumber)
{
List<string> calculations;
if (Session["CALCULATIONS"] == null)
{
calculations = new List<string>();
}
else
{
calculations = (List<string>)Session["CALCULATIONS"];
}
string strTransaction = firstNumber.ToString() + " + "
+ secondNumber.ToString()
+ " = " + (firstNumber + secondNumber).ToString();
calculations.Add(strTransaction);
Session["CALCULATIONS"] = calculations;
return firstNumber + secondNumber;
}
[WebMethod(EnableSession = true)]
public List<string> GetCalculations()
{
if (Session["CALCULATIONS"] == null)
{
List<string> calculations = new List<string>();
calculations.Add("You have not performed any calculations");
return calculations;
}
else
{
return (List<string>)Session["CALCULATIONS"];
}
}
}
}
Step 2: The next step is to update the proxy class in the client application, that is in the CalculatorWebApplication.
To achieve this, right click on CalculatorService in Service References folder and select Update Service Reference option.
Step 3: Copy and paste the following HTML in WebForm1.aspx
<table style="font-family: Arial">
<tr>
<td>
<b>First Number</b>
</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Second Number</b>
</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Result</b>
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick="btnAdd_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvCalculations" runat="server">
</asp:GridView>
</td>
</tr>
</table>
Step 4: Copy and paste the following code in WebForm1.aspx.cs
using System;
namespace CalculatorWebApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorWebServicesSoapClient client =
new CalculatorService.CalculatorWebServicesSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString();
gvCalculations.DataSource = client.GetCalculations();
gvCalculations.DataBind();
gvCalculations.HeaderRow.Cells[0].Text = "Recent Calculations";
}
}
}
Step 5: In web.config file of CalculatorWebApplication, set allowCookies attribute to true.
<basicHttpBinding>
<binding allowCookies="true" name="CalculatorWebServicesSoap" />
</basicHttpBinding>
When allowCookies attribute is set to true, the client application accepts the cookie returned from the ASMX web service, and copies it into all future requests that are made to the web service. This ensures that the same session is maintained between the client and the web service.
O/p:
http://mvkr.blogspot.in/2014/03/how-to-consuming-web-service-in-aspnet.html
Please go through the link before you proceed for this article
To use asp.net session object in a web service, the web service class must inherit from System.Web.Services.WebService class and EnableSession property of WebMethod attribute must be set to true.
Let us now use Session object with the Calculator Service that we have built in Part 2.
We want to display all the calculations that a user has performed as shown below. Here are the steps to achieve this.
Step 1: Copy and paste the following code in CalculatorWebServices.asmx file
using System.Web.Services;
using System.Collections.Generic;
namespace WebServicesDemo
{
[WebService(Namespace = "http://pragimtech.com/webservices")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class CalculatorWebServices : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public int Add(int firstNumber, int secondNumber)
{
List<string> calculations;
if (Session["CALCULATIONS"] == null)
{
calculations = new List<string>();
}
else
{
calculations = (List<string>)Session["CALCULATIONS"];
}
string strTransaction = firstNumber.ToString() + " + "
+ secondNumber.ToString()
+ " = " + (firstNumber + secondNumber).ToString();
calculations.Add(strTransaction);
Session["CALCULATIONS"] = calculations;
return firstNumber + secondNumber;
}
[WebMethod(EnableSession = true)]
public List<string> GetCalculations()
{
if (Session["CALCULATIONS"] == null)
{
List<string> calculations = new List<string>();
calculations.Add("You have not performed any calculations");
return calculations;
}
else
{
return (List<string>)Session["CALCULATIONS"];
}
}
}
}
Step 2: The next step is to update the proxy class in the client application, that is in the CalculatorWebApplication.
To achieve this, right click on CalculatorService in Service References folder and select Update Service Reference option.
Step 3: Copy and paste the following HTML in WebForm1.aspx
<table style="font-family: Arial">
<tr>
<td>
<b>First Number</b>
</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Second Number</b>
</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Result</b>
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick="btnAdd_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvCalculations" runat="server">
</asp:GridView>
</td>
</tr>
</table>
Step 4: Copy and paste the following code in WebForm1.aspx.cs
using System;
namespace CalculatorWebApplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorWebServicesSoapClient client =
new CalculatorService.CalculatorWebServicesSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString();
gvCalculations.DataSource = client.GetCalculations();
gvCalculations.DataBind();
gvCalculations.HeaderRow.Cells[0].Text = "Recent Calculations";
}
}
}
Step 5: In web.config file of CalculatorWebApplication, set allowCookies attribute to true.
<basicHttpBinding>
<binding allowCookies="true" name="CalculatorWebServicesSoap" />
</basicHttpBinding>
When allowCookies attribute is set to true, the client application accepts the cookie returned from the ASMX web service, and copies it into all future requests that are made to the web service. This ensures that the same session is maintained between the client and the web service.
O/p:
Labels:
Web Services
Mar 12, 2014
How to Consuming a web service in Asp.net
http://mvkr.blogspot.in/2014/03/how-to-create-aspnet-web-services.html
Please go through the link before you proceed for this article
Step 1: Right click on WebServicesDemo solution in solution explorer and add new asp.net web application project and name it CalculatorWebApplication.
Step 2: Now we need to add a reference to web service. To achieve this
a) Right click on References folder in the CalculatorWebApplication project and select Add Service Reference option
b) In the Address textbox of the Add Service Reference window, type the web service address and click GO button. In the namespace textbox type CalculatorService and click OK.
Step 1: Right click on WebServicesDemo solution in solution explorer and add new asp.net web application project and name it CalculatorWebApplication.
Step 2: Now we need to add a reference to web service. To achieve this
a) Right click on References folder in the CalculatorWebApplication project and select Add Service Reference option
b) In the Address textbox of the Add Service Reference window, type the web service address and click GO button. In the namespace textbox type CalculatorService and click OK.
Step 3: Right click on CalculatorWebApplication project in solution explorer and add new webform.
Step 3: Copy and paste the following HTML <table style="font-family: Arial"> <tr>
<td>
<b>First Number</b>
</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td> </tr> <tr>
<td>
<b>Second Number</b>
</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td> </tr> <tr>
<td>
<b>Result</b>
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td> </tr> <tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick="btnAdd_Click" />
</td> </tr> </table>
Step 4: Copy and paste the following code in the code-behind file protected void btnAdd_Click(object sender, EventArgs e) {
CalculatorService.CalculatorWebServicesSoapClient client =
new CalculatorService.CalculatorWebServicesSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString(); }
In an interview the interviewer may ask you the following questions related to consuming a web service.
1. What is WSDL and what is it's purpose
2. How is a proxy class generated
3. What is the use of a proxy class
4. What actually happens when a web service reference is added
The following 2 paragraphs should provide the answers for the above questions
Visual studio generates a proxy class using the WSDL (Web Service Description Language) document of the web service.
The WSDL document formally defines a web service. It contains
1. All the methods that are exposed by the web service
2. The parameters and their types
3. The return types of the methods
This information is then used by visual studio to create the proxy class. The client application calls the proxy class method. The proxy class will then serialize the parameters, prepares a SOAP request message and sends it to the web service. The web service executes the method and returns a SOAP response message to the proxy. The proxy class will then deserialize the SOAP response message and hands it the client application. We don't have to serialize or deserialize dot net CLR objects to and from SOAP format. The proxy class takes care of serialization and deserialization and makes the life of a developer much easier.
O/P:
Please go through the link before you proceed for this article
Step 1: Right click on WebServicesDemo solution in solution explorer and add new asp.net web application project and name it CalculatorWebApplication.
Step 2: Now we need to add a reference to web service. To achieve this
a) Right click on References folder in the CalculatorWebApplication project and select Add Service Reference option
b) In the Address textbox of the Add Service Reference window, type the web service address and click GO button. In the namespace textbox type CalculatorService and click OK.
Step 1: Right click on WebServicesDemo solution in solution explorer and add new asp.net web application project and name it CalculatorWebApplication.
Step 2: Now we need to add a reference to web service. To achieve this
a) Right click on References folder in the CalculatorWebApplication project and select Add Service Reference option
b) In the Address textbox of the Add Service Reference window, type the web service address and click GO button. In the namespace textbox type CalculatorService and click OK.
Step 3: Right click on CalculatorWebApplication project in solution explorer and add new webform.
Step 3: Copy and paste the following HTML <table style="font-family: Arial"> <tr>
<td>
<b>First Number</b>
</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td> </tr> <tr>
<td>
<b>Second Number</b>
</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td> </tr> <tr>
<td>
<b>Result</b>
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td> </tr> <tr>
<td colspan="2">
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick="btnAdd_Click" />
</td> </tr> </table>
Step 4: Copy and paste the following code in the code-behind file protected void btnAdd_Click(object sender, EventArgs e) {
CalculatorService.CalculatorWebServicesSoapClient client =
new CalculatorService.CalculatorWebServicesSoapClient();
int result = client.Add(Convert.ToInt32(txtFirstNumber.Text),
Convert.ToInt32(txtSecondNumber.Text));
lblResult.Text = result.ToString(); }
In an interview the interviewer may ask you the following questions related to consuming a web service.
1. What is WSDL and what is it's purpose
2. How is a proxy class generated
3. What is the use of a proxy class
4. What actually happens when a web service reference is added
The following 2 paragraphs should provide the answers for the above questions
Visual studio generates a proxy class using the WSDL (Web Service Description Language) document of the web service.
The WSDL document formally defines a web service. It contains
1. All the methods that are exposed by the web service
2. The parameters and their types
3. The return types of the methods
This information is then used by visual studio to create the proxy class. The client application calls the proxy class method. The proxy class will then serialize the parameters, prepares a SOAP request message and sends it to the web service. The web service executes the method and returns a SOAP response message to the proxy. The proxy class will then deserialize the SOAP response message and hands it the client application. We don't have to serialize or deserialize dot net CLR objects to and from SOAP format. The proxy class takes care of serialization and deserialization and makes the life of a developer much easier.
O/P:
Labels:
Web Services
How to create ASP.net Web Services
ASMX web
services are a legacy technology. Most of the companies are now using
WCF (Windows Communication Foundation) to build XML Web services and XML
Web service clients. However, this course will be useful for those who
are searching for a job as a dot net developer as there are some
companies still using ASMX web services today, and could ask interview
questions related to them.
What are web services and why should we use them?
Web services are a standardized way for developing interoperable applications i.e enabling an application to invoke a method of another application.
These applications can be on the same computer or different computers. Web services use open standards and protocols like HTTP, XML and SOAP.
Since these are open and well known protocols, applications built on any platform can interoperate with web services. For example, a JAVA application can interoperate with a web service built using .NET. Similarly a web service built using JAVA can be consumed by a .NET application. Hyper Text Transfer Protocol (HTTP) is the protocol widely used by web services to send and receive messages.
The messaging protocol is SOAP. SOAP stands for Simple Object Access Protocol. SOAP messages are in XML format. Building ASP.NET web services
Building ASP.NET web services is easy. Here are the steps.
Step 1: Create a an ASP.NET Empty Web Application and name it WebServicesDemo. Step 2: Right click on WebServicesDemo project in solution explorer and add - New Item.
From the Add New Item dialog box select Web Service. Change the name of the WebService1.asmx to CalculatorWebServices.asmx. Web Services have .asmx extension. For this reason web services are also often called as ASMX web services. Notice that a webservice is a class that is decorated with [WebService] attribute and inherits from System.Web.Services.WebService base class.
The [WebService] attribute tells that the this class contains the code for a web service. WebService Namespace is used to uniquely identify your web service on the internet from other services that are already there on the Web. WebService Namespace can be any string, but it is common to give it a company's internet domain name as they are usually unique. Something like
[WebService(Namespace = "http://mvkrblogspot.com/webservices")] It is not mandatory for a web service to inherit from
System.Web.Services.WebService base class. However, if the web service has to use ASP.NET session or application state objects, then inheriting from System.Web.Services.WebService base class will provide direct access to these asp.net objects. To allow a web service to be called from Javascript, using ASP.NET AJAX, then decorate the web service class with
[System.Web.Script.Services.ScriptService] attribute. In a later video session, we will discuss calling a web service using asp.net AJAX. Step 3: Copy and paste the following code in CalculatorWebServices.asmx
using System.Web.Services;
namespace WebServicesDemo {
[WebService(Namespace = "http://mvkrblogspot.com/webservices")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class CalculatorWebServices : System.Web.Services.WebService
{
//[WebMethod]
// public string HelloWorld()
// {
return "Hello World";
// }
// change the above method to int and add 2 parameters so im commenting above method
[WebMethod]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
} }
Notice that, the CalculatorWebServices class contains a single method called Add().
This method adds 2 numbers and return the sum.
This method is decorated with [WebMethod] attribute.
If you want the method exposed as part of the Web service, then the method must be public and should be decorated with [WebMethod] attribute.
This attribute has got several properties which can be used to configure the behavior of the XML Web service method. We will discuss these properties in a later video session. At this point we are done building a web service. Run the application by pressing CTRL + F5. You should see a page similar to the one below.
O/p:
http://localhost:52311/CalculatorWebServices.asmx
What are web services and why should we use them?
Web services are a standardized way for developing interoperable applications i.e enabling an application to invoke a method of another application.
These applications can be on the same computer or different computers. Web services use open standards and protocols like HTTP, XML and SOAP.
Since these are open and well known protocols, applications built on any platform can interoperate with web services. For example, a JAVA application can interoperate with a web service built using .NET. Similarly a web service built using JAVA can be consumed by a .NET application. Hyper Text Transfer Protocol (HTTP) is the protocol widely used by web services to send and receive messages.
The messaging protocol is SOAP. SOAP stands for Simple Object Access Protocol. SOAP messages are in XML format. Building ASP.NET web services
Building ASP.NET web services is easy. Here are the steps.
Step 1: Create a an ASP.NET Empty Web Application and name it WebServicesDemo. Step 2: Right click on WebServicesDemo project in solution explorer and add - New Item.
From the Add New Item dialog box select Web Service. Change the name of the WebService1.asmx to CalculatorWebServices.asmx. Web Services have .asmx extension. For this reason web services are also often called as ASMX web services. Notice that a webservice is a class that is decorated with [WebService] attribute and inherits from System.Web.Services.WebService base class.
The [WebService] attribute tells that the this class contains the code for a web service. WebService Namespace is used to uniquely identify your web service on the internet from other services that are already there on the Web. WebService Namespace can be any string, but it is common to give it a company's internet domain name as they are usually unique. Something like
[WebService(Namespace = "http://mvkrblogspot.com/webservices")] It is not mandatory for a web service to inherit from
System.Web.Services.WebService base class. However, if the web service has to use ASP.NET session or application state objects, then inheriting from System.Web.Services.WebService base class will provide direct access to these asp.net objects. To allow a web service to be called from Javascript, using ASP.NET AJAX, then decorate the web service class with
[System.Web.Script.Services.ScriptService] attribute. In a later video session, we will discuss calling a web service using asp.net AJAX. Step 3: Copy and paste the following code in CalculatorWebServices.asmx
using System.Web.Services;
namespace WebServicesDemo {
[WebService(Namespace = "http://mvkrblogspot.com/webservices")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class CalculatorWebServices : System.Web.Services.WebService
{
//[WebMethod]
// public string HelloWorld()
// {
return "Hello World";
// }
// change the above method to int and add 2 parameters so im commenting above method
[WebMethod]
public int Add(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}
} }
Notice that, the CalculatorWebServices class contains a single method called Add().
This method adds 2 numbers and return the sum.
This method is decorated with [WebMethod] attribute.
If you want the method exposed as part of the Web service, then the method must be public and should be decorated with [WebMethod] attribute.
This attribute has got several properties which can be used to configure the behavior of the XML Web service method. We will discuss these properties in a later video session. At this point we are done building a web service. Run the application by pressing CTRL + F5. You should see a page similar to the one below.
O/p:
http://localhost:52311/CalculatorWebServices.asmx
Labels:
Web Services
Subscribe to:
Posts (Atom)













