Whats the difference between Classic ASP and ASP.NET?
Major difference: Classic ASP is Interpreted. ASP.NET is Compiled. If code is changed, ASP.NET recompiles, otherwise does'nt. Other differences: ASP works with VB as the language. ASP.NET works with VB.NET & C# as the languages (Also supported by other languages that run on the .NET Framework). ASP.NET is the web technology that comes with the Microsoft .NET Framework. The main process in ASP.NET is called aspnet_wp.exe that accesses system resources. ASP.NET was launched in 2002 with version 1.0. Subsequent versions are 1.1 and version 2.0. ASP.NET is built up using thousands of objects, ordered in the System namespace. When an ASP.NET class is compiled, its called an assembly. In Classic ASP, complex functionalities are achieved using COM components, that are nothing but component objects created using VB 6, C++ etc, and are usually in a DLL format. These components provide an exposed interface to methods in them, to the objects that reference these components. Last version of classic ASP is version 3.0. ASP has 7 main objects - Application, ASPError, ObjectContext, Request, Response, Server, Session.
What is the difference between ADO and ADO.NET?
The old ADO (ActiveX Data Object) has evolved to ADO.NET in the .NET Framework. The ADO.NET object is a lightweight object. The ADO Recordset was a huge object in ADO. It provided the ability to support multiple types of cursors. It provided fast lightweight "firehose" cursor and also supported a disconnected client-side cursor that supported tracking, optimistic locking, and automatic batch updates of a central database. However, all of this functionality was difficult to customize. ADO.NET breaks the functionality of the ADO object to multiple classes, thereby allowing a focused approach to developing code. The ADO.NET DataReader is equivalent to the "firehose" cursor. The DataSet is a disconnected cache with tracking and control binding functionality. The DataAdapter provides the ability to completely customize how the central data store is updated with the changes to a DataSet.
Whats the difference betweeen Structure, Class and Enumeration
Structures and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory. Classes are Reference-Types, means they are stored as a heap on the memory. Structures are implicitly derived from a class called System.ValueType. The purpose of System.ValueType is to override the virtual methods defined by System.Object. So when the runtime encounters a type derived from System.ValueType, then stack allocation is achieved. When we allocate a structure type, we may also use the new keyword. We may even make a constructor of a structure, but, remember, A No-argument constructor for a structure is not possible. The structure's constructor should always have a parameter.
So if we define the following structure
struct MyStruct { public int y,z; } and we create a structure type MyStruct st = new MyStruct();
In case of a class, no-argument constructors are possible. Class is defined using the class keyword.
A struct cannot have an instance field, whereas a class can.
class A { int x = 5; //No error ... }
struct { int x = 5; //Syntax Error }
A class can inherit from one class (Multiple inheritance not possible). A Structure cannot inherit from a structure.
Enum is the keyword used to define an enumeration. An enumeration is a distinct type consisting of a set of named constants called the enumerator list. Every enumeration has an underlying type. The default type is "int". Note: char cant be the underlying data type for enum. First value in enum has value 0, each consequent item is increased by 1.
enum colors {red, green, blue, yellow};
Here, red is 0, green is 1, blue is 2 and so on. An explicit casting is required to convert an enum value to its underlying type
int x = (int)colors.yellow;
What is the difference between abstract class and interface?
If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:
abstract public class Vehicle { }
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created. Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method. Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below
Example: Abstract Class with Abstract method namespace Automobiles { public abstract class Vehicle { public abstract void Speed() //No Implementation here, only definition } }
Example: Abstract Class with Virtual method namespace Automobiles { public abstract class Vehicle { public virtual void Speed() //Can have an implementation, that may be overriden in child class { ... } }
Public class Car : Vehicle { Public override void Speed() //Here, we override whatever implementation is there in the abstract class { ... //Child class implementation of the method Speed() } } }
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:
Public interface IVehicle //As a convention, an interface is prefixed by letter I { Boolean HasFourWheels() }
Time to discuss the Difference between Abstract Class and Interface
1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe. 2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier. 3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.
"SELECT Field2, Field3, Field4, SUM(DECODE(Field6,Val1,Count(Field1),0)) AS Val1, SUM(DECODE(Field6,Val2,Count(Field1),0)) AS Val2, SUM(DECODE(Field6,Val3,Count(Field1),0)) AS Val3 FROM [Table] GROUP BY Field2, Field3, Field4 WHERE Field5 IS NOT NULL"
SELECT Field2, Field3, Field4, SUM(DECODE(Field6,Val1,Count(Field1),0)) AS Val1, SUM(DECODE(Field6,Val2,Count(Field1),0)) AS Val2, SUM(DECODE(Field6,Val3,Count(Field1),0)) AS Val3 FROM [Table] GROUP BY Field2, Field3, Field4 WHERE Field5 IS NOT NULL
I have to admit that I am totally hooked on the The Rozenshtein Method. My buddy, Richard Campbell showed it to me a year or two ago and I have been hooked ever since. I recently demoed it at TechED in Dallas, a recent WebCast, VSLive in New York and will be showing it off at TechEd in Malaysia next week. I have gotten lots of email and positive feedback so I decided to blog it here.
Here is how it works. You need a crosstab query. You have to move rows into columns. You also need ANSI 92 SQL that will run in any database.Well there are several ways to do this, but the most generic and one of the most powerful ways is called the Rozenshtein Method, which was developed by the Russian mathematician David Rozenshtein. This technique was taken from his book: Optimizing Transact-SQL : Advanced Programming Techniques.
First let’s look at the desired results. We want to take the orders data from Northwind and pivot the sales date (aggregated by month) as columns with the sum of the total sales in the row grouped by customer. It would look something like this:
CompanyName TotalAmount Jan Feb Mar…(etc)
Company110025 3310
Company246776 6287
(etc)
The TSQL query to do this is, go ahead and run it in Northwind in SQL Server:
SELECTCompanyName, SUM((UnitPrice*Quantity)) As TotalAmt,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-1)))) AS Jan,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-2)))) AS Feb,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-3)))) AS Mar,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-4)))) AS Apr,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-5)))) AS May,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-6)))) AS Jun,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-7)))) AS Jul,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-8)))) AS Aug,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-9)))) AS Sep,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-10)))) AS Oct,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-11)))) AS Nov,
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-12)))) AS Dec
FROMCustomers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID INNER JOIN
[Order Details] ON Orders.OrderID = [Order Details].OrderID
Group By Customers.CompanyName
So how does this work?
This method uses Boolean aggregates, so that each column has a numeric expression that resolves each row as a zero or one and that value (0 or 1) is multiplied by your numeric expression (Like TotalSales or (UnitPrice*Quantity). That is all there is to it, quite simple. But wait, there’s more to explain:
We want to create columns for each Month in our data. To find a month use DatePart. But we need to subtract the DatePart value (1-12) from the amount you’re looking for (1 for Jan, 2 for Feb, etc) as shown here for January:
DatePart(mm,OrderDate)-1
So that true = zero, false > 0 or <>
Next you have to compute the sign of the expression and get the absolute value like so:
ABS(SIGN(DatePart(mm,OrderDate)-1)))
This will give us a positive value. Remember 0 is still true. Now subtract the value computed from 1 in order to get a 0 or 1 from the value of your expression (the Boolean aggregate). The code is:
(1-ABS(SIGN(DatePart(mm,OrderDate)-1))))
For example if you had March return 3 from the Datepart, 3-1=2 and 1-2 =-1. The absolute value is 1. This will always return 0 or 1. If your expression was zero, the value is now one. If was one, the value is zero.
Last step. Taking the SUM of the Boolean values will give you a count of the values that qualify. So you can find out how many sales you made in Jan, Feb, etc. So now multiply the value by the price and quantity, but remember its now one = true. Take a look here:
SUM((UnitPrice*Quantity)*(1-ABS(SIGN(DatePart(mm,OrderDate)-1)))) AS Jan
If its zero, nothing gets added, if its one, you get the value of the sale. The sum of the total expression is the total of sales for the month. If you have a DatePart that is evaluated to 0 then ((UnitPrice*Quantity)*0) is 0 and those results are ignored in the SUM. If you have a month that matches your expression resolves to 1 and ((UnitPrice*Quantity)*1) is the value of the sale.
How easy!
But wait, there’s more! Suppose you wanted two values combined? Compute each value down to zero or one separately. Now you can use AND by multiplying, OR by adding (and reduce to 1 or 0 using SIGN).
This example shows how you can import the content of an excel sheet to a datagrid and export from a datagrid to an excel sheet, no automation is required. The application is explained with the help of File Field HTML component. Author: ManojRajan
Posted Date: 20 Apr, 2004 .NET Classes used :
System.Data.DataSetSystem.Data.OleDb.OleDbDataAdapterSystem.Data.OleDb.System.IO.StringWriterSystem.Web.UI.HtmlTextWriter This application uses a FileField (UploadFile)(HTML control) , One label (lblMessage), Button (btnSubmit), Button (btnExportToExcel), DataGrid (DataGrid1), This also explains how to upload a file.
Imports System Imports System.Data Imports System.Data.OleDb Imports System.IO
Code :
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim intFileNameLength As Integer Dim strFileNamePath As String Dim strFileNameOnly As String
If Not (UploadFile.PostedFile Is Nothing) Then strFileNamePath = UploadFile.PostedFile.FileName
'If File.Exists(paths & strFileNameOnly) Then 'lblMessage.Text = "Image of Similar name already Exist,Choose other name" 'Else If UploadFile.PostedFile.ContentLength > 40000 Then lblMessage.Text = "The Size of file is greater than 4 MB" ElseIf strFileNameOnly = "" Then Exit Sub Else strFileNameOnly = Session("AdminID") & "-" & Session("Acountry") & "-" & Format(Date.Today, "mm-dd-yyyy").Replace("/", "-") & ".xls" UploadFile.PostedFile.SaveAs(paths & strFileNameOnly) lblMessage.Text = "File Upload Success." Session("Img") = strFileNameOnly End If End If 'End If
Dim myDataset As New DataSet() Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("/excelreading/") & "excel/" & strFileNameOnly & ";" & _ "Extended Properties=Excel 8.0;"
''You must use the $ after the object you reference in the spreadsheet Dim myData As New OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn) myData.TableMappings.Add("Table", "ExcelTest") myData.Fill(myDataset)
DataGrid1.DataSource = myDataset.Tables(0).DefaultView DataGrid1.DataBind() End Sub
Private Sub btnExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click ' Set the content type to Excel. Response.ContentType = "application/vnd.ms-excel" ' Remove the charset from the Content-Type header. Response.Charset = "" ' Turn off the view state. Me.EnableViewState = False
Dim tw As New System.IO.StringWriter() Dim hw As New System.Web.UI.HtmlTextWriter(tw)
' Get the HTML for the control. DataGrid1.RenderControl(hw) ' Write the HTML back to the browser. Response.Write(tw.ToString()) ' End the response. Response.End() lblMessage.Text = "For any more information , feel free to contact ...!!!" End Sub
Read Excel files from ASP.NET: This page provides a simple example of how to query an Excel spreadsheetfrom an ASP.NET page using either C# or VB.NET. Check it out!This code was written in response to a message posted on one ofCharles Carroll''s ASP.NET lists. You can ...
This page provides a simple example of how to query an Excel spreadsheet from an ASP.NET page using either C# or VB.NET. Check it out!
This code was written in response to a message posted on one of Charles Carroll''s ASP.NET lists. You can sign up for one or all of the lists here. Here is the code:
<script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs) Dim myDataset As New DataSet()
''You can also use the Excel ODBC driver I believe - didn''t try though Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\exceltest.xls;" & _ "Extended Properties=""Excel 8.0;"""
''You must use the $ after the object you reference in the spreadsheet Dim myData As New OledbDataAdapter("SELECT * FROM [Sheet1$]", strConn) myData.TableMappings.Add("Table", "ExcelTest") myData.Fill(myDataset)
DataGrid1.DataSource = myDataset.Tables(0).DefaultView DataGrid1.DataBind() End Sub </script>
<script language="C#" runat="server"> protected void Page_Load(Object Src, EventArgs E) { string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\exceltest.xls;" + "Extended Properties=Excel 8.0;"; //You must use the $ after the object you reference in the spreadsheet OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",strConn);
AJAX (Asynchronous JavaScript and XML) has become so popular, thanks to Google Suggest. AJAX has opened the possibility to make more responsive and interactive web applications, bringing them closer to Windows form applications. Web developers are the bunch of guys who were happy at first. They have a new toy, which is composed of old toys they have neglected so far, and now they can make cool things with the toy. On the other hand, after getting their free account in GMail, end users demand more with their department web application. They hate postback, they want no refresh, and everything just stays there but still gets up-to-date. Is it possible?
Those demanding users are my motivation to create this custom control. Let me introduce AjaxDropDownList, my first attempt to contribute into AJAX world. AjaxDropDownList is a dropdownlist control that has the following features:
* Fetch data asynchronously in the background from a server source, with no postback. * Can trigger change event to other dropdownlists, thus generating a cascading linked dropdownlist effect. * Is encapsulated into a single control which can be easily dragged and dropped into the designer or added from the server code. * Uses common code to access the selectedItem just like a normal dropdownlist, thus can be easily integrated with other UI framework. * Compatible with Internet Explorer 6, Mozilla Firefox 1.04, and Netscape 8.02.
Although I call the control as AjaxDropDownList, it does not use XML to transfer the data. I use JSON (JavaScript Object Notation) by Douglas Crockford which is more lightweight and can be easily consumed by JavaScript as an object. I am aware of the potential and flexibility that XML offers compared to JSON. But in my case, JSON is enough to serve the requirements. How to use the control Starting from the sample project
Download and open the project in VS.NET 2003. Edit GetLookupData.aspx.cs and change the connection string to point to a valid NorthWind database. If for some reason you don’t have NorthWind database, you can download the database script from Microsoft. Just do a search on Google.
Once the solution is built successfully, run and browse the default.aspx. Evaluate if this is the control you are looking for. What the demo is about
In this demo page, we have three AjaxDropDownLists: Customers (ddlCustomers), Orders (ddlOrders) and Products (ddlProducts).
Orders dropdownlist depends on Customers. It means if we make a selection in Customers dropdownlist, then the Order dropdownlist will be filtered based on our selection. Furthermore, Products is depending on Orders. So a selection on Customers will trigger a change in Orders, and subsequently trigger a change in Products. Please note that all this happens without any postbacks.
While playing around with the dropdownlist, you may encounter a JavaScript alert box showing an error message. It could mean a lot of things, but most probably your connection to the database is not working.
Now press the Submit button and the page will finally do a postback. The selected text of each dropdownlist will be shown on the right hand side. This is to demonstrate that the standard code to access the selection in ASP.NET DropDownList still applies to AjaxDropDownList. What is in there
There are three important parts:
* AjaxDropDownList.cs
It contains the custom control. Put this file in a separate Class Library project so that we can add the control to the toolbox without any trouble. * Default.aspx
It is a sample web page that uses AjaxDropDownList controls. The controls are dropped into the designer from the Toolbox.
To add AjaxDropDownList into your toolbox, right click on the toolbox pane, and then select Add/Remove Items. It will bring up Customize Toolbox dialog. Press Browse button then select CustomControl.dll or the assembly that contains AjaxDropDownList. A big list of control with checkboxes will appear. Ensure that AjaxDropDownList is selected and close the dialog. The control will appear in the toolbox, ready to be dropped to the designer. * GetLookupData.aspx
This is the page that handles the request from xmlHttp and returns the appropriate JSON. It needs to handle two query strings: o “id” is the lookup name or identifier, e.g., Country, Currency, Order, Product, and InvoiceStatus. o “filter” (optional) describes the filter in name-value pair, e.g., Customer, ALFKI.
It is up to you how you want to implement the request handler.
Warning: GetLookupData.aspx is just a simple example which is not suitable for a product environment.
Code Walkthrough
AjaxDropDownList control uses JavaScript intensively. The JavaScript code is embedded into the control and will be injected into the response stream when the control is rendered. In order to minimize HTTP payload, the JavaScript code has been minimized using JavaScript Minifier. However, this will make debugging on the real code difficult and frustrating.
Therefore, in the sample project I provide the source code in its original format and all comments still in place. Please refer to SourceScript.aspx during this walkthrough. XMLHTTP
JavaScript code utilizes xmlHttp object to make requests to the web server either asynchronously or synchronously. As the request can be made without refreshing the page, the web page looks more responsive and interactive. The method getXMLHTTP() is called to a get reference to the xmlHttp object, regardless of how the browser implements this object. Controller
The source code of Ajax.NET is now available! More details...
NEW: Ajax.NET Professional
Did you had a look at the beta version of Ajax.NET Professional? More security features like AJAX Token, encryption on client-side JavaScript and on the server, faster JavaScript wrapper files cached using HTTP ETag header values, using Namespaces on the client-side JavaScript to ensure that there are no variable name conflicts, a fully new written JSON parser that will allow you to use any object as method argument or result value without writing an IAjaxObjectConverter, ...
Download the Ajax.NET Professional Library and start working on the client-side JavaScript as you are already working on the server.
Some of the new features will be added in the next few weeks to the Ajax.NET Library available at BorgWorx.
The library can be downloaded from this web page. As this project is a technology demonstration of XmlHttp requests there is no warranty:
THE LIBRARY IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE LIBRARY IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD ANY PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION.
There is a usage guide (will be updated in the next days) available for the first version of the free Ajax.NET: AjaxGuide.doc quickGuide.txt
Neues zu ASP.NET 2.0 Die finale Version von Visual Studio 2005 und SQL Server 2005 kommt im November 2005. Bei der 12. ASP konferenz spielt die neue Version von ASP.NET 2.0 die zentrale Rolle. Neue Controls, 70 % weniger Code und eine Menge mehr, das müssen Sie sich einfach ansehen.
Highlights
AJAX.NET Erfinder und Guru Michael Schwarz zeigt erstmalig wie Microsoft aus AJAX Atlas macht.
Die magische Zahl 7: IIS 7 und IE 7
Die drei Musketiere, Karsten, Hannes und Christoph MVP's für ASP.NET
This example will post a form to the server, invoke the Test1 method there and return a HTML string.
On the server you will have a typical method with an additional attribute:
[Ajax.AjaxMethod] public string Test1(string firstName, string familyName, string email, string comment) { string html = "";
html += "Hello " + firstName + " " + familyName + " "; html += "Thank you for your comment "; html += System.Web.HttpUtility.HtmlEncode(comment); html += ".";
Hello Michael æøå Thank you for your comment (10.12.2007 12:02:50): sdssdssdsdsdddddddddddddddddd.
If your browser does not accept displaying Unicode characters (like Japanese characters) you will see small boxes instead of the real char.
Send a custom type as argument
The second sample will show you how to pass a real .NET object as an argument for your method. The Test2 method will have a System.DateTime argument. The IAjaxObjectConverter will give you a simple to use client script to create the wrapper for .NET. On the client script you can use following script to create such an object:
var d = new DateTime(2005, 4, 20, 0, 0, 0); // April 20th 2005
To call the AJAX.NET method you will write:
DemoMethods.Test2(d, callback);
The AJAX.NET wrapper on the server will check which converter can decode the Javascript object and passes the method a correct object. You can create your own IAjaxObjectConverters to allow every object to be returned or accepted.
[Ajax.AjaxMethod] public string Test2(DateTime d) { d = d.AddDays(1); return "The next day will be " + d.ToLongDateString() + "."; }
Currently I have following IAjaxObjectConverters: - System.Collections.ArrayList - System.Data.DataSet/DataTable/DataRow - System.DateTime/TimeSpan - System.Array
Use a System.Data.DataSet to fill a drop down box
Because you can return any object it is possible to fill a drop down box with only two lines. The list of countries will be fetched from the server after you have clicked on the link.
The next example will throw a security exception on the server (System.Security.SecurityException). The callback handler will check if the error property is filled an will show the exception.
function callback(res) { if(res.error != null) alert(res.error); }
The error object will have three properties: name will be the type of the exception, description the .Message property of the exception thrown on the server, and number will be a unique ID (not yet implemented!). There is a toString() method that will output the name and the description as one string.
Session State handling with Ajax.NET
A lot of developers asked for the session station access. Now, we you can access your session variables.
First click on write to save the value i.e. "demo" to the session on the server. Now, you can press F5 (reload) and click on read. You should see the same value as you have written to the session state.
On the server the C# method looks like following code:
[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public void Test5(string value) { System.Web.HttpContext.Current.Session["example"] = value; }
[Ajax.AjaxMethod(HttpSessionStateRequirement.Read)] public string Test6() { if(System.Web.HttpContext.Current.Session["example"] != null) return (string)System.Web.HttpContext.Current.Session["test"];
return "First set the value..."; }
Is it possible to wait for events?
Yes, you can use System.Threading.Thread to wait for events instead of pooling every second. Because the server process does not get informed when a client browser has been closed you should not use a infinite loop.
Why to use a loop at the server instead of polling every second? You will save client requests to the server that will use the Internet bandwidth and will create a new request on the server. So, you will have 10 requests if you will poll and one request if you loop at the server for 10 seconds!
Click here to start the process at the server. There is no timer at the client's javascript. In 10 seconds the request will response and call the client callback function which will show a alert box. There will be no network traffic until the method returns. Click on the link two times and you will get two alert boxes!
Note: You can have simultaneous requests at the same time, there are no restrictions.
[Ajax.AjaxMethod] public void Test7() { int c = 0;
do { System.Threading.Thread.Sleep(1000); c++; } while(c < 10); }
Using a context on the client-side Javascript
If I want to update several elements (i.e. DIV) on the screen I had to use different callback functions in the last release. Now, you can add a context that is accessable in the callback function.
The following sample will update the element you clicked on. There is only one Javascript function that will handle the callback:
Element1 Element2
DIV elements: Click hereClick hereClick here
Return arrays and System.Collections.ICollection objects
The free Ajax.NET library is supporting arrays and objects the using the ICollection interface.
[Ajax.AjaxMethod] public System.Collections.Specialized.StringCollection Test9() { System.Collections.Specialized.StringCollection s = new System.Collections.Specialized.StringCollection();
s.Add("Michael"); s.Add("Hans");
return s; }
[Ajax.AjaxMethod] public object[] Test10() { object[] o = new object[3];
Click here to get the result of the method DemoMethods.Test11.
Enable tracing for Ajax.NET requests
If you want to enable tracing for your Ajax.NET requests enable the tracing in your web.config file:
true" requestLimit="100" pageOutput="false" />
To view the trace open a new browser window and open the trace.axd page. This is the default ASP.NET page that will display tracing information off all your requests.
Category Message From First(s) From Last(s) Ajax.NET Begin ProcessRequest Ajax.NET Invoking CSharpSample.DemoMethods.Test11 0,000181 0,000181 Ajax.NET JSON string: ['Michael',new Date(2005,4,10,9,39,27),true] 0,000365 0,000184 Ajax.NET End ProcessRequest 0,000387 0,000022
Use your own common Javascript file
Some developers asked for a debug version of the common.ashx (Javascript) file. With one setting in the web.config you can use your own common Javascript file:
true" path="ajax.js" language="javascript" />
The example above will include the ajax.js instead of the common.ashx.
Add/remove your own IAjaxObjectConverters
The free Ajax.NET library has already some useful build-in object converters. Currently there are following IAjaxObjectConverters available:
Ajax.JSON.ArrayListConverter (obsolete, replaced by IEnumerableConverter)
Ajax.JSON.DataRow/DataTable/DataSetConverter
Ajax.JSON.DateTime/TimeSpanConverter
and the Ajax.JSON.DefaultConverter which will use the .ToString() method to get the value of the object.
All of them are enabled be default. To remove or add your own IAjaxObjectConverters you can modify your web.config file:
The example above will add a converter Namespace.Class, Assembly and remove the default converter that will handle the DataSet objects.
To implement your own IAjaxObjectConverters the source code of the IEnumerableConvert.cs will be available in this exmaple. Feel free to download the source code here.
Return your own classes
With Ajax.NET you can return your own classes you are already using in C#. You only have to add the [Serializable] attribute to the class:
[Serializable] public class Person { public string FirstName; public string FamilyName; public int Age = 0;
public Person NewChild() { Person p = new Person(); p.FamilyName = FamilyName;
return p; }
public Person[] Children = null; }
On the client-side you can use it like you will do it on the server:
function test12_callback(res) { var s = res.value.FirstName + " " + res.value.FamilyName + ":\r\n";
for(var i=0; i s += "\t" + res.value.Children[i].FirstName + "\r\n";
A lot of web applications are using the MSDE or Microsoft SQL Server to store data. In some case you want to return a complete DataSet (or DataTable/DataRow) to the client. With the free Ajax.NET library you can directly return a DataSet to the client without any need to convert. There is no sourc code change, only add the Ajax.AjaxMethod to the method:
[Ajax.AjaxMethod] public DataSet Test15() { SqlConnection conn = new SqlConnection("server=(local);Integrated Security=true;Initial Catalog=master;"); SqlCommand cmd = new SqlCommand("SELECT [name], [filename] FROM dbo.sysdatabases", conn); SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try { conn.Open();
try { da.Fill(ds); // fill DataSet with data } catch(Exception) { return null; } finally { conn.Close(); conn.Dispose(); } } catch(Exception) { return null; }
return ds; }
On the client-side Javascript I made a object that will have similar properties as the object in .NET. A DataTable will have the .Tables array, and each table will have their .Rows. The columns will be properties instead of an array, see the example below:
Each column value will have its correct data type: an integer will be a number, a DateTime will be a correct date object can be used in Javascript:
New: Some developers asked me if it is possible to select a table by name. I added a method to the returned DataSet where you can get the first table given by the name:
function test15_callback(res) { var dt = res.value.getTable('Overview');
if(dt != null) alert(dt.Rows.length); }
Build a simple to use NewsTicker
Some developers asked me how to build a news ticker with the Ajax.NET library. I build a small example how you can do this. On the server-side we will have a database (or xml file, whatever) that stores the T to be displayed, the URL and the Seconds each news ticker will be on the screen. I'm using a simple array of 10 NewsTicker objects that hold these information and select one with System.Random:
[Ajax.AjaxMethod] public NewsTicker Test13() { NewsTicker[] nt = new NewsTicker[10];
// following code will be replaced by getting a random item // from a database or xml file
nt[0] = new NewsTicker("Ajax.NET Library", "http://ajax.schwarz-interactive.de", 20); nt[1] = new NewsTicker("Google Search", "http://www.google.com", 20); [...] nt[9] = new NewsTicker("Free Download!!", "http://ajax.schwarz-interactive.de", 20);
Random r = new Random(System.DateTime.Now.Second); int i = r.Next(0, nt.Length);
return nt[i]; }
The NewsTicker will be a own class the has the Serializable attribute:
[Serializable] public class NewsTicker { public NewsTicker(string text, string url, int duration) { this.Text = text; this.URL = url; this.Duration = duration; }
public string Text; public string URL; public int Duration = 60; }
On the client-side I will use the window.setTimeout command to wait the time is specified in the .Duration property:
function test13() { // call the Ajax.NET method on the server to get // a new news ticker object
DemoMethods.Test13(test13_callback); }
function test13_callback(res) { if(typeof(res.value) == 'object') { // display the news ticker
Here you can have a look on the live news ticker using Ajax.NET: [Please wait...]
Is it possible to return images?
Currently I have implemented a ImageConverter that will support System.Drawing.Bitmap objects. On the server-side method you can create a Bitmap with GDI+ methods. On the client-side you will get a Image object that you can append to HTML elements. The Image object will have the .src property where you can get the URL of the image:
[Ajax.AjaxMethod] public System.Drawing.Bitmap Test16() { Bitmap bmp = new Bitmap(200, 50); Graphics g = Graphics.FromImage(bmp);
g.FillRectangle(new SolidBrush(Color.Yellow), 0, 0, 199, 49); g.DrawString(DateTime.Now.ToString(), new Font("Arial", 10), new SolidBrush(Color.Red), 10, 10);
return bmp; }
On the client you will get a Image object that you can add to an element or where you can read the .src property:
function test16_callback(res) { if(typeof(res.value) == 'object') document.getElementById("imageholder").appendChild(res.value); }
Click here to create a bitmap showing the current time:
I got some requests what new on this? We could refresh images in the past, too! Ok, the difference is that you can return more than one image, or you can return a class with a lot of properties and one image. Others asked me if they should use it for MouseOvers. No, I think onmouseover is used with static images instead of dynamic rendered images. You can use it i.e. to return an object with a diagram and some values in a DataSet.
The images will be created in the subfolder images in the ApplicationPath. You can configure in which subfolder you will create temporary files and how long they should be available (delete files after x minutes):
Use arrays for argument values
Ajax.NET was designed to retreive structered data. But with the IAjaxObjectConverters we can get and post every value/object. Yesterday I added the possibility to use arrays as argument values:
On the server-side method we will have a real integer array:
[Ajax.AjaxMethod] public int Test17(int[] i) { int r = 0;
foreach(int ii in i) r += ii;
return r; }
[Ajax.AjaxMethod] public string Test18(string[] s) { string r = ""; foreach(string ss in s) r += "
" + ss + "
\r\n";
return r; }
I only have done integer and string arrays, other arrays coomin soon. Click here to invoke the method DemoMethods.Test18 with an array including 3 strings.
Use HtmlControls as argument and return value
Now, it is possible to send any HtmlControl to the server-side method, use C# to change properties on it and return the object to the client. A lot of developers are afrait of writing Javascript code. I have added a small function that will update any HtmlControl.
Let's have a look at the server-side method. We will have two HtmlSelect controls on the page (DropDown):
The first drop down list will display some car companies. The second one will be filled after changing the car company in the first one. In the onchange event we will call following code. Note: the second element is embedded in a parent control. I did not find a good solution that works in all common browsers. This will be changed in future releases!
The C# method will get the second drop down element as first argument, the second argument will be the selected value from the first drop down:
[Ajax.AjaxMethod] public System.Web.UI.HtmlControls.HtmlSelect Test19(string car) { System.Web.UI.HtmlControls.HtmlSelect control = new System.Web.UI.HtmlControls.HtmlSelect();
switch(car) { case "VW": control.Items.Add("Golf"); control.Items.Add("Passat"); control.Items.Add("Beetle"); control.Items.Add("Phaeton"); break;
case "Citroen": control.Items.Add("C3 Pluriel"); control.Items.Add("C5 Break"); control.Items.Add("C8"); control.Items.Add("Berlingo"); break; }
return control; }
The special function HtmlControlUpdate will get the Ajax.NET method as a string, the element to be updated and the optional arguments used for the C# method. In our example we will update the same control that we also send to the server:
Try it, now! If you change the car company you will get a new drop down list with the available models:
If you want to update a control you can use the client-side element, send it to the server, modify it there and send it back to the client:
The element with the ID dropDisplay will be send to the server. On the server it will be converted to a real System.Web.UI.HtmlControl. You can use .NET to change properties, add child controls,... and then the control on the client will be refreshed.
The following C# code will have a dropdown list as argument that I will fill with values on the server:
[Ajax.AjaxMethod] public System.Web.UI.HtmlControls.HtmlSelect Test21(System.Web.UI.HtmlControls.HtmlSelect dropdown) { dropdown.Items.Add("New option added at " + DateTime.Now); return dropdown; }
If you have same requests that will result the same result it would be nice to cache those requests. The only thing you have to add are the duration the request should be cached (in seconds):
[Ajax.AjaxMethod(30)] public System.DateTime Test20() { return DateTime.Now; }
In the above example this call wil be cached for 30 seconds. If you click here you will only get the current time every 30 seconds.
Add namespace mappings to hide Ajax.NET script proxy locations
With the new version you can add namespace mappings in the web.config to hide internal knowledge about your assemblies:
This will create the virtual proxy files in the folder /ajax/MyPath for the namespace Namespace.ClassName,AssemblyName.
Asynchronous JavaScript and XML (AJAX) has recently become the craze thanks, in no small part, to Google’s usage of it in Google Suggest as well as Google Maps. In ASP.NET terms, AJAX allows server-side processing to occur without requiring postback, thus enabling clients (browsers) with rich server-side capabilities. In other words it provides a framework for asynchronously dispatching and processing requests and responses from the server. AJAX leverages a number of existing technologies, which aren't particularly new, however fondness for what these technologies have to offer (collectively, they are AJAX) has recently soared.
Enter Michael Schwarz's AJAX .NET wrapper which allows ASP.NET developers to quickly and easily deploy pages capable of easily capitalizing on AJAX. Users should be cautioned that the wrapper is early in development, and as such isn't fully matured.
It should be pointed out that technologies such as AJAX are very likely going to lead to violations of layered architectures (N-Tier). My opinion is that AJAX increases the likelihood that the presentation logic layer (or worse, the business layer) will leak into the presentation layer. Strict architects, like me, might cringe at this notion. I feel that even if AJAX is used in a manor which slightly violates layer boundaries, the payoffs are well worth it. Of course, that's something you'll need to look at for your specific project and environment.