<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Undisciplined Bytes &#187; Oliver Mezquita</title>
	<atom:link href="http://www.undisciplinedbytes.com/author/olivermezquita/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.undisciplinedbytes.com</link>
	<description>Web Application Development Tips, Tricks and Techniques</description>
	<lastBuildDate>Tue, 03 Aug 2010 14:02:09 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Unit testing</title>
		<link>http://www.undisciplinedbytes.com/2010/08/unit-testing/</link>
		<comments>http://www.undisciplinedbytes.com/2010/08/unit-testing/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 14:02:09 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=413</guid>
		<description><![CDATA[A unit test is a piece of code written with the sole intention of verifying that a routine or function behaves as we’re expecting it to. Unit testing attempts to provide a collection of tests to check every method of the different classes the developed program may contain works flawlessly. The general idea is that, [...]]]></description>
			<content:encoded><![CDATA[<p>A unit test is a piece of code written with the sole intention of verifying that a routine or function behaves as we’re expecting it to. Unit testing attempts to provide a collection of tests to check every method of the different classes the developed program may contain works flawlessly. The general idea is that, if all the parts of the program work properly independently, it’s highly likely that the program as a whole will function as expected. Of course, after all the unit tests are passed, integration tests must be performed as well to ensure the complete system doesn’t have any unintended behavior.</p>
<p><span id="more-413"></span></p>
<p>Those who have never tried unit testing before might be wondering right now… so, you’re saying that we need to write code that isn’t destined to make the application work? As if regular coding wasn’t hard enough! Well, keep in mind that these isolated tests provide different basic advantages:</p>
<ul>
<li><strong>Unit testing promotes change</strong>: It facilitates a programmer to rewrite some code to improve its structure, architecture or performance (what is called refactoring). These tests will be run afterwards, making sure the code still has the same functionality as before.</li>
<li><strong>Unit testing simplifies integration</strong>: If we apply unit tests to all the different parts of our code, once we reach the integration phase we can be certain the code is actually working properly. This way integration tests will be simplified and the time spent in this phase will be highly reduced.</li>
<li><strong>Unit testing documents the code</strong>: The very tests themselves tell other programmers how to use the code and its intended behavior.</li>
<li><strong>Unit testing facilitates and promotes separation between interface and implementation</strong>: Since the only interaction between test cases and the code being tested are their interface, any change to them must be done without changing it.</li>
<li><strong>Unit testing make errors bounded and easier to locate</strong>: since you’re checking the behaviour of a small piece of code at a time.</li>
<li><strong>Unit testing discovers bugs very early in the development process</strong>: always remember that <strong>the effort to solve a bug is not a linear but an exponential function in time</strong>: the more time elapsed from the writing of the code till the discovery of a bug, the more difficult it will be to remove it. The majority of bugs of a module must be taken care of before marking that module as finished.</li>
</ul>
<p>Unit tests are a fundamental tool to catch bugs early in the development process. I will never get tired to repeat that <strong>bugs must be discovered as soon as possible</strong>: if a bug is discovered in pre-production phase it will most likely be extremely difficult to take care of… or it might not even be removed at all!</p>
<p>Although I mention some of the benefits of using unit tests here, I can’t really explain how much your experience as developer will improve by using them! If you start writing unit tests for all the code you write, you will very shortly start to produce modules with <strong>many many many less bugs </strong>than before, making you a faster and more productive developer, and improving the relationship with your boss and clients.</p>
<p>So, if I have already convinced you of how convenient the habit of writing unit tests is, take a look at <a href="http://www.nunit.org/" target="_blank">NUnit</a>. NUnit is the most used unit testing framework for .NET and Mono. It is open source, and has a whole bunch of <a href="http://www.nunit.org/index.php?p=documentation" target="_blank">documentation</a> available, so it shouldn’t be very difficult to get started with it.</p>
<p>Just to get an idea of what NUnit is about, here’s some example code:</p>
<pre class="brush:c#">using NUnit.Framework; 

[TestFixture]
public class NUnitExample
{
    [Test]
    public void Test()
    {
         Assert.AreEqual(10, 5+5, "Add");
    }
}</pre>
<p>Simple enough, right? Well, trust me when I tell you that it can really get much more complicated than this… but still, this will give you an idea about what this whole thing is about.</p>
<p>Now, you have to keep in mind that, as with all writing of code, the quality of unit tests depends on the programmer. If you write bad unit tests, then you won’t have advanced a great deal in discovering possible bugs. <strong>Unit tests are not miracles, they are just one more tool you have to do your job better.</strong></p>
<p>But as true as this is, I totally recommend you to start trying out unit testing ASAP! Don’t be lazy to start writing unit tests! The time you loose today in writing one will be recovered tomorrow multiplied by a factor of 10. Once you have the habit of always writing unit tests, you’ll see that you’re much more productive than before.</p>
<p>You just must keep on practicing writing unit tests. As all things in life, the more you practice, the better you’ll do!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/07/improving-software-quality-automatic-testing/' rel='bookmark' title='Permanent Link: Improving software quality: automatic testing'>Improving software quality: automatic testing</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/08/unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Improving software quality: automatic testing</title>
		<link>http://www.undisciplinedbytes.com/2010/07/improving-software-quality-automatic-testing/</link>
		<comments>http://www.undisciplinedbytes.com/2010/07/improving-software-quality-automatic-testing/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 14:14:15 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/2010/07/improving-software-quality-automatic-testing/</guid>
		<description><![CDATA[Providing high quality software from early stages in the software project is the key to a successful project. We must check the quality of our software in every single release and make sure it’s meeting our expectations. It’s much easier to code having quality requirements in mind from the very beginning than finishing a module [...]]]></description>
			<content:encoded><![CDATA[<p>Providing high quality software from early stages in the software project is the key to a successful project. We must check the quality of our software in every single release and make sure it’s meeting our expectations. It’s much easier to code having quality requirements in mind from the very beginning than finishing a module and then fixing all the unexpected behavior afterwards.</p>
<p>There are many tools to improve the quality of our work. Developers have refactoring tools, memory profilers, code coverage, etc. But in a software project we also have testing resources, also known as Quality Assurance. Their job is to test the application and find as many bugs as possible: to achieve a high quality product, thorough testing is a very important step. However, this can be a very tedious and time-consuming task. Fortunately, part of this work can be performed automatically using some tools.</p>
<p><span id="more-368"></span></p>
<p>Automated testing tools provide:</p>
<ol>
<li><strong>Better software</strong><br />
By building a library of automated tests, you are generally going to ship better software that you can guarantee will work when used in certain, predictable, preconceived ways (the uses cases that have been accounted for in the tests).</li>
<li><strong>Continuously-run tests<br />
</strong>Once you have tests automated, there is very little cost to running the tests. As such, once you’ve made the investment in building automated tests scripts, there is no good reason not to run them frequently. You could schedule a process to run all tests every night, and get the results in the morning to start fixing the bugs as soon as possible.</li>
<li><strong>Cheaper to fix bugs</strong><br />
The moment in which you find the bug and how much it costs to fix are highly correlated. The more time that elapses from when the bug was created to when the bug is actually found, the more expensive the bug becomes to find and fix. If it is found in a matter of hours instead of weeks (or maybe even months) the amount of effort involved in fixing it is going to be <em>orders of magnitude </em>smaller.</li>
<li><strong>Freedom to change and evolve the software</strong><br />
As software systems get bigger, it becomes harder and harder to make changes without breaking things. If you’ve got a large battery of automated test scripts, it frees the programmers to touch parts of the code that they might have fear to break otherwise.  the automated testing is a “safety net”: they can refactor the code, add or change features, etc. with a lot less loss of sleep.</li>
<li><strong>Happier clients</strong><br />
Less bugs mean less problems with customers, less support costs and higher retention rates.</li>
</ol>
<p>A growing trend in software development is the use of testing frameworks that allow the execution of <strong>unit tests</strong> to determine whether various sections of the code are acting as expected under various circumstances. Test cases describe tests that need to be run on the program to verify that the program runs as expected. These tests are written to define the functionality <em>before</em> the code is written. Only when all tests pass is the code considered complete.</p>
<p>Many test automation tools provide record and playback features that allow users to interactively record user actions and replay it back any number of times, comparing actual results to those expected. The advantage of this approach is that it requires little or no software development to perform the tests. This approach can be applied to any application that has a graphical user interface. These tools perform what is called <strong>Graphical User Interface (GUI) testing</strong>.</p>
<p>In the next two posts we’ll be discussing Unit and GUI testing tools. Stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/08/unit-testing/' rel='bookmark' title='Permanent Link: Unit testing'>Unit testing</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/07/improving-software-quality-automatic-testing/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>HTML 5 C# Web Sockets server and ASP.NET client implementation</title>
		<link>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/</link>
		<comments>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 14:02:14 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=396</guid>
		<description><![CDATA[In the previous post we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.
I’ve developed a very basic Web [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a title="HTML 5 Web Sockets" href="http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/" target="_blank">previous post</a> we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.</p>
<p>I’ve developed a very basic Web Socket server implementation in C# just as a proof of concept. It handles the most basic operations you would expect from a server: start a new connection, disconnect, and send and receive data. Besides, I’ve developed the client part as well using regular ASP.NET. Actually it’s just plain HTML and JavaScript being served from an ASP.NET server – this example doesn’t use any fancy <em>runat=server </em>controls or anything of the like. The functionality is achieved with very simple and easy to understand JavaScript.</p>
<p><span id="more-396"></span></p>
<p>So what does this example do? It provides two projects: a Web Socket server and a Web Socket client. The server is a windows console application that once executed just sits there waiting for a connection request. When a client connects, the server sends its date and time to the client every 10 seconds. The client is a web page with some controls to connect/disconnect and to send data to the server, as well as a log window to see what’s going on. Take a look at the example at the bottom of the page.</p>
<p>Here’s a description of the public members of the Web Socket Server:</p>
<pre class="brush:c#">// Possible status of the server
enum ServerStatusLevel { Off, WaitingConnection, ConnectionEstablished };
// Constructor of the server with default values
WebSocketServer();
// Constructor of the server with the specified values
WebSocketServer (int serverPort, string serverLocation, string connectionOrigin);
// Close the server and release all resources
void Dispose();
// Start the server and make it listen for connection requests
void StartServer();
// Send data to the connected client
void Send (string message);
// Whether events should be logged or not
bool LogEvents;
// Origin of the connection
string ConnectionOrigin;
// Location of the server
string ServerLocation;
// Port of the server
int ServerPort;
// Current status of the server
ServerStatusLevel Status;
// Fired when data is received from the client
event DataReceivedEventHandler DataReceived;
// Fired when client is disconnected
event DisconnectedEventHandler Disconnected;
// Fired when a new connection is established
event NewConnectionEventHandler NewConnection;</pre>
<p>Note how I provide two constructors for the Web Socket Server class: one with default parameters (if you want to keep it as simple as possible), and another one to specify the values you want. Anyways, you can still change them after creating the new instance, as the properties are public. You can also specify whether you want the server to log out the events to the console with the <code>LogEvents</code> property.</p>
<p>In order to get the data being sent from the client, you must attach your own function to the <code>DataReceived</code> event, which will then receive the message as a parameter.</p>
<p>So here’s how you would use this Web Socket Server:</p>
<pre class="brush:c#">public void Test()
{
    WebSocketServer WSServer = new WebSocketServer();  // Default values
    WSServer.NewConnection += new NewConnectionEventHandler(WSServer_NewConnection);
    WSServer.Disconnected += new DisconnectedEventHandler(WSServer_Disconnected);
    WSServer.DataReceived += new DataReceivedEventHandler(WSServer_DataReceived);
    WSServer.StartServer();
}

void WSServer_DataReceived(string message, EventArgs e)
{
    Console.WriteLine("Data received from the client: " + message);
}

void WSServer_Disconnected(EventArgs e)
{
    Console.WriteLine("Server disconnected");
}

void WSServer_NewConnection(EventArgs e)
{
    Console.WriteLine("New connection established");
    WSServer.Send("Hello new client! I hope you enjoy your visit!");
}</pre>
<p>It’s a very simple Web Socket server, so it’s very easy to use. You shouldn’t have much problem understanding it.</p>
<p>Go ahead and download the Visual Studio solution and give it a try!</p>
<p><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/06/WebSocketsTest.zip" target="_self">WebSocketsTest.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/' rel='bookmark' title='Permanent Link: HTML 5 Web Sockets'>HTML 5 Web Sockets</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>HTML 5 Web Sockets</title>
		<link>http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/</link>
		<comments>http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/#comments</comments>
		<pubDate>Sun, 30 May 2010 17:07:48 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=386</guid>
		<description><![CDATA[Following the series of posts discussing AJAX calls, today we’ll see what is going to be its evolution: Web Sockets. It’s still a very new technology, and support is starting to be implemented in most major browsers and web servers. But don’t count on using it yet, since most of the clients of your web [...]]]></description>
			<content:encoded><![CDATA[<p>Following the <a title="ajax calls" href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/" target="_blank">series of posts discussing AJAX calls</a>, today we’ll see what is going to be its <strong>evolution</strong>: Web Sockets. It’s still a very new technology, and support is starting to be implemented in most major browsers and web servers. But don’t count on using it yet, since most of the clients of your web app will not be able to use them. I’ll discuss web sockets here just so you know what the future is going to bring to the web apps world.</p>
<h4>The history: the beginning of AJAX</h4>
<p>The world wide web and the Internet started as a stateless content delivery mechanism, taking a step backwards compared to traditional desktop applications. Early Internet applications needed to explicitly request every piece of information, and the server sent only the requested data.</p>
<p>Then came what we now call “Web 2.0 application development”: Dynamic HTML, heavy usage of JavaScript, AJAX, and various plugins (Adobe Flash and Microsoft Silverlight). These applications were dynamic and responsive, and they brought much of that rich interactive experience users enjoyed in desktop client/server applications to the Internet. However, due to the request and response architecture that these applications are based on, the latest Rich Internet Applications still cannot match the connectivity and the capability to get real-time data that client/server applications had more than a decade ago.</p>
<p><span id="more-386"></span></p>
<p>The reason is that these applications still need to initiate the communication from the web browser to get some data from the server: that is, the client part of the application running in the web browser has no way to know whether the server has some data for it.</p>
<h4>The next logical step: polling and Comet programming techniques</h4>
<p>Thus, software engineers started working in solving this problem. The client needed to be conscious of any request the server might have for it. But how to achieve this? Well, if communication can only be started by the client, then let’s just make it that way. We’ll make the client constantly ask the server whether there’s some data ready for it. This is what is called <strong>polling</strong>.</p>
<p>By using this technique, the web application essentially polls the server on a regular basis, based on a timer, using a simple HTTP request each time the timer expires. However, the cost of polling frequently is very high – both in terms of network bandwidth as well as server infrastructure needed to support a huge number of polling requests. The server must have the capability to buffer the data that it needs to send to the client until the next request comes from the client.</p>
<p>After a short while, this technique was seen totally unusable due to its great resource requirements. Then came the <strong>Comet programming techniques –</strong> long polling and streaming:</p>
<p>In <strong>long polling</strong>, also known as asynchronous polling, the browser sends a request to the server and the server keeps the request open for a set period. If a notification is received within that period, a response containing the message is sent to the client. If a notification is not received within the set time period, the server sends a response to terminate the open request and the browser resends the request to the server.</p>
<p>When <strong>streaming</strong> is used, the browser sends a complete request, but the server sends and maintains an open response that is continuously updated. A request is sent and kept open indefinitely (or for a set period of time) and the response is updated whenever a message is ready to be sent, but the server never signals to complete the response, thus keeping the connection open to deliver future messages.</p>
<p>But if you think about it, these techniques are just <strong>hacks</strong>, <strong>tricks</strong> used to <em><strong>simulate</strong></em> a technology that doesn’t exist: server-sent events. If the server could actually start the communication, none of these ugly tricks would be needed.</p>
<h4>The evolution: server-sent events &amp; Web Sockets</h4>
<p>We had to wait until HTML 5 came to solve this problem. The Communication section in the HTML 5 specification section introduces server-sent events and Web Sockets. These new features enable a new paradigm of web application programming that will revolutionize the way to develop and deploy web applications.</p>
<p>Server-sent events are not quite the solution, but a formalization of Comet programming techniques. The server-sent event HTML 5 specification introduces a new DOM element called <em>eventsource</em>.</p>
<p>But the guy we must pay all our attention to is the HTML 5 Web Socket specification: the Web Socket interface defines a<strong> full duplex communications channel</strong> that is exposed via a JavaScript interface in HTML 5 compliant browsers.</p>
<p>When a new Web Socket connection is established, the browser opens an HTTP connection to the server first and then negotiates with the server to upgrade the connection to a dedicated and persistent Web Socket connection. This process automatically sets up a tunnel through to the server, solving numerous issues that the various Comet programming techniques encountered. Once established the Web Socket is a full duplex channel between the client and the server.</p>
<p>I&#8217;ve developed a Web Socket server and client implementation. <a href="http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/">Check it out</a> for yourself and see what I&#8217;m talking about!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>AJAX call using ASP.NET Web Services</title>
		<link>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/</link>
		<comments>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 19:17:10 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=382</guid>
		<description><![CDATA[We’ve already seen quite a few ways of performing AJAX calls: web pages, HTTP Handlers and Page Methods. Today we’ll see how to request data from the server using ASP.NET Web Services.
Web Services are a very general model for building applications, and can be implemented for any operation system that supports communication over the Internet. [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already seen <a href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/">quite a few ways of performing AJAX calls</a>: <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/">web pages</a>, <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/">HTTP Handlers</a> and <a href="http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/">Page Methods</a>. Today we’ll see how to request data from the server using ASP.NET Web Services.</p>
<p>Web Services are a very general model for building applications, and can be implemented for any operation system that supports communication over the Internet. A Web Service is some programmable application logic accessible via standard Web protocols. It is often referred to as <em>Web APIs </em>as well, since they are a set of methods that provide some functionality through remote method calls. It is a way of <strong>offering some of your functionality to all of the internet</strong>. But, of course, some kind of restrictions and security can be built into your web services, if that’s what you wish.</p>
<p><span id="more-382"></span></p>
<p>As it turns out, the previous article I posted showing how to use Page Methods was also a Web Service: Web Methods are the building blocks of Web Services (a Web Service has many different Web Methods). But it was a very small and simple implementation, intended to return simple data to a small script placed in that same web page. The example we’re going to see follows the same concept, but in a larger way. We’re going to see the basics of how to implement a full-blown Web Service that can be accessed from anywhere on the internet.</p>
<p>This is very handful if you want to develop a collection of methods to be called from anywhere in your application. Imagine you’d like to know in which moment the user logged in to the system: you could write this server method and then make it public as a web service. This way, you’ll have this server functionality available through an AJAX call from anywhere in the application.</p>
<p>Ok, enough theory, now let’s get our hands dirty. Get to the .aspx part of the web page in which you wish to implement your ajax call, and write the HTML code we’ve been using in all our examples:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>We need a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now, the Javascript code:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
    function ExecuteAJAXCall() {
        $.ajax({
            type: "POST",
            url: "AJAXCalls.asmx/GetServerTime",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data.d;
    };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. This time, this function has changed a bit from other examples. Web Services calls require more parameters to set the communication between client and server up. The content type must be declared as “application/json; charset=utf-8”. And, as with the <a href="http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/">previous Page Method example</a>, server procedures are called using the syntax <code>[page name] + “/” + [method name]</code>.</p>
<p>When the AJAX call returns, we have the usual function that takes care of painting the result on the screen. Note how we need to use the <code>d</code> property to access the data this time.</p>
<p>Now, we need to write the Web Service. The easiest way is to right-click on your project and add a new item from there. Select Web Service, and you’ll get a skeleton from which you can implement the functionality you wish in your web service. For our example, we’ll write this piece of code:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceAJAXCall
{
    /// &lt;summary&gt;
    /// Summary description for AJAXCalls
    /// &lt;/summary&gt;
    [WebService(Namespace = "http://www.undisciplinedbytes.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class AJAXCalls : System.Web.Services.WebService
    {

        [WebMethod] public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}</pre>
<p>As you can see, we’ve only written the code required to return the server date and time. If you compare this example to the previous one where I explained how to implement AJAX calls with page methods, you can see that this is essentially the same thing. It all comes down to using the <code>WebMethod</code> attribute from the <code>System.Web.Services library</code>. However, this example that we’re seeing today is more complete, as it is implemented using a full-blown web service. The objective of this article is not to fully explain ASP.NET Web Services (I’ll leave that to some other post I have in mind), but to explain the very basics to be able to implement and AJAX call using them, so I won’t bother about diving into the details. But keep in mind that <strong>Web Services are much more powerful than this</strong>, and that <a title="Web Services" href="http://en.wikipedia.org/wiki/Web_service" target="_blank">their intention aim much higher</a> than simple AJAX calls.</p>
<p>Here’s the Visual Studio project for you to play with:</p>
<p><a title="Web Service AJAX Call" href="http://en.wikipedia.org/wiki/Web_service" target="_blank">WebServiceAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET Page Method</title>
		<link>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/</link>
		<comments>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 18:26:09 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=367</guid>
		<description><![CDATA[We’ve already been through AJAX calls using simple web pages and HTTP Handlers. But there’s still more ways to request data from the server. Today we’ll take a look at how to do so using server methods.
ASP.NET allows you to define methods in the code-behind of an ASPX page. This is very helpful in situations [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already been through AJAX calls using simple web pages and HTTP Handlers. But there’s still more ways to request data from the server. Today we’ll take a look at how to do so using server methods.</p>
<p>ASP.NET allows you to define methods in the code-behind of an ASPX page. This is very helpful in situations where you want to expose some specific server side functionality such as data retrieval for a specific page. If you need to make the operation available to multiple different .aspx pages it’s a better idea to use a web service so your pages can share the functionality. We’ll see how to use web services in the next post.</p>
<p>Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carried around by an ASP.NET page.</p>
<p><span id="more-367"></span></p>
<p>Ok, so we’ll set up the HTML we need to run this test. We’ll use the same one we’ve been using in all our examples:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>As usual, we’ll draw a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now, the Javascript call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
    function ExecuteAJAXCall() {
        $.ajax({
            type: "POST",
            url: "default.aspx/GetServerTime",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data.d;
    };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. This time, this function has changed a bit from other examples. Page method AJAX calls require more parameters to set up the communication between client and server. We need to set the content type, and send the parameters to the method, even if it is a parameter-less method. Note how we’re calling the method by using the syntax <code>[page name] + “/” + [method name]</code>.</p>
<p>When the AJAX call returns, we have the usual function that takes care of painting the result on the screen. Note how we need to use the <code>d</code> property to access the data this time.</p>
<p>Now comes the interesting part. As we saw before, we’re programming a serverside method in the same web page to return the data from the server, so we don’t need any more web pages in our project. To implement this functionality, get to the codebehind part of the web page and write this code:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace PageMethodAJAXCall
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod] public static string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}</pre>
<p>The secret behind this magic is just the <code>System.Web.Services</code> library we’re importing. This library provides the <code>WebMethod</code> attribute, which can be used in <code>public static</code> methods to indicate they’re to be accessed by remote client calls. Whatever the function returns will be sent to the client. Note how this time we don’t need to serialize the data nor we need to deactivate the cache: everything is taken care of by the Web Services library. You just need to set the <code>WebMethod</code> attribute and return the data you want. Nothing more is required.</p>
<p>I would say this way of performing AJAX calls is the easiest of all. It requires almost no more concepts than what a developer will have from regular programming, and hides much of the complexity. However, it is not the standard way of communicating with the server for controls, plugins and widgets out there, so it is not always possible to use it. But if you’re developing your own web control from scratch or you can tweak the way some other web control requests data, you should consider using this technique. Remember: <strong>keep it simple!</strong></p>
<p>As usual, you can take the Visual Studio project from here and take a look at it:</p>
<p><a title="Page Method AJAX Call Project" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/04/PageMethodAJAXCall.zip" target="_self">PageMethodAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET HTTP Handler</title>
		<link>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/</link>
		<comments>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 14:56:19 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=357</guid>
		<description><![CDATA[We’ve already seen how to perform an AJAX call using just a simple ASP.NET web page. Now we’ll see how to do it with an HTTP handler instead of a web page.
But, what is an HTTP handler? Well, as its names suggests, it is an element that handles HTTP requests. Well, but that’s what an [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already seen <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/" target="_blank">how to perform an AJAX call using just a simple ASP.NET web page</a>. Now we’ll see how to do it with an HTTP handler instead of a web page.</p>
<p>But, what is an HTTP handler? Well, as its names suggests, it is an element that <em>handles </em>HTTP requests. Well, but that’s what an .aspx web page does, right? Sure, but in a lengthier, slower and resource-hungrier way. Regular web pages inherit from the <code>System.Web.UI.Page</code> class, which contains a lot of overhead and pre and post-processing in order to make it easier for the programmer to return HTML code to the client performing a request. In other words, the web page class has stuff to make it easier to develop a web page. It’s got some logic, doesn’t it?</p>
<p><span id="more-357"></span></p>
<p>But, what if we don’t want to return a web page? Then we’re just wasting resources in our server, since we’re not to going to use any of the facilities the web page class provides. If what we want to return is not an actual web page, then you should avoid using the <code>System.Web.UI.Page </code>class.</p>
<p>We’ll take a closer look at HTTP handlers in some other post I’m preparing, but for now you should know that they’re more adequate for processing AJAX requests.</p>
<p>This example is quite similar to the <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/" target="_blank">previous one</a>: the only difference is that the HTTP handler replaces the web page. Except for that, we’ll be doing the same call and using the same javascript code. However, just for clarity’s shake, I’ll be posting all the code involved here.</p>
<p>Ok, so now we’ll get our hands dirty and start doing some work! First, we’ll need some HTML code to draw a simple test page. Start a new Visual Studio Project and get to the newly created page. On the C# codebehind of the new page we won’t be changing anything. Leave everything by default. We’ll be doing our work in the .aspx part. This HTML code should be sufficient for our needs:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;jQuery AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>This is a very simple page. We’ll just have a heading, a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now we need some actual code to make the AJAX call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
   function ExecuteAJAXCall() {
         $.ajax({
             url: "AJAXRequest.ashx",
             dataType: 'json',
             success: Callback_AJAXCall
         });
   };

   function Callback_AJAXCall(data) {
         document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data;
   };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. We’re passing three parameters to the function: the URL of the element that will get called, they type of data we’re expecting back (JSON in this case) and the javascript function to execute once the data gets back to the client. The jQuery ajax function has <a href="http://api.jquery.com/jQuery.ajax/">many more parameters</a>, but we didn’t need them this time since the example is not very complicated.</p>
<p>The function called when the data is returned is very simple: its only purpose is to take the string returned from the server and write it in the container we previously created for this purpose. Note that the parameter it receives, data, is already a javascript object. The AJAX call returns a simple string from the server, but the jQuery function is smart enough to convert that string to a javascript object and pass it to the function we indicated.</p>
<p>Ok, now we’re getting to the interesting point. Now that we have the test page in place, let’s deal with the AJAX call server-side. The <code>AJAXRequest.ashx </code>HTTP handler is the link between the client web browser and the server. Here we’ll process everything we need and we’ll return a string to the client with the data requested.</p>
<p>So here’s how we program an HTTP handler:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    ///
    /// Processes AJAX requests
    ///
    public class AJAXRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            string CurrentDate = DateTime.Now.ToString();

            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            context.Response.Write(JSSerializer.Serialize(CurrentDate));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}</pre>
<p>To implement an HTTP handler you just need to implement the <code>System.Web.IHttpHandler</code> interface. You need to provide the desired behaviour to the <code>ProcessRequest</code> method and the  <code>IsReusable</code> property. The first method is the one which actually takes care of processing the HTTP requests and returning the data. The <code>IsReusable</code> property determines whether this instance of HTTP handler can be reused for fulfilling another request of the same type.</p>
<p>This implementation is very simple: it just takes the current date and time from the server, converts it to JSON format and returns it. Note the <code>System.Web.Script.Serialization</code> class we’re importing. This class takes care of converting the object we want to return to JSON format. Note the line in which we deactivate the cache as well. If you don’t do this, the AJAX call will always seem to return the same data, as the web browser will have kept a copy of it the first time it was executed. Most AJAX calls need the cache disabled in order to work properly.</p>
<p>You can download a copy of the Visual Studio project and do some tests to check how it works:</p>
<p><a title="jQuery AJAX HTTP Handler Call Visual Studio Project" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/03/jQueryAJAXHTTPHandlerCall.zip" target="_self">jQueryAJAXHTTPHandlerCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET web page</title>
		<link>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/</link>
		<comments>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 14:56:18 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=336</guid>
		<description><![CDATA[We already saw what an AJAX call is and the different types there are. Today we’re going to see how to perform an AJAX call using a regular web page at the server. The page will be the connection between the client’s web browser and the server. It will take care of performing the operations [...]]]></description>
			<content:encoded><![CDATA[<p>We already saw what an <a title="AJAX calls" href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/" target="_blank">AJAX call is and the different types there are</a>. Today we’re going to see how to perform an AJAX call using a regular web page at the server. The page will be the connection between the client’s web browser and the server. It will take care of performing the operations at the server (let it be some kind of processes or calculations, or just a regular database access).</p>
<p>I’ll be using <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a> in this example. <strong>jQuery is a superb </strong><a title="Javascript frameworks" href="http://www.undisciplinedbytes.com/2009/10/javascript-frameworks-overview/" target="_blank">Javascript framework</a>, and is the one I use the most. If you don’t know what it is yet, then the first thing you should do is getting acquainted with it. This JavaScript framework has <a title="jQuery functions to make an AJAX call" href="http://docs.jquery.com/Ajax" target="_blank">many convenient functions to make an AJAX</a> call. These functions hide much of the complexity of an AJAX call: you can forget about the <a title="XMLHttpRequest" href="http://en.wikipedia.org/wiki/XMLHttpRequest" target="_blank">XMLHttpRequest</a> object if you wish, and only worry about what to do with the data once you get it back from the server.</p>
<p><span id="more-336"></span></p>
<p>So, in order to perform an AJAX request, we’ll follow these steps:</p>
<ol>
<li>We’ll perform an AJAX call from the client, using Javascript. As I said before, we’ll be using jQuery. It makes the process much easier.</li>
<li>We’ll construct some way for the server to receive the request: in this example we’ll use a regular .aspx web page.</li>
<li>We’ll fetch the data to be returned to the client. This example is just a proof of concept, so we’ll leave this task to the reader. We’ll just return the server time.</li>
<li>We’ll convert that data into JSON notation.</li>
<li>Once the data gets back to the client, the jQuery library takes care of the conversion of the string received from the server to a Javascript object.</li>
<li>In this point we’ll have the data available to us. We’ll do something with it to show it on screen, for example.</li>
</ol>
<p>Ok, we already have the theory covered. Now, let’s get to work! Start a new Visual Studio project, and get to the newly created page. On the C# codebehind of the new page we won’t be changing anything. Leave everything by default. We’ll be doing our work in the .aspx part. First, we’ll need a little bit of HTML to draw our page:</p>
<pre class="brush:xml">&lt;body&gt;
   &lt;form id="form1" runat="server"&gt;
     &lt;h2&gt;jQuery AJAX call test page&lt;/h2&gt;
     &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
     &lt;br /&gt;&lt;br /&gt;
     &lt;div id="DataContainer" &gt;&lt;/div&gt;
   &lt;/form&gt;
&lt;/body&gt;</pre>
<p>This is a very simple page. We’ll just have a heading, a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server.</p>
<p>Now we need some actual code to make the AJAX call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;

    function ExecuteAJAXCall() {
        $.ajax({
            url: "AJAXCall.aspx",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data;
    };

&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. We’re passing three parameters to the function: the URL of the page that will get called, they type of data we’re expecting back (JSON in this case) and the javascript function to execute once the data gets back to the client. The jQuery ajax function has <a href="http://api.jquery.com/jQuery.ajax/" target="_blank">many more parameters</a>, but we didn’t need them this time since the example is not very complicated.</p>
<p>The function called when the data is returned is very simple: its only purpose is to take the string returned from the server and write it in the container we previously created for this purpose. Note that the parameter it receives, data, is already a javascript object. The AJAX call returned a simple string from the server, but the jQuery function is smart enough to convert that string to a javascript object and pass it to the function we indicated.</p>
<p>Ok, so now that we have the test page in place, let’s deal with the AJAX call server-side. The <code>AJAXCall.aspx </code>page is the link between the client web browser and the server. Here we’ll process everything we need and we’ll return a string to the client with the data requested.</p>
<p>Here is the C# codebehind from the <code>AJAXCall.aspx</code> page:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

namespace jQueryAJAXCall
{
    public partial class AJAXCall : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) // Returns the server current date and time
        {
            JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            string CurrentDate = DateTime.Now.ToString();
            Response.CacheControl = "no-cache";
            Response.Write(JSSerializer.Serialize(CurrentDate));
        }
    }
}</pre>
<p>Note the <code>System.Web.Script.Serialization</code> class we’re importing. This class takes care of converting the object we want to return to JSON format.</p>
<p>This page is very simple: it just takes the current date and time from the server, converts it to JSON format and returns it. Nothing more is needed. Simple enough, right? Be aware that this page must not return anything else than the JSON string: if you’re using Visual Studio be careful when creating this new webpage, as VS adds a bunch of HTML code by default in the .aspx page. Erase all HTML code, otherwise your javascript won’t be able to understand the data sent back.</p>
<p>Note the line in which we deactivate the cache. If you don’t do this, the AJAX call will always seem to return the same data, as the web browser will have kept a copy of it the first time it was executed. Most AJAX calls need the cache disabled in order to work properly.</p>
<p>So this is it! Nothing else is required. Donwload the Visual Studio project and play with it as much as you want:</p>
<p><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/02/jQueryAJAXCall.zip">jQueryAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Different ways to use AJAX in ASP.NET</title>
		<link>http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/</link>
		<comments>http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 14:53:34 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=314</guid>
		<description><![CDATA[Today’s web applications are unthinkable without AJAX techniques. These techniques provide an improved user experience, and tighten the gap between traditional desktop applications and web applications. This means that mastering AJAX technologies is a must for anyone who’s doing serious web application development. In this article I’ll explain the basics of AJAX, and I will [...]]]></description>
			<content:encoded><![CDATA[<p>Today’s web applications are unthinkable without <a title="AJAX" href="http://en.wikipedia.org/wiki/AJAX" target="_blank">AJAX</a> techniques. These techniques provide an improved user experience, and tighten the gap between traditional desktop applications and web applications. This means that mastering AJAX technologies is a must for anyone who’s doing serious web application development. In this article I’ll explain the basics of AJAX, and I will show how to program some AJAX calls using ASP.NET technology.</p>
<p><span id="more-314"></span></p>
<h4>First things first: the basics</h4>
<p><a href="http://en.wikipedia.org/wiki/AJAX" target="_blank">AJAX</a> is a set of web application development techniques used to create <a href="http://en.wikipedia.org/wiki/Rich_Internet_application" target="_blank">RIA</a> (<em>Rich Internet Applications</em>). These techniques are used in the web browser at the client’s computer, while an asynchronous communication with the web server is held in the background. Thus, it is possible to make changes in the pages without the need to reload them, increasing interactivity, speed and usability in these applications, compared to traditional click-and-wait web pages.</p>
<p>An AJAX call is nothing more than a request to the server for some data. It is the same thing as when you type in a web page address in your browser’s address box and hit Enter: your browser requests the server the HTML code representing that webpage. The only difference is that with an AJAX call, all this process takes place in the background, without the user’s knowledge. It is performed programmatically, using JavaScript.</p>
<p>AJAX stands for <strong><em>Asynchronous JavaScript and XML</em></strong>, which means that in its first conception XML was used to transmit data from the server to the client. But XML is not used much anymore, <a title="JSON" href="http://en.wikipedia.org/wiki/Json" target="_blank">JSON</a> is the preferred notation for this task. JSON is a lighter notation as it uses less characters, and follows the natural syntax of the JavaScript language. This means that, once you’ve received the data from the server in your JavaScript code, it is much simpler and faster to process it if it’s in JSON notation.</p>
<p>Let’s see a couple of examples to understand it better. This would be <strong>XML</strong>:</p>
<pre class="brush:xml">&lt;Person firstName="John" lastName="Smith"&gt;
    &lt;address&gt;
      &lt;streetAddress&gt;21 2nd Street&lt;/streetAddress&gt;
      &lt;city&gt;New York&lt;/city&gt;
      &lt;state&gt;NY&lt;/state&gt;
      &lt;postalCode&gt;10021&lt;/postalCode&gt;
    &lt;/address&gt;
    &lt;phoneNumber type="home"&gt;212 555-1234&lt;/phoneNumber&gt;
    &lt;phoneNumber type="fax"&gt;646 555-4567&lt;/phoneNumber&gt;
    &lt;newSubscription&gt;false&lt;/newSubscription&gt;
    &lt;companyName /&gt;
&lt;/Person&gt;</pre>
<p>And this would be the same data transmitted in <strong>JSON</strong> notation:</p>
<pre class="brush:javascript">{
       "firstName": "John",
       "lastName": "Smith",
       "address": {
           "streetAddress": "21 2nd Street",
           "city": "New York",
           "state": "NY",
           "postalCode": 10021
       },
       "phoneNumbers": [
           { "type": "home", "number": "212 555-1234" },
           { "type": "fax", "number": "646 555-4567" }
       ],
       "newSubscription": false,
       "companyName": null
}</pre>
<p>As you can see XML is lengthier to transmit. Besides, as it is not natural to JavaScript, the data must be interpreted and translated to a JavaScript object once it gets to the client, whereas JSON must not. Don’t worry though, you won’t have to deal with converting data to JSON and back, all this is done automatically.</p>
<h4>Different ways of requesting data from the web server</h4>
<p>There are several different techniques used to retrieve data from the server using ASP.NET technology. The most common ones are:</p>
<ul>
<li><strong>URL.</strong> This is the most used technique to provide data through AJAX. Most JavaScript plugins are designed to work this way, so it can be considered the most important technique as well. At the server, this type of request can be processed using two different approaches:
<ul>
<li>The request is processed as if it was a regular web page</li>
<li>The request is processed through an HTTP Handler</li>
</ul>
</li>
<li><strong>Page method.</strong> Server methods can be easily called just by using an attribute.</li>
<li><strong>Web service.</strong> Web services can be consumed from JavaScript, providing for an easy way to request data to the server.</li>
<li><strong>Web sockets.</strong> Not quite AJAX itself, web sockets are here to revolutionize the logic behind traditional client-server communication. Web sockets bring full-duplex and server-initiated communications, two techniques not possible in the web till now. They belong to the new HTML5 specification, and as such must be treated, meaning there’s not much support for it yet.</li>
</ul>
<p>We’ll be taking a look at each of these techniques. Stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP or ASP.NET?</title>
		<link>http://www.undisciplinedbytes.com/2010/02/php-or-asp-net/</link>
		<comments>http://www.undisciplinedbytes.com/2010/02/php-or-asp-net/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 14:58:22 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=234</guid>
		<description><![CDATA[The other day a friend of mine was telling me he was going to start a new project. He wanted to develop a new web app from scratch, and was telling me he was going to use PHP. He did have experience with ASP.NET from some other projects, so I told him to use this [...]]]></description>
			<content:encoded><![CDATA[<p>The other day a friend of mine was telling me he was going to start a new project. He wanted to develop a new web app from scratch, and was telling me he was going to use PHP. He did have experience with ASP.NET from some other projects, so I told him to use this technology. But he still preferred PHP. The reasons he gave me were:</p>
<ol>
<li>PHP is free. You do not have to pay to use it. With ASP.NET you need to pay a whole bunch of licenses.</li>
<li>PHP runs faster than ASP.NET.</li>
<li>PHP hosting is cheaper.</li>
<li>Out there on the internet, you can see more PHP than ASP.NET applications.</li>
<li>There’s more CMS on PHP than on ASP.NET.</li>
</ol>
<p>Ok, he had his reasons, but I didn’t fully agree with him. So I discussed some of those ideas with him:</p>
<p><span id="more-234"></span></p>
<ol>
<li>Yes, PHP is free, like ASP.NET. Well, at least for basic stuff. I mean, the core of ASP.NET is <a href="http://www.mono-project.com/ECMA" target="_blank">standardized</a>, which means that anyone can develop a compiler/server for these specifications. As a matter of fact, the <a href="http://mono-project.com/Main_Page" target="_blank">Mono Project</a> aims to develop alternative components to replace Microsoft’s products. So far, they have released an implementation of the .NET runtime, a .NET development environment, and much more stuff. You can read more about this on <a href="http://mono-project.com/FAQ:_Licensing" target="_blank">Mono FAQ</a>.<br />
Besides, if you don’t like <a href="http://monodevelop.com/" target="_blank">MonoDevelop</a>, you can still use the free version of Microsoft’s Visual Studio: Visual Web Developer. It’s pretty much the same thing, only designed to be used just by one person coding by himself.</li>
<li>PHP is an interpreted script, while ASP.NET applications are compiled. This means that ASP.NET is way faster than PHP. Yes, you could still use some techniques to accelerate PHP (like caching), but those same techniques can be applied to ASP.NET as well, making it even faster. If you want facts, you can take a look at <a href="http://misfitgeek.com/blog/aspnet/php-versus-asp-net-ndash-windows-versus-linux-ndash-who-rsquo-s-the-fastest/" target="_blank">this comparison</a>.</li>
<li>Well, it depends. If you’re talking about installing your application in your own server, then you might need to install some windows server and IIS, and both of them cost money. Actually, Windows does cost money, but IIS is already included in the most recent versions. But, as I said before, the Mono Project provides some free alternative to that.<br />
If you’re talking about deploying your web app in some external hosting and paying a monthly fee, then it is not more expensive at all. I’ve found similar offers in both technologies… it’s not even hard to find free external hosting for both platforms – although that might not be the best experience, depending on your needs.</li>
<li>So? Other people might have some other different reasons. Or maybe they want to adopt the cheapest platform and they just don’t know that ASP.NET is standardized and that there’s open source solutions for this technology as well.</li>
<li>He might be right, the number of CMS implemented with PHP might be greater than those that use ASP.NET. But that doesn’t mean they’re better. In order to choose a CMS for your project, you should compare some of them and decide which one better fits your needs. And you can find almost identical functionality on CMS from both platforms.</li>
</ol>
<p>But I still had some more points to add:</p>
<ul>
<li>Although many of them are not free, there&#8217;s a bunch of pre-programmed controls and components you can incorporate in your web app in ASP.NET (some of them are really impressive). And many of them don&#8217;t require much effort from your part&#8230; just drag&amp;drop the component on your web app and you&#8217;re done. You can even develop your own highly-complex, highly-reusable web app controls and share them among many different apps in just a matter of minutes. This is especially useful for GUI widgets.</li>
<li>By having full access to the .NET Framework, your ASP.NET application can have all the power of any Windows app.</li>
<li>PHP is a single threaded application, while .NET framework supports multi-threading. In a highly loaded app, this can make a huge difference.</li>
</ul>
<p>I know this discussion has been going on ever since ASP.NET was first released&#8230; but I’d say that asking whether PHP or ASP.NET is better just doesn&#8217;t make sense. There’s no such thing as <em>the best language</em>. The language you should use is the one that fits your needs best in the least amount of time. For some people it will be ASP.NET, and for others it will be PHP.</p>
<p>Still, I consider the ASP.NET platform an important skill every web application developer should have. But still, the whole point here is that you can find enough reasons to prefer or dislike any of these platforms&#8230; so it just comes down to personal preferences and project requirements.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/02/php-or-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
