Guruji Point - Code You Want To Write

  • Home
  • Asp.Net
  • WCF
  • SQL
  • Type Script
  • AngularJS
  • Tech News
  • Blog
  • Earn Online

Tuesday, 28 March 2017

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

 Webservice     1 comment   


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;
        }
        catch( Exception 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 


  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to TwitterShare to Facebook
Newer Post Older Post Home

1 comment:

  1. for ict 9931 July 2020 at 22:24

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Projects for CSE It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai


    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

Facebook Updates

Guruji Point

Categories

comma seperated string in sql Comman table Expression in SQL Dynamic Grid Row IQueryable in c# Learn AngularJS row_number() and dense_rank() salary table structure. Scope_Identity() Use of indexes while loop in sql why do we need cursor why tuple used

About Us

This blog is about the Programming ,Tech News and some intresting facts related Contents. Here you can find fundamental and expert level topic of programming languages very practically related to C# , Asp.Net ,Sql-Server, JavaScript, Jquery, WebServices And also Web-Api, WCF ,WPF, Angular Js.

Contact Us

Email Us - gurujipoints@gmail.com
Contact- 8077657477

Reach Us

Copyright © Guruji Point - Code You Want To Write