Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Sunday, October 2, 2011

The Repository Pattern

I'm not sure if Martin Fowler conceptualized the repository pattern, but his book Patterns of Enterprise Application Architecture (PoEAA) is where I first came across the definition:

"Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."

He has very carefully selected his words. I have my own definition. Consider it the layman's version:

"Separates data from its source." 

Let's dig into an example.

The Repository Pattern in .NET

Every .NET programmer has written some sort of code that accesses a database or web service and returns something. Traditionally, the ever-present n-tier/three-tier philosophy dictates that the code for that should be in its own package/layer, the data access layer. What that philosophy does not dictate is the method signature and the return type; they're extremely important. Let's look at your traditional DAL:

What will the dev on this project do if the People DB gets outsourced and is now accessed via webservice? Convert the web service return into datasets, or change all the business layer classes to work with whatever the new return is? Or, what if they change to a db that doesnt easily convert into datasets? Not a great position to be in... Why not change it to something more generic that will never change?...

Here's a look at the repository pattern implementation:

Notice how this implementation could survive through any sort of data source change because it is using "a collection-like interface"? Much more maintainable.

The Repository Pattern in JavaScript

JavaScript's implementation would need to take into account the fact that AJAX requests (or all node.js functions) are meant to happen asynchronously. In order to allow for this, all we really need to do is implement the callback pattern, which really just boils down to passing an extra function.

That's it!

Monday, May 3, 2010

Making Cross Domain jQuery AJAX Calls

Today's web browsers do not allow web pages to make cross-domain ajax calls. By this i mean that if you are at www.ajax.com and try to make an Ajax call ( an HTTP request using the XmlHttpRequest object) to www.other-domain.com the browser would not allow this to happen. Why? For security purposes that i cannot currently name.

However, at some point you get to a project where you're interfacing this third-party site that needs to talk to your main site, or some other similar situation where the only way you're going to get the data you need from point a to point b is with some javascript magic. Here is how to accomplish it:

How to get/post data using jQuery/javascript (JSONP)

The short answer: its not ajax at all, its JSONP. Yes, JSONP is not Ajax. I just learned this today. Like i said earlier, browsers do not allow XHR/Ajax cross-browser requests. JSONP avoids this by making a request for a script file-- no Ajax at all. Let me explain:

  1. Instead of accessing the XHR object, the browser first creates a new script tag to inject into the HTML DOM
  2. The script tag's URL is set to the URL you're looking to get/post(using HTTP GET) data to
  3. The script tag is injected into the page, causing...
  4. The request is sent to the server, even if its cross-domain
  5. The server returns the data in the form of a javascript function call
  6. The browser receives the data and executes the function call

jQuery code

//use a get to post a querystring value via HTTP GET to an asp.net webhandler
$.getJSON("http://www.example.com/get-post.ashx?var1=var1value&callback=?",function(data){
     //really no need to do anything here, we're just posting data
     //but this will output success
     alert(data.return);
});

asp.net generic handler/webhandler code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace jsonp_test
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class get_post : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string callback = "";
            try
            {
                if (!string.IsNullOrEmpty(context.Request["callback"]))
                {
                    if (!string.IsNullOrEmpty(context.Request["var1"]))
                        SaveData(context.Request["var1"]);
                    callback = context.Request["callback"];

                    context.Response.Write(callback + "({ \"return\": \"Success\" })");
                }
            }
            catch (Exception exc)
            {
                //hopefully this error doesnt contain any quotes... you know?
                context.Response.Write(callback + "({ \"return\": \"" + exc.Message + "\" })");
            }
        }

        private void SaveData(string value)
        {
            //do something with the var1 posted to us
        }

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

So what we effectively have here is the setup for asp.net cross domain ajax calls using jQuery

How to do cross-domain calls to others' servers: YQL

What if you need to do a get but don't have the ability to make the page its posting to return a JSONP response? Using YQL is a great way to achieve this.

YQL is a way to query the internet like it is a database. For example, one could easily run

select * from html where url="http://www.microsoft.com"

and recieve a JSONP return containing all of the site's HTML. You could also, do the following

select * from html where url="http://www.mircorosft.com?var1=var1value"

and HTTP GET values to the server. YQL does not allow this to happen on any area of any site that is blocked by the robots.txt file. Here's full example code:

//feel free to add querystring vars to this
var myurl="http://www.example.com/get-post.ashx?var1=var1value&callback=?";
//make the call to YQL 
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent(myurl)+
                "%22&format=xml'&callback=?",
        function(data){
          if(data.results[0]){
            //this data.results[0] is the return object you work with, 
            //if you actually want to do something with the returned json
            alert(data.results[0]);
          } else {
            var errormsg = '

Error: could not load the page.

'; //output to firebug's console //use alert() for other browsers/setups conole.log(errormsg); } } );

Friday, November 13, 2009

jQuery & .NET WebMethods: An Introduction

At some point in my programming I began to dislike the .NET page life-cycle. Sometimes I feel as though it was Microsoft's way of trying to impose a structure on something that really didn't need a structure. PHP and Java Servlets have proved this.

Regardless, with the advent of .NET AJAX WebMethods one can skip the life-cycle. For those of you who have been living in a cave for the last few years: 1) Your beard rocks. 2) AJAX (Asynchronous Javascript and XML) basically means that the web browser has a new role. In the old days, the browser would make a request and the server would send it an entirely new page for it to spit at the user. With AJAX, the browser sends a request and the server returns data, and then the browser performs actions on that data (like applying logic to the data and then updating page content). With AJAX the browser is in on the action; it is no longer just a middleman.

Setting Up Your First WebMethod



How do you add a WebMethod to your .NET page-behind code? Check out this code:

[WebMethod]
public static string SayHi()
{
return "Hi";
}

If you were to add this code as well as import System.Web.Services, you could call this function from your client-side JavaScript. No page life-cycle, no post-back; just a request for some data and a response. Using jQuery, the JavaScript code for this would look something like:

//this is the same as jQuery's $(document).ready([function])
//which means that it will call this function as soon as the page is loaded
$(function() {
$.ajax({
type: "POST",
//notice we put the page name and the function name here
url: "default.aspx/SayHi",
//the json data to send to the server (we'll discuss later)
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
//if the request is a success do something with the data
success: function(msg) {
//this alert box would say hi
alert(msg.d);
//this paragraph with id="hiparagraph" would say hi
$('p#hiparagraph').html(msg.d);
//this textbox with class="hitextbox" would say hi
$('input.hitextbox').val(msg.d);
},
//if the request is a failure, blame the user
error: function(xhr, textStatus, exception) {
alert('You are a failure.');
}
});
});

I know what you're thinking-- wow this is boring. And it is at this point. However, if you were to ask .NET to do this the old fashioned way, with a label and some code-behind assign-age I bet it would take twice as long-- maybe longer. In my experience, I have seen request/response times get cut to 1/10th (even 1/20th) the original time by using jQuery and WebMethods. For real.

What is JSON and What Happened to the XML?



All I know is that I haven't used XML directly yet in an AJAX call. JSON is JavaScript Object Notation. Its simple to learn-- check out this page for a little background.

What can you send or receive in the JSON? Short answer: anything. In our example we sent nothing, and received a string. With AJAX calls you can send any sort of JavaScript object. As for what you can receive, feel free to use any of the .NET generic types and any of your own custom made classes-- .NET will translate them into JSON for you.

In Conclusion


Now that we have a better way of communicating with the server, what can we do with it? In the next post we will get into some advanced scenarios and techniques with jQuery and .NET WebMethods.