Tuesday, March 31, 2009
Using jQuery with ASP.NET
jQuery is just a JavaScript library so it will work seamlessly with ASP.NET both from page code as well as through backend driven code using the Page.ClientScript object or ScriptManager. You can use jQuery on its own as a client side and Ajax library that communicates with ASP.NET or you can use jQuery in combination with ASP.NET AJAX. The two actually complement each other quite well as jQuery provides functionality that the ASP.NET AJAX library does not and vice versa. For the most part the interaction between the two libraries is trouble free except for a few very rare edge cases.
In this article I’m not going to be talking much about ASP.NET AJAX since that’s been covered ad finitum in other places – the procedure doesn’t vary much if you’re using it with jQuery. Instead I’ll focus on using only jQuery plus a few small helpers to make callbacks to the server easily. In the process you’ll get to see how some of jQuery’s AJAX features work and how to manage the data coming back from the server in a few different ways.
First Ajax Steps with jQuery
One of the most obvious client side features of any Javascript client library is the ability to make AJAX calls to the server. jQuery includes a host of Ajax functions that make it easy to retrieve content from a Url starting with the low level and do-everything $.ajax() function plus a number of others that are simpler and more focused to specific tasks. Here’s a list of some of the functions available:
$.ajax(opt)
This the low level Ajax function with many, many options that lets you create just about any kind of Ajax request. If you need full control over requests or you want to create a generic component that calls back to the server (like the WCF/ASMX client proxy I’ll discuss later) you’ll want to use this function. For now check out the documentation on the multitude of options available.
$(sel).load(url,data,callback)
The .load() function is the only Ajax function that works off a jQuery selector. It calls a URL on the server and loads the result as content into selected element(s). It’s a very quick and easy way to load Html fragments and inject them into the document if your result is HTML. An optional callback can be provided to be notified with the server result text when the callback completes which is useful if you want to visually adjust the retrieved content – like applying an effect to visually cue the user to an update. Note this function is heavily overloaded: If no URL is specified .load() acts as a load event handler that fires when an element has loaded its data (ie. an image or script).
$.get(url,callback),$.post(url,data,callback)
These functions are simple helpers that provide basic get and post operations to the server. You specify a URL and a callback which is called with the HTTP response from the server. $.post() also allows you to pass either formatted POST buffer string or an object the properties of which are turned into POST encoded key value pairs.
$.getJSON(url,data,callback)
Similar to $.post(), but expects the result to be JSON which is automatically deserialized into a Javascript value and passed to the callback as a parameter. While this function is handy for simple JSON results there are two things to watch out for: Dates are not parsed since there’s no date literal in Javascript, so whatever the server returns will be used (typically a string). $.getJSON() also doesn’t support JSON POST data – only POST encoded variables. This function is useful for simple JSON results returned from arbitrary services, but not usable for calling WCF or ASMX ASP.NET services since they expect JSON POST input. More on this later in the article.
.getJSON() also supports cross domain JSONP callbacks. If you specify a query string parameter of callback=? you can force the result to be routed to the callback you specify in the parameter list.
$.getScript(url,callback)
This function loads script code from the server and executes it once downloaded if no callback is specified. If specified the optional handler is fired instead and passed the Javascript, plus the current ajax request. This can be useful for JSONP cross domain callbacks where you have no control over the parameters used.
Global Ajax Events
There also a number of global Ajax events that you can take advantage of all of which take callbacks as parameters: ajaxCallback(), ajaxError(), ajaxSend(), ajaxStart(),ajaxStop(),ajaxSuccess(). These are useful for setting up global handlers that can centrally manage Ajax requests. You’re not likely to need these much unless you build components that need to know status of requests.
Read More
Monday, March 30, 2009
An Extensive Examination of LINQ: An Introduction to LINQ
LINQ, or Language INtegrated Query, is set of classes added to the .NET Framework 3.5
along with language enhancements added to C# 3.0 and Visual Basic 9, the versions of the language that ship with Visual Studio 2008. LINQ adds a rich, standardized
query syntax as a first-class citizen in .NET programming languages that allows developers to interact with any type of data.
Consider a typical data-driven application. There may be times when you are working with a database, displaying records or editing, inserting, and deleting data. Certain
parts of the application may require retrieving certain elements from an XML file, or constructing an XML file based on user input. Or perhaps you have a collection of objects
returned from a business object that you now want to work with by sorting them, computing the average value of a particular numeric property value, and displaying only those
objects that meet a specified criteria. Prior to LINQ, working with each data source requires writing a different style of code. Moreover, working with external resources like
data bases, XML files, and the like typically involves communicating with that external resource in some syntax specific to that resource. To retrieve data from a database you
need to send it a string that contains the SQL query to execute; likewise, to work with a subset of XML elements in an XML document involves specifying an XPath expression
in the form of a string. The idea is that using LINQ you can work with disparate data sources using a similar style without having to know a separate syntax for communicating
with the data source (e.g., SQL or XPath) and without having to resort to passing opaque strings to external resources.
This article is the first in a series of articles that explores the goals of LINQ, its underpinnings, its syntax, and LINQ providers like LINQ to Objects, LINQ to XML, LINQ
to SQL, and so forth. This inaugural article offers an overview of LINQ, looks at some simple examples of using the LINQ classes and syntax, and examines the core LINQ
classes in the .NET Framework. Read on to learn more!
Read More >
An Extensive Examination of LINQ: Extension Methods, Implicitly Typed Variables, and Object Initializers
One of the more substantive additions to the .NET Framework 3.5 and C# 3.0 and Visual Basic 9 languages was LINQ, a set of classes along with language enhancements that
allow developers to use a common library and SQL-like query syntax to work with common data stores. The initial article in this series,
An Introduction to LINQ, provided an overview of LINQ and its core pieces: the standard query
operators, the language extensions that allow for LINQ's query syntax, and LINQ providers. We also looked at some simple LINQ examples using both the standard query operators
and the query syntax.
LINQ's standard query operators - Select, Where, OrderBy, Average, and so on - can be used as if they were instance methods
of any object that implements IEnumerable<T>. For example, given a string array named FileNames we can determine how many strings in the array start
with the letter "S" by using the Where and Count standard query operators like so:
|
The Where method and Count methods look like they are members of the Array class. However, they are defined in the Enumerable class in the System.Linq namespace as extension methods on the IEnumerable<T>
interface. Also note the syntax that is used to specify the input parameter for the Where method: name => name.StartsWith("S"). This syntax is a lambda
expression and provides a shorthand notation for developers to define a function.
This installment (and the next one) explore the language enhancements Microsoft made to C# 3.0 and Visual Basic 9 in more depth. (C# 3.0 and Visual Basic 9 are, at the time
of this writing, the most recent versions of these two programming languages. They are the versions that were released with the .NET Framework 3.5 and Visual Basic 2008.)
The key language enhancements that make LINQ possible include: extension methods; implicitly typed variables; object initializers; lambda expressions; and anonymous types.
This article explores the first three of these language extensions; the latter two will be covered in the next installment. Read on to learn more!
Read More >
Using Expression Builders in ASP.NET
ASP.NET offers a variety of ways to inject the results of a server-side expression (such as DateTime.Now.ToString()) into the rendered markup of an ASP.NET page.
The most common way is to add a Label Web control to the page and then from the Page_Load event handler (or some other suitable event handler) assign the value
to display to the Label's Text property. If you ever created web applications using ASP.NET's predecessor, classic ASP, or if you are familiar with
Microsoft's ASP.NET MVC, then you know that another way to inject server-side information is to add <%= expression %> to the declarative content like so:
The current time is: <%= DateTime.Now.ToString() %> |
The <%= expression %> syntax is translated into Response.Write(expression), injecting the value of expression into the
page's rendered output. Because <%= expression %> is translated into (essentially) a Response.Write these statements cannot be used to set the values
of Web control properties. In other words, you cannot have markup like the following:
<asp:Label runat="server" id="CurrentTime" Text="<%= DateTime.Now.ToString() %>" /> |
An alternate way to display server-side information is to assign it to a Web control property directly from the declarative markup using an expression builder. An
expression builder is denoted using the syntax <%$expression %> (note the $ after <%).
The expression cannot be an arbitrary snippet of code as with <%= ... %>, but instead is limited to what expression builders the website is configured
to use. Moreover, expression builders must be assigned to a Web control property; they cannot appear in any which place in the declarative markup like <%= expression %>.
ASP.NET ships with three built-in expression builder classes that let you declaratively access the values in the configuration's AppSettings collection, the ConnectionStrings collection, and in the website's resources (typically defined in the App_LocalResources and App_GlobalResources folders).
With a little bit of code you can create your own expression builders. This article provides an overview of how expression builders work and shows how to create your
own expression builders. Read on to learn more!
Read More >
skmExpressionBuilders - A Suite of Custom Expression Builder Classes
An ASP.NET Web control's properties can be set in one of two ways: declaratively and programmatically. Declaratively setting a Web control's properties entails specifying
the property in the control's declarative syntax. For example, Web controls have their ID property set declaratively, like so:<asp:WebControl runat="server" ID="ID" ... />. Properties can also be set programmatically in the ASP.NET
page's code-behind class. If you need to set a Web control's property to some dynamic value you may think you need to set it programmatically. However, this is not the case.
Expression builders make it possible to assign a dynamic value to a Web control property through the declarative syntax.
Last week's article, Using Expression Builders in ASP.NET, examined the ins and outs of expression
builders, their syntax, and how to use them in an ASP.NET page. ASP.NET ships with three built-in expression builder classes: AppSettingsExpressionBuilder,
which retrieves a value from the <appSettings> section defined in Web.config; ConnectionStringsExpressionBuilder, which retrieves a
value from the <connectionStrings> section; and ResourceExpressionBuilder, which retrieves a resource value. These expression builders can be
used in the declarative markup using syntax similar to the following: <asp:Label runat="server" id="Copyright" Text="<%$ AppSettings:CopyrightNotice .
%>" />
With a little bit of elbow grease you can create your own custom expression builder classes. I've spent some time creating a handful of custom expression builder classes,
which I've packaged into a class library named skmExpressionBuilders. This article walks through the custom expression builders in this library and shows how to use them in
your ASP.NET application. Read on to learn more!
Read More >
An Extensive Examination of LINQ: Lambda Expressions and Anonymous Types
The previous installment in this article series, Extension Methods, Implicitly Typed Variables, and Object
Initializers, examined three new features to the C# 3.0 and Visual Basic 9 languages that allow for developers to use LINQ's standard query operators and providers to
write SQL-like query syntax to work with common data stores. But extension methods, implicitly typed variables, and object initializers are only part of the story. Two additional
language features - lambda expressions and anonymous types - are also essential ingredients in LINQ's unique syntax.
Recall that LINQ's standard query operators can work with any collection of data that implements the IEnumerable<T> interface. Some of the standard query
operators perform rather straightforward operations on the collection; the Count standard query operator, for instance, simply returns the number of elements
in the collection. However, other standard query operators are more flexible, allowing the page developer to dictate how the operator will work. The Where standard query
operator is such an example - it filters the elements in the collection based on a developer-specified filtering method. But just how can a developer "pass" a method to theWhere standard query operator as an input parameter? The .NET Framework has long supported the notion of delegates, which are type-safe function pointers. However,
the syntax for delegates is a little confusing and verbose. Lambda expressions offer a much more terse syntax for defining an anonymous method.
Anonymous types allow for inline types. In a nutshell, anonymous types let you clump a set of values together into a new type without having to first declare the type
via a class. For example, imagine that you have a collection of Employee objects, where each Employee object has properties like Name, Salary, HireDate, and so on. You may want to apply some filtering condition on this collection using the Where standard query operator and
then project the collection of Employee objects into a collection of objects that includes just the Name and Salary properties.
With anonymous types this style of projection is straightforward and natural. Without anonymous types you would first have to create a class like EmployeeSimplified
that contained only those two properties of interest.
This article provides an overview of lambda expressions and anonymous types. These two language enhancements, along with extension methods, implicitly typed variables, and object
initializers, are what allows for LINQ's query syntax. Read on to learn more!
Read More >
Syndicating and Consuming RSS 1.0 (RDF) Feeds in ASP.NET 3.5
Websites that produce new content on a regular basis should include a syndication feed, which is a specially formatted XML file that includes a summary of the most recently
published items. Virtually all blogs, news sites, and social media sites have a syndication feed, and 4Guys is no exception. The
4GuysFromRolla.com syndication feed contains the most recent articles. Syndication feeds are meant to be
consumed by computers. Sites like Technorati parse the syndication feeds from blogs and use that data to determine the topic du jour.
Also, syndication feeds are commonly used by websites to display the latest headlines from related sites. For example, an ASP.NET community website could consume
the 4GuysFromRolla.com syndication feed to display the latest 4Guys headlines.
Until recently, there was no built-in support for creating or consuming syndication feeds in the .NET Framework. That changed with the release of the .NET Framework version
3.5, which included a new namespace: System.ServiceModel.Syndication.
This new namespace includes a handful of classes for working with syndication feeds. As aforementioned, syndication feeds are XML files, and for the syndication feed to be
of any use it must conform to one of the popular syndication feed standards. The two most popular syndication feed standards are
RSS 2.0 and Atom 1.0, and these are the standards
supported by the classes in the System.ServiceModel.Syndication namespace. But there is a third format that, while not as popular as RSS 2.0 or Atom 1.0, is still
used. That standard is RSS 1.0.
The good news is that with a little bit of work we can create a class that works with the RSS 1.0 standard and have this class used by the syndication feed-related classes in
the .NET Framework 3.5 can be. This article introduces a free library, skmFeedFormatters, which you can use in an ASP.NET 3.5 application to create and consume RSS 1.0 feeds.
(This same concept could be applied to creating and parsing Atom 0.3 feeds, as well.) Read on to learn more!
Read More >