Exploring the depths and potentials of ASP.NET RSS 2.0 or Subscribe to .BenRush by Email
 Wednesday, August 22, 2007

I don't know if you've ever tried calling a web service from client script before, but with ASP.NET AJAX it's amazingly simple. In fact, a great deal of the built-in features (such as authentication, my next topic) of ASP.NET AJAX are accomplished through the web services infrastructure inherent to ASP.NET AJAX.

However, there are plenty out there who may never have attempted to call a web service from client script, instead always accomplishing their task with their ASPX pages either through a synchronous or asynchronous page requests. Yet, there are many good reasons to execute a web service from your client script:

  1. Responsiveness: To render an ASP.NET web page (even one through ASP.NET AJAX) still takes a fair amount of server resources. A great number of controls still must be rendered out and the entire page lifecycle must be executed in order for the response to be generated back to the client. If you want a simple bit of information, why put the strain on your server when you can simply call a basic web service instead?
  2. Coding Simplicity: Sometimes a web service simply makes more sense than calling a web page. For example, what if you wanted to update a stock ticker on your web page with fresh content every ten seconds. Rather than calling back to the server to process a page that must magically return content that seamlessly updates the stock ticker, the ticker can simply call a web service from the browser and update itself through the browser DOM.
  3. Cleanliness: Asynchronous behavior is cleaner in a web browser than a full post-back, and a web service, with less data, requires less time to process and will therefore typically return to the client faster.
  4. Reuse: A web service can be reused many, many times over by many, many different clients. Whether you're writing a desktop application, a script application that runs in your browser, or a legacy UNIX-based mainframe application that leverages pure socket-based programming, one web-service can "service" them all. If you are in the business of implementing stock tickers in web pages, then it makes sense you're likely to use that same application code in other areas; building it as a web-service simplifies the matter (and now that you can easily call it from script code, there's no reason for clumsy shared libraries, etc).
  5. Mashupability: Mashups are the way of the future - at least for the next year or so until the next way of the future hits the web. A web-service front-end lends itself to mashable behavior much more than some heavy ASPX page. Making your components interact with script increases their overall exposure by allowing them to partake in the new Web 2.0 atmosphere (plus it looks good to your boss too).

Honestly the list could go on and on. I'm sure if you sat and thought you could list off any number of other reasons why updating components on your page using the asynchronous, relatively light-weight nature of web services (at least more so than ASPX pages) wins out over synchronous and asynchronous page-refreshes.

In ASP.NET AJAX it's also wicked simple. The steps are as follows:

  1. Create a web service,
  2. Register said web service with the ScriptManager on the ASPX page,
  3. Call the auto-generated script wrappers for the service and consume the response from the service as properly-typed JavaScript.

I'm going to shamelessly steal the example code from the ASP.NET AJAX sample on using web services for this post because it's about as simple as it gets. So, first we create our web service:

....note the use of the [ScriptService] attribute, this is a must...

Next, we simply register the service address with the ScriptManager that we already have existing on our ASPX page:

And then we simply call an auto-generated script method (scoped the same as the class of the web service method):

To you, the developer, the script method magically appears on the client, ready to use. But, we all know it wasn't magical and there was a great deal of cool work under the hood to make all of this come to life. Just how this works, and how you can leverage it best in your applications, will follow over the next couple days.....


kick it on DotNetKicks.com
Tuesday, August 21, 2007 11:46:33 PM (Central Standard Time, UTC-06:00)  #    Comments [1] - Trackback
AJAX | ASP.Net | JavaScript | Web 2.0
 Tuesday, August 21, 2007

I'm preparing to write a number of posts over the next week or two on the topic of authentication in ASP.NET AJAX; again going under the hood and exploring how the internals work as well as showing you all of the features of authentication (and how to best leverage it in your applications). I should have a post ready by tonight on the topic, but if you have any particular interests in this area feel free to comment on this post and I'll make sure to bring up your topic in this or the next couple articles.


kick it on DotNetKicks.com
Tuesday, August 21, 2007 1:24:02 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net
 Thursday, August 16, 2007

                The UpdatePanelAnimationExtender is an interesting and useful extender control found in the ASP.NET AJAX Control Toolkit that enables you to run animations when an UpdatePanel control updates or has finished updating on the client. The sample on the control toolkit website shows how you can animate the UpdatePanel when it updates by leveraging the extender control.

                However, because the Animation framework is quite extensive, you can also do many interesting things to controls outside of the UpdatePanel when it updates by leveraging a bit of JavaScript and the UpdatePanelAnimationExtender. This is possible without the UpUpdatePanelAnimationExtender, but by using it you can accomplish scripting in a much cleaner and manageable manner. For example, say I wanted to disable a button outside of my UpdatePanel when the panel updates:

                To do this with the UpdatePanelAnimationExtender is trivial, you simply add the Extender to your page:

                Note that it has an Animations sub-element; this is where you place the Animations you want ran when the UpdatePanel updates or has finished updating (OnUpdating and OnUpdated respectively).  Now, you can add any animations under the event nodes, but I want to add some script to disable the button and re-enable it when the UpdatePanel has finished refreshing:

                Now your script is clearly and concisely placed within Animation event framework where you can make it invisible, disabled, etc. To me this is a much nicer solution than writing script directly into the page output.

 


kick it on DotNetKicks.com
Thursday, August 16, 2007 9:52:19 AM (Central Standard Time, UTC-06:00)  #    Comments [2] - Trackback
AJAX | ASP.Net | JavaScript | Web 2.0
 Monday, August 13, 2007

So, I got to reading a couple blog posts this weekend and one of them (which I found from dotnetkicks.com) was interesting. It presented a problem that I've encountered before but always skirted architecturally (I just changed the design of my web application a bit so I wasn't faced with it anymore). I got to thinking about a few ways to solve this issue and one way popped out at me as one way - but not necessarily the best way (possibly not even close, in certain circumstances). Anyway, I'm presenting it here to open the discussion up if anyone wishes, but otherwise to just write it down so that I have it here for later reference.

The Problem

You cannot easily reference objects from client script if their server-side counterparts are housed within certain parent controls. For example, if you place a TextBox control within a Wizard control and then attempt to reference that TextBox control from client script, you will undoubtedly have difficulties.

Why?

When the control is rendered out to the browser, it's client-side ClientID will not be the same as it's server side ClientID for various reasons. Suffice it to say that if you name a TextBox "MyTextBox", place it within a Wizard control, and then attempt to reference that control from client script with the ID "MyTextBox" it will fail (for the sake of posterity, the name of the TextBox will probably be the name of the wizard + underscore + "MyTextBox").

This is obviously a problem if you're writing script to reference objects through the $get() shortcut handler, etc.

One Solution

One solution is to not use ID as the reference attribute, but to instead add some other attribute and reference controls that way. Now, I'm not sure how browser-compliant this nor how standards compliant it is, but it works for me locally and I thought I'd at least mention it for those who may be on their last leg trying to back out of a problem like this. I just picked a random attribute name "googliebah" and decorated a couple controls on my page with it; then my custom script will locate a control with the googliebah ID and then determine if its value matched the search value. Obviously it works.

Now, in terms of efficiency I can't say this ranks as a an optimal solution; but perhaps a more eager person could introduce some level of caching the elements once they're found (or limiting the scope of the objects you're searching by doing some post-processing on the ASP.NET page). I have a few ideas around that solution, but I can't say as though I have the time at the moment to implement them.

Regardless, this is the script:

        <script type="text/javascript">
            function newFind(name)
            {
                var elems = document.getElementsByTagName('*');
                var num = elems.length;
                for(var c=0;c<num;c++)
                {
                    var val = elems[c].getAttribute('googliebah');
                    if(val!=null && val==name)
                        return elems[c];
                }
            }
        </script>

And you use it to find some control like this:

<div googliebah='test' id='test' class="title">

By doing something like this:

<input id="Button2" onclick="var elem = newFind('test'); if(elem)alert(elem.id);" ....


kick it on DotNetKicks.com
Monday, August 13, 2007 11:02:37 AM (Central Standard Time, UTC-06:00)  #    Comments [1] - Trackback
AJAX | ASP.Net | JavaScript
 Saturday, August 11, 2007

In this post, I'm going to end my discussion on Animations in ASP.NET AJAX by showing you how they work, internally. At the end of this post you should not only know how Animations work, but also how ExtenderControl's work in general.

What is an ExtenderControl?

An Animation is actually just an ExtenderControl, so it will do us some good to understand what an ExtenderControl is all about.

ExtenderControls are script controls that apply a particular feature from ASP.NET AJAX to an already existing ASP.NET (non-AJAX) control. For example, if you wanted to apply some cool, new feature of ASP.NET AJAX to a standard radio button control, you'd do so through the implementation of an ExtenderControl. Extender control's work by emitting JavaScript that is attached to and extends functionality of an ASP.NET control. You will always need to reference the control to which you are applying the extender because it will need to know which control the emitted script should target. The key thing to remember is that it's an ExtenderControl is an auxiliary to an existing control, and typically the extending features are done through JavaScript.

Exactly how does the script emitted by an ExtenderControl become attached to the target ASP.NET control? Script becomes successfully attached to pre-existing controls through the runtime execution of the ScriptManager on the server, the use of a type known as the ScriptDescriptor, and the bootstrap client-side code of ASP.NET AJAX on the client.

On the server, the process looks something like this

 

The process starts when the ASP.NET runtime asks the ScriptManager (a native, server-side control) to render itself out. The result of doing so causes the ScriptManager to ask every control that has attached itself to the ScriptManager to render itself out too (an Animation, being an ExtenderControl, is therefore asked to render).

A script control is a special, new type of control introduced into the ASP.NET AJAX framework as a control that relies heavily on the scripting facilities of ASP.NET AJAX. One of the important features of a script control that sets it apart from other controls is that it has a great deal of functionality that must be executed on the client (through JavaScript) for it to function properly. A script control is responsible for giving all scripts and script types it requires to operate to the ScriptManager when it renders; doing so guarantees that the script will be included in the page output and therefore included in the rendered page.

Script controls hand off all the necessary script and script types to the ScriptManager as nicely packaged objects known as ScriptDescriptors and ScriptReferences.  We’re more interested in ScriptDescriptors, however, as they are the layout for the JavaScript types and so (if you refer to the diagram above) you see that our extender control (when asked to render) calls back into the ScriptManager to register all its types. Doing so finally calls into ScriptDescriptor.GetScript() which returns back a block of script leveraging the $create() shortcut method and a series of JSON-formatted data.

When the ScriptManager renders, then, it guarantees that the JSON-formatted data of the control will be instantiated and initialized on the client through the $create() method. How? Because the ScriptManager will wrap the output of GetScript around the Sys.Application.add_init() javascript method. Add_init() actually attaches code to the initialization script of ASP.NET AJAX’s client libraries; this guarantees that, when ASP.NET AJAX is fully started up on the client when the page has fully loaded, your initialization routine will be called. What the initialization routine does, however, is up to you.  

How Does an Animation Work?

You're 90% of the way to understanding Animations now. All that's really required is a bit of a filler-explanation for what, specifically, the Animation extender control is doing.

On the server the Animation control will take your XML markup and create an in-memory Animation object instance representing all of the properties and child/parent associations. Since an Animation is an extender control, the ScriptManager will ask it to render. The result of the Render call will be the JSON-formatted version of the Animation object from the server (property values, event-handling code and all). Just like above, the JSON-formatted initialization code will be wrapped around a Sys.Application.add_init() script method so that it will be executed when the page is loaded on the client. This is an example of what the output looks like:

 

…this is actually the result of a view source on one of the animation examples on www.asp.net. There is a lot of code here, but if you squint carefully you can see it all starts with a Sys.Application.add_init() call. Also if you look carefully you’ll see that it’s actually instantiating, on the client, an object of type AjaxControlToolkit.Animation.AnimationBehavior.

The AnimationBehavior Object

If you recall from earlier discussions about Animations, there are actually many instances where multiple animation effects (a fade out, or a color change) can occur in sequence as the result of a single event (onclick). Each animation effect is actually an Animation object, and the object that surrounds each Animation (to make them happen in sequence) is also an Animation object – so we have Animation objects housing multiple Animation objects. This can be confusing when rendered out to the client, so the ASP.NET AJAX client framework wraps all the animations that need to be rendered to the client for a single Animation extender as an AnimationBehavior object. The AnimationBehavior object is what gets instantiated on the client and has its initialize() method called.

The initialize() method of the AnimaitonBehavior object will inspect which events need to be registered (OnClick, etc) and attach event handlers to the target control on the page (the client-side control which we’re extending). Whenever that event occurs on the client, the event handler for the AnimationBehavior will be called and it will route that event to the proper Animation object. Here is an example of the AnimationBehavior’s OnClick event hander:

…which, after a bit more traversing the internals of the script library, plays the Animation.

How does the Animation object actually play the animation?

It may seem like somewhat of a mystery when you declare XML on your page that then translates into some dynamically updating DHTML object, but if you think carefully about what it take to animate a DHTML object the mystery subsides.

All that it takes to animate something on your page is a timer ticking at a regular interval whose callback method updates some DHTML object property (x- and y-position, for example). And that’s all an Animation object is on the client – just a fancy timer that updates properties with values you specify; invoking the play method above simply starts off the timer, and thus the DHTML effects. Therefore all that’s needed within the JSON data is enough information to identify what property you’re updating on what object, at what interval, and with what values – the existing script of the Animation object will take care of the rest. If you look at some of the JSON-serialized data that is being rehydrated on the client, you actually can see just that information (take a closer look):


..and that’s how Animations work.

 

 


kick it on DotNetKicks.com
Saturday, August 11, 2007 3:55:07 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | Under the Hood | Web 2.0
 Thursday, August 09, 2007

The CollapsiblePanel is an ASP.NET AJAX extender control in the AJAX Control Toolkit. This particular extender control extends the default behavior of the standard ASP.NET Panel to collapse and expand when a particular element on the page is clicked (it will scroll open or closed when this trigger element is clicked). It's very easy and elegant to use, but one common question seems to be - when a full post back is triggered - what is the current (or most recent) state of the panel - collapsed or expanded?

The way to find out is by inspecting the ClientState property on the CollapsiblePanel's instance:

If ClientState is true, then the panel is collapsed; if the ClientState is false, then the panel is expanded.


kick it on DotNetKicks.com
Thursday, August 09, 2007 2:46:48 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | JavaScript | Web 2.0
 Wednesday, August 08, 2007

In my first post in this series on using ASP.NET AJAX animations I described the basics of what an Animation was and the foundations behind using it. In my second post, I then started showing you how to go about using it (the basics). What remains are a few exceptional Animations that will be used in unusual circumstances (hence them being "exceptional") but which enable you with a great deal of power when you do decide to use them.

The Condition Animation

Why stop a good thing? So I'm going to continue using the (somewhat lame) example from my previous posts where I take a simple ASP.NET button control and do things to it using the Animation framework. In this example I leverage an animation called the Condition Animation; it gives you the ability to programmatically choose one of two (at most) animations to run depending on the boolean result of some script. For example, take the following Animation XML:

By clicking button Button1, the Condition Animation will be executed (if this block doesn't make sense, see my first post and read forward). Take note of the Condition Animation and it's child Animations. The first thing to take note of is the ConditionScript attribute on the Condition element; it's a simple statement: "false;". Although this is just a boolean result (false), it could be an entire JavaScript statement which evaluates to either true or false. For Condition Animations, if the resultant script statement evaluates to true, then the first child Animation is executed (in this sample, the FadeOut animation); if the script statement evalutes to false, then the second child Animation (which is the Color animation) would be executed.

Given that you now have programmatic control over what Animation is executed, you can take conditions on the page, evaluate them through the script, and then decide which Animation to run.

The Case Animation

Being limited to one of two Animations is, well limiting. In the event that you need to pick from a wider spectrum of Animations, but still do so using the result of a script statement, then you would leverage the Case Animation. Take the following XML Animation block:

The result of the SelectScript must be a 0-based index into the array of child Animations (0 is the first Animation or the "FadeOut" animation, 1 is the second animation or the "Color" animation in our example, and so forth). In my example I simply return "1" but, like the Condition Animation above, you could have an entire script statement as the SelectScript value. So long as your script statement evaluates to a valid index into the array of child Animations beneath your Case animation it will behave properly.

In the above example, the Color animation will be executed.

The Script Animation

To flat out execute script in the Animation you would leverage the Script Animation. Take the following example:

What we have here is a Sequence Animation housing a FadeOut and then a ScriptAction animation. Given what we already know about a Sequence animation, the child nodes (or child Animations) will be executed sequentially from top to bottom. Therefore, when Button1 is clicked, the Button will fade out over half a second and then a script modal window will pop up saying "All done". Of course, much more advanced script could be executed from the ScriptAction, but you get the basic idea.

What's Next?

Okay, next we are going to dive into the pipeline to see just how this magic is done. Stick around...


kick it on DotNetKicks.com
Wednesday, August 08, 2007 7:46:50 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | JavaScript | Under the Hood | Web 2.0
 Monday, August 06, 2007

If you get MSDN, you can read my new article "ASP.NET ScriptManager Enables AJAX in your web apps". It received top billing in the September issue of MSDN.

If you have feedback, please post it here - I have another article planned soon.


kick it on DotNetKicks.com
Monday, August 06, 2007 9:02:36 AM (Central Standard Time, UTC-06:00)  #    Comments [4] - Trackback
AJAX | ASP.Net

Computers Blogs - Blog Top Sites

Archive
<August 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008
Benjamin Rush
Sign In
Statistics
Total Posts: 444
This Year: 0
This Month: 0
This Week: 0
Comments: 127
Themes
Pick a theme:
All Content © 2008, Benjamin Rush
DasBlog theme 'Business' created by Christoph De Baene (delarou)