Thursday, July 2, 2015

Routing to ASHX


Here is the piece of code that I found in CodeProject.com. By adding this extention method, you will be able to route the request to ASHX:

namespace System.Web.Routing
{
    public class HttpHandlerRoute : IRouteHandler
    {
        private String _virtualPath = null;
        private IHttpHandler _handler = null;

        public HttpHandlerRoute(String virtualPath)
        {
            _virtualPath = virtualPath;
        }

        public HttpHandlerRoute(IHttpHandler handler)
        {
            _handler = handler;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            IHttpHandler result;
            if (_handler == null)
            {
                result = (IHttpHandler)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(IHttpHandler));
            }
            else
            {
                result = _handler;
            }
            return result;
        }
    }

    public static class RoutingExtensions
    {
        public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
        {
            var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(physicalFile));
            RouteTable.Routes.Add(routeName, route);
        }

        public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, IHttpHandler handler, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
        {
            var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(handler));
            RouteTable.Routes.Add(routeName, route);
        }
    }
}

To access the routing data in ASHX, you need to do this:


            var o = context.Request.RequestContext.RouteData.Values["id"];
            if (o != null)
            {
                q = o.ToString();
            }

Reference:
http://www.codeproject.com/Tips/272258/ASP-net-HttpHandler-Routing-Support

Posting data in JSON format to the ASP.NET website using WinForm

Previously, we have shown how to post JSON data using JQuery to ASP.NET.

  http://laucsharp.blogspot.com/2013/03/posting-data-in-json-format-to-aspnet.html

Now, we are going to post JSON data using WinForm:

This is our business object which will reside at the server and client.

    public class Class1
    {
        public string code { get; set; }
        public string name { get; set; }

        public override string ToString()
        {
            return string.Format("code={0}, name={1}",
                this.code,
                this.name);
        }
    }

In the WinForm client program, when the user hit Button1 after keyed in the client code and name, the data will be submitted to the server:

        private void button1_Click(object sender, EventArgs e)
        {
            // store the user input into the business object.
            Class1 data = new Class1();
            data.code = this.client_code.Text;
            data.name = this.client_name.Text;

            // convert it into json format.
            JavaScriptSerializer js = new JavaScriptSerializer();
            string json_data = js.Serialize(data);

            // create the web request.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:57655/dataGateway.ashx");
            request.ContentType = "application/json;";           
            request.Method = "POST";

            // write the json data into the request stream.
            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(json_data);
            }

            // get the server response.
            using (WebResponse response = request.GetResponse())
            {
                // read the server response.
                Stream response_stream = response.GetResponseStream();
                using (StreamReader r = new StreamReader(response_stream))
                {
                    // do what ever you want with the response.
                    this.label5.Text = r.ReadToEnd();
                }
            }           
        }

Finally, at the server side, we add a Generic Handler (dataGateway.ashx) and it looks like this:

<%@ WebHandler Language="C#" Class="dataGateway" %>

using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;

public class dataGateway : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string s;
       
        // get the contents from the request stream
        Stream stream = context.Request.InputStream;
        using (StreamReader r = new StreamReader(stream))
        {
            s = r.ReadToEnd();
        }

        // ensure that the content is not empty.
        if (string.IsNullOrEmpty(s) || s.Length == 0)
        {
            context.Response.Write("'data' cannot be blank");
            return;
        }

        // convert it from json format to our business object
        JavaScriptSerializer js = new JavaScriptSerializer();
        Class1 obj = js.Deserialize<Class1>(s);

        // do whatever you want
        context.Cache["data"] = obj;

        // returns the response code/status to the caller.
        context.Response.Write("ok. received the data =>" + s);
    }

    public bool IsReusable { get { return false; } }
}

Next, sending compressed data in WinForm:

    http://laucsharp.blogspot.my/2018/04/posting-compressed-data-in-json-format.html