Tuesday, 28 March 2017

Basic Calculator Service with Error Handling In Asp.Net Using c#


Introduction
In this post we will learn how to handle Errors in Web Service. We will create a basic calculator with error handling techniques. In previous posts we already learned What is Web Service, How to create a web service using c# , how to consume web service in asp.net. and how to host a web service in IIS.

Practice
We already know how to create a and consume a Web Service in Asp.net and in this article we take one step ahead. Error handling is most important point for any application. Because you can provide a error message according to your application using try catch .

First we create a ErrorResponse class for responding the Result or ErrorMessage to our Application.

Step 1.  Right click on your service project and add a New class named it ErrorResponse                   and create two  properties on this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class WebServiceResponse
{   public string Result = string.Empty;
    public string ErrorMsg = string.Empty;
    public WebServiceResponse(){ }
}

Step 2.  After creating this class now we use this class in our Service method 


[WebMethod]
 public string Calculate(string first, string second, char operation)
 {
  WebServiceResponse response = new WebServiceResponse();
  try
   {
     switch (operation)
      {
        case '+':
          {
            response.Result = (Convert.ToInt32(first) + 
                               Convert.ToInt32(second)).ToString();
            break;
           }
         case '-':
           {
             response.Result = (Convert.ToInt32(first) 
                                - Convert.ToInt32(second)).ToString();
             break;
           }
          case '*':
             {
              response.Result = (Convert.ToInt32(first) *
                                  Convert.ToInt32(second)).ToString();
              break;
             }
          case '/':
             {
               response.Result = (Convert.ToInt32(first) /
                                   Convert.ToInt32(second)).ToString();
               break;
             }
          case '%':
              {
                                       response.Result = (Convert.ToInt32(first) % Convert.ToInt32(second)).ToString();
               break;
              }

           default:
               response.Result = "Please enter a correct input";
               break;
            }
            return response.Result;
        }
        catchException ex)
        {
            response.ErrorMsg = ex.Message;
        }

        if (response.Result != "")
            return response.Result;
        else
            return response.ErrorMsg;
    }

Step 3. Build your service project run and test your Service directly.

Step 4. Create a WebApplication for consuming this service. Here i named my application                  ConsumeCalC_Service and add your service reference from Solution Explorer  Add reference.


Step 5. Create a Web Form and do few code for according to created service. 
<form id="form1" runat="server">
 <div>
   <table>
   <tr>
        <td> <asp:Label ID="lblFirst" runat="server" Text="First Number"> </asp:Label></td>
        <td> <asp:TextBox ID="txtFirst" runat="server"> </asp:TextBox></td>
   </tr>
   <tr>
      <td> <asp:Label ID="lblSecond" runat="server" Text="Second Number"> </asp:Label></td>
      <td> <asp:TextBox ID="txtSecond" runat="server"> </asp:TextBox></td>
   </tr>
    <tr>
       <td> <asp:Label ID="lblOperator" runat="server" Text="Operator"> </asp:Label></td>
       <td> <asp:TextBox ID="txtOperator" runat="server"> </asp:TextBox></td>
    </tr>
    <tr >
        <td></td>
        <td> <asp:Button ID="btnOperation"  runat="server" Text="Result" 
                 OnClick="btnOperation_Click"/> </td>
     </tr>
     <tr >
       <td><asp:Label ID="lblname" Font-Bold="true" Text="Your output is :"
                     runat="server"/> </td>
      <td> <asp:Label ID="lblResult" Font-Bold="true" ForeColor="Red" runat="server"/></td>
       </tr>
   </table>
   </div>
   </form>
 
And on the click event of Get Age here is the C# Code for using service
protected void btnOperation_Click(object sender, EventArgs e)
    {
        Calculator_ServiceSoapClient service = new Calculator_ServiceSoapClient();
        string res = service.Calculate(txtFirst.Text, txtSecond.Text,
                                        Convert.ToChar(txtOperator.Text));
        lblResult.Text = res;
    }
 

Step 6. Now run your application and provide input in Text fields.
Here i divide 21 by 0 and it simply displayed error message in red text as i want to displayed. But what happend if we did not implement Error Handling in our service code, the answer is simple it breaks our code and user did not get what exactly happend.

Now any type of error handled by our error handling class and it will not through exception directly to user but through a error message in response .

If you have any query related to this post please let me know by comment down below 


No comments:

Post a Comment