: Use of undefined constant archives - assumed 'archives' (this will throw an Error in a future version of PHP) in
: Use of undefined constant page - assumed 'page' (this will throw an Error in a future version of PHP) in
class="post-576 dw-article type-dw-article status-publish has-post-thumbnail hentry category-code tag-c tag-sql-server tag-xml">
The trick is to leave the middle-tier c# layer as thin as possible, implementing only the things your client layer cant do reliably: Security and Data Access.
In this example I am only showing how to write minimal code for Data Access, Security is too long a topic for a single article.
READING FROM THE DATABASE
Say you have a database with products in it. For this example I am using the Northwind database:
Here is some C# code I wrote earlier to open up the database and read the first record. If you want some examples of valid connection strings you can look here and here.
Here is the output when you run this code in your browser:
The magic here happens in lines 32 and 38.
Line 32 uses DataTable.Load() to get the database contents into a .NET data table as follows:
32 table.Load(reader, LoadOption.Upsert);
Line 38 uses the DataTable.WriteXml() method to write the contents of the table in XML format as a HTTP response.
Now in order to go one step further, your AJAX application needs to read INDIVIDUAL records, that means one at a time, and show them to the user.
Here is some modifications I made to the earlier code for this purpose:
And thats it.
So where is the trick? Is that everything?
Ahh.. For those accustomed to programming ASP.NET I guess it comes as a bit of a surprise that it would be so easy to get XML formatted records out to the client layer.
Surely there has to be a catch somewhere? … A WCF service with implemented data contracts? An Object-Relational Mapping framework operating behind the scenes? Or at least a strongly typed Collection using Generics?
Here is the source code I used in this example, there are 2 files here: Product.aspx and Product.aspx.cs (code-behind) so I’ve zipped them up into this archive:
You are free to copy the code here but since you are not paying me for it I accept no liability if your site goes topsy-turvy. One more free tip, if you are going to put this into production you may want to use a Generic Handler (.ashx file) instead, its more light-weight and you don’t need all the functionality in the Page class.
Please note: I’ve left you the section “WRITING TO THE DATABASE” for a separate article.