Monday, November 23, 2009

Currency format in asp.net

we can convert currency into required format in asp.net

float amount =100
label.Text=amount.ToString("N2");

it displays as 100.00

by default the currency format is US-format

if you want to change this into indian rupee format

include this code in to your web.config file

< system.web />
< globalization culture="te-IN" uiCulture="auto"/>
</system.web>

Currency format with commas in sql server

select convert (varchar(20), convert(money, 9123456789.00), 1 )

output::9,123,456,789.00

If u want to format into indain rupees format here is my suggestion ::


create function dbo.RupieFormat(@v float)
returns varchar(200)
as
begin
declare @res varchar(50)
declare @p1 varchar(40)
declare @p2 varchar(10)

set @res = replace(convert (varchar(20), convert(money, @v), 3 ) , ',','')
set @p1 = left(@res, charindex('.', @res)-1)
set @p2 = substring(@res, charindex('.', @res), 10)

set @res = right(@p1, 3) + @p2

if(len(@p1)>2)
set @p1 = left(@p1, len(@p1)-3)
else if(len(@p1)>1)
set @p1 = left(@p1, len(@p1)-2)
else
set @p1 = left(@p1, len(@p1)-1)

while (@p1<>'')
begin
set @res = right(@p1, 2) + ',' + @res
if (len(@p1) > 2)
set @p1 = left(@p1, len(@p1)-2)
else
set @p1= ''
end

return(@res)
end


Eg::

select dbo.RupieFormat(price) as price from products

or

select dbo.RupieFormat(9123456789.12)

output:9,12,34,56,789.00

CAST and CONVERT (T-SQL)

CAST and CONVERT (T-SQL)
Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality.
Syntax
Using CAST:
CAST(expression AS data_type)
Using CONVERT:
CONVERT (data_type[(length)], expression [, style])
Arguments
expression
Is any valid Microsoft® SQL Server™ expression. For more information, see Expressions.
data_type
Is the target system-supplied data type. User-defined data types cannot be used. For more information about available data types, see Data Types.
length
Is an optional parameter of nchar, nvarchar, char, varchar, binary, or varbinary data types.
style
Is the style of date format you want when converting datetime or smalldatetime data to character data (nchar, nvarchar, char, varchar, nchar, or nvarchar data types), or the string format when converting float, real, money, or smallmoney data to character data (nchar, nvarchar, char, varchar, nchar, or nvarchar data types).
In the table, the two columns on the left represent the style values for datetime or smalldatetime conversion to character data. Add 100 to a style value to get a four-place year that includes the century (yyyy).

Without
century
(yy) With
century
(yyyy)

Standard

Input/Output**
- 0 or 100 (*) Default mon dd yyyy hh:miAM (or PM)
1 101 USA mm/dd/yy
2 102 ANSI yy.mm.dd
3 103 British/French dd/mm/yy
4 104 German dd.mm.yy
5 105 Italian dd-mm-yy
6 106 - dd mon yy
7 107 - mon dd, yy
8 108 - hh:mm:ss
- 9 or 109 (*) Default + milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM)
10 110 USA mm-dd-yy
11 111 JAPAN yy/mm/dd
12 112 ISO yymmdd
- 13 or 113 (*) Europe default + milliseconds dd mon yyyy hh:mm:ss:mmm(24h)
14 114 - hh:mi:ss:mmm(24h)
- 20 or 120 (*) ODBC canonical yyyy-mm-dd hh:mi:ss(24h)
- 21 or 121 (*) ODBC canonical (with milliseconds) yyyy-mm-dd hh:mi:ss.mmm(24h)
* The default values (style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121) always return the century (yyyy).
** Input when converting to datetime; Output when converting to character data.

________________________________________
Important By default, SQL Server interprets two-digit years based on a cutoff year of 2049. That is, the two-digit year 49 is interpreted as 2049 and the two-digit year 50 is interpreted as 1950. Many client applications, such as those based on OLE Automation objects, use a cutoff year of 2030. SQL Server provides a configuration option (two digit year cutoff) that changes the cutoff year used by SQL Server and allows the consistent treatment of dates. The safest course, however, is to specify four-digit years.
________________________________________
When you convert to character data from smalldatetime, the styles that include seconds or milliseconds show zeros in these positions. You can truncate unwanted date parts when converting from datetime or smalldatetime values by using an appropriate char or varchar data type length.
This table shows the style values for float or real conversion to character data.

Value Output
0 (the default) 6 digits maximum. Use in scientific notation, when appropriate.
1 Always 8 digits. Always use in scientific notation.
2 Always 16 digits. Always use in scientific notation.

In the following table, the column on the left represents the style value for money or smallmoney conversion to character data.

Value Output
0 (the default) No commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 4235.98.
1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.
2 No commas every three digits to the left of the decimal point, and four digits to the right of the decimal point; for example, 4235.9819.

Return Types
Returns the same value as data type 0.
Remarks
Implicit conversions are those conversions that occur without specifying either the CAST or CONVERT function. Explicit conversions are those conversions that require the CAST (CONVERT) function to be specified. This chart shows all explicit and implicit data type conversions allowed for SQL Server system-supplied data types.

________________________________________
Note Because Unicode data always use an even number of bytes, use caution when converting binary or varbinary to or from Unicode supported data types. For example, this conversion does not return a hexadecimal value of 41, but of 4100:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary)
________________________________________
Automatic data type conversion is not supported for the text and image data types. You can explicitly convert text data to character data, and image data to binary or varbinary, but the maximum length you can specify is 8000. If you attempt a conversion that is not possible (for example, if you convert a character expression that includes letters to an int), SQL Server generates an error message.
When converting character or binary expressions (char, nchar, nvarchar, varchar, binary, or varbinary) to an expression of a different data type, data can be truncated, only partially displayed, or an error is returned because the result is too short to display. Conversions to char, varchar, nchar, nvarchar, binary, and varbinary are truncated, except for the conversions shown in this table.
From data type To data type Result
int, smallint, or tinyint char *
varchar *
nchar E
nvarchar E
money, smallmoney, numeric, decimal, float, or real

char

E
varchar E
nchar E
nvarchar E
* Result length too short to display.
E Error returned because result length is too short to display.

Microsoft SQL Server guarantees that only roundtrip conversions, conversions that convert a data type from its original data type and back again, will yield the same values from release to release. This example shows such a roundtrip conversion:
DECLARE @myval decimal (5, 2)
SET @myval = 193.57
SELECT CAST(CAST(@myval AS varbinary(20)) AS decimal(10,5))
-- Or, using CONVERT
SELECT CONVERT(decimal(10,5), CONVERT(varbinary(20), @myval))
Do not attempt to construct, for example, binary values and convert them to a data type of the numeric data type category. SQL Server does not guarantee that the result of a decimal or numeric data type conversion to binary will be the same between releases of SQL Server.
When data types are converted with a different number of decimal places, the value is truncated to the most precise digit. For example, the result of SELECT CAST(10.6496 AS int) is 10.
This example shows a resulting expression that is too small to display.
USE pubs
SELECT SUBSTRING(title, 1, 25) AS Title, CAST(ytd_sales AS char(2))
FROM titles
WHERE type = 'trad_cook'

Here is the result set:
Title
------------------------- --
Onions, Leeks, and Garlic *
Fifty Years in Buckingham *
Sushi, Anyone? *

(3 row(s) affected)

When data types in which the target data type has fewer decimal points than the source data type are converted, the value is rounded. For example, the result of CAST(10.3496 AS money) is $10.35.
SQL Server returns an error message when char, nchar, varchar, or nvarchar data is converted to int, float, numeric, or decimal; or when an empty string (“ “) is converted to int or float.
Using Binary String Data
When binary or varbinary data is converted to character data and an odd number of values is specified following the x, SQL Server adds a 0 (zero) after the x to make an even number of values.
Binary data consists of the characters 0 through 9 and A through F (or through f), in groups of two characters each. Binary strings must be preceded by 0x. For example, to input FF, type 0xFF. The maximum value is a binary value of 8000 bytes, each of which is FF. The binary data types are not for hexadecimal data, but rather for bit patterns. Conversions and calculations of hexadecimal numbers stored as binary data can be unreliable.
When specifying the length of a binary data type, every two characters count as one. A length of 10 signifies that 10 two-character groupings will be entered.
Empty binary strings, represented by 0x, can be stored as binary data.
Examples
A. Use both CAST and CONVERT
Each example retrieves the titles for those books that have a 3 in the first digit of year-to-date sales, and converts their ytd_sales to char(20).
-- Use CAST.
USE pubs
GO
SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE CAST(ytd_sales AS char(20)) LIKE '3%'
GO

-- Use CONVERT.
USE pubs
GO
SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE CONVERT(char(20), ytd_sales) LIKE '3%'
GO

Here is the result set for either query:
Title ytd_sales
------------------------------ -----------
Cooking with Computers: Surrep 3876
Computer Phobic AND Non-Phobic 375
Emotional Security: A New Algo 3336
Onions, Leeks, and Garlic: Coo 375

(4 row(s) affected)

B. Use CAST with arithmetic operators
This example calculates a single column computation (Copies) by dividing the total year-to-date sales (ytd_sales) divided by the individual book price (price). This result is converted to an int data type after being rounded to the nearest whole number.
USE pubs
GO
SELECT CAST(ROUND(ytd_sales/price, 0) AS int) AS 'Copies'
FROM titles
GO

Here is the result set:
Copies
-----------
205
324
6262
205
102
7440
NULL
383
205
NULL
17
187
16
204
418
18
1263
273

(18 row(s) affected)

C. Use CAST to concatenate
This example concatenates noncharacter, nonbinary expressions using the CAST data type conversion function.
USE pubs
GO
SELECT 'The price is ' + CAST(price AS varchar(12))
FROM titles
WHERE price > 10.00
GO

Here is the result set:
-------------------------
The price is 19.99
The price is 11.95
The price is 19.99
The price is 19.99
The price is 22.95
The price is 20.00
The price is 21.59
The price is 10.95
The price is 19.99
The price is 20.95
The price is 11.95
The price is 14.99
(12 row(s) affected)

D. Use CAST for more readable text
This example uses CAST in the select list to convert the title column to a char(50) column so the results are more readable.
USE pubs
GO
SELECT CAST(title AS char(50)), ytd_sales

FROM titles
WHERE type = 'trad_cook'
GO

Here is the result set:
ytd_sales
-------------------------------------------------- ---------
Onions, Leeks, and Garlic: Cooking Secrets of the 375
Fifty Years in Buckingham Palace Kitchens 15096
Sushi, Anyone? 4095
(3 row(s) affected)
E. Use CAST with LIKE clause
This example converts an int column (the ytd_sales column) to a char(20) column so that it can be used with the LIKE clause.
USE pubs
GO
SELECT title, ytd_sales
FROM titles
WHERE CAST(ytd_sales AS char(20)) LIKE '15%'
AND type = 'trad_cook'
GO
Here is the result set:
title ytd_sales
------------------------------------------------------------ -----------
Fifty Years in Buckingham Palace Kitchens 15096
(1 row(s) affected)

Friday, September 11, 2009

Web Services in C#

Introduction

Web Service is known as the software program. These services use the XML to exchange the information with the other software with the help of the common internet Protocols. In the simple term, we use the Web Service to interact with the objects over the internet.

Here are some points about the Web Service

  1. Web Service is not dependent on any particular language.
  2. Web Service is a protocol Independent.
  3. Web Service is platform-independent.
  4. Web Service is known as the Stateless Architecture. These services are dependent only on the given input.
  5. Web Service is also Scalable.
  6. Web Service is based on the XML (Open, Text-Based Standard).

Technology Used in Web Service:

XML: Web Service specifies only the data. So, the application which understands the XML regarding the programming language or the platform can format the XML in different ways.

SOAP: The communication between the Services and the application is set up by the SOAP.

WSDL: WSDL gives us a uniform method that is helpful to specify the Web Services to the other programs.

UDDI: With the help of UDDI, we can search the Web Service registries.

At the time of the deployment of these technologies, this allows the developers to do the packaging of the applications in the form of the Service and publishing of the Service on the network.

Advantages of Web Services:

  1. Web Services always use the open, text-based standard. Web service uses all those components even they are written in various languages for different platforms.
  2. Web Service promotes the modular approach of the programming so that the multiple organizations can communicate with the same web service.
  3. Web Services are easy to implement but expensive because they use the existing infrastructure, and we can repackage most of the applications as the Web Service.
  4. Web Service reduces the cost of enterprise application integration and B2B communications.
  5. Web Services are the interoperable Organization that contains the 100 vendors and promote them interoperability.

Limitations of Web Services:

Limitation of Web Services are:

  1. One of the limitations of the Web Services is that the SOAP, WSDL, UDDI requires the development.
  2. Supports to the interoperability is also the limitation of the Web Service.
  3. The limitation of web service is also royalty fees.
  4. If we want to use web services for the high-performance situation, in that case, web service will be slow.
  5. The use of web service increases the traffic on the network.
  6. The security level for Web Services is low.
  7. We use the standard procedure to describe the quality of particular web services.
  8. The standard for the Web Service is in the draft form.
  9. To retain the intellectual property of the specific standard by the vendor is also the limitation of the web service.

Example of the Web Service:

Web Service can do almost any kind of task.

Web Portal: Web portal is used to fetch the headline news from the linked web service.

Weather Reporting: For the reporting of weather, we will use Weather Reporting Web Service for displaying the information about the weather on our website.

Stock Quote: The latest information about the share market with the Stock Quote can display on our website.

News headline: By using the news headline Web Service, we can show the latest update of the news on our website.

We can make our web service and can give them back to use. Here we are taking an example like we can make the Free SMS Sending Service with the footer for the company advertisement. So, whenever any person uses this Service, they will indirectly advertise our company. For taking advantage of the web service, we can apply the N number of ideas.

For creating the Web Service first, we will think about a scenario. For creating any web service, firstly, we should have to get to know why we need Web Service.

The need for Web Service:

We will think about a scenario which we want to show on our website. On our website, we want to show the information about the region, nation and about the international as well. Here if we are thinking of writing the code for all these functionalities, this will take lots of time and the effort to write the code for all these functionalities. All of the above information is already provided by some existing sites, so in that case, we want to use that current logic of other sites. But there is a problem arises how could I use the existing logic in my application.

The solution to this problem is Web Services.

By using the Web Service, we can reuse someone else's business logic, instead of replicating this. To use the business logic of someone else, we just have to write a few lines of the code. This technique is similar to the libraries of API, DLLs, and plug-ins.

The only difference between the libraries of API and the Web Service is that the Web Service is located remotely on another server.

Web Services can be invoked by the other applications. Web Services are known as the pieces of the business logic, which is hosted on the internet, and the other application can use them.

Here we have some points about the Web Services.

Note1: Web Services are not limited only to the .Net Framework. The standards of Web Services were already defined before the release of the .NET. Web Services and supported by the vendors other than Microsoft.

Note:2: Web Services can also work on the cross-platform. If the services were written in one language, these could be used by the other application despite, and the application used the other language. If we want to use the web services, the only way for that is we only need the internet to connect where we will make the HTTP request.

As we know that the Web Service is cross-platform, but despite this, there should be an understandable language so that we can make a request for the services and can get the Service in their response. Web Services use the XML, which can be understood easily.

This is the only reason why the web services were built with the XML based standards of exchanging the data.

Web Services uses the Set of Data type. The XML Schema easily recognizes these data types.

Web Services uses a simple data type like strings and numbers. These data types are helpful for communication with Web Services. And we cannot send the proprietary .NET objects like image, FileStream, or the EventLogs. The other programming language does not have any way to contact these .NET objects. If we use some devices to send them to the client, still the different programming languages will not be able to interpret.

Note:3 If we want to work with the .NET objects, we can use the .NET remoting. .NET remoting is known as distributed technology through which we can use the .NET objects. But the non-.NET client can't use it.

Data Types supported by the Web Service:

  • Built-in Types (Basic):
    Data Types used by the Web Services are:
    Web Services uses the built-in C# data types like short, int, long, short, float, char, byte, string, and DateTime.
  • Objects: WPF uses the object of the user-defined class. In spite of this thing that the class contains the methods, the class will not be possible to transmit to the client.
  • Arrays: WPF uses the arrays of any supported data type (built-in or customs). We can also use the ArrayList in WPF.
  • Enumerations: WPF supports enum. For the value of the enumeration, WPF uses the string name. WPF will not use integer.
  • XmlNode: Objects which are based on the System.Xml.XmlNode represents the portion of the XML document. We can use the XmlNode to send the arbitrary XML.

DataSet and DataTable: The WPF supports dataSet and DataTable, but the WPF does not support the ADO.NET data objects like DataColumns and DataRows.

Creating a Webservice in C#

A simple asmx page is known as Web Service. For the creation of the web service, we will use the Visual Studio 2017, which is using the .NET Framework 4.8. For creating the Web Service, we will follow the following steps:

Step 1: Firstly, we will create a Web Application for creating the Web Service.

For that, we will click on the File-> Select Project as shown in the below screenshot:

How to create Web Service

After that the new window will open as shown in the below screenshot:

From here, we will select the Web->Asp.Net Web Application->Name of the Web Application-> Click on OK.

How to create Web Service

After this a new window will be shown us like as shown below:

How to create Web Service

For creating the Web Service, we will do the right click on the project name-> Click on Add-> Add New Item. As shown in the below screenshot:

How to create Web Service

After this, a new window will appear. From where we have to click on the Web-> Select Web Service(.asmx page)-> Give a name to the Web Service as shown in the below screenshot:

How to create Web Service

After adding the Web Service to the application, a new window will appear which is shown as below:How to create Web Service

Visual Studio creates the not changeable web service-Analyzation of template used in the Visual Studio.

Explanation of Default Code

[WebService(Namespace="http://tempuri.org/"))]

The Web Service based on XML required the unique namespace for the client application, which is helpful to distinguish the web service from the other services on the Web. Web Service uses the default namespace, which is tempura.org. This namespace is available for the XML Web services, which is under development. The XML Web Services, which is going to be published, should use the permanent namespace. The instance of Web Services should replace it with other URI, which is more meaningful in the production system.

We will identify the Web Service as the namespace used in the Web Service; its company will control namespace. Here we are taking an example of the company's internet domain name, which we can use as part of the namespace—the namespace of the XML Web service, which will look like the URLs. We used the URLs for pointing out the actual resources on the Web.

Points to be noted:

Here are some points which should be noted while creating web service.

  • We cannot have more than one [WebService]tag.
  • Changes in the namespace will not affect the namespace.

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

Directly method overloading is not supported by the web service. To allow the method overloading in the Web Service, we have to add the MessageName property to differentiate the one method used in the web service from the other method, which is having the same name and used parameter.

[WebServiceBinding(ConformsTo= WsiProfiles.BasicProfile1_1)] to

 [WebServiceBinding (ConformsTo = WsiProfiles.None)].

  1. [WebMethod]  
  2.         public int SumOfNums(int FirstNumber, int SecondNumber)  
  3.         {              return FirstNumber + SecondNumber;           }    
  4. //here we will use MessageName property to do the differentiation between both of the methods.  
  5.         [WebMethod(MessageName = "SumOfFloats")]    
  6.         public float SumOfNums(float FirstNumber, float SecondNumber)  
  7.         {              return FirstNumber + SecondNumber;          }  

If we want to call the Web service from the Script, we will use ASP.NETAJAX and uncomment the below line.

[System.Web.Script.Services.ScriptService]

[WebMethod]

This attribute is always used at the top of the method. We write this attribute in the Web Service. [WebMethod] attribute is used to define that the method used this attribute is exposed to the user/client access.

If we remove this attribute, in that case, the client will not be able to see the details of the method; hence they cannot implement it.

Proxy class or WSDL

WSDL (Web Service Development Language) document is used to generate the proxy class of the Web Service. WSDL document defines the Web Service. WSDL document contains the

  1. All the method which is exposed by the Web service.
  2. WSDL document contains the parameters and their types.
  3. WSDL document contains the return type of the methods.

Visual Studio used the information to create the proxy class. The client application will call the proxy class method. The proxy class will serialize the parameters, prepare the SOAP request message and send it to the Web Service. Web Service executes this method and returns the SOAP return message to the Proxy. The proxy class will then deserialize the SOAP response message and give it to the Client application. There is not any need to serialize or deserialize the dot net CLR objects to and from the SOAP format. The proxy class has all the responsibility of the serialization and deserialization, which makes the life of the developer easy.

Now we will see the WebService1.asmx.cs window:

1. WebService.asmx.cs page includes the System.Web.Services, and it also consists of the four other namespaces which are included by the visual Studio in the Web Application.

2. "Service1" class is inherited from the "System.Web.Services.WebServices". After inheriting the class from the "System.Web.Services.WebService" we can access the built-in ASP.Net objects such as (Application, Session, User, Context, Server ). If there is not any need for the built-in objects of .NET, then there is also do not any need of the service class from "WebService".

3. "Service1" includes the "WebService" attribute. If we want to expose any class as a service, then there is also a need to include the attribute of the "WebService".

WebService attribute contains the different properties like:

NameSpace: The use of the namespace property makes the Service uniquely identifiable. The nameSpace is the property of the XML. The client application can contain different services, so that's why there can be the chances of the collision. To avoid the collision, it is the responsibility of the provider to make the namespace unique.

Name: By using the Name property, we will provide the descriptive name to the Service.

Description: This property is used to avoid a brief description of the Service.

4. "Service1" contains another attribute as well, which is "WebServiceBinding". This is used to indicate the standard of the Service. If the Service does not follow this standard, we will get an exception.

5. With the Service, one more attribute is added, which is "[System.Web.Script.Services.ScriptService]", for making the Service accessible from the client script, Services should be decorated with this Service.

6. The "Service1" class contains a method "Hello World". This method is decorated with the "[WebMethod]" attribute. The client application accesses the service method. The Client Application should add the "Service1" method.

There can be chances that the Service is using some method for internal functionality. The client application does not have any need to use them. There is not any need to use those methods with the Web Method attribute.

WebMethod attribute contains the Name and Description property, which we can use to provide the self-describing name or description, respectively.

Mark-up

Now we will see the mark-up.

For the mark-up, we have to the right click on the Service1.asmx in the window of the Solution Explorer and select the view mark-up as shown in the below screenshot:

How to create Web Service

In the Service1.asmx, we will see that the Service uses the WebService directive with the attribute. From here, this will show us that the application invokes the Service, not by the end-user. Hence the asmx page has no mark-up.

Service1.asmx

  1. <%@ WebService Language="C#" CodeBehind="Service1.asmx.cs" Class="WebApplication7.Service1" %>  

Here are some points about the Service1.asmx.

  • "Web Service" directive: This directive shows that the asmx page is a web service.
  • "Language"="C#": This indicates that the C# language is used for the Service.
  • "CodeBehind": This property has not any role with the ASP.NET or web service. CodeBehind is the property of the Visual Studio. This property is used to map the asmx page with the code behind the page.
  • "Class" property contains the qualified name of the class. This is the entry point of the Service, just like the main () in C language.

Now we will run this application after pressing the button F5. Vary). Here will find a link for the Service Description as shown in the below screenshot:

How to create Web Service

There is also another link to the HelloWorld. After clicking on this link, this will redirect us to the testing page.

How to create Web Service

After clicking on this link, this will redirect us to the Service1 Web Service page for the testing.

How to create Web Service

Implementation of web Service

Now we will implement the Service. Now we will rename the file "Service1" in the Solution Explorer to "MyService". Here we will change the class name to MyService from Service1. Now we will open the mark-up(.asmx) page.

How to create Web Service

From the above screenshot here, we will see that the visual Studio is unable to resolve the "Service1" in the class property. Here class shows the fully-qualified name of the Service, and we renamed the Service1 class to MyService, but Visual Studio is unable to resolve it.

Here we change the property of the class to "Web application.MyService" and will change the "CodeBehind" property from "Service1.asmx.cs" to "MyService.asmx.cs" like as we name the file also.

MyService.asmx

  1. <%@ WebService Language="C#" CodeBehind="MyService.asmx.cs" Class="WebApplication7.MyService" %>  

MyService.asmx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Web.Script.Serialization;  
  7.   
  8.   
  9. namespace WebApplication7  
  10. {  
  11.     /// <summary>  
  12.     /// Summary description for Service1  
  13.     /// </summary>  
  14.     [WebService(Namespace = "http://tempuri.org/")]  
  15.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  16.     [System.ComponentModel.ToolboxItem(false)]  
  17.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  18.     [System.Web.Script.Services.ScriptService]  
  19.     public class MyService : System.Web.Services.WebService  
  20.     {  
  21.   
  22.         [WebMethod]  
  23.         public int SumOfNums(int First, int Second)  
  24.         {  
  25.             return First + Second;  
  26.         }  
  27.     }  
  28. }  

After this, the Service is ready to use. Now we will compile and run this application.

After the compilation a new window will open as shown in the below screenshot:

How to create Web Service

Testing of a Web Service

Now we will run the application by clicking on the F5 button. The http://localhost:62639/MyService.asmx page will open. The page will contain the link for the Service Description (the WSDL document, documentation of Web Service) and contains another link of SumOfNums. This page is the test page of the SumOfNums method as shown in the below screenshot:

How to create Web Service

Now we will use the OOP (Object Oriented Programming Concept) concept method overloading. Now we add the WebMethod in the MyService class.

MyService.asmx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System. Linq;  
  4. using System. Web;  
  5. using System.Web.Services;  
  6. using System.Web.Script.Serialization;    
  7. namespace WebApplication7  
  8. {  
  9.     /// <summary>  
  10.     /// Summary description for Service1  
  11.     /// </summary>  
  12.     [WebService(Namespace = "http://tempuri.org/")]  
  13.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  14.     [System.ComponentModel.ToolboxItem(false)]  
  15.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  16.     [System.Web.Script.Services.ScriptService]  
  17.     public class MyService : System.Web.Services.WebService  
  18.     {  
  19.         [WebMethod(MessageName = "SumOfFloats")]    
  20.         public float SumOfNums(float First, float Second)  
  21.         {  
  22.             return First + Second;  
  23.         }    
  24.     }  
  25. }  

Now we will run this application by pressing the button F5. The http://localhost:62639/MyService.asmx page will open which contains the link for the Service Description(the WSDL document, documentation for the web service). Here we have another link SumOfNums which is the test page of the SumOfNums method as shown in the below screenshot:

How to create Web Service

After entering the values in the first text box and second text box, this will invoke the method as shown in the below screenshot:

How to create Web Service

Method Overloading

Now we will use the overloading method in the Service. Web service does not support method overloading. This will throw an error in the case of the method overloading. Here we are taking an example to show the method overloading done in the Web Service and throw an error because it does not support the overloading.

MyService.asmx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System. Linq;  
  4. using System. Web;  
  5. using System.Web.Services;  
  6. using System.Web.Script.Serialization;  
  7.   namespace WebApplication7  
  8. {  
  9.     /// <summary>  
  10.     /// Summary description for Service1  
  11.     /// </summary>  
  12.     [WebService(Namespace = "http://tempuri.org/")]  
  13.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  14.     [System.ComponentModel.ToolboxItem(false)]  
  15.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  16.     [System.Web.Script.Services.ScriptService]  
  17.     public class MyService : System.Web.Services.WebService  
  18.     {    
  19.         [WebMethod]  
  20.         public int SumOfNums(int First, int Second)  
  21.         {              return First + Second;          }    
  22.         [WebMethod(MessageName = "SumOfFloats")]    
  23.         public float SumOfNums(float First, float Second)  
  24.         {  
  25.             return First + Second;  
  26.         }    
  27.     }  
  28. }  

OUTPUT

How to create Web Service

In the above example, Web Service does not support the method overloading and shows the error message that the Service "WebApplication7.MyService" does not conform to WS-I Basic Profile v1.1. Now to support the overloading method, we have to follow the following steps either we have to remove the 

"[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]," 

or we have to make some changes "[WebServiceBinding(ConformsTo = WsiProfiles.None)]".

To support the overloading method, we have to make some changes in the code, as shown in the box which is highlighted:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System. Linq;  
  4. using System. Web;  
  5. using System.Web.Services;  
  6. using System.Web.Script.Serialization;    
  7. namespace WebApplication7  
  8. {  
  9.     /// <summary>  
  10.     /// Summary description for Service1  
  11.     /// </summary>  
  12.     [WebService(Namespace = "http://tempuri.org/")]  
  13.     //make the WsiProfiles to None   
  14.     [WebServiceBinding(ConformsTo = WsiProfiles.None)]  
  15.     [System.ComponentModel.ToolboxItem(false)]  
  16.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  17.     [System.Web.Script.Services.ScriptService]  
  18.     public class MyService : System.Web.Services.WebService  
  19.     {    
  20.         [WebMethod]  
  21.         public int SumOfNums(int First, int Second)  
  22.         {  
  23.             return First + Second;  
  24.         }    
  25. //here we have to add the MessageName property to make the difference between both of the methods.    
  26.         [WebMethod(MessageName = "SumOfFloats")]  
  27.   
  28.         public float SumOfNums(float First, float Second)  
  29.         {  
  30.             return First + Second;  
  31.         } 
  32.     }  
  33. }  

After all these changes the Web Service will looks like as shown in the below screenshot:

How to create Web Service

Here web service supports the method with the same name. By adding the message name property, we can create the differences between both of the methods.

By using the above property, we can use the method overloading in the Web Service.

Testing of the Page

After clicking on the SumOfFloats, the page will redirect to the http://localhost:62639/MyService.asmx?op=SumOfFloats here we will see that the "?op=SumOfNums" is appended to the Service URL. This page contains the two text boxes for the two input values (First, Second), where the SumOfNums value will take as an input parameter and a "invoke" button. After clicking on this invoke button, we will redirect to the http://localhost:62639/MyService.asmx/SumOfFloats, which is having the value where the SumOfNums method returns the XML format.

How to create Web Service

After clicking on the invoke button, we will redirect to http://localhost:62639/MyService.asmx/SumOfFloats page. This page contains the value in the XML format.

How to create Web Service

Similarly, after clicking on the "SumOfNums MessageName="SumOfFloats"". We will redirect to the "http://localhost:62639/MyService.asmx?op=SumOfFloats" . So the "SumOfNums MessageName="SumOfFloat"" method which is known as the "SumOfFloats" for client application. 

Here a question is arising from where the test page came. Because we didn't add the Mark-up, but still the page was rendered.

Test Pages are not part of the Web Service. Test Page is rendered by the ASP.NET by using the Web Page c:\[WinDir]\Microsoft. NET\Framework\ [Version] \Config\DefaultWsdlHelpGenerator.aspx. "Reflection" concept renders to the test page.

WSDL Document

Web Services are self-describing, which means ASP.Net itself provides us all the information required for the client to consume a web service in the form of the WSDL document. WSDL document tells the client about the methods which are present in the Web Service. And the what parameter and return value used by the method and how a client application can communicate with them. WSDL is an XML standard.

Hosting of the Web Service

For the hosting of the web service, we will add the reference to the Service and consume it from the different applications. Here we suppose that the port number can vary, so now we will host the Service on the IIS (Internet Information Server) for getting the particular address of the server. For this, we will open the Internet Information Server-> Go to the default web site-> Right-click on the application-> Add the Application->browse to the physical location of our Service for the physical path field-> Click "OK". Now we will browse the application with the alias name http://localhost/WebServiceDemo/ for the testing if the application was correctly hosted. Here we will get an error "HTTP Error 403.14-Forbidden". This error was coming because there is not set any default document for this application. Now we will add a page as a default document "MyService.asmx". Now we can browse our application by adding this URL in the browser localhost/WebServiceDemo/MyService.asmx.

Popular Posts