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
 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
 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
 Friday, August 03, 2007

In my previous post I gave a brief overview of what an Animation is in ASP.NET AJAX, and now it's time to understand how you go about actually using them. By the end of this post you should be able to look at a block of Animation XML and understand what it's doing and you should be able to write a block of Animation XML without needing to lookback on a sample block of code (too much).

Let's Recap for a Moment

Before diving, let's recap from my previous post: an Animation in the ASP.NET AJAX framework is any DHTML effect that leverages the Animation framework provided by the ASP.NET AJAX toolkit (which can be found here). The problem found in playing with DHTML in the past has been that you've needed JavaScript (and sometimes pretty hairy JavaScript) to do anything meaningful with it. As programmers we're "resourceful" (or lazy) and therefore don't want to do more work than we need. With the Animation framework in ASP.NET AJAX, you only need to worry about XML markup specific to the animation you want.

In short, ASP.NET AJAX Animations are the easy way of adding cool DHTML animations and effects to your page - it achieves this by letting you define and play with your animations declaratively through an XML syntax.  

Show Me an Example

Let's go back to an earlier example that I did (because of its utter simplicity) and work out from there. In my previous post I showed an example effect on a button where, once you clicked the button, it's text color changed red and then faded out:

to....

You achived this effect by using declarative XML syntax. The syntax let you play with the properties (the starting color and ending color in this example) without needing to write any code; thereby making things easier and more manageable for everyone. Let's break the syntax I showed you earlier down one element at a time so that you can see why a particular element exists and what it does.

Understanding the ASP.NET Animation XML Syntax

As I said earlier, to write an Animation in ASP.NET AJAX, you use an XML syntax. The syntax that resulted in the above button color change looks like this:

First thing to take away is that this is a control extender - or an object in the ASP.NET AJAX framework that let's you apply AJAX'ish properties to an already existing, standard ASP.NET control (you can learn more about extenders here). What this means, practically, is that the animation needs to know to what standard ASP.NET control the animation will be applied. If you take a look at the first line of XML, you'll see the TargetControlID property pointing to Button1. You should know that this Animation will, then, be applied to Button1.

Second is the Animations element which will house all of the animations you will apply to Button1 (that's right, you can apply more than one, even in parallel). This may seem somewhat redundant, but it is required.

Third we have an event name. In our example, OnClick, means that the Animations will be executed during the OnClick event of Button1 (bear in mind that this is the client onclick event, not the server one). Therefore when someone clicks Button1, the animations specified below the OnClick event node will be executed.

The events OnClick, OnLoad, OnMouseOver, OnMouseOut, OnHoverOver and OnHoverOut are valid events; meaning you don't have to just use OnClick, you could also use OnHover. It's interesting to note that you can have all of these event handlers under the same Animations element if you wanted to - therefore, you could have one Animation registered for OnClick, and a totally different one registered for OnMouseOver, thereby creating a very dynamic control!

Fourth we have a sequence element; but - I have to admit to something here, this is actually not necessary in our example. I added it because I wanted to make a point about something. The point I want to make is a subtle one: you can only have one Animation registered for a particular event type (OnClick, OnMouseOver). The reason this isn't a limitation, however, is because there are two Animations called Sequence and Parallel which are not only valid Animations themselves, but allow nesting of other animations. Therefore, Sequence is an Animation itself that will call each child Animation one after another (in "Sequence"), and Parallel is an Animation that will call each child Animation at the same time (in "Parallel"). This is a subtle, yet powerful, thing to realize.

So..the following XML is actually valid (note the missing Sequence element):

But, if you wanted to change the color of the button and THEN fade it away completely, for example, you would have to nest the Color Animation and FadeOut animation within a Sequence Animation (not doing so will result in a runtime exception). The XML must look like this:

The result from the above XML declaration is to fade the button's color from FF0000 to 666666 and then completely fade it out of existence in .5 seconds. What's really cool is if you wanted to do both at the same time, all you have to do is change the Sequence element to a Parallel element:

Cool, huh? Now the color change and the fade-to-nothing will happen at the same time or in Parallel.

The lowest level element of the structure is always the actual Animation itself (Color for color change, FadeOut for fading out the element, etc).

Does it Get Tougher?

Yes, somewhat because you can actually tie into the XML script to be executed when certain events occur and conditional statements. We'll explore that, however, next time...


kick it on DotNetKicks.com
Friday, August 03, 2007 3:34:22 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | JavaScript | Under the Hood | Web 2.0
 Thursday, August 02, 2007

In two previous articles here and here I did a fairly high-level description of JSON and why it's important in ASP.NET AJAX. Hopefully you either read those or you already have a fairly decent understanding of the topic. The point behind writing those posts was to give you the knowledge required to understand the internals of the Animation framework in ASP.NET AJAX. I'm going to begin the dive now, but before doing so actually give a brief overview of, exactly, what Animations are in ASP.NET AJAX. I'll attempt to answer the questions why are they important, and why should you - as a .NET developer - care.

What are Animations in ASP.NET AJAX?

Animations are not built-in to ASP.NET AJAX, they are an addition to it brought about by the ASP.NET control toolkit, an open-source project going on over here. What they provide is an easy-to-use method of adding fancy DHTML effects (such as call-out windows, flashing buttons, rotating objects, etc) to your page. You will find a feature such as this handy when you need to make a web-site that stands out above the rest and is a bit more interactive than, say, your typical web application. For example, you could make a window pop-out at the user when he/she clicks a button, like this:

What makes the ASP.NET Animation framework compelling, however, is not that you can do things as above (after all, you have been able to do shtick like this for years in JavaScript), but that all that's required  is a bit of XML markup in your ASPX page:

<ajaxToolkit:AnimationExtender id="MyExtender"
  runat="server" TargetControlID="MyPanel">
  <Animations>
    <OnClick>
      <FadeOut Duration=".5" Fps="20" />
    </OnClick>
  </Animations>
</ajaxToolkit:AnimationExtender>

...therein lies the cool factor.

Cool, how do I do it?

I'll show you, but I'll do it with a rather simple example first so that we don't spend a great deal of time (and space) with the inconsequential.

First, you create a new ASP.NET AJAX web application using Visual Studio 2005. I won't go into the details of doing this as you already know how to do this.

Second, you add a reference to the control toolkit's main assembly to your project (if you do not have this, then you can download it and all the supporting stuff from here).

Third, register the assembly and it's namespace in your ASPX page:

Fourth, slap a button on your ASPX page:

Fifth, flip over to the code view and add the following code:

...note two things: first, I added OnClientClick event handler to the button to prevent it fom posting back to the server; second, I added a block of XML markup as an AnimationExtender (the ajaxToolkit:AnimationExtender block). Also note how I assigned the TargetControlID property of the AnimationExtender to the Button I just added moments ago.

Now, if you F5 and run the application, you'll see that - when you click the button - the button text will turn red:

...and then fade out:

What else can Animations do?

Practically anything you want. It's a framework, mind you, so it's very extensible and maleable; but the nice folks that built the framework have supplied a great deal of pre-made animations for your consumption, and you can find the list here (which includes everything from fadeouts to movement).

After following through the list of pre-made animations, you can't help but get a bit excited about the kinds of things you can do. In the next section I'll explain the nature of Animations (the mindset you need when working with them), and then in the section after that I'll explain how they work (given that we now understand JSON).

....stay tuned.  


kick it on DotNetKicks.com
Thursday, August 02, 2007 12:40:55 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | JavaScript | Under the Hood | Web 2.0
 Wednesday, August 01, 2007

Okay, in my last post on this topic I gave a brief overview of what JSON is and how it comes into play with your ASP.NET AJAX solution. Now I'm going to stretch out a bit and show you a few examples doing something practical with JSON data in ASP.NET AJAX. I'll be careful to explain what I'm doing along the way. By understanding this, you'll be ready to move into how Animations work in ASP.NET AJAX, and therefore be able to leverage them in your applications.

You know that JSON is a "stringified" version of an object, and you know that this stringified version is used to preserve the object across boundaries where raw, binary data transmission is not practical (or possible). However, one thing I didn't really touch on, and so I'll now explain, is exactly why someone would transmit an object to some other environment anyway. Objects are nice ways to not only pack functionality, but also state - so in the case of browser-based programming, for example, you could easily see yourself creating an object that represents the behavior of a button element, setting some state (such as color, what happens when the button is clicked, etc) and sending it down to the client. So, the reason you'd do such a thing as send an object down to the client is because that object represents state and functionality specified by you on the server; once downloaded to the client browser it can then be used to reflect that state to elements within the browser in a nice, packaged form.

Let's step back a bit and make up a quick example.

Say you have a DIV tag on your page and this DIV tag is to do something when you click it. You could set the div tag's onclick handler to run some kind of javascript:

<div id='mydiv' onclick='doSomething();"/>

We've all seen this before and it's nothing new; it's just JavaScript. However, what if you wanted some sort of variation in what the method doSomething() actually does? Perhaps it displays something a bit different depending on the user logged in, or perhaps you want something special done because it's Halloween - whatever.  Now you're in a pinch. In ASP.NET, you might go ahead and start doing more dynamic things to it through inline ASPX or through Response.Write(); basically modifying what the browser gets through the output stream (such as tweaking arguments to doSomething()). After a while, however, this gets really, really ugly to manage. What would be nicer is if an object basically represented the functionality of the DIV tag, and so on the server all you had to do was set up a couple properties (such as the text displayed to the user when he/she clicks the DIV tag) and have those properties get reflected in the client browser. In this scenario, an object would exist on the server where you can programmatically tweak properties, and then it gets sent down to the client where it actually "behaves" as script.

As you can imagine, the way the object would be sent down to the client is as a JSON-seralized object.

We saw earlier that the modern browser has capabilities, through the eval() method, to rehydrate an object out of JSON-formatted data. We also saw earlier how the ASP.NET AJAX framework provides a number of ways to wrap the eval() method to make it more robust and secure. All that's needed, then, is a way to take an object on the server and create a JSON-formatted string of data out of it so that the browser can create a version of it for itself. There is - it's called the JavaScriptSerializer.

If you had an instance of the JavaScriptSerializer in your class like this:

Then you could serialize an object with it like this:

...you can see here that I'm taking some instance of an Animation type and serializing it as a JSON string. Note that the Animation type isn't JavaScript, it's a full-blown .NET type (a real managed typed). The string returned simply represents the properties and events of the type.

If my animation had properties (like, say, the text that is displayed when I click something), then the JSON string will represent the property and the  value of that property. Anything that will rehydrate the object from that JSON string will set the property to the original value. Therefore, the object's state gets preserved as it crosses from the server to the client.

There are a number of ways to rehydrate the object using the client framework of ASP.NET AJAX so it gets reborn in the browser. A handy shortcut method for doing this is $create(). The create method will take the type it is to create as the first argument, and then a initialize properties and events on the type through JSON-formatted data. The $create() method, then, creates objects out of JSON. Once done, the newly created object will have it's initalize() method called by $create() (giving you the opportunity to attach event handlers and the like).

Therefore, say we had some JavaScript class called AnimationBehavior and it has a series of properties. On the server you set those properties and then create a JSON string out of the object. $create() can take that string, initilialize a JavaScript version of the type and then call the new AnimationBehavior object's initalize() method. From there you can attach event handlers based on the properties and events you set through JSON.

So....

  1. You have a fully-qualified .NET object.
  2. You can set properties on that object and have that object serialized as a JSON string.
  3. The ASP.NET AJAX client framework can take that string and create a version of the managed type in JavaScript for it's own use through JSON and the $create() method.
  4. The $create() method, once finished initializing the new type, will call the type's initialize() method, giving you the opportunity to do something meaningful (such as initialize your object).

Note that eval(), normally, creates an opaque object out of JSON data. eval(), used alone, will not create anything typed strongly. $create(), on the other hand, expects an already existing type in JavaScript to instantiate and initialize through the JSON data. If you're creating a valid ASP.NET AJAX client type, it will have an initialize() member method, thereby working perfectly fine with $create().

In the next section I'll walk you through exactly what an Animation is, and then we'll see how they use all of what you just learned.


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

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)