Search This Blog

2013/12/29

Calling Local ASMX SERVICE using JQUERY:



Calling Local ASMX SERVICE using JQUERY:

1)      First Creating Local Web service:

Add a new Asmx template say MyService.asmx, Now add a service reference tohttp://www.webservicex.net/CurrencyConvertor.asmx.Which is used to get conversion
rate from one currency to Other say from USD to INR.
Change C# Part of Asmx with following
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
[System.ComponentModel.ToolboxItem(false)]
public class MyService : System.Web.Services.WebService {

    public MyService () {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetConvertionRate(string from, string to)
    {
        ProxyCurrencyConvertor.CurrencyConvertorSoapClient client = new ProxyCurrencyConvertor.CurrencyConvertorSoapClient();
        ProxyCurrencyConvertor.Currency frmEnum = (ProxyCurrencyConvertor.Currency) Enum.Parse(typeof(ProxyCurrencyConvertor.Currency), from);
        ProxyCurrencyConvertor.Currency toEnum = (ProxyCurrencyConvertor.Currency) Enum.Parse(typeof(ProxyCurrencyConvertor.Currency), to);

        ConversionObject obj = new ConversionObject();
        obj.FROM = from;
        obj.TO = to;
        obj.ConversionRate = client.ConversionRate(frmEnum, toEnum);

        System.Web.Script.Serialization.JavaScriptSerializer Serializer = new JavaScriptSerializer();
        return Serializer.Serialize(obj);
    }
   
}

public class ConversionObject
{
    public string FROM
    {
        get;
        set;
    }

    public string TO
    {
        get;
        set;
    }

    public double ConversionRate
    {
        get;
        set;
    }
}

2)      Creating ASPX Page to use aspx
Create a aspx page in which add
Textboxes
1)       TxtFrom
2)       TxtTo
3)       TxtResult

Button
1) BtnGetTheResult
Change it’s onclient click property as  OnClientClick="return GetMeResultByAjax()"

4)      Calling ASMX service using JQUERY & Displaying response in aspx

Add script tag to head of our aspx page

<script type="text/javascript">
      function GetMeResultByAjax(){

           var frm = $('#TxtFrom').val();
           var to = $('#TxtTo').val();


           var data_to_post = "{from:'" + frm + "',to:'" + to + "'}";

           $.ajax({
               type: "POST",
               url: "MyService.asmx/GetConvertionRate",
               data: data_to_post,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: processSuccess,
               error: processError
            });
                return false;
            }


            function processSuccess(data, status, req) {
                var req_text = '';
                var req_value = ''

                if (status == "success") {
                    json_object = JSON.parse(req.responseText);
                    $.each(json_object, function (key, element) {
                        if (key == 'd') {
                           req_text = element;
                           req_value = JSON.parse(req_text).ConversionRate
                        }
                   });
                   $("#TxtResult").val(req_value);
                }
            }

            function processError(data, status, req) {
                alert("Failure:" + req.responseText + " " + status);
            } 
    </script>

Explanation:
On JavaScript onclick event of buttonBtnGetTheResult”  method “GetMeResultByAjax” get called Here in method

a)       data to be posted is created as JSON string
b)       $.ajax is jquery api to do ajax
c)       In $.ajax we are sending data as json string
d)       If ajax call succeed function “processSuccess” in which we are extracting required output.
Screenshot:


2013/11/21

Bridge Design Pattern & Logging System

   While going through some basic stuff about design pattern, I come across the Bridge design pattern & decided to implement it for Logging system. 
  My take is to separate concern about What Is Being Logged & where is being Logged.
An application can log errors as well as user actions too. Same time logging can go to various places like Database, EventLog or a File. 
   Here is Code for Classes that implement Logging system as Bridge Design pattern.
Code here is from a console application 'POALoggingAgent' with a class file 'LoggingAgent.cs' & implicitly created entry point i.e. Program.cs.

[LoggingAgent.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Data.SqlClient;

namespace POALoggingAgent
{
    //Process of Logging Should be Decoubled from Loggable Message
    abstract class LogImplementor
    {
        public abstract bool Log(string Message);
    }

    //Let us to change Logging Implementation at any latter moment when new requirement arise
    class LogAbstraction
    {
        protected LogImplementor Implementor;
        protected string Message;

        public LogAbstraction(string Msg)
        {
            Message = Msg;
        }

        // Implementor
        public LogImplementor LogImplementor
        {
            set
            {
                Implementor = value;
            }
        }

        public virtual  bool Log()
        {
            return Implementor.Log(Message);
        }
    }

    //what is to be logged an error,a user event,application event etc
    class ErrorLogAbstraction : LogAbstraction
    {
        Exception LogggbleException;
        public ErrorLogAbstraction(Exception exp):base(string.Empty)
        {
            LogggbleException = exp;
        }

        public override bool Log()
        {
            /*manipulate exception object propeties to build */
            Message = FormatMessage();
            return Implementor.Log(Message);
        }

        public string FormatMessage()
        {
            //Do Some work on LogggbleException to create formated message and set it to Message inherited Variable
            return "***" + LogggbleException .Message+ "***";
        }
    }

    //initial logging was on console
    class ConsoleLogImplementor : LogImplementor
    {
        public override bool Log(string Message)
        {
            try
            {
                /*BEGIN - Code To Log Message To Console*/
                /*END   - Code To Log Message To Console*/

                //Place Holder
                Console.WriteLine("Class:ConsoleLogImplementor,Method:Log,Message:" + Message);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }

    //logging to database is new requirement generated
    class DbLogImplementor : LogImplementor
    {
        public override bool Log(string Message)
        {
            try
            {
                /*BEGIN - Code To Log Message To DB*/
                /*END   - Code To Log Message To Db*/

                //Place Holder
                Console.WriteLine("Class:DbLogImplementor,Method:Log,Message:" + Message);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

Calling above code from our console Application

[Program.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace POALoggingAgent
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int i = 0;
                int j = 1;
                Console.WriteLine("Trying to Divide 1 by 0,Output = " + Convert.ToString(j / i));
            }
            catch (Exception exp)
            {
                LogAbstraction LogAb = new ErrorLogAbstraction(exp);

                //  choose console Logging Implementation
                LogAb.LogImplementor = new ConsoleLogImplementor();
                LogAb.Log();

                // choose Database Logging Implementation
                LogAb.LogImplementor = new DbLogImplementor();
                LogAb.Log();
            }
            // Wait for user
            Console.ReadKey();
        }
    }
} 
   To be Frank, I am not sure if Bridge Design Pattern is suitable case for Logging system as there are Singleton & Command, Chain of Responsibility & Subscriber- Publisher; that are often used with logging system.

   Anyone who willing to help me to improve above design of so called Logging system is more than welcomed!