<?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; backend</title>
	<atom:link href="http://www.undisciplinedbytes.com/category/backend/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.undisciplinedbytes.com</link>
	<description>Web Application Development Tips, Tricks and Techniques</description>
	<lastBuildDate>Tue, 31 Jan 2012 09:07:24 +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>Entity Framework</title>
		<link>http://www.undisciplinedbytes.com/2012/01/entity-framework/</link>
		<comments>http://www.undisciplinedbytes.com/2012/01/entity-framework/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 09:07:24 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=640</guid>
		<description><![CDATA[Entity framework is the new kid on the block on the ORM realm. It’s Microsoft new technology for data access, and although it didn’t receive very good comments on its first version, things have been greatly improved in its latest release. It now looks really interesting, with some features which surpass the most seasoned ORM [...]]]></description>
			<content:encoded><![CDATA[<p>Entity framework is the new kid on the block on the ORM realm. It’s Microsoft new technology for data access, and although it didn’t receive very good comments on its first version, things have been greatly improved in its latest release. It now looks really interesting, with some features which surpass the most seasoned ORM frameworks that have been in the game for years.</p>
<p>Here’s what Entity Framework (EF) has to offer:</p>
<p><span id="more-640"></span></p>
<ul>
<li>Using EF with the <strong>Model First approach</strong>, you design a schema of the model you want to implement, and EF generates a database and the code to implement it. Now, that’s what I call saving time! Using this approach, you can get going really really quick.</li>
<li>If you already have the code for your model, then EF can generate the database to store this model as well as the rest of the code handling persistance to this database, using the<strong> Code First approach</strong>.</li>
<li>In case you already have the database, EF can generate the code using the <strong>Database First approach</strong>.</li>
<li><strong>EF uses </strong><strong>Plain .Net objects (POCOs)</strong> with navigational properties to implement your model. Very easy stuff. The way EF lets you interact with the data once it’s retrieved from the DB is piece of cake (not the fact of data retrieval itself, that can get tricky).</li>
<li><strong>Automatic code generation</strong> with T4 templates. Once you have EF set up in your project, there’s a bunch of templates to generate a lot of code for you. That doesn’t mean you must use it, but it’s there for your convenience, in case you think some templates can help you. Me myself I use some of the T4 templates, but not all of them. There’s some things I actually prefer doing manually.</li>
<li><strong>Self-tracking entities</strong> will greatly simplify the process of implementing an over-the-wire scenario, in which you have different layers spanning across different systems and you have to serialize and de-serialize your entities. EF makes this really easy.</li>
<li><strong>Local caching</strong>, to speed up your data access.</li>
<li><strong>Lazy loading</strong>, which can improve overall application performance.</li>
<li>Support for <strong>LINQ</strong> (both coming from Microsoft, you would expect this, right?).</li>
<li><strong>Convention over configuration.</strong> The hottest trend in software development. You wouldn’t think EF would miss it, would you? When starting up a new project with EF, the only thing you need to configure are the database server and its name. Nothing else. All other things are taken care of for you. Of course, if you want more control over what EF is doing, you can tweak it to meet your criteria. But that isn’t something you have do right at the beginning. This way, you can be productive much faster.</li>
<li><strong>Support for the major databases</strong>: MS SQL Server (of course), Oracle, MySQL, PostgreSQL, etc…</li>
</ul>
<p>And last but not least:</p>
<ul>
<li>Coming from a big player in the industry like Microsoft, Entity Framework has great resources and a great community behind it. If you ever have a problem with EF, or want to tweak its behavior, chances are you’ll be finding what you need really fast. If you’re a seasoned developer, you’ll find this is one of the most important features of EF.</li>
</ul>
<p>If you haven’t tried it out yet, don’t wait any longer and <a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx">see for yourself what I’m talking about!</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/' rel='bookmark' title='Permanent Link: Persistance layer: object-relational mapping tools'>Persistance layer: object-relational mapping tools</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/03/which-database-to-use-for-a-personal-project/' rel='bookmark' title='Permanent Link: Which database to use for a personal project?'>Which database to use for a personal project?</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/01/sluggish-database-view-materialize-it/' rel='bookmark' title='Permanent Link: Sluggish database view? Materialize it!'>Sluggish database view? Materialize it!</a></li>
<li><a href='http://www.undisciplinedbytes.com/2012/01/asp-net-4-5-and-visual-studio-11/' rel='bookmark' title='Permanent Link: ASP.NET 4.5 and Visual Studio 11'>ASP.NET 4.5 and Visual Studio 11</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2012/01/entity-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Persistance layer: object-relational mapping tools</title>
		<link>http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/</link>
		<comments>http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 10:36:16 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=242</guid>
		<description><![CDATA[Nowadays it&#8217;s very usual to work with object-oriented programming and relational data bases. Relational data bases are all about tables, relations and groups. However, the object-oriented programming paradigm consists of objects, attributes and inter-object relationships. When these objects need to be stored using a relational data base, it&#8217;s very obvious that these two models of [...]]]></description>
			<content:encoded><![CDATA[<p>Nowadays it&#8217;s very usual to work with object-oriented programming and relational data bases. Relational data bases are all about tables, relations and groups. However, the object-oriented programming paradigm consists of objects, attributes and inter-object relationships. When these objects need to be stored using a relational data base, it&#8217;s very obvious that these two models of representing information are very different from each other. We need some kind of translation to transfer data from one to the other.</p>
<p>If we&#8217;re using objects in our application and we want to save them, we&#8217;ll probably use some data base system. We&#8217;ll most likely establish a connection to the data base, create a SQL sentence with the values of the object (or call some kind of stored procedure), and save them to some table. Easy enough, right? Well, this may seem trivial for a small object with 4 or 5 properties. Just consider an object not so small, with 40 or 50 properties. But&#8230; what happens with associations? And&#8230; what if the object itself contains some other objects? We&#8217;ll store them in the data base as well? All of them or just some? What will we do with foreign keys? We can see that, as the application gets more complex, this translation is not so trivial anymore&#8230; As a matter of fact, storing objects in the database can become a very usual source of headaches. There are some studies which state that <strong>up to 35% of code is dedicated to the role of translating data between the application and the data warehouse.</strong></p>
<p><span id="more-242"></span></p>
<p><strong> </strong></p>
<p>And this is where <strong><em>Object-Relational Mapping tools</em></strong> come into play. ORM tools applied to databases transform a DB register to a code object and vice-versa, allowing us to abstract away from writing code to directly access the database. This will speed up development and will allow us to follow the mantra of<strong> focusing on business functionalities, not on application plumbing</strong>.</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">But, what exactly can an ORM tool help me with? Well, they usually do some things like:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Handle object persistance (to a database, for example). You won&#8217;t have to write code for this. And remember, less code means less bugs and less headaches.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Access different databases. Most of these tools support communicating with different database providers (Oracle, MS SQL Server, MySql, Postgre, etc.).</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Cache. Many of these tools offer some way of caching objects in memory, resulting in much faster data access.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Help with design. Some of these tools also provide some kind of wizar or graphical interface to aid in the design of the schema and/or database, which leads us to the following point:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Create your database for you. If you have your data schema already modeled, some of these tools will not only handle how to get the data or how to write it. They can also create the database.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">So now that you&#8217;ve decided to use an ORM, take a look at the most popular ORM tools available for .NET:</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Linq to SQL: not really a full-blown ORM, but it does help with data access.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- NHibernate: I would say NHibernate is one of the most mature ORM projects in .NET, and one of the most used as well.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">- Entity Framework: Microsoft&#8217;s new kid on the block. Its first version didn&#8217;t receive very positive comments, but its latest release looks very good indeed.</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">In the next post I&#8217;ll be covering Entity Framework a bit. Stay tuned!</div>
<p>But, what exactly can an ORM tool helps us with? Well, they usually do some things like:</p>
<ul>
<li><strong>Handle object persistance </strong>(to a database, for example). You won&#8217;t have to write code for this. And remember, less code means less bugs and less headaches.</li>
<li><strong>Access different databases</strong>. Most of these tools support communicating with different database providers (Oracle, MS SQL Server, MySql, Postgre, etc.).</li>
<li><strong>Cache</strong>. Many of these tools offer some way of caching objects in memory, resulting in much faster data access.</li>
<li><strong>Help with design</strong>. Some of these tools also provide some kind of wizard or graphical interface to aid in the design of the schema and/or database, which leads us to the following point:</li>
<li><strong>Create your database for you</strong>. If you have your data schema already modeled, some of these tools will not only handle how to get the data or how to write it. They can also create the database.</li>
</ul>
<p>You&#8217;re already convinced to use an ORM for your project, right? Good. Now take a look at the most popular ORM tools available for .NET:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb425822.aspx" target="_blank">Linq to SQL</a>: not really a full-blown ORM, but it does help with data access.</li>
<li><a href="http://nhforge.org/" target="_blank">NHibernate</a>: I would say NHibernate is one of the most mature ORM projects in .NET, and one of the most used as well.</li>
<li><a href="http://msdn.microsoft.com/en-us/data/aa937723.aspx" target="_blank">Entity Framework</a>: Microsoft&#8217;s new kid on the block. Its first version didn&#8217;t receive very positive comments, but its latest release looks very good indeed.</li>
<li><a href="http://www.llblgen.com/defaultgeneric.aspx" target="_blank">LLBLGen Pro</a>: very mature project, although it&#8217;s not the simplest of all.</li>
<li><a href="http://dataobjects.net/" target="_blank">DataObjects.Net</a>: quite new, but very promising. It already has a lot of interesting features. Definetely worth taking a look at.</li>
</ul>
<p>In the next post I&#8217;ll be covering Entity Framework a bit. Stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2012/01/entity-framework/' rel='bookmark' title='Permanent Link: Entity Framework'>Entity Framework</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/04/some-open-source-projects-for-net-you-should-take-a-look-at/' rel='bookmark' title='Permanent Link: Some open source projects for .NET you should take a look at'>Some open source projects for .NET you should take a look at</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/03/which-database-to-use-for-a-personal-project/' rel='bookmark' title='Permanent Link: Which database to use for a personal project?'>Which database to use for a personal project?</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/01/sluggish-database-view-materialize-it/' rel='bookmark' title='Permanent Link: Sluggish database view? Materialize it!'>Sluggish database view? Materialize it!</a></li>
<li><a href='http://www.undisciplinedbytes.com/2009/12/software-design-patterns-ii-creational-patterns/' rel='bookmark' title='Permanent Link: Software design patterns (II): creational patterns'>Software design patterns (II): creational patterns</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parallel programming with .NET</title>
		<link>http://www.undisciplinedbytes.com/2011/09/parallel-programming-with-net/</link>
		<comments>http://www.undisciplinedbytes.com/2011/09/parallel-programming-with-net/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 10:35:25 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/2011/02/parallel-programming-with-net/</guid>
		<description><![CDATA[When I’m talking to people about the new things that Visual Studio 2010 and ASP.NET 4.0 bring, and the easy it is to write code to be executed in parallel, many people just don’t care. They see it as if it wasn’t related to them. It’s true that some kind of applications don’t really need [...]]]></description>
			<content:encoded><![CDATA[<p>When I’m talking to people about the new things that Visual Studio 2010 and ASP.NET 4.0 bring, and the easy it is to write code to be executed in parallel, many people just don’t care. They see it as if it wasn’t related to them. It’s true that some kind of applications don’t really need this type of optimization… but that’s not an excuse to try to take advantage of our hardware as much as possible.  From several years ago the most common thing in any computer is to have at least two processor cores. As a matter of fact, we’re starting to see now desktop computers with 8-core processors. The trend is to have an ever-increasing number of cores in our computers. This means that any application will have the chance to work in an environment where more than one thread can be executed simultaneously.  Besides, nowadays if you want your software to perform faster, you can no longer just move it to a machine with a faster processor and forget about it. We’re approaching the maximum speed a processor can get, so improvements in next CPUs will come from the side of more threads, not a higher clock-rate.  I think parallel programming  is a key concept all programmers should care about.  ASP.NET 4.0 and Visual Studio 2010 bring new libraries, types and tools to ease multi-core development. ASP.NET 4.0 includes the new “Parallel Extensions”, which are formed by:</p>
<p><span id="more-565"></span></p>
<ul>
<li>Task Parallel Library: this new library, included in the namespace System.Threading.Tasks.Parallel, has new elements to execute tasks in parallel automatically. It’s got, for example, a parallel <em>For</em> loop, and a parallel <em>ForEach</em> loop.</li>
<li>Parallel LINQ Execution Engine: as you can guess, it’s a parallelized version of Linq to Objects. It’s the same thing, except that it will run in parallel whenever possible.</li>
<li>Coordination Data Structures: it’s a set of primitives for sincronization and thread-safe collections. For example, we have thread-safe dictionaries, stacks and buffers, and special objects for thread sincronization, such as <em>SpinWait</em> or <em>SpinLock</em>.</li>
</ul>
<p>Now, the good part about these parallel extensions is that it gets extremely easy to do parallel programming. Just by using these new features, your code will escalate to use as many parallel threads as possible. For example, in a machine with just one processor all your code will execute sequentially, just as always. But, in an 8-core-processor computer, your code will be broken down into 8 different threads, and they all will execute your code in parallel –assuming all 8 cores are available, of course.  You can learn more <a href="http://msdn.microsoft.com/en-us/library/dd460693.aspx" target="_blank">this article</a> from MSDN.</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/' rel='bookmark' title='Permanent Link: Persistance layer: object-relational mapping tools'>Persistance layer: object-relational mapping tools</a></li>
<li><a href='http://www.undisciplinedbytes.com/2012/01/asp-net-4-5-and-visual-studio-11/' rel='bookmark' title='Permanent Link: ASP.NET 4.5 and Visual Studio 11'>ASP.NET 4.5 and Visual Studio 11</a></li>
<li><a href='http://www.undisciplinedbytes.com/2012/01/entity-framework/' rel='bookmark' title='Permanent Link: Entity Framework'>Entity Framework</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/09/parallel-programming-with-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Which database to use for a personal project?</title>
		<link>http://www.undisciplinedbytes.com/2011/03/which-database-to-use-for-a-personal-project/</link>
		<comments>http://www.undisciplinedbytes.com/2011/03/which-database-to-use-for-a-personal-project/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 14:03:16 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[backend]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=458</guid>
		<description><![CDATA[When starting a new project, the choice of which database to use usually boils down to the one the company usually uses. The systems that are usually considered are just Oracle and Microsoft’s SQL server (MS-SQL). There’s no doubt that big bucks companies have the resources to make the best-of-its-breed products, and almost no other [...]]]></description>
			<content:encoded><![CDATA[<p>When starting a new project, the choice of which database to use usually boils down to the one the company usually uses. The systems that are usually considered are just Oracle and Microsoft’s SQL server (MS-SQL). There’s no doubt that big bucks companies have the resources to make the best-of-its-breed products, and almost no other database system comes close to what Oracle and MS-SQL can offer in terms of quality, features, and highly skilled professionals around their products. Yes, all this is true, but there’s a price. And usually this price tag can only be afforded by a company, not by a sole individual.</p>
<p>So, what if I want to develop my own personal project and I require a RDBMS (<em>Relational DataBase Management System</em>)? Oracle and MS-SQL are out of the question because of their high cost. MS-SQL Express has great limitations, so, although it is free, we won’t be considering it for our purpose. Which is the best open source RDBMS?</p>
<p><span id="more-458"></span></p>
<p>Today’s most known open source RDBMS are MySQL and PostgreSQL. PostgreSQL is considered to beat MySQL in the features war. This used to be true some time ago, but it’s no longer the case anymore. 99% of the needs you will have with your RDBMS will be covered by both MySQL and PostgreSQL. Still, there’s many people who think that MySQL has improved a lot, but it’s just not PostgreSQL.</p>
<p>If you want to compare performance, fans of both systems will tell you their RDBMS is faster than the other one. On one hand, PostgreSQL has been recently paying attention to speed, and has been making its product faster and faster with every release. On the other hand, MySQL proponents say that, if configured properly, MySQL’s MyISAM tables are indeed lightweight and make for a faster database.</p>
<p>But probably, the most important thing to consider when choosing which RDBMS you should use, is which one is easier to use. I can tell you that previous Oracle experience will make you feel at home and comfortable with PostgreSQL. Still, the MySQL community seems to be much bigger than PostgreSQL’s, so, should you require some assistance when developing your project, if you’re using MySQL chances are that you will get quick help from them.</p>
<p>MySQL is licensed under the GNU GPL, but offers an alternative commercial license for those who don’t want to be restricted by that license. PostgreSQL uses the BSD license, which stipulates that the credits have to be maintained, but beyond that you can do whatever you want with it.</p>
<p>But, after all, it just all comes down to personal tastes. Just choose whatever you like and whichever you think might fit your needs better. What might be the best for one person, might be a bad choice for another.</p>
<p>Check these links for more info:</p>
<ul>
<li><a href="http://www.devx.com/dbzone/Article/29480" target="_blank">Open Source Database Feature Comparison Matrix</a></li>
<li><a href="http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems" target="_blank">Comparison of RDBMS</a></li>
</ul>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/01/sluggish-database-view-materialize-it/' rel='bookmark' title='Permanent Link: Sluggish database view? Materialize it!'>Sluggish database view? Materialize it!</a></li>
<li><a href='http://www.undisciplinedbytes.com/2012/01/entity-framework/' rel='bookmark' title='Permanent Link: Entity Framework'>Entity Framework</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/' rel='bookmark' title='Permanent Link: Persistance layer: object-relational mapping tools'>Persistance layer: object-relational mapping tools</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/03/which-database-to-use-for-a-personal-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 15: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>
<li><a href='http://www.undisciplinedbytes.com/2010/10/gui-testing/' rel='bookmark' title='Permanent Link: GUI Testing'>GUI Testing</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/07/test-driven-development/' rel='bookmark' title='Permanent Link: Test-driven development'>Test-driven development</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/10/load-testing/' rel='bookmark' title='Permanent Link: Load testing'>Load testing</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/04/some-open-source-projects-for-net-you-should-take-a-look-at/' rel='bookmark' title='Permanent Link: Some open source projects for .NET you should take a look at'>Some open source projects for .NET you should take a look at</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/08/unit-testing/feed/</wfw:commentRss>
		<slash:comments>1</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 15: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><strong>UPDATE </strong><strong>(October 12th, 2010):</strong></p>
<p><strong>The Web Socket protocol is not closed yet, so it is being constantly updated. This means that previous Web Socket server implementations might stop working after an update has been made to the API. The original version of the code I released here complied with version 75 of the Web Socket draft. The current version is 76, so I updated my code and released a second project.</strong></p>
<p>No idea of what I&#8217;m talking about? I&#8217;ll make it easy for you&#8230; download the v76 implementation first, and if it doesn&#8217;t work then check out the v75 implementation. If you&#8217;re using one of the latest browsers, you should have no trouble.</p>
<p><del><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/06/WebSocketsTest.zip" target="_self">WebSocketsTest (draft 75).zip</a></del> (Older browsers)</p>
<p><a title="Web Sockets Test" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/10/WebSocketsTestdraft76.zip" target="_self"><strong>WebSocketsTest (draft 76).zip</strong></a><strong> (Latest browsers)</strong></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/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-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/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/feed/</wfw:commentRss>
		<slash:comments>35</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 18: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-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>12</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 20: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-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-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 19: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>
	</channel>
</rss>

