Posts

....
Technical Blog for .NET Developers ©

Thursday, February 28, 2013

Send and Retrieve Json data

When we develop web applications and we are adding Ajax functionality, it's a best practice using js libraries that implement code for cross-browsing and encapsulate the callings in a clear code way, such as jQuery, instead of using raw Ajax

In this post we have a web site making an async call to the server, the process continues querying a database and returning the response to the client side in json format, so the whole circuit of the process will be the next



The code in the server-side looks like this

     
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static JsonResult getElement(string atomicSymbol)
{
    using (SqlConnection connection = new SqlConnection
    (ConfigurationManager.ConnectionStrings["chemical_bd"].ConnectionString))
    {
        try
        {
            connection.Open();

            SqlCommand proc = new SqlCommand("K_SELECT_ELEMENT", connection);
            proc.CommandType = System.Data.CommandType.StoredProcedure;

            SqlParameter p_ASymbol = new SqlParameter("@asymbol", 
              System.Data.SqlDbType.VarChar, 3);
            p_ASymbol.Value = atomicSymbol;
            p_ASymbol.Direction = System.Data.ParameterDirection.Input;

            SqlParameter p_Name = new SqlParameter("@name",  
              System.Data.SqlDbType.VarChar, 20);
            p_Name.Direction = System.Data.ParameterDirection.Output;

            SqlParameter p_LatinName = new SqlParameter("@latin_name", 
              System.Data.SqlDbType.VarChar, 20);
            p_LatinName.Direction = System.Data.ParameterDirection.Output;

            proc.Parameters.AddRange(new SqlParameter[] { p_ASymbol, p_Name, p_LatinName });

            proc.ExecuteNonQuery();

            Chemical element = new Chemical()
            {
                name = p_Name.Value.ToString(),
                latin_name = p_LatinName.Value.ToString()
            };

            return new JsonResult() { Data = element };
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

Notice that the method which processes the request is defined as static. The class JsonResponse is defined in System.Web.Mvc namespace

The calling code in the client-side has the next structure

     
function getElement(atomicSymbol) {

    var jsonData = new Object();
    jsonData.atomicSymbol = atomicSymbol;

    var jsonString = JSON.stringify(jsonData);

    $.ajax({
        url: "callprocedure.aspx/getElement",
        type: "POST",
        data: jsonString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            var element = response.d.Data;
            $('#lblResult').text(element.name + " : " + element.latin_name);
        },
        error: function (result) {
            alert('ERROR: ' + result.status + ' ' + result.statusText);
        }
    });   
}

The result with a correct execution is the next




<METHOD SOFTWARE © 2013>

Sunday, February 3, 2013

Add data to Cache

A good use of the cache memory can improve notoriously the deployment of our web applications

While the HTML response associated to a page is stored in cache, the sent requests from this page will not be processed by the server, this implies a considerable reduction of time responses

In order to the server stores the HTML response associated to a page the first time it makes a request we have to apply the OutPutCache directive in our ASP view

     
<%@OutPutCache Duration="30" VaryByParam="*" %>

Where the attribute Duration indicates the time in seconds that the response will be held in cache. Through the attribute VaryByParam we indicate to the server how many kinds of responses should store, if the value is "none", only stores one, with the value "*" stores many different types of responses as different parameter values be added to the url in the request

The class HttpCachePolicy provides the control of cache through code. Every response has an object of type HttpCachePolicy associated, and we can find it in the property Cache of the Response object. Its main properties and methods are the next

- VaryByParams: controls the value of the attribute VaryByParam in the OutPutCache directive

- SetExpires: controls the value of the attribute Duration in the OutPutCache directive

- SetCacheability: this method controls the site where the response will be stored through the enum HttpCacheability, which possible values are the next:
· Private: the response will be cached in the client side, storing a copy of the response in the browser
· Public: The response is cached on both the client and the server and in intermediate proxy servers
· Server: The response is cached only in the server side

The cache memory of the server allows also storing application data in explicit way. The access to cache is key-value pair based

In this example we are adding a float type object to cache stored in the client side for 60 seconds, and reading it in the button's method

     
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.Private);
        this.Cache.Insert("data1", 1234.5F, null, DateTime.Now.AddSeconds(60),
            System.Web.Caching.Cache.NoSlidingExpiration, 
            System.Web.Caching.CacheItemPriority.High, null);
    }

    protected void btnReadCache_Click(object sender, EventArgs e)
    {
        object data = getDataCache("data1");
        if (data != null)
            lblData.Text = data.ToString();
        else
            lblData.Text = "Time expiration exceeded for data1 key";
    }

    private object getDataCache(string key)
    {
        if (this.Cache.Get(key) != null)
            return this.Cache[key];
        else
            return null;
    }
    





<METHOD SOFTWARE © 2013>